SQLAlchemy小知识点

1.创建数据库模型的时候增加添加上注释
SQLAlchemy1.2新增了comment参数telephone = db.Column(db.String(11), nullable=False, comment='电话')
class User(Base):
    __tablename__ = 'user'
    id = Column(Integer,primary_key=True,autoincrement=True)
    username = Column(String(50),nullable=False,comment='这个是添加的注释信息')
    def __repr__(self):
       return '<User %s>' % self.username
2.创建数据库模型的时候设置字段的编码类型等
class User(Base):
    __tablename__ = 'user'
    __table_args__ = {
        'mysql_charset': 'utf8mb4'
    }
    id = Column(Integer,primary_key=True,autoincrement=True)
    username = Column(String(50),nullable=False,comment='这个是添加的注释信息')
    def __repr__(self):
       return '<User %s>' % self.username
3.Flask-SQLAlchemy中解决1366报错
使用的是pymysql驱动,1366报错,更换连接MySQL的驱动
pip install mysql-connector
'SQLALCHEMY_DATABASE_URI' = 'mysql+mysqlconnector://root:password@localhost/database?charset=utf8mb4'
4.pip安装包超时
使用豆瓣源
https://www.cnblogs.com/clockwork/p/6133720.html
    解决方法一:
pip install <包名> -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
    解决方法二:
在当前用户目录下新建pip文件夹
pip.ini
[global]
index-url = http://pypi.douban.com/simple
trusted-host = pypi.douban.com

5.使用 flask-sqlacodegen 扩展 方便快速生成 ORM model
windows系统下注意输出models.py文件的路径写法
flask-sqlacodegen "mysql+mysqlconnector://root:root@127.0.0.1/food_db" --tables user --outfile "common\models\user.py"  --flask
linux
flask-sqlacodegen "mysql+mysqlconnector://root:root@127.0.0.1/food_db" --tables user --outfile "common/models/user.py"  --flask

注意:生成的models.py文件中默认使用的是如下的db
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
根据项目的实际需要进行修改,比如修改成下面的这种
from application import db

posted @   哈喽哈喽111111  阅读(620)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示