Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

python - Change static folder from config in Flask

Has anyone tried this snippet flask config based static folder code cnippet?

The code:

import flask
class MyFlask(flask.Flask):
    @property
    def static_folder(self):
        if self.config.get('STATIC_FOLDER') is not None:
            return os.path.join(self.root_path, 
                self.config.get('STATIC_FOLDER'))
    @static_folder.setter
    def static_folder(self, value):
        self.config.get('STATIC_FOLDER') = value

# Now these are equivalent:
app = Flask(__name__, static_folder='foo')

app = MyFlask(__name__)
app.config['STATIC_FOLDER'] = 'foo'

In my case in complains about this line:

self.config.get('STATIC_FOLDER') = value

The error message: Can't assign to function call

Does anyone how to set the static_folder from the config.py file in Flask?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okay, I assume you want to use a custom path to the static folder for whatever reason. I wanted to do the same for the sake of better app modularity.

Here's my app folder structure:

instance/
core/
  |_templates/
  |_static/
  |_views.py
run.py
config.py

As you can see, my static folder is inside the core folder.

In run.py, you can do the following:

app = Flask(__name__, static_url_path=None)

if __name__ == '__main__':
    app.config.from_object('config')

    # config file has STATIC_FOLDER='/core/static'
    app.static_url_path=app.config.get('STATIC_FOLDER')

    # set the absolute path to the static folder
    app.static_folder=app.root_path + app.static_url_path

    print(app.static_url_path)
    print(app.static_folder)

    app.run(
        host=app.config.get('HOST'),
        port=app.config.get('PORT'),
        threaded=True
        )

This is what I did, and it works perfectly fine. I'm using flask 0.12.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...