Python之Flask和Django框架解决跨域问题,配合附加ajax和fetch等js代码

时间:2024-08-01 13:35:38

Flask框架py解决跨域问题示例:

# -*- coding: utf- -*-
# by zhenghai.zhang from flask import Flask, render_template, jsonify, request
from flask_pymongo import PyMongo,DESCENDING
import datetime
import time app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'service'
app.config['MONGO_URI'] = 'mongodb://xxx:27017/service'
mongo = PyMongo(app) def get_context():
return {
'success': True,
'message': '',
'code': ,
"data": [],
"count":
} @app.route('/', methods=["GET"])
def index():
return render_template("op.html") # /mongo?num=&page=&size=
@app.route('/mongo', methods=['GET','OPTIONS'])
def getmongodata(): # num = request.args.get('num', "")
page = request.args.get('page', "")
size = request.args.get('size', "")
rstart = request.args.get('startdate', "") # like ---::
rend = request.args.get('enddate', "") # like ---::
rdeviceid = request.args.get('deviceid', "") # like xxxx
ctx = get_context() if rstart =="" and rend == "":
endtts = int(time.time()*)
today = datetime.datetime.now()
delta = datetime.timedelta(days=)
start = today - delta
dt = start.strftime("%Y-%m-%d-%H:%M:%S")
timeArray = time.strptime(dt, "%Y-%m-%d-%H:%M:%S")
startts = int(time.mktime(timeArray)) *
else:
try:
startts = int(time.mktime(time.strptime(rstart, '%Y-%m-%d-%H:%M:%S'))*)
endtts = int(time.mktime(time.strptime(rend, '%Y-%m-%d-%H:%M:%S'))*)
# end1 = time.strptime(rend, '%Y-%m-%d-%H:%M:%S')
# end2 = datetime.datetime(end1.tm_year, end1.tm_mon, end1.tm_mday)
# delta1 = datetime.timedelta(days=)
# end3 = end2 + delta1
# endtts = int(time.mktime(end3.timetuple())*) except:
print("parameter is wrong!!!") collection = mongo.db['trace_log']
print(endtts, startts, page, size )
if rdeviceid == "":
results = collection.find({'sr': {'$gte': startts, '$lt': endtts}})\
.sort('sr', DESCENDING)\
.skip((int(page) - )*int(size))\
.limit(int(size))
ctx['count'] = collection.find({'sr': {'$gte': startts, '$lt': endtts}}).count() else:
results = collection.find({"$and":[{'sr': {'$gte': startts, '$lt': endtts}}, {"debug_log":{'$elemMatch':{"device_id": rdeviceid}}}]})\
.sort('sr', DESCENDING) \
.skip((int(page) - ) * int(size)) \
.limit(int(size))
ctx['count'] = collection.find({"$and":[{'sr': {'$gte': startts, '$lt': endtts}}, {"debug_log":{'$elemMatch':{"device_id": rdeviceid}}}]}).count() for res in results:
d = {}
annotation = res.get("annotation")
for anno in annotation:
if anno.get("name") == "asr":
debug_log = anno.get("debug_log")
asr = debug_log[].get("asr")
debug_log = res.get("debug_log")
debug_log0 = debug_log[]
session_id = debug_log0.get("session_id")
codec = debug_log0.get("codec")
if not session_id:
session_id = "" #超级无敌重要
wavfile = session_id + ".wav"
codecfile = session_id + "." + codec asrtimestr = session_id.split("-")[-]
st = time.localtime(float(asrtimestr))
asrtime = time.strftime("%Y-%m-%d %H:%M:%S", st)
asrthedate = time.strftime("%Y%m%d", st)
asrdeviceid = debug_log0.get("device_id")
asrdevicetype = debug_log0.get("device_type")
asrdevicekey = debug_log0.get("device_key") # print(asrtime,asrdeviceid,asrdevicekey,asrdevicetype,asr,file) d['asrtime'] = asrtime
d['asrthedate'] = asrthedate
d['asrdeviceid'] = asrdeviceid
d['asrdevicekey'] = asrdevicekey
d['asrdevicetype'] = asrdevicetype
d['asr'] = asr
d['wavfile'] = wavfile
d['codecfile'] = codecfile
d['codec'] = codec ctx['data'].append(d)
ctx['data'] = sorted(ctx['data'], key=lambda k: k['asrtime'], reverse=True) resp = jsonify(ctx)
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Access-Control-Allow-Methods'] = 'POST'
resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
return resp
if __name__ == '__main__':
app.run("0.0.0.0",port=)

Django框架views.py解决跨域问题示例:

from django.http import JsonResponse
from django.db import connection
import datetime
import time
import json def get_context():
return {
'errcode': 0,
'errmsg': '',
'data': []
} def ctxWraped(ctx):
response = JsonResponse(ctx)
response["Access-Control-Allow-Headers"] = "content-type"
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
response["Access-Control-Max-Age"] = "1000"

return response # 获取每天语音交互数
def speechtrend(request): startdate = request.GET.get("startdate", "")
enddate = request.GET.get("enddate", "") if startdate == "" or enddate == "":
today = datetime.datetime.now()
delta = datetime.timedelta(days=30)
start = today - delta
startdate = start.strftime("%Y%m%d")
enddate = today.strftime("%Y%m%d") cursor = connection.cursor()
sql = "select thedate, sum(count) as count from dwb_speech_domain_d where thedate >= '"+startdate+"' and thedate < '"+enddate+"' group by thedate"
cursor.execute(sql) result = cursor.fetchall()
ctx = get_context()
ctx["namelist"] = []
ctx["namevalue"] = []
for rec in result:
record = {}
record["name"] = rec[0]
record["value"] = int(rec[1])
ctx["namelist"].append(rec[0])
ctx['data'].append(record)
ctx["namevalue"].append(int(rec[1]))
connection.close() return ctxWraped(ctx)

网站端JavaScript代码

ajax代码:

      let url = 'http://localhost:8000/product/speechdistinctsn/', self = this;
$.ajax({
type: 'GET',
async: true,
url: url,
dataType: 'json',
success: function (result) {
self.speechdistinctsnname = result.namelist;
self.speechdistinctsndata = result.namevalue;
self.drawSpeechDistinctSn('speechdistinctsn'); #echarts 渲染
},
error: function (errorMsg) {
console.log(errorMsg)
}
})

fetch代码:

        let url = 'http://localhost:8000/product/speechdomain/', self = this;
fetch(url, {
method: 'GET',
dataType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then(function(response) {
response.json().then(function (result) {
self.opinion = result.namelist;
self.opinionData = result.data;
self.drawGraph('main')
})
})

以上,网站+后端配合完美解决跨域问题。

参考文章

Django通过设置settings解决跨域问题:http://www.jianshu.com/p/1fd744512d83 PS:我自己试了N次发现不管用,不知道是姿势不对还是怎么着,

如有错误,还请各位大虾指教。