为什么create_all函数不能创建我的表?

时间:2019-03-31 14:20:59

标签: python-3.x postgresql flask-sqlalchemy

我正在用Flask和SQLAlchemy创建一个小应用程序。 (我是Python新手)
好吧,我希望Flask-SQLAlchemy创建代码中已经定义的表。

我的项目结构如下:

application
├── models
│   ├── __init__.py
│   ├── device.py
│   └── user.py
├── static
├── templates
├── __init__.py
├── flask_config.py
└── wsgi.py

__init__.py包中的models如下所示:

from flask_sqlalchemy import SQLAlchemy
from configparser import ConfigParser


class DBHandler:
    def __init__(self):
        self.config = ConfigParser()
        self.configPath = r"application/config.ini"
        self.config.read(self.configPath)

        self.db_username = self.config.get("DEV", "db_username")
        self.db_password = self.config.get("DEV", "db_password")
        self.db_host = self.config.get("DEV", "db_host")
        self.db_port = self.config.get("DEV", "db_port")
        self.db_name = self.config.get("DEV", "db_name")

        self.DB_URL = 'postgresql+psycopg2://' + self.db_username + ':' + self.db_password + '@' + \
        self.db_host + ':' + self.db_port + '/' + self.db_name

        self.db = SQLAlchemy()  


我定义的模型非常简单。这是user.py的示例:

from application.models import DBHandler

db_handler = DBHandler()


class User(db_handler.db.Model):
    __tablename__ = 'user'
    id = db_handler.db.Column(db_handler.db.Integer, primary_key=True)
    username = db_handler.db.Column(db_handler.db.String(200), unique=True, nullable=False)
    email = db_handler.db.Column(db_handler.db.String(200), unique=False, nullable=False)  



应用程序的__init_.py文件如下所示:

from application.models import DBHandler
from application.flask_config import FlaskConfig

from flask import Flask
from flask_restful import Api


def create_app():
    application = Flask(__name__)
    flask_config_obj = FlaskConfig()
    application.config.from_object(flask_config_obj)

    db_handler_obj = DBHandler()
    db_handler_obj.db.init_app(application)

    return application  



要创建表,我在python控制台中运行以下代码:

from application import create_app
import application.models
from application.models.user import User
from application.models.port import Port
from application.models.device import Device
app = create_app()
db_handler = application.models.DBHandler()
with app.app_context():
    db_handler.db.create_all()  

代码运行没有错误,但是未创建表。
我在做什么错了?


编辑:
这是我连接到数据库的Flask配置类:

from application.models import DBHandler


class FlaskConfig:
    def __init__(self):
        db_handler = DBHandler()
        self.SQLALCHEMY_DATABASE_URI = db_handler.DB_URL
        self.SQLALCHEMY_TRACK_MODIFICATIONS = False
        self.SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'

1 个答案:

答案 0 :(得分:0)

您需要将DB_URL添加到应用程序配置中才能连接到数据库:

db_handler_obj = DBHandler()
application.config['SQLALCHEMY_DATABASE_URI'] = db_handler_obj.DB_URL
db_handler_obj.db.init_app(application)