Flask Referencing understanding

i’m building a blog with flask to get used to the different modules, sqlalchemy, auth, current user, blueprints, uploads/downloads etc

when i use blueprints my directory structure would be as follows


i create the app in app.py, and the blueprints in views.py and other_views.py and register the blueprints in app.py all fine and working

to get uploads working i need

path = ‘path/to/uploads’
app.config[‘uploads’] = path

in app.py

when i

return send_from_directory(app.config[“uploads”], name)

app is not defined as its in app.py rather than the views.py

i worked around this by just providing the path directly

return send_from_directory(’/path/to/uploads’, name)

would that be a problem?
is there another way to get around this?

It sounds like you just need a config file you load:


Just load that and get the value from there, and don’t try to be fancy about it. Just load it right at the top of whatever file you have this function in.

so for instance


class configs():

    def __init__(self):
        self.config = {'uploads': '/path/to/uploads'}


import config

app = config.configs()

def download_file(name):
    return send_from_directory(app.config['uploads'], name)

so is this what we are essentially doing when we use the Flask app.config? pushing the information to a config file within flask?

uploads = '/path/to/uploads'
app = Flask(__name__)
app.config['SECRET_KEY'] = 'helloworld'
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///data.db'
app.config['UPLOADS'] = uploads

Yes, that’s all you’re doing. I think though you might be missing a key thing that’s important about Python:

You can put any variable in a .py file and then import it directly. NO need to triple wrap it in a class. That means you could just do:

config.configs = { "uploads": "/path/to/uploads"}

But, you could also just do:

uploads = "/path/to/uploads"

Right in config.py, then just import that and use it directly rather than config.configs.uploads.

Basically, modules are dicts already, and objects are dicts already, so no need to put your dict inside an object inside a module.

P.S. If anyone tells you that objects/classes/modules are not dicts then ask them why they have a dict variable, or why globals() returns a dict. They’re just dicts with fancy syntax tacked on.

Thanks zed, so its just a question of utility then?

for a small application just for yourself you could just declare a variable in the file and use that, for larger applications where you want to be able to define something that can be changed easily by the end user.

you would use a config file and import that so things like categories, nav links, directory paths which are custom could be changed to suit without having to find each reference in the full application?

Yep, basically that’s what you’d do.

1 Like