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代码的更多相关文章

  1. Django框架 之 跨域请求伪造

    Django框架 之 跨域请求伪造 浏览目录 同源策略与Jsonp 同源策略 Jsonp jQuery对JSONP的实现 CORS 简介 两种请求 同源策略与Jsonp 同源策略 同源策略(Same ...

  2. 在django中解决跨域AJAX

    由于浏览器存在同源策略机制,同源策略阻止从一个源加载的文档或脚本获取另一个源加载的文档的属性. 特别的:由于同源策略是浏览器的限制,所以请求的发送和响应是可以进行,只不过浏览器不接收罢了. 浏览器同源 ...

  3. django中解决跨域问题

    -跨域问题 -浏览器的:同源策略,浏览器拒绝不是当前域域返回的数据 -ip地址和端口号都相同才是同一个域 -如何解决: -CORS:跨域资源共享 -简单请求:发一次请求 -非简单请求:非简单请求是发送 ...

  4. python bottle框架 解决跨域问题的正确方式

    经查询,网上有几种说法 https://www.cnblogs.com/EmptyFS/p/6138923.html 我首先查到的就是这个,我采用了文中所说的修改源码的方式, 但是经测试发现,修改源码 ...

  5. Django项目解决跨域问题

    在配置文件INSTALLED_APPS中添加: 'corsheaders', 在MIDDLEWARE中添加: 'corsheaders.middleware.CorsMiddleware', 最后添加 ...

  6. jeecg框架解决跨域问题

    controller层方法体中添加如下代码 response.setHeader("Access-Control-Allow-Origin", "*");res ...

  7. Django后端彻底解决跨域问题

    最近在接一个前后端分离的项目,后端使用的django-restframework,前端使用的Vue.后端跑起来后,发现前端在访问后端API时出了了跨域的问题. 类似如下报错: 关于跨域问题,之前这篇文 ...

  8. 如何用Nginx解决跨域问题

    一. 产生跨域的原因 1.浏览器限制 2.跨域 3.XHR(XMLHttpRequest)请求 二. 解决思路 解决跨域有多重,在这里主要讲用nginx解决跨域 1.JSONP 2.nginx代理 3 ...

  9. django框架进阶-解决跨域问题

    ####################################### """ 一.为什么会有跨域问题? 是因为浏览器的同源策略是对ajax请求进行阻拦了,但是不 ...

随机推荐

  1. GO语言中的几个关键思想

    GO语言的设计理念与C++,Java,Python之流大相径庭. 一.没有函数重载 GO语言里面没有函数重载,Java.C#.C++三位大牛都是支持函数重载的,Python虽然不支持函数重载,但是支持 ...

  2. 【总结 】550,535,553 Mail from must equal authorized user— jenkins(hudson) email163邮箱和26邮箱成功配置总结

    Failed to send out e-mail com.sun.mail.smtp.SMTPSendFailedException: 553 Mail from must equal author ...

  3. 开发 Swift 和 Objective-C 混编的 Framework

    来源:黄文臣 blog.csdn.net/hello_hwc/article/details/58320433 前言 为什么要写这样一篇文章,因为昨天和一个朋友讨论到Swift和Objective C ...

  4. cobbler启动问题

    [root@localhost ~]# cobblerTraceback (most recent call last): File "/usr/bin/cobbler", lin ...

  5. webpack window 使用sass来编译css样式

    1.执行安装: npm install sass-loader --save-dev (此处不行的话就换上npm install node-sass) 2.稍微修改一下config,删掉我们先前添加的 ...

  6. 记录EntityValidationErrors的详细信息

    0.一个问题 使用过EF的人相信都会遇到Validation failed for one or more entities. See ‘EntityValidationErrors’这种异常,这是由 ...

  7. 【Servlet】Java Serlvet Filter 过滤器

    Filter的设计思想Filter是一种AOP(aspect-oriented programming)的设计思想 : 面向切面编程.用于的请求和响应都会走 使用filter的登录案例我们通过一张图片 ...

  8. HTML页面中显示HTML标签<xmp>

    最近做东西遇到一个HTML页面中显示HTML标签的需求,比如要显示</span> 解决方法如下 HTML页面中显示HTML标签代码,可以使用<xmp>html标签内容</ ...

  9. solrj索引操作

    添加索引 Solr添加文档至索引: http://www.cnblogs.com/dennisit/p/3621717.html 删除索引: 每天索引记录有一个唯一标识,索引的删除通过唯一标识操作,如 ...

  10. 实现一个简单的android开关

    近期在学习android中的graphics中绘图系列.依照大神思路.找葫芦画瓢实现了一个开关.如图下: 记录一下实现方式: 1.画背景 上图形状.分成两个半圆与一个矩形,那么代码能够写成: priv ...