flask跨域请求

 1 需要flask将数据发送到web前端,定义一个路由,访问该路由获取数据。
 2 res= make_response(json.dumps(result)):
 3 通过make_response封装数据及类型转换,返回res即可。
 4 一般纯的api接口需要考虑跨域访问问题,下面是简单的跨域访问装饰器在flask中的实现。
 5 
 6 from functools import wraps
 7 from flask import make_response
 8 一:
 9 @app.route('/result', methods=['GET', 'POST'])
10 def index():
11     file_object = open('/home/pyspark_project/pyspark_output_result.json')
12     try:
13         result_text = file_object.read()
14     finally:
15         file_object.close()
16     #
17     rst = make_response(result_text)
18     rst.headers['Access-Control-Allow-Origin'] = '*'
19     # rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
20     # allow_headers = "Referer,Accept,Origin,User-Agent"
21     # rst.headers['Access-Control-Allow-Headers'] = allow_headers
22     return rst, 201
23     #return result_text, 201 #, {'Content-Type': 'application/json'}
24 
25 二:
26 @app.route('/articles_list/contents/')
27 def json_contents():
28     response = make_response(jsonify(response=get_articles(ARTICLES_NAME)))
29     response.headers['Access-Control-Allow-Origin'] = '*'
30     response.headers['Access-Control-Allow-Methods'] = 'POST'
31     response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type' 
32     return response
33 
34 
35 启动本地Flask Sever,准备响应 ajax

 

posted @ 2017-07-09 21:15  失落的黎明  阅读(6466)  评论(0编辑  收藏  举报