当前位置:网站首页>Flask对模型类的操作
Flask对模型类的操作
2022-07-20 21:15:00 【du fei】
1. 创建一个config文件夹,里面在创建一个settings.py文件写入配置
class DefaultConfig():
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/h2111p7'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = True
2. 创建一个models文件夹,里面在创建一个model.py文件,写入模型类
from flask_sqlalchemy import SQLAlchemy
# 去app.py文件中初始化
db = SQLAlchemy()
class UserModel(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='ID')
username = db.Column(db.String(32), nullable=False, default='', comment='用户名')
password = db.Column(db.String(64), nullable=False, default='', comment='密码')
sex = db.Column(db.Boolean, nullable=False, default=True, comment='性别 0:男 1:女')
3. 在创建一个app.py文件写入代码
from flask import Flask
from models.models import db
from config.settings import DefaultConfig
# 初始化Flask
app = Flask(__name__)
app.config.from_object(DefaultConfig)
print(app.config)
# 初始化数据库
db.init_app(app)
if __name__ == ' __main__ ':
app.run()
- 一定要在根目录下创建一个manage.py迁移文件
from flask_migrate import Manager
from flask_migrate import MigrateCommand, Migrate
from models.model import db
from app import app
# 生成命令行管理对象
manage = Manager(app)
# 生成迁移对象
migrate = Migrate(app, db)
manage.add_command('db', MigrateCommand)
if __name__ == ' __main__ ':
manage.run()
- 迁移命令
python manage.py db init
python manage.py db migrate
python manage.py db upgrade
4. 模型类的增、删、改、查
- 首先在app.py里注册一个蓝图
from order import order_bp
app.register_blueprint(border_bp)
- 创建一个order.py文件写入代码
from flask import Buleprint
from flask_restful import Api, Resource, marshal, fields
from models.model import UserModel, db
# 初始化类方法
order_bp = Blueprint('order_bp', __name__, url_prefix='/order')
# 初始化Api
api = Api(order_bp)
# 对数据库的增、删、改、查方法
class OrderView(Resoure):
def get(self):
# 添加数据
# ul = UserModel(
# username='wangwu',
# password='111',
# sex=False
# )
# us = UserModel(
# username='lisi',
# password='111',
# sex=False
# )
# # db.session.add(ul) # 添加一条数据
# db.session.add_all([ul, us]) # 添加多条数据
# db.session.commit()
"""查看数据"""
# 查看所有数据
# query_set = UserModel.query.all()
# print(query_set)
# 查询单个数据
# query_set = UserModel.query.get(2)
#
# return marshal(query_set, {
# 'id': fields.Integer,
# 'username': fields.String,
# 'password': fields.String,
# 'sex': fields.Integer
# })
"""修改数据"""
# 1、
# UserModel.query.filter_by(username='zhangsan').update({'password': '222'})
# 2、
# query_put = UserModel.query.filter_by(username='zhangsan').first()
# query_put.password = '333'
# 修改所有
# UserModel.query.update({'password': '222'})
# db.session.commit()
# return '修改成功'
"""删除数据"""
# UserModel.query.filter_by(username='zhangsan').delete()
# 删除所有
UserModel.query.delete()
# 提交事务
db.session.commit()
return '删除成功'
# 配置路由
api.add_resource(OrderView, '/order')
边栏推荐
- 【Coggle 30 Days of ML】糖尿病遗传风险检测挑战赛(1)
- BGP (border gateway protocol) border gateway protocol
- 中金证券是正规证券公司嘛?股票开户安全吗?
- 处理浏览器缓存图片,只请求一次
- SwiftUI 中使用 SpriteKit 创建雨动画效果(教程含源码)
- CFile类
- 3D转换之三维坐标系,透视旋转等基础知识
- Arm assembly instruction set with examples
- 第二章第十一节:元组
- Rip and OSPF (open shortest path first, OSPF) configuration
猜你喜欢
Web3 Traffic Aggregation Platform Starfish os, Explaining Real Business' p2e 'Ecology
The relationship between data warehouse and data center
图解LeetCode——1260. 二维网格迁移(难度:简单)
Spark Sql编译模块-词法、语法分析器Antlr4(一
第二章 第五节:查找和判断
Section 11 of Chapter 2: tuples
(open shortest path first, OSPF) comprehensive experiment
Php talent Recruitment site source
项目总结:文件管理系统
Math.random()的用法
随机推荐
SwiftUI 中使用 SpriteKit 创建雨动画效果(教程含源码)
Visual Studio 好用的插件分享
On the surface, the meta universe may fundamentally change people's way of production and life
BGP (border gateway protocol) border gateway protocol
token与refresh_token
面试中常见的的 web 安全问题
Implementation details of SAP e-commerce cloud Spartacus UI sitecontexturlparams
第二章第七节:列表的概念
Section 14 of Chapter 2: the concept of dictionary
(Open Shortest Path First,OSPF)综合实验
2.3 分支语句
asp. Net - edit hyperlink event
第二章第九节:练习答案
Web3流量聚合平臺Starfish OS,詮釋真正商業的“P2E”生態
(Open Shortest Path First,OSPF)拓展配置
超级App是什么?小程序有4个特性,你知道吗?
微信小程序--》数据绑定和事件绑定
std::string 不能跨dll的一种解决方法
C call stored procedure to transfer table valued parameters
Research Report - visible light communication and visible light positioning