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/ ...
随机推荐
- 数论Keynote
[同余] 1.整数a,b对模m同余的充分与必要条件是m|(a-b),即a=b+mt,t是整数. 2.性质丁.若a1=b1(mod m),a2=b2(mod m),则(a1+a2)=(b1+b2)(mo ...
- Codeforces 919F——A Game With Numbers
转自大佬博客:https://www.cnblogs.com/NaVi-Awson/p/8405966.html; 题意 两个人 Van♂ 游戏,每人手上各有 8'>88 张牌,牌上数字均为 [ ...
- 674. Longest Continuous Increasing Subsequence最长连续递增子数组
[抄题]: Given an unsorted array of integers, find the length of longest continuous increasing subseque ...
- OpenNebula 深入分析
-------------------OpenNebula 深入分析------------------- #容量清单 属性 描述 NAME 如果名字是空的,那么默认名字是:one-<VID&g ...
- 4.SELECT DISTINCT 语句
在表中,可能会包含重复值.这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值. 关键词 DISTINCT 用于返回唯一不同的值. 语法: SELECT DISTINCT 列名称 F ...
- xgboost 完全调参指南
http://www.2cto.com/kf/201607/528771.html xgboost: https://www.analyticsvidhya.com/blog/2016/03/comp ...
- SQLAlchemy 进阶
SQLAlchemy使用 1.执行原生SQL语句 from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engin ...
- Entity Framework 6.0 Tutorials(10):Index Attribute
Index Attribute: Entity Framework 6 provides Index attribute to create Index on a particular column ...
- 【原创测试】MongoDB千万级插入数据测试(MMO在线游戏应用场合)
一.筹备 我们要做一次千万级的MONGODB测试,操作系统选用CentOS 5.5 64位版,基本模拟实际的使用环境,采用单机集群模型(测试单机多CPU情况下的实际效果). 测试基准数据: 服务器配置 ...
- ASP.NET Web Pages (Razor) FAQ
ASP.NET Web Pages (Razor) FAQ By Tom FitzMacken|February 7, 2014 Print This article lists some fre ...