你好,我正在尝试用SQLAlchemy创建数据库及其表,为了做到这一点,我有以下代码和结构:
.
├── api
│ ├── api.py
│ ├── config.py
│ ├── connector.py
│ ├── detector
│ │ ├── __init__.py
│ │ └── route.py
│ └── user
│ ├── __init__.py
│ └── model.py
├── database.db
├── manager.py
├── queue
│ ├── __init__.py
│ └── queue.py
└── requirements.txt
要求:
dictalchemy~=0.1.2.7
Flask-RESTful
redis
Flask-SQLAlchemy
Flask-Script
Flask-Migrate
python-dotenv
SQLAlchemy~=1.3.18
Flask~=1.1.2
flask-cors
用户模型
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Text
from api.connector import BaseModel, engine
class User(BaseModel):
__tablename__ = 'users'
id = Column(
Integer,
name='id',
nullable=False,
primary_key=True,
autoincrement=True,
)
email = Column(
Text,
name='email',
)
Base.metadata.create_all(engine)
连接器
from contextlib import contextmanager
import functools
from dictalchemy import DictableModel
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine("sqlite:///database.db", echo=True)
_db_session = sessionmaker(bind=engine)
BaseModel = declarative_base(cls=DictableModel)
Api
from flask import Flask
from flask_restful import Api
from api.detector.route import Detector
from flask_cors import CORS
app = Flask(__name__)
api = Api(app)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
api.add_resource(检测器,'/api/v.0/det'(
经理
from api.api import app
from flask_script import Manager
from api.connector import engine, BaseModel
from api.detector.route import Detector
manager = Manager(app)
app.config['DEBUG'] = True
@manager.command
def create_tables():
"Create relational database tables."
BaseModel.metadata.create_all(engine)
if __name__ == '__main__':
manager.run()
为了创建表,我使用这个python manager.py create_tables,返回:
2020-07-23 00:45:15815信息sqlalchemy.engine.base.engine SELECTCAST("最纯返回"AS VARCHAR(60((AS anon_1 2020-07-2300:45:15815信息sqlalchemy.engine.base.engine((2020-07-2300:45:15816信息sqlalchemy.engine.base.engine SELECT CAST(测试unicode返回"AS VARCHAR(60("AS anon_1 2020-07-23 00:45:15816信息sqlalchemy.engine.base.engine((
已创建数据库文件,但该文件为空。
为什么模型没有加载到数据库中?
谢谢。
create_all()
为它所知道的模型创建表。如果它不知道任何信息,那么它非常乐意创建一个具有空模式的数据库。
似乎create_all()
在导入user.model
之前运行。解决这个问题,你应该得到桌子。