python flask高级编程之restful_Flask实现RESTful API(示例代码)

本文档详细介绍了如何使用Python的Flask-RESTful库创建RESTful API,包括安装、实例化API、定义资源、使用字段和参数解析等。通过示例代码展示了如何处理GET和POST请求,以及不同类型的参数解析方法。
摘要由CSDN通过智能技术生成

准备工作

首先安装flask_restful三方组件

pip install flask_restful

在models.py中新建一个类,生成表,往里面插入一些数据。(flask要想使用ORM的话需要安装flask_sqlalchemy三方组件,之前已经说过了,此处不再赘述)

然后写了一个urls文件,实例化我们的api,把api对象和app绑定,然后在__init__.py加入绑定的函数

具体实现

api_urls.py

fz.gif

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/‘)

api.add_resource(Four,‘/four//‘)

api.add_resource(Five,‘/five‘)

api.add_resource(Six,‘/six‘)

api.add_resource(Seven,‘/seven‘)

fz.gif

__init__.py

fz.gif

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

fz.gif

输出字段与参数解析的不同实现

fz.gif

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‘:‘好了‘}

fz.gif

参数解析的位置:

fz.gif

# 从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‘)

fz.gif

PS:当指定多个解析位置,location 指定为一个列表

文档参考:https://flask-restful.readthedocs.io/en/latest/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值