How to reference create_app from different sub-domain?

57 views Asked by At

The relevant part of my app structure looks like the following:

hp/
|
|---app/
     |---admin/
     |---auth/
     |---errors/
     |---main/
     |---__init__.py
     |---email.py
     |---models.py
     |---search.py
|---config.py
|---quiz.py

I want to create a scripts/ domain in either hp/ or app/. In those scripts I need to be able to reference config values. I'm using dotenv to do that. In order to use dotenv, I need app to be available so that I can call app.config['CONFIG_NAME'].

Here's more or less what I'm trying to do:

import requests
from app import app

access_key = app.config['ACCESS_KEY']
secret_key = app.config['SECRET_KEY']

data = requests.get(f'https://api.foo.com/search?client_id={access_key}&page=1&query=foo').json()

If I try from app import app, as I have above, I get a ModuleNotFoundError: No module named 'app' error. If I try from .. import app I get a ValueError: attempted relative import beyond top-level package error.

Any guidance/advice is greatly appreciated!

1

There are 1 answers

0
Zach Rabin On BEST ANSWER

I ended up solving this by changing the sys.path.

I added the following:

import sys
import os
import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
appdir = os.path.dirname(currentdir)
hpdir = os.path.dirname(appdir)
sys.path.insert(0, hpdir)
from app import create_app

app = create_app()

After that I was able to successfully call app.config