最近Flask项目要根据数据库表生成model,所以报错合集来啦!
import os def create_models(): db_url = "mysql+pymysql://jxz_user:123456jxz!@localhost:3306/bnh_novel?charset=utf8mb4" project_path = os.getcwd() print(project_path) model_path = os.path.join(project_path, 'models.py') cmd = 'flask-sqlacodegen --flask {}'.format(db_url) try: output = os.popen(cmd) resp = output.buffer.read().decode(encoding='utf-8') content = str(resp) output.close() # w+ 读写权限 with open(model_path, 'w+', encoding='utf-8') as f: f.write(content) print('create models successfully!') except Exception as e: print(e) if __name__ == '__main__': create_models()
上面就是创建models.py代码。非常简单!然后不注意就会有非常多的报错!以下记录报错信息:
1.记得pip基本数据库连接依赖包!
pip install flask-sqlacodegen pip install pymysql pip install flask-sqlalchemy
2.数据库密码注意点!密码主要@符号,因为设置的密码是123456!@#$%^,所以就报错以下信息了:
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '#$%@localhost' ([Errno 11003] getaddrinfo failed)")
3.代码中os.popen()之后,再read(),可能会报以下错误:
'gbk' codec can't decode byte 0xac in position 298: illegal multibyte sequence
所以这个情况下,可以修改自己代码为:
之前代码是: output = os.popen(cmd) content = str(output.read()) 修改后代码: output = os.popen(cmd) resp = output.buffer.read().decode(encoding='utf-8') content = str(resp) str()可以不加没关系
4.最后要output.close(),不然会报错:
OSError: [WinError 6] 句柄无效。
好了,完结啦!
其实中间还出现了
RuntimeError: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods
因为我删了这个依赖包也没有重现这个问题,所以就写在最后啦!只需要pip install cryptography就好,这里有个注意点就是版本号(cryptography==2.8),尽量不要最新版本就好