当前位置:网站首页>Flask-RESTful请求响应与SQLAlchemy基础
Flask-RESTful请求响应与SQLAlchemy基础
2022-08-02 14:01:00 【czy1206527605】
一.flask_restfun处理请求
1.处理的流程
from flask import Flask
from flask_restful import Api, Resource
from flask_restful import reqparse
app = Flask(__name__)
api = Api(app)
class Index(Resource):
def get(self):
parser = reqparse.RequestParser()
parser.add_argument('id')
args = parser.parse_args()
return '参数ID的值为: {}'.format(args['id'])
api.add_resource(Index, '/index')
if __name__ == '__main__':
app.run()
2.思路
1.导入RequestParser类
2.实例化RequestParser对象
3.向RequestParser对象中添加需要检验或转换的参数声明
4.使用parse_args()方法启动检验处理
5.通过args.id或args[‘id’]的方法获取参数
二.序列化数据
1.装饰器形式的序列化
from flask import Flask
from flask_restful import Api, Resource
from flask_restful import fields, marshal_with
app = Flask(__name__)
api = Api(app)
class User(object):
def __init__(self, name, age, password):
self.name = name
self.age = age
self.password = password
resource_fields = {
'name': fields.String,
'age': fields.Integer,
}
class Index(Resource):
@marshal_with(resource_fields, envelope='data')
def get(self, **kwargs):
user = User('Jeremy', 18, '123456')
return user
# 指定路由
api.add_resource(Index, '/index')
if __name__ == '__main__':
app.run()
2.marshal方法直接序列化
from flask import Flask
from flask_restful import Api, Resource
from flask_restful import fields, marshal_with, marshal
app = Flask(__name__)
api = Api(app)
class User(object):
def __init__(self, name, age, password):
self.name = name
self.age = age
self.password = password
resource_fields = {
'name': fields.String,
'age': fields.Integer,
}
class Index(Resource):
def get(self, **kwargs):
user = User('Jeremy', 18, '123456')
return marshal(user, resource_fields)
api.add_resource(Index, '/index')
if __name__ == '__main__':
app.run()
其中 若想要响应返回json数据格式时 应return
{
"msg": "发送成功",
"code": 200,
"data": {
...}
}
一.SQLAlchemy
1.SQLAlchemy数据库的配置
安装Flask-SQLAlchemy
pip install flask-sqlalchemy
from flask import Flask
app = Flask(__name__)
class Config(object):
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/jiyunstus'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = True
app.config.from_object(Config)
2.SQLAlchemy数据库模型类的创建
from flask_sqlalchemy import SQLAlchemy
from app import app
db = SQLAlchemy(app)
class UserModel(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
3.SQLAlchemy数据库迁移文件
from flask_migrate import Migrate, MigrateCommand
from flask_script import Shell, Manager
from models.user_models import db
from app import app
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
PS:文件迁移的命令
初始化迁移文件
python manage.py db init
生成迁移文件
python manage.py db migrate
执行迁移
python manage.py db upgrade
边栏推荐
- Shell脚本完成pxe装机配置
- 不精确微分/不完全微分(Inexact differential/Imperfect differential)
- 世界上最大的开源基金会 Apache 是如何运作的?
- 面试SQL语句,学会这些就够了!!!
- 【Tensorflow】AttributeError: module 'keras.backend' has no attribute 'tf'
- 网络安全第一次作业(2)
- Differences and concepts between software testing and hardware testing
- 线代:已知一个特征向量快速求另外两个与之正交的特征向量
- 网络安全第一次作业
- Interview | with questions to learn, Apache DolphinScheduler Wang Fuzheng
猜你喜欢
You can't accept 60% slump, there is no eligible for gain of 6000% in 2021-05-27
IDEA打包jar包
Supervision strikes again, what about the market outlook?2021-05-22
stack && queue
文件加密软件有哪些?保障你的文件安全
C language improvement (3)
关于市场后市的发展预测? 2021-05-23
C语言提高篇(三)
理解TCP长连接(Keepalive)
不精确微分/不完全微分(Inexact differential/Imperfect differential)
随机推荐
Sentinel源码(一)SentinelResourceAspect
劲爆!阿里巴巴面试参考指南(嵩山版)开源分享,程序员面试必刷
logback源码阅读(二)日志打印,自定义appender,encoder,pattern,converter
Sentinel源码(六)ParamFlowSlot热点参数限流
CVE-2020-27986(Sonarqube敏感信息泄漏) 漏洞修复
【Tensorflow】AttributeError: module ‘keras.backend‘ has no attribute ‘tf‘
Data Organization---Chapter 6 Diagram---Graph Traversal---Multiple Choice Questions
打破文件锁限制,以存储力量助力企业增长新动力
Mysql's case the when you how to use
二极管及其应用
C# 编译错误:Compiler Error CS1044
VMM是什么?_兮是什么意思
tinymce 如何实现动态国际化
Break the limit of file locks and use storage power to help enterprises grow new momentum
The most complete ever!A collection of 47 common terms of "digital transformation", read it in seconds~
多个驻外使领馆发提醒 事关赴华出行、人身财产安全
Sentinel源码(五)FlowSlot以及限流控制器源码分析
Awesome!Alibaba interview reference guide (Songshan version) open source sharing, programmer interview must brush
deal!It's July 30th!
The future of financial services will never stop, and the bull market will continue 2021-05-28