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

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

# -*- coding: utf-8 -*-
# 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': 0,
        "data": [],
        "count": 0
    }


@app.route('/', methods=["GET"])
def index():
    return render_template("op.html")


# /mongo?num=10&page=10&size=10
@app.route('/mongo', methods=['GET','OPTIONS'])
def getmongodata():

    # num = request.args.get('num', "30")
    page = request.args.get('page', "1")
    size = request.args.get('size', "30")
    rstart = request.args.get('startdate', "0") # like 2017-08-27-00:00:00
    rend = request.args.get('enddate', "0") # like 2017-08-29-00:00:00
    rdeviceid = request.args.get('deviceid', "") # like xxxx
    ctx = get_context()

    if rstart =="0" and rend == "0":
        endtts = int(time.time()*1000000)
        today = datetime.datetime.now()
        delta = datetime.timedelta(days=7)
        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)) * 1000000
    else:
        try:
            startts = int(time.mktime(time.strptime(rstart, '%Y-%m-%d-%H:%M:%S'))*1000000)
            endtts = int(time.mktime(time.strptime(rend, '%Y-%m-%d-%H:%M:%S'))*1000000)
            # 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=1)
            # end3 = end2 + delta1
            # endtts = int(time.mktime(end3.timetuple())*1000000)

        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) - 1)*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) - 1) * 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[0].get("asr")
        debug_log = res.get("debug_log")
        debug_log0 = debug_log[0]
        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("-")[-1]
        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=5000)

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", "0")
    enddate = request.GET.get("enddate", "0")

    if startdate == "0" or enddate == "0":
        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次发现不管用,不知道是姿势不对还是怎么着,

 

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

 

posted @ 2017-09-19 15:55  宝山方圆  阅读(1642)  评论(0编辑  收藏  举报