Tengo una aplicación Flask que usa sqlite.
Tengo una aplicación web simple que tomará la información del usuario y la almacenará en tablas sqlite.
El problema que tengo es intentar acceder a la base de datos sqlite en otros archivos que forman parte de la aplicación web.
Estoy usando el flujo de fábrica de aplicaciones en el tutorial .
Cuando intento acceder a la base de datos en otro archivo, aparece un error de contexto.
from flaskr.db import get_db def get_data_from_db(): db = get_db() user_from_db = db.execute( 'SELECT name' ' FROM user ' ).fetchall() return user_from_dbCuando hago esto, dice que estoy fuera del contexto.
2021-07-07T22:28:20.111376+00:00 app[clock.1]: File "/app/flaskr/alerts.py", line 25, in get_data_from_db 2021-07-07T22:28:20.111583+00:00 app[clock.1]: db = get_db() 2021-07-07T22:28:20.111612+00:00 app[clock.1]: File "/app/flaskr/db.py", line 9, in get_db 2021-07-07T22:28:20.111809+00:00 app[clock.1]: if 'db' not in g: 2021-07-07T22:28:20.111839+00:00 app[clock.1]: File "/app/.heroku/python/lib/python3.9/site-packages/werkzeug/local.py", line 422, in __get__ 2021-07-07T22:28:20.112208+00:00 app[clock.1]: obj = instance._get_current_object() 2021-07-07T22:28:20.112236+00:00 app[clock.1]: File "/app/.heroku/python/lib/python3.9/site-packages/werkzeug/local.py", line 544, in _get_current_object 2021-07-07T22:28:20.112638+00:00 app[clock.1]: return self.__local() # type: ignore 2021-07-07T22:28:20.112666+00:00 app[clock.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/globals.py", line 40, in _lookup_app_object 2021-07-07T22:28:20.112866+00:00 app[clock.1]: raise RuntimeError(_app_ctx_err_msg) 2021-07-07T22:28:20.112936+00:00 app[clock.1]: RuntimeError: Working outside of application context.¿Cómo consigo que esto esté en contexto para poder acceder a la base de datos?
aquí está el repositorio y la rama en la que estoy trabajando. https://github.com/besteman/futurama-mining/tree/first-pass-web-app Básicamente, quiero tener este archivo con la conexión DB: https://github.com/besteman/futurama-mining/ blob/first-pass-web-app/flaskr/alerts.py#L26-L36
Puede crear un archivo extensions.py y agregarlo allí, e init_app en la función create_app:
extensions.py :
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() # other extensions, ( if you have ) app.py :
from flask import Flask from extensions import db from blueprints.example_blueprint_ import example_blueprint def create_app(): app = Flask(__name__) db.init_app(app) # you can do any blueprint registration if any: # app.register_blueprint(example_blueprint) return app app = create_app() app.app_context().push() from db_models import whatever_db_models db.create_all() blueprints/example_blueprint_.py :
from flask import Blueprint from extensions import db from db_models import model example_blueprint = Blueprint(__name__) @example_blueprint.route("/example") def test(): # An Example db.session.query(model).filter(condition).update({field_to_update: value_to_be_updated})Entonces su estructura de archivos podría ser así:
- app.py - extensions.py - db_models.py - blueprints - example_blueprint_.pyNo necesitas esa función, get_from_db