如何使Flask-SQLAlchemy与应用程序工厂模式一起使用

时间:2019-02-01 21:42:22

标签: python flask sqlalchemy flask-sqlalchemy

我想使用flask-SQLalchemy建立一个sqlite数据库。我收到操作错误“(sqlite3.OperationalError)没有这样的表”

这是针对用flask编写的Web应用程序。我想使用Flask-SQLAlchemy扩展名与数据库进行交互。我觉得这可能与应用程序上下文有关,但我不确定。

您可以看到该应用程序具有一个模块(“身份验证”模块)。该模块通过蓝图注册到应用程序。我在auth子软件包的models.py类中为Researcher类定义模型。 app / init .py保存应用程序工厂和数据库初始化。 因为我只是想使基本功能正常工作,所以只有两个视图是在app / auth / routes.py中定义的。


.
|-- app
|   |-- __init__.py
|   |-- auth
|   |   |-- __init__.py
|   |   |-- __pycache__
|   |   |-- models.py
|   |   `-- routes.py
|   |-- static
|   `-- templates
|-- app.db
|-- config.py
|-- instance
|   `-- config.py
`-- run.py

app / init .py

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile("../config.py")

    db.init_app(app)
    with app.app_context():
        db.create_all()

    from app.auth import auth
    app.register_blueprint(auth, url_prefix="/auth/")

    return app 

app / auth / routes.py

from flask import Flask
from app import db
from models import User
from app.auth import auth

@auth.route("/insert")
def insert():
    #r = Reasearcher("Pat","Den", "Pat_Den@mail.com", "operator","Dr.","Mr", "08611111", "+353", "0001")
    u = User(1,"Elija")
    db.session.add(u)
    db.session.commit()

@auth.route("/query")
def query():
    us = users.query.all()
    s = ""
    for u in us:
        s += u.name
    return s

app / auth / models.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from app import db

class User(db.Model):
    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

    def __init__(self,ids, name):
        self.id = ids
        self.name = name

app / auth / init .py

from flask import Flask, Blueprint

auth = Blueprint("auth", __name__)

import routes
import models

config.py

DEBUG = True

import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))

SQLALCHEMY_DATABASE_URI = "sqlite:////" + os.path.join(BASE_DIR, "app.db")
DATABASE_CONNECT_OPTIONS = {}
THREADS_PER_PAGE = 2

CSRF_ENABLED     = True

CSRF_SESSION_KEY = "secret"
SECRET_KEY = "secret"

我应该能够请求/ auth / query并获取数据库表的内容,但是却出现了错误- “ OperationalError:(sqlite3.OperationalError)没有这样的表:研究人员[SQL:u'INSERT INTO researchers(prefix,suffix,phone,phone_ext,orcid)VALUES(?,?,?,?,?)'] [参数:( 'Dr。','Mr','08611111','+ 353','0001')](此错误的背景位于:http://sqlalche.me/e/e3q8)”

enter image description here

2 个答案:

答案 0 :(得分:1)

代码正在执行/>时,尚未导入模型。导入它们具有副作用,即填充SQLAlchemy在后台使用的某些数据结构。如果db.create_all()发生在SQLAlchemy尚未了解模型之前,它就认为无事可做。

尝试以下操作:在db.create_all()中,删除__init__.py并将with app.appcontext(): db.create_all()添加到底部。然后将管理命令添加到import models。看起来像

run.py

然后

app = create_app()

@app.cli.command()
def createdb():
    db.create_all()

将创建表。

答案 1 :(得分:0)

我无法重现您的问题,但这对我有用。

在您的应用文件夹中:     python3 -m venv venv     来源venv / bin / activate     pip安装烧瓶flask_sqlalchemy     pip install -e。     烧瓶运行

__init__.py

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile("../config.py")

    db.init_app(app)
    with app.app_context():
        db.create_all()

        import auth
        app.register_blueprint(auth.routes.auth, url_prefix="/auth/")

        return app 

setup.py

from setuptools import setup

setup(
    name='yourapplication',
    include_package_data=True,
    install_requires=[
        'flask',
        ],
    )

auth / __init__.py

from flask import Flask, Blueprint

import auth.routes
import auth.models

auth / models.py

from flask import Flask, Blueprint
from app import db
from auth.models import Researcher

auth = Blueprint("auth", __name__)

@auth.route("/insert")
def insert():
    #r = Reasearcher("Pat","Den", "Pat_Den@mail.com", "operator","Dr.","Mr", "08611111", "+353", "0001")
    r = Researcher("Dr.","Mr", "08611111", "+353", "0001")
    db.session.add(r)
    db.session.commit()

    @auth.route("/query")
    def query():
        rs = Researcher.query.all()
        s = ""
        for r in rs:
            s += r.prefix + " " + r.phone
            return s

auth / routes.py

from flask import Flask, Blueprint
from app import db
from auth.models import Researcher

auth = Blueprint("auth", __name__)

@auth.route("/insert")
def insert():
    #r = Reasearcher("Pat","Den", "Pat_Den@mail.com", "operator","Dr.","Mr", "08611111", "+353", "0001")
    r = Researcher("Dr.","Mr", "08611111", "+353", "0001")
    db.session.add(r)
    db.session.commit()

    @auth.route("/query")
    def query():
        rs = Researcher.query.all()
        s = ""
        for r in rs:
            s += r.prefix + " " + r.phone
            return s