Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 783|回复: 0

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

[复制链接]
  • TA的每日心情
    奋斗
    2024-11-24 15:47
  • 签到天数: 804 天

    [LV.10]以坛为家III

    2053

    主题

    2111

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    726782
    发表于 2021-8-28 13:34:40 | 显示全部楼层 |阅读模式

    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次发现不管用,不知道是姿势不对还是怎么着,

     

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

     

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-12-22 02:04 , Processed in 0.055901 second(s), 27 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表