Justin Besteman
Justin Besteman

Reputation: 398

With Flask and SQLite, access database out side of web app

I have a Flask app that is using sqlite.

I have a simple web app that will take in user info and store it into sqlite tables.

The issue that I am having is trying to access the sqlite database in other files that are part of the web app.

I am using the application factory flow in the tutorial

When I try to access the database in another file, I get a context error.

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_db

When I do this, it says that I am outside the context.

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.

How do I get this to be in context so that I can access the db?

here is the repo and the branch I am working on. https://github.com/besteman/futurama-mining/tree/first-pass-web-app Basically, I want to have this file with the DB connection: https://github.com/besteman/futurama-mining/blob/first-pass-web-app/flaskr/alerts.py#L26-L36

Upvotes: 2

Views: 1000

Answers (1)

Hridaya Agrawal
Hridaya Agrawal

Reputation: 325

You can create an extensions.py file and add it there, and init_app in the create_app function:

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})

So your file structure could be like this:

- app.py
- extensions.py
- db_models.py
- blueprints
     - example_blueprint_.py

You don't need that function, get_from_db

Upvotes: 3

Related Questions