flask-restful基本使用

基本使用

from flask_restful import Api,Resource,reqparse,inputs
from flask import Flask,render_template, url_for # 注册
app = Flask(__name__)
api = Api(app) # 类继承自Resource
class LoginView(Resource):
def post(self):
return {"username":"zhiliao"} # 这里可字典 api.add_resource(LoginView,'/login/',"/register/") # 可以写多个路由
url_for("loginview") # 注意默认情况下会把类名转换为小写

参数验证

add_argument可以指定这个字段的名字,这个字段的数据类型等。具体参数如下:

1. default:默认值,如果这个参数没有值,那么将使用这个参数指定的值。
2. required:是否必须。默认为False,如果设置为True,那么这个参数就必须提交上来。
3. type:这个参数的数据类型,如果指定,那么将使用指定的数据类型来强制转换提交上来的值。
4. choices:选项。提交上来的值只有满足这个选项中的值才符合验证通过,否则验证不通过。
5. help:错误信息。如果验证失败后,将会使用这个参数指定的值作为错误信息。
6. trim:是否要去掉前后的空格。

其中的type,可以使用python自带的数据类型(但参数必须有一个,例如str等),同时flask_restful.inputs提供了一些特定的数据类型来强制转换。比如一些常用的:
1. url:会判断这个参数的值是否是一个url,如果不是,那么就会抛出异常。
2. regex:正则表达式。
3. date:将这个字符串转换为datetime.date数据类型。如果转换不成功,则会抛出一个异常。

class LoginView(Resource):
def post(self):
from datetime import date
parser = reqparse.RequestParser()
parser.add_argument('birthday',type=inputs.date,help='生日字段验证错误!') # 验证是否是日期
parser.add_argument('telphone',type=inputs.regex(r'1[3578]\d{9}'))
# 正则验证
parser.add_argument('home_page',type=inputs.url,help='个人中心链接验证错误!')
# url验证
parser.add_argument('username',type=str,help='用户名验证错误!',required=True)
# parser.add_argument('age',type=int,help='年龄验证错误!')
# 验证是否是数字
parser.add_argument('gender',type=str,choices=['male','female','secret']) # 验证是否在选项中
args = parser.parse_args() # 进行验证并返回结果
print(args)
return ...

Serialization

通过使用序列化可以将表信息直接转化为json字符串

from flask_restful import marshal_with, Resource, fields

class ProfileView(Resource):
resource_fields = {
'username': fields.String,
'age': fields.Integer,
'school': fields.String
} @marshal_with(resource_fields)
def get(self,user_id):
user = User.query.get(user_id)
return user

序列化属性

resource_fields = {
'education': fields.String(attribute='school')
} # 表字段为school 但想输出的key 为education

attribute:表字段重命名

resource_fields = {
'age': fields.Integer(default=18)
}

default: 默认值

class ArticleView(Resource):
resource_fields = {
'aritlce_title':fields.String(attribute='title'),
'content':fields.String,
'author': fields.Nested({ # 多对一
'username': fields.String,
'email': fields.String
}),
'tags': fields.List(fields.Nested({ # 多对多
'id': fields.Integer,
'name': fields.String
})),
'read_count': fields.Integer(default=80)
} @marshal_with(resource_fields)
def get(self,article_id):
article = Article.query.get(article_id)
return article

多对一&多对多结构

其他

配合蓝图使用

在蓝图中,如果使用`flask-restful`,那么在创建`Api`对象的时候(api = Api(app)),传入蓝图对象。

渲染模板

返回response对象

如果继承了Resource但是又想返回response对象通过@api.representation('text/html')

from flask import Blueprint,render_template,make_response
@api.representation('text/html')
def output_html(data,code,headers):
# 函数名不需要关联,如果发现继承Resource的视图返回的是response对象会自动找到这里
print(data) # 这个data为render_template传入的index.html
# 在representation装饰的函数中,必须返回一个Response对象
resp = make_response(data)
return resp class ListView(Resource):
def get(self):
return render_template('index.html')
api.add_resource(ListView,'/list/',endpoint='list')

示例

最新文章

  1. [LeetCode] Remove Linked List Elements 移除链表元素
  2. spring mvc中使用freemark的一点心得
  3. GitHub初体验(小菜新手github用起来)
  4. NOI OpenJudge 8469 特殊密码锁 Label贪心
  5. POJ-1655 Balancing Act
  6. 配置centos 7 mysql
  7. centos下部署redis服务环境的操作记录
  8. vector 对象中存放指针类型数据
  9. PHP实现跨域解决方法
  10. 跨平台原生AR/VR应用研发引擎-NVisionXR开放内测
  11. Android学习笔记之AppWidget
  12. SQL Server 2008R2 :远程调用失败 的解决方法(全部方法)
  13. SpringBoot项目@RestController使用 redirect 重定向无效
  14. ht学习流程
  15. JS截取字符串多余的为...
  16. jar包的读取
  17. linux环境下mysql默认是区分表名大小写的
  18. apache ant 修改java版本 方法之一
  19. JSP 九大隐式对象
  20. GO 功能注释

热门文章

  1. SpringMVC总结一:快速入门
  2. laravel 验证表单信息
  3. jquery触发两次onchange事件
  4. 如何给网页标题栏上添加图标(favicon.ico)(转)
  5. 581. Shortest Unsorted Continuous Subarray连续数组中的递增异常情况
  6. Apache ab命令
  7. 使用mail架包发送邮件javax.mail.AuthenticationFailedException: failed to connect at javax.mail.Service.connec
  8. 13.JOIN
  9. 9.TOP 子句--mysql limit
  10. The user specified as a definer (”@sa’%') does not exist 解决方法