1. 程式人生 > 實用技巧 >Flask實現RESTful API

Flask實現RESTful API

準備工作

首先安裝flask_restful三方元件

pip install flask_restful

  在models.py中新建一個類,生成表,往裡面插入一些資料。(flask要想使用ORM的話需要安裝flask_sqlalchemy三方元件,之前已經說過了,此處不再贅述)

  然後寫了一個urls檔案,例項化我們的api,把api物件和app繫結,然後__init__.py加入繫結的函式

具體實現

api_urls.py

from flask_restful import Api
from myapp.api import *

api = Api()

def init_api(app):
    api.init_app(app)

api.add_resource(One,'/one')
api.add_resource(Two,'/two')
api.add_resource(Three,'/three/<int:id>')
api.add_resource(Four,'/four/<int:page>/<int:per_page>')
api.add_resource(Five,'/five')
api.add_resource(Six,'/six')
api.add_resource(Seven,'/seven')

__init__.py

from flask import Flask
from myapp.api_urls import init_api
from myapp.ext import init_ext
from myapp.settings import conf


def create_app(env_name):
    app = Flask(__name__)

    app.config.from_object(conf.get(env_name,'debug'))

    init_ext(app)

    init_api(app)
    return app

輸出欄位與引數解析的不同實現

from flask import request
from flask_restful import Resource, marshal_with, fields, reqparse
from myapp.models import *

#輸出欄位
#字典套字串 one_fields = { 'id':fields.Integer(default=1), #default設定為預設值 'user':fields.String(attribute='name'),       #attribute設定為對映到models中的name欄位 'content':fields.String, 'hahaha':fields.String(default='lalala') } class One(Resource): @marshal_with(one_fields) def get(self,*args,**kwargs): id = int(request.args.get('id')) data = News.query.get(id) return data
#字典套列表 two_fields = { 'id':fields.Integer(default=1), 'name':fields.String(default='wusir'), 'hobby':fields.List(fields.String) } class Two(Resource): @marshal_with(two_fields) def get(self): hobby = ['閱讀','運動','敲程式碼'] return {'hobby':hobby} #字典套字典 three_fields = { 'id': fields.Integer(default=1), 'name': fields.String(default='alex'), 'content':fields.Nested(one_fields) } class Three(Resource): @marshal_with(three_fields) def get(self,id): news = News.query.get(id) return {'content':news}
#字典套列表,列表再套字典 four_fields = { 'id':fields.Integer(default=1), 'name':fields.String(default='wusir'), 'content':fields.List(fields.Nested(one_fields)) } class Four(Resource): @marshal_with(four_fields) def get(self,page,per_page): news = News.query.paginate(page,per_page,error_out=False) #分頁實現 return {'content':news.items}

#引數解析 five_args = reqparse.RequestParser() five_args.add_argument('id',type=int,required=True,help='id是必填欄位,趕緊的填上') #required為True表示是必填欄位,help為錯誤提示資訊 five_args.add_argument('name',dest='my_name') #dest表示起別名 five_args.add_argument('hobby',action='append') #action='append'表示欄位可以追加寫多個 class Five(Resource): def get(self): my_args = five_args.parse_args() print(my_args) print(my_args.get('hobby')) return {'msg':'ok'}
six_args = reqparse.RequestParser() six_args.add_argument('content',location='form') class Six(Resource): def get(self): my_args = six_args.parse_args() print(my_args) return {'msg':'get'} def post(self): my_args = six_args.parse_args() print(my_args) return {'msg':'post'}
seven_args = five_args.copy() seven_args.replace_argument('id',type=int,help='隨便你填不填',required=True) seven_args.remove_argument('name') seven_args.remove_argument('hobby') class Seven(Resource): def get(self): my_args = seven_args.parse_args() print(my_args) return {'msg':'好了'}

引數解析的位置:

# 從post請求的form裡拿引數
parser.add_argument('name', type=int, location='form')

# 從get請求的args裡拿引數
parser.add_argument('PageSize', type=int, location='args')

# 從請求頭拿引數 headers
parser.add_argument('User-Agent', location='headers')

# 從cookies拿引數
parser.add_argument('session_id', location='cookies')

# 獲取檔案
parser.add_argument('picture', type=werkzeug.datastructures.FileStorage, location='files')

PS:當指定多個解析位置,location 指定為一個列表

文件參考:https://flask-restful.readthedocs.io/en/latest/