Flask and SQLAlchemy, an application not registered in the instance

I'm currently trying to build a small flash drive app. This is my structure.

run.py application __init__.py database.py models.py views.py 

database.py contains only the SQLAlchemy object:

 db = SQLAlchemy() 

Then I import it into my models.py to create my models. Finally, inside __init__.py I import db from database.py and do:

 from .database import db from flask import Flask app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///application.db' db.init_app(app) db.create_all() 

However, I cannot create tables from the models that appeared. If I remove db.create_all() . The application will work without problems, but, obviously, the database is not created. When db.create_all() present, I get "RuntimeError: an application not registered on the db instance and the application is not bound to the current context."

I was honestly confused, because before I had problems running the application without creating a database, but moving db to its own file seems to somehow fix this problem. Now there remains only the problem of creating the database.

Can someone tell me what could be the problem? I am sincerely dead end.

+5
source share
1 answer

The answer is here: http://flask-sqlalchemy.pocoo.org/latest/api/#configuration

See the section on:

The difference between the two is that in the first case, methods like create_all () and drop_all () will work all the time, but in the second case, the flask .Flask.request_context () should exist.

Here's more info: http://flask-sqlalchemy.pocoo.org/latest/contexts/

If all of this is confusing (probably due to the rather complex Flask function), the short short version of db.init_app(app) modifies the app object, but doesn't change anything in the db object. This is special because more than one app can fly, and db may have to talk to all of them. (I said this is an advanced feature.)

Therefore, when you call db.create_all() without having a live request (which creates a global one that has the current current app ), it does not know what to connect to and the bombs. What does the error mean.

In your case, I would put the SQLAlchemy call in __init__.py and pass it the app , which is the easiest way:

 db = SQLAlchemy(app) 

Or keep everything as it is and run the setup before the first request:

 @app.before_first_request def create_database(): db.create_all() 

I hope this helps! Let me know if you have any problems.

+8
source

Source: https://habr.com/ru/post/1205244/


All Articles