Flask-restful在flask下的使用

Flask-restful在flask下的使用

安装

  1. 通过pip安装
1
pip install flask-restful
  1. 通过源码安装
1
2
3
git clone https://github.com/javyxu/flask-restful.git
cd flask-restful
python setup.py develop

简单的使用

  1. 一个简单的使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
def get(self):
return {'Hello, World!'}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
app.run(debug=True)

应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# -*- coding: utf-8 -*-
# pylint: disable=C,R,W

from flask import Flask, jsonify, Response, request
from flask_restful import reqparse, Resource, Api
from flask_cors import CORS

import logging
import simplejson as json

# 实现跨域操作
CORS(app, supports_credentials=True)
CORS(app, resources=r'/api')
api = Api(app)

# 获取参数
parser = reqparse.RequestParser()

def json_result(code=0, data=None, msg='success'):
# res = Response(json_msg, status=status, mimetype='application/json')
return jsonify({"code":code, "data": data, "msg":msg})

## 实现Get
class TestGet(Resource):
parser.add_argument('name', type=str)
parser.add_argument('age', type=int)
def get(self):
try:
args = parser.parse_args()
name = args['name']
age = args['age']
except Exception as e:
logging.exception(e)
# return json_error_response(e)
return json_result(code=500, msg=str(e))
return json_result(data={"get_reslut": json.dumps({'name': name, 'age' : age})})

api.add_resource(TestGet, '/api/v1/testget')


## 实现Post和options
class TestPost(Resource):
## 实现跨域必须执行options
def options(self):
return json_result()

def post(self):
try:
# 如果参数较长,或者较多时,从json直接传入
dict_rep = dict(request.json)
except Exception as e:
logging.exception(e)
# json_error_response(e)
return json_result(code=500, msg=str(e))
return json_result(data={"post_reslut": json.dumps(dict_rep)})

api.add_resource(TestPost, '/api/v1/testpost')

## 实现delete
class TestDelete(Resource):
parser.add_argument('id')
def delete(self):
try:
args = parser.parse_args()
id = args['id']
except Exception as e:
logging.exception(e)
# return json_error_response(e)
return json_result(code=500, msg=str(e))
return json_result(data={"delete_reslut": json.dumps({'id' : id})})

api.add_resource(TestDelete, '/api/v1/testsdelete')