Python之Flask和Django框架解决跨域问题,配合附加ajax和fetch等js代码
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次发现不管用,不知道是姿势不对还是怎么着,
如有错误,还请各位大虾指教。
Python之Flask和Django框架解决跨域问题,配合附加ajax和fetch等js代码的更多相关文章
- Django框架 之 跨域请求伪造
Django框架 之 跨域请求伪造 浏览目录 同源策略与Jsonp 同源策略 Jsonp jQuery对JSONP的实现 CORS 简介 两种请求 同源策略与Jsonp 同源策略 同源策略(Same ...
- 在django中解决跨域AJAX
由于浏览器存在同源策略机制,同源策略阻止从一个源加载的文档或脚本获取另一个源加载的文档的属性. 特别的:由于同源策略是浏览器的限制,所以请求的发送和响应是可以进行,只不过浏览器不接收罢了. 浏览器同源 ...
- django中解决跨域问题
-跨域问题 -浏览器的:同源策略,浏览器拒绝不是当前域域返回的数据 -ip地址和端口号都相同才是同一个域 -如何解决: -CORS:跨域资源共享 -简单请求:发一次请求 -非简单请求:非简单请求是发送 ...
- python bottle框架 解决跨域问题的正确方式
经查询,网上有几种说法 https://www.cnblogs.com/EmptyFS/p/6138923.html 我首先查到的就是这个,我采用了文中所说的修改源码的方式, 但是经测试发现,修改源码 ...
- Django项目解决跨域问题
在配置文件INSTALLED_APPS中添加: 'corsheaders', 在MIDDLEWARE中添加: 'corsheaders.middleware.CorsMiddleware', 最后添加 ...
- jeecg框架解决跨域问题
controller层方法体中添加如下代码 response.setHeader("Access-Control-Allow-Origin", "*");res ...
- Django后端彻底解决跨域问题
最近在接一个前后端分离的项目,后端使用的django-restframework,前端使用的Vue.后端跑起来后,发现前端在访问后端API时出了了跨域的问题. 类似如下报错: 关于跨域问题,之前这篇文 ...
- 如何用Nginx解决跨域问题
一. 产生跨域的原因 1.浏览器限制 2.跨域 3.XHR(XMLHttpRequest)请求 二. 解决思路 解决跨域有多重,在这里主要讲用nginx解决跨域 1.JSONP 2.nginx代理 3 ...
- django框架进阶-解决跨域问题
####################################### """ 一.为什么会有跨域问题? 是因为浏览器的同源策略是对ajax请求进行阻拦了,但是不 ...
随机推荐
- 快排法求第k大
快排法求第k大,复杂度为O(n) import com.sun.media.sound.SoftTuning; import java.util.Arrays; import java.util.Ra ...
- Java实现List数组的几种替代方案
在Java中,禁止定义List<Integer>a[],这种List数组结构. 但是还是可以使用其它一些方式来实现列表数组. 一.使用Node把List包裹起来 public class ...
- lu协程练习
生产者和消费者问题:当协程调用yield时,从一个悬而未决的resume中返回.简单的协程练习: function receive() local status,value = coroutine.r ...
- Redis踩过的坑
现象:在使用redis云提供的redis服务后,经常出现connect timeout: redis.clients.jedis.exceptions.JedisConnectionException ...
- thinkphp日志分析
#!/usr/bin/perl -w use strict; use warnings; use Tie::File; #### # Thinkphp日志分析 # 日志基本格式:{$now} &quo ...
- 关于varchar(max), nvarchar(max)和varbinary(max)
在MS SQL2005及以上的版本中,加入大值数据类型(varchar(max).nvarchar(max).varbinary(max) ).大值数据类型最多可以存储2^30-1个字节的数据.这几个 ...
- 如何调试makefile变量
六.七年前写过一篇<跟我一起写Makefile>,直到今天,还有一些朋友问我一些Makefile的问题,老实说,我有一段时间没有用Makefile了,生疏了.回顾,这几年来大家问题我的问题 ...
- Android下的联网下载的操作
一:从网络下载图片 MainActivity: NetService 1.由路径获取Url 2.使用url打开HttpURLConnection连接 3.根据路径查找本地sd卡是否有缓存文件,如果文件 ...
- 《KAFKA官方文档》入门指南(转)
1.入门指南 1.1简介 Apache的Kafka™是一个分布式流平台(a distributed streaming platform).这到底意味着什么? 我们认为,一个流处理平台应该具有三个关键 ...
- supervisor 完整安装步骤
Supervisorhttp://www.jianshu.com/p/bf2b3f4dec73http://www.jianshu.com/p/9abffc905645http://blog.csdn ...