Monday, 12 July 2021

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



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

No comments:

Post a Comment