Skip to content

Commit 5794b6a

Browse files
committed
add flask-cors
1 parent da789ed commit 5794b6a

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

Flask-17-cors/manage.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from flask import Flask, jsonify
2+
from flask_restful import Api, Resource, reqparse
3+
from flask_cors import CORS
4+
5+
USERS = [
6+
{"name": "zhangsan"},
7+
{"name": "lisi"},
8+
{"name": "wangwu"},
9+
{"name": "zhaoliu"}
10+
]
11+
12+
class Users(Resource):
13+
def get(self):
14+
return jsonify(USERS)
15+
16+
def post(self):
17+
args = reqparse.RequestParser() \
18+
.add_argument('name', type=str, location='json', required=True, help="名字不能为空") \
19+
.parse_args()
20+
21+
self.logger.debug(args)
22+
23+
if args['name'] not in USERS:
24+
USERS.append({"name": args['name']})
25+
26+
return jsonify(USERS)
27+
28+
29+
app = Flask(__name__)
30+
CORS(app)
31+
api = Api(app, default_mediatype="application/json")
32+
33+
api.add_resource(Users, '/users')
34+
35+
app.run(host='0.0.0.0', port=5001, use_reloader=True, debug=True)

Flask-17-cors/requirements.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
flask
2+
flask-cors
3+
flask-restful

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@
1515
13. [常用项目结构](https://xugaoxiang.com/2020/08/19/flask-13-project-struture/)
1616
14. [蓝图](https://xugaoxiang.com/2020/08/24/flask-14-blueprint/)
1717
15. [日志](https://xugaoxiang.com/2020/08/25/flask-15-logging/)
18-
16. [RESTful-API](https://xugaoxiang.com/2020/08/26/flask-16-restful-api/)
18+
16. [RESTful-API](https://xugaoxiang.com/2020/08/26/flask-16-restful-api/)
19+
17. [flask-cors](https://xugaoxiang.com/2020/08/26/flask-17-cors/)

0 commit comments

Comments
 (0)