flask-restful基础
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')
示例
flask-restful基础的更多相关文章
- Python Flask Restful
Flask Restful 1.flask restful 在flask基础上进行一些封装,主要用于实现restful接口 2.restful的理解 1)URI(统一资源标识符):每一个URI代表一 ...
- SpringCloud系列二:Restful 基础架构(搭建项目环境、创建 Dept 微服务、客户端调用微服务)
1.概念:Restful 基础架构 2.具体内容 对于 Rest 基础架构实现处理是 SpringCloud 核心所在,其基本操作形式在 SpringBoot 之中已经有了明确的讲解,那么本次为 了清 ...
- 使用swagger 生成 Flask RESTful API
使用swagger 生成 Flask RESTful API http://www.voidcn.com/article/p-rcvzjvpf-e.html swagger官网 https://swa ...
- 知了课堂 Python Flask零基础 笔记整理
目录 起步 安装Python2.7: Python虚拟环境介绍与安装: pip安装flask: 认识url: URL详解 web服务器和应用服务器以及web应用框架: Flask 第一个flask程序 ...
- Flask restful源码分析
Flask restful的代码量不大,功能比较简单 参见 http://note.youdao.com/noteshare?id=4ef343068763a56a10a2ada59a019484
- 如何用rflask快速初始化Flask Restful项目
如何用rflask快速初始化Flask Restful项目 说明 多啰嗦两句 我们在创建flask项目的时候,使用pycharm创建出来的项目比较简陋,而且随着项目的功能完善,项目目录结构会比较多,多 ...
- [flask]Restful接口测试简单的应用
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : shenqiang from flask import Flask,make_res ...
- 超实用的Flask入门基础教程,新手必备!
Flask入门基础教程 Flask简介 Flask是一个轻量级的可定制框架,使用Python语言编写,较其他同类型框架更为灵活.轻便.安全且容易上手.它可以很好地结合MVC模式进行开发,开发人员分工合 ...
- 快速创建Flask Restful API项目
前言 Python必学的两大web框架之一Flask,俗称微框架.它只需要一个文件,几行代码就可以完成一个简单的http请求服务. 但是我们需要用flask来提供中型甚至大型web restful a ...
- python Flask restful框架
框架地址:https://github.com/flask-restful/flask-restful 文档:http://flask-restful.readthedocs.io/en/0.3.5/ ...
随机推荐
- php 数据导出csv 注意问题。
总共10W数据每次下载到9.5W就停了. 加上这个就好了 ini_set('memory_limit','512M'): //脚本运行无时间限制. set_time_limit(0); 要设置一个se ...
- openebula vm无法获取IP问题解决
http://archives.opennebula.org/documentation:archives:rel2.2:cong Contextualizing Virtual Machines 2 ...
- 19. AUTO INCREMENT 字段
Auto-increment 会在新记录插入表中时生成一个唯一的数字. AUTO INCREMENT 字段 我们通常希望在每次插入新记录时,自动地创建主键字段的值. 我们可以在表中创建一个 auto- ...
- JavaEE互联网轻量级框架整合开发(书籍)阅读笔记(3):常用动态代理之JDK动态代理、CGLIB动态代理
一.动态代理的理解 动态代理的意义在于生成一个占位(又称代理对象),来代理真实对象,从而控制真实对象的访问. 先来谈谈什么是代理模式. 假设这样一个场景:你的公司是一家软件 ...
- Tomcat调优总结
Tomcat 优化分为系统优化,Java虚拟机调优,Tomcat本身的优化. Tomcat 如何起停 ./catalina.sh stop ./catalina.sh start/sbin/servi ...
- string Format转义大括号
String.Format("{0} world!","hello") //将输出 hello world!,没有问题,但是只要在第一个参数的任意位置加上一个大 ...
- 小议C#接口的隐式与显示实现(续)
上文连接,讲的比较模糊,而且调用起来感觉比较混乱 http://www.cnblogs.com/walleyekneel/p/3581489.html 这次改为显式接口调用,可能项目也有这个一个需求 ...
- 小度wifi在window server2008R2系统下创建不了
小度wifi在window server2008R2系统下创建的时候会一直显示正在创建,然后又消失的情况.这是因为win server 2008下默认的无线lan服务没开启 解决方法: 在“服务管理器 ...
- angular 路由传参
第一种:<a [routerLink]="['/product']" [queryParams]="{id: 1}">商品详情</a> ...
- jquery.validate弹窗验证
$(document).ready(function () { //开始验证 $("#form1").validate({ submitHan ...