0

我尝试在 MVC 结构的 Quart 应用程序中实现 Flask-SqlAlchemy。所以我希望每个模型都有它的文件和功能。

这是我的文件:
app.py

__package__ = 'nini'

from .setups import create_app
from .db import db

if __name__ == '__main__':
    app = create_app()
    db.init_app(app)

    app.run(host='127.0.0.1', debug=True)

数据库.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

tests.py模型文件

from nini.db import db
import datetime


class Test(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.VARCHAR)
    created = db.Column(db.DATETIME, default=datetime.datetime.now())
    pass

    def __init__(self, text):
        self.text = text

    def __repr__(self):
        return '<Test %r>' % self.id, self.created

    @classmethod
    async def create_new(cls, **kw):
        obj = cls(**kw)
        db.session.add(obj)
        db.session.commit()
        pass

测试.py

import logging

from quart import jsonify, app, current_app
from quart_openapi import PintBlueprint
from datetime import datetime

from nini.models import tests
from nini.db import db

results = PintBlueprint('test', __name__)


@results.route('/test/test')
async def get_tests():
    logging.error("HELLO")
    t = await tests.Test.create_new(text="TT")
    logging.error("Done")
    return jsonify(t), 200

当我运行/test/test路径时,它工作正常,直到 `db.session.add(obj)1 行。然后我得到这个错误:

RuntimeError:未找到应用程序。在视图函数中工作或推送应用程序上下文。请参阅 http://flask-sqlalchemy.pocoo.org/contexts/。信息:quart.serving:127.0.0.1:50537 GET /test/test 1.1 500 - 21836

我尝试在以下位置添加此代码app.py

db.init_app(app) ### This line was already in my code
with app.app_context():
        db.create_all()

也像这样:

db.init_app(app) ### This line was already in my code
app.app_context().push():
db.create_all()

我还尝试create_newtasts.py上下文中运行。尝试在create_all内部实现和测试模型db.py

基本上,db.init_app(app)每当我使用后,db我都会收到错误消息。

很想得到一些帮助。

4

0 回答 0