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基础的更多相关文章

  1. Python Flask Restful

    Flask  Restful 1.flask restful 在flask基础上进行一些封装,主要用于实现restful接口 2.restful的理解 1)URI(统一资源标识符):每一个URI代表一 ...

  2. SpringCloud系列二:Restful 基础架构(搭建项目环境、创建 Dept 微服务、客户端调用微服务)

    1.概念:Restful 基础架构 2.具体内容 对于 Rest 基础架构实现处理是 SpringCloud 核心所在,其基本操作形式在 SpringBoot 之中已经有了明确的讲解,那么本次为 了清 ...

  3. 使用swagger 生成 Flask RESTful API

    使用swagger 生成 Flask RESTful API http://www.voidcn.com/article/p-rcvzjvpf-e.html swagger官网 https://swa ...

  4. 知了课堂 Python Flask零基础 笔记整理

    目录 起步 安装Python2.7: Python虚拟环境介绍与安装: pip安装flask: 认识url: URL详解 web服务器和应用服务器以及web应用框架: Flask 第一个flask程序 ...

  5. Flask restful源码分析

    Flask restful的代码量不大,功能比较简单 参见 http://note.youdao.com/noteshare?id=4ef343068763a56a10a2ada59a019484

  6. 如何用rflask快速初始化Flask Restful项目

    如何用rflask快速初始化Flask Restful项目 说明 多啰嗦两句 我们在创建flask项目的时候,使用pycharm创建出来的项目比较简陋,而且随着项目的功能完善,项目目录结构会比较多,多 ...

  7. [flask]Restful接口测试简单的应用

    #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : shenqiang from flask import Flask,make_res ...

  8. 超实用的Flask入门基础教程,新手必备!

    Flask入门基础教程 Flask简介 Flask是一个轻量级的可定制框架,使用Python语言编写,较其他同类型框架更为灵活.轻便.安全且容易上手.它可以很好地结合MVC模式进行开发,开发人员分工合 ...

  9. 快速创建Flask Restful API项目

    前言 Python必学的两大web框架之一Flask,俗称微框架.它只需要一个文件,几行代码就可以完成一个简单的http请求服务. 但是我们需要用flask来提供中型甚至大型web restful a ...

  10. python Flask restful框架

    框架地址:https://github.com/flask-restful/flask-restful 文档:http://flask-restful.readthedocs.io/en/0.3.5/ ...

随机推荐

  1. Spring总结十:事务案例

    数据库表Account: 导包: <dependencies> <!--测试--> <dependency> <groupId>junit</gr ...

  2. solrcloud学习记录

    1.今天看了下solrcloud提供的软提交的作用 硬提交:solr的建索引数据是要在提交时写入磁盘的,这是确保即便是停电也不会丢失数据: 软提交:为了提供更实时的检索能力,Solr设定了一种软提交方 ...

  3. 【bzoj2705】[SDOI2012]Longge的问题

    2705: [SDOI2012]Longge的问题 Time Limit: 3 Sec  Memory Limit: 128 MBSubmit: 2507  Solved: 1531[Submit][ ...

  4. mysql数据库中插入表情4个字节的

    这个问题,原因是UTF-8编码有可能是两个.三个.四个字节.Emoji表情或者某些特殊字符是4个字节,而Mysql的utf8编码最多3个字节,所以数据插不进去. 我的解决方案是这样的 1.在mysql ...

  5. 453. Minimum Moves to Equal Array Elements 一次改2个数,变成统一的

    [抄题]: Given a non-empty integer array of size n, find the minimum number of moves required to make a ...

  6. 345. Reverse Vowels of a String翻转字符串中的元音字母

    [抄题]: Write a function that takes a string as input and reverse only the vowels of a string. Example ...

  7. struts2 框架的基本使用

    <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http:// ...

  8. C/C++预处理指令常见的预处理指令

    C/C++预处理指令常见的预处理指令如下: #空指令,无任何效果 #include包含一个源代码文件 #define定义宏 #undef取消已定义的宏 #if如果给定条件为真,则编译下面代码 #ifd ...

  9. [算法基础]Big O Notation时间复杂度计算方法

    首先一点就是无视任何常量 从最简单的开始 statement; 这段时间复杂度为常数1,所以O(1). 然后 ; i < N; i++ ) statement; 这一段是线性的,则时间复杂度为N ...

  10. 《PRC:更新项目汇总额》报错

    请求报红,日志如下: +---------------------------------------------------------------------------+ 项目: Version ...