前言

其实准备把这篇删掉,先写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使用的更多相关文章

  1. flask, SQLAlchemy, sqlite3 实现 RESTful API 的 todo list, 同时支持form操作

    flask, SQLAlchemy, sqlite3 实现 RESTful API, 同时支持form操作. 前端与后台的交互都采用json数据格式,原生javascript实现的ajax.其技术要点 ...

  2. flask SQLAlchemy中一对多的关系实现

    SQLAlchemy是Python中比较优秀的orm框架,在SQLAlchemy中定义了多种数据库表的对应关系, 其中一对多是一种比较常见的关系.利用flask sqlalchemy实现一对多的关系如 ...

  3. Python Flask高级编程之RESTFul API前后端分离精讲 (网盘免费分享)

    Python Flask高级编程之RESTFul API前后端分离精讲 (免费分享)  点击链接或搜索QQ号直接加群获取其它资料: 链接:https://pan.baidu.com/s/12eKrJK ...

  4. python3 + flask + sqlalchemy +orm(1):链接mysql 数据库

    1.pycharm中新建一个flask项目 2.按装flask.PyMySQL.flask-sqlalchemy 3.项目下面新建一个config.py 文件 DEBUG = True #dialec ...

  5. python 全栈开发,Day142(flask标准目录结构, flask使用SQLAlchemy,flask离线脚本,flask多app应用,flask-script,flask-migrate,pipreqs)

    昨日内容回顾 1. 简述flask上下文管理 - threading.local - 偏函数 - 栈 2. 原生SQL和ORM有什么优缺点? 开发效率: ORM > 原生SQL 执行效率: 原生 ...

  6. Flask SQLAlchemy & model

    Flask-SQLAlchemy Flask-SQLAlchemy库让flask更方便的使用SQLALchemy,是一个强大的关系形数据库框架,既可以使用orm方式操作数据库,也可以使用原始的SQL命 ...

  7. Python利用flask sqlalchemy实现分页效果

    Flask-sqlalchemy是关于flask一个针对数据库管理的.文中我们采用一个关于员工显示例子. 首先,我们创建SQLALCHEMY对像db. from flask import Flask, ...

  8. 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 ...

  9. Flask – SQLAlchemy成员增加

    目录 简介 结构 展示 技术 运行 代码 创建数据库表单 views视图 home主页 添加成员addnew.html 展示页show_all 简介 结构 $ tree -I "__pyca ...

随机推荐

  1. Python静态网页爬取:批量获取高清壁纸

    前言 在设计爬虫项目的时候,首先要在脑内明确人工浏览页面获得图片时的步骤 一般地,我们去网上批量打开壁纸的时候一般操作如下: 1.打开壁纸网页 2.单击壁纸图(打开指定壁纸的页面) 3.选择分辨率(我 ...

  2. python 三元运算符、推导式、递归、匿名函数、内置函数

    三目运算符 # 三目(元)运算符:就是 if...else...语法糖 # 前提:简化if...else...结构,且两个分支有且只有一条语句 # 注:三元运算符的结果不一定要与条件直接性关系 cmd ...

  3. 函数中的this与argument对象,以及argument中的callee与caller属性

    相关阅读:https://segmentfault.com/a/1190000015438195 相关阅读: https://zhuanlan.zhihu.com/p/23804247 相关阅读: h ...

  4. [BJOI2019] 删数

    https://www.luogu.org/problemnew/show/P5324 题解 首先我们需要弄清这个答案是什么. 对于一个长度为n的序列,那么它先删的肯定是\(n\),删完之后它就会跳到 ...

  5. 洛谷P3268 [JLOI2016]圆的异或并(扫描线)

    扫描线还不是很熟啊--不管是从想的方面还是代码实现的方面-- 关于这题,考虑一条平行于\(y\)轴的扫描线从左到右扫描每一个圆,因为只有相离和内含两种关系,只用在切线处扫描即可 我们设上半圆为1,下半 ...

  6. react16 渲染流程

    前言 react升级到16之后,架构发生了比较大的变化,现在不看,以后怕是看不懂了,react源码看起来也很麻烦,也有很多不理解的地方. 大体看了一下渲染过程. react16架构的变化 react ...

  7. 2017-12-20python全栈9期第五天第一节之昨日内容回顾和作业讲解之字母变大写

    #!/user/bin/python# -*- coding:utf-8 -*-lis = [2,3,'k',['qwe',20,['k1',['tt','3','1']],89],'ab','adv ...

  8. Exp4 恶意代码分析

    一.原理与实践说明 1. 实践目标 1.1 监控你自己系统的运行状态,看有没有可疑的程序在运行. 1.2 分析一个恶意软件,就分析Exp2或Exp3中生成后门软件:分析工具尽量使用原生指令或sysin ...

  9. [转载] win10进行端口转发

    1.添加端口转发netsh interface portproxy add v4tov4 listenport=4000 listenaddress=127.0.0.1 connectport=400 ...

  10. Linux基础命令(三)——>文件过滤及内容编辑处理命令

    1.cat   合并文件或查看文件内容 基本功能:cat   test.txt     查看文件内容 也可以多文件显示 cat  test1.txt test2.txt >test3.txt   ...