Flask+SQLAlchemy+alembic+Flask-RESTful使用
前言
其实准备把这篇删掉,先写Flask-restful相关的,后来想想大体框架还是先写出来,这两天踩了很多坑,有的谷歌也没有答案.一直摸索也总算是开始了.
正文
SQLAlchemy/alembic 的 使用方法之前写过,详见我的博客,今天讲讲如何与 flask-restful 结合一起(只是简单的讲讲搭配,Flask-restful以后会详细讲述)
搭建大体框架
其实与普通的 Flask 差不多,只不过app的功能模块中我们需要加一个 models 文件存放我们建立的 model,在按功能写py,大致如下

编辑model
models.py
# -*- coding=utf- -*- from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, ForeignKey, DateTime # 用户名:密码@访问地址:端口/数据库?编码方式
engine = create_engine('mysql+mysqldb://root:***@***:***/website?charsite=utf8mb4') # 创建DBSession类型
DBSession = sessionmaker(bind=engine) # 创建Base基类
Base = declarative_base() class AdminUser(Base):
# 超级用户表
__tablename__ = 'admin_user' # 表名
id = Column(Integer, primary_key=True) # 主键
username = Column(String(), nullable=False, index=True, unique=True) # 用户名,Varchar12位,不可为空,常规索引
pwd = Column(String(), nullable=False) # 密码,不可为空
token = Column(String(), nullable=True) # token
token_end_time = Column(DateTime, nullable=True) # token过期时间 class Vip(Base):
# VIP用户
__tablename__ = 'vip' # 表名
id = Column(Integer, primary_key=True) # id
name = Column(String(), nullable=False, index=True, unique=True) # name
pwd = Column(String(), nullable=False) # pwd
money = Column(Integer, nullable=False) # 金币
status = Column(Integer, nullable=False) # 账号状态(:正常,:封禁,:审核)
fk_vip_on_vip_lv = Column(Integer, ForeignKey('vip_lv.id'), nullable=False) # 关联VIPLV等级(多对一)
VipLv = relationship('VipLv', backref=backref('Vip', uselist=True)) class VipInfo(Base):
# VIP信息
__tablename__ = 'vip_info' # 表名
id = Column(Integer, primary_key=True) # id
info = Column(String(), nullable=True) # 备注,可为空
last_time = Column(DateTime, nullable=True) # 最后登陆时间,可为空
fk_vip_info_on_vip = Column(Integer, ForeignKey('vip.id'), unique=True, index=True, nullable=False) # 关联外键VIP.id(一对一)
Vip = relationship('Vip', backref=backref('VipInfo', uselist=False)) # 设置关联使VIPInfo能查询到VIP class VipLv(Base):
# VIP等级
__tablename__ = 'vip_lv' # 表名
id = Column(Integer, primary_key=True) # id
lv = Column(Integer, nullable=False) # 等级
name = Column(String(), nullable=False) # 等级名称
info = Column(String(), nullable=False) # 等级说明
month_money = Column(Integer, nullable=True) # 月费
year_money = Column(Integer, nullable=True) # 年费 class VipOrder(Base):
# VIP订单
__tablename__ = 'vip_order' # 表名
id = Column(Integer, primary_key=True) # id
found_time = Column(DateTime, nullable=False) # 订单创建时间
check_status = Column(Integer, nullable=False) # 订单确认状态,1成功/0失败/2待确认/3已过期
err_info = Column(String(), nullable=True) # 订单错误原因(订单错误时填写)
success_time = Column(DateTime, nullable=True) # 订单确认时间
fk_vip_order_on_vip_lv = Column(Integer, ForeignKey('vip_lv.id'), nullable=False) # 关联外键VIP等级(多对一)
VipLv = relationship('VipLv', backref=backref('VipLv', uselist=True))
money = Column(Integer, nullable=False) # 订单金额
go_time = Column(DateTime, nullable=False) # 开始时间
on_time = Column(DateTime, nullable=False) # 结束时间 # if __name__ == '__main__':
# Base.metadata.create_all(engine)
初始化Flask-restful/蓝图
我们在 website下的 __init__中初始化 restful
# -*- coding=utf- -*-
from flask import Blueprint
from flask_restful import Api
from .VIP import Vip, Token website_1_0 = Blueprint('website_1_0', __name__, url_prefix='/api/v1.0') # 生成蓝图,名称为website_1_0,设置蓝图下的统一前缀为/api/v1.
api = Api(website_1_0) # 初始化api
# 下方是添加路由控制
# api.add_resource(引入view的视图类, 匹配url)
api.add_resource(Vip, '/website/vip/<int:vip_id>') # 获取VIP常用信息(匹配url带有int数字的传给Vip视图,url的参数命名为vip_id)
导入注册蓝图/restful
在app下的__init__.py中
# -*- coding=utf- -*-
from flask import Flask
from datetime import timedelta
from flask_restful import Api
# from flask_wtf.csrf import CsrfProtect
from flask_cors import * # 导入模块
import datetime def create_app():
app = Flask(__name__)
CORS(app, supports_credentials=True) # 设置跨域
# CsrfProtect(app)
# from .website import website
# app.register_blueprint(website)
# from .website.views import VIP
# VIP.init_app(app)
from .website import api
api.init_app(app) # restful需要initaoo
from .website import website_1_0
app.register_blueprint(website_1_0) # 结合蓝图使用
return app
写Vip相关的视图类
vip.py
# -*- coding=utf- -*- from flask_restful import reqparse, abort, Api, Resource, request
# from . import website
from flask import render_template, Flask, \
request, redirect, url_for
from app.website.models import DBSession, Vip, VipInfo, AdminUser, VipLv, VipOrder
from ..tools import info_tool class Vip(Resource):
# VIP信息(单)
def get(self, vip_id):
# 获取vip基本信息
from app.website.models import DBSession, Vip
session = DBSession()
obj = session.query(Vip).filter(Vip.id==vip_id).first()
inf = info_tool.oneobj_to_safe(obj) # info_tool是我自己写的序列化
return inf
这样就能成功将其组合到一起了
Flask+SQLAlchemy+alembic+Flask-RESTful使用的更多相关文章
- flask, SQLAlchemy, sqlite3 实现 RESTful API 的 todo list, 同时支持form操作
flask, SQLAlchemy, sqlite3 实现 RESTful API, 同时支持form操作. 前端与后台的交互都采用json数据格式,原生javascript实现的ajax.其技术要点 ...
- flask SQLAlchemy中一对多的关系实现
SQLAlchemy是Python中比较优秀的orm框架,在SQLAlchemy中定义了多种数据库表的对应关系, 其中一对多是一种比较常见的关系.利用flask sqlalchemy实现一对多的关系如 ...
- Python Flask高级编程之RESTFul API前后端分离精讲 (网盘免费分享)
Python Flask高级编程之RESTFul API前后端分离精讲 (免费分享) 点击链接或搜索QQ号直接加群获取其它资料: 链接:https://pan.baidu.com/s/12eKrJK ...
- python3 + flask + sqlalchemy +orm(1):链接mysql 数据库
1.pycharm中新建一个flask项目 2.按装flask.PyMySQL.flask-sqlalchemy 3.项目下面新建一个config.py 文件 DEBUG = True #dialec ...
- python 全栈开发,Day142(flask标准目录结构, flask使用SQLAlchemy,flask离线脚本,flask多app应用,flask-script,flask-migrate,pipreqs)
昨日内容回顾 1. 简述flask上下文管理 - threading.local - 偏函数 - 栈 2. 原生SQL和ORM有什么优缺点? 开发效率: ORM > 原生SQL 执行效率: 原生 ...
- Flask SQLAlchemy & model
Flask-SQLAlchemy Flask-SQLAlchemy库让flask更方便的使用SQLALchemy,是一个强大的关系形数据库框架,既可以使用orm方式操作数据库,也可以使用原始的SQL命 ...
- Python利用flask sqlalchemy实现分页效果
Flask-sqlalchemy是关于flask一个针对数据库管理的.文中我们采用一个关于员工显示例子. 首先,我们创建SQLALCHEMY对像db. from flask import Flask, ...
- flask建表遇到的错误: flask,sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1071, 'Specified key was too long; max key length is 767 bytes')
error:flask,sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1071, 'Specifie ...
- Flask – SQLAlchemy成员增加
目录 简介 结构 展示 技术 运行 代码 创建数据库表单 views视图 home主页 添加成员addnew.html 展示页show_all 简介 结构 $ tree -I "__pyca ...
随机推荐
- redis 开启远程访问权限
1 开启redis端口访问权限 redis默认的端口是6379,要远程访问redis服务,确保服务器上的6379端口打开. 1.1 查看打开的端口 /etc/init.d/iptables statu ...
- zookeeper-3.5.4-beta安装
官网地址 https://zookeeper.apache.org/ 下载文件解压进入conf目录下将zoo_sample.cfg名称修改为zoo.cfg # The number of millis ...
- BaseEntity
@MappedSuperclasspublic class BaseEntity { @Id @GenericGenerator(name="idGenerator", strat ...
- Netty 中 LengthFieldBasedFrameDecoder 构造函数取值备忘
public LengthFieldBasedFrameDecoder(ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, ...
- hdu-1711(hash)
题意:给你T组数据,每组数据分别输入n,m和长度为n的数字数组,和长度为m的数字数组,问你长度为m的数组第一次出现在长度为n的数组的位置 解题思路:标准字符串匹配问题,一般用kmp解,拿来练hash ...
- vs code 的便捷使用
鼠标滚动 改变字体大小 打开编辑器设置,搜索 editor.mouseWheelZoom 或者文本设置 自动保存 打开设置 搜索 autosave
- Centos 利用yum安装卸载软件常用命令[转载]
一.使用yum安装和卸载软件,有个前提是yum安装的软件包都是rpm格式的. 安装的命令是,yum install ~,yum会查询数据库,有无这一软件包,如果有,则检查其依赖冲突关系,如果没有依赖冲 ...
- 【BZOJ4029】[HEOI2015]定价(贪心)
[BZOJ4029][HEOI2015]定价(贪心) 题面 BZOJ 洛谷 题解 每次加上十进制下的\(lowbit\)就行了??? #include<iostream> #include ...
- 分享自己总结的PMP项目管理20个G的资料,本人去年过的pmp认证,过了5A
版权归作者所有,任何形式转载请联系作者. 我在去年6月拿到的pmp证书,5A的,现在来分享下自己的资料. 这些资料是从我开始学习,到问了很多朋友.老人,到后来报班学习,再到之后做项目管理中总结的很多经 ...
- sharding-jdbc学习
sharding-jdbc的全局id生成策略是通过雪花算法来实现的. sharding-jdbc也是一个数据的中间件,可实现读写分离和分库分表,比mycat要简单些. nginx与ribbon实现负载 ...