I try to implement Flask-SqlAlchemy in a Quart application it MVC structure. So I want every Model Have its file and functions.
This is my files:
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)
db.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
tests.py Model file
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
test.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
When I run /test/test
path it works fine until `db.session.add(obj)1 line.
Then I get this error:
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/. INFO:quart.serving:127.0.0.1:50537 GET /test/test 1.1 500 - 21836
I tried adding this code at app.py
:
db.init_app(app) ### This line was already in my code
with app.app_context():
db.create_all()
Also like this:
db.init_app(app) ### This line was already in my code
app.app_context().push():
db.create_all()
I also tried running create_new
at tasts.py
with context.
Tried implementing the create_all
and test model inside db.py
Basically after db.init_app(app)
whenever I use db
I get the error.
Would love for some help.