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 "commonmodelsuser.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

原文地址:https://www.cnblogs.com/sanduzxcvbnm/p/10219099.html