¡Esta es una revisión vieja del documento!
There are several ways to set configuration:
app = Flask(__name__) # Using app.config app.config['DEBUG'] = True # Just debug (and few more) allow to configure like this: app.debug = True # Updating multiple app.config.update( DEBUG=True, SECRET_KEY='...' ) # From a file app.config.from_object('yourapplication.default_settings') # From an environment var: # $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg # $ python run-app.py app.config.from_envvar('YOURAPPLICATION_SETTINGS')
It would be a config file:
# Example configuration DEBUG = False SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'
You can use a default config that is always loaded and part of the version control, and a separate configuration that overrides the values as necessary as mentioned in the example above:
app = Flask(__name__) app.config.from_object('yourapplication.default_settings') app.config.from_envvar('YOURAPPLICATION_SETTINGS')
If you do not want an error when load the config:
app.config.from_envvar('PERSONAL_WEBPAGE_SETTINGS', silent=True)
Another pattern is to use a class:
class Config(object): DEBUG = False TESTING = False DATABASE_URI = 'sqlite://:memory:' class ProductionConfig(Config): DATABASE_URI = 'mysql://user@localhost/foo' class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True # To enable such a config you just have to call into from_object(): app.config.from_object('configmodule.ProductionConfig')
When you locate the static files (js, css…) in static/ folder you can automatically access them like <img src='/static/images/logo.png'>.
However you can change it providing a parameter static_folder to the application object, even changing the path with static_url_path parameter:
app = Flask(__name__, static_folder='/path/to/static/folder', static_url_path='/differentstatic')
Then: <img src='/differentstatic/logo.png'>
@app.route('/users/') def show_users(page): users = User.query.all() return render_template('users.html', users=users)
You can create an external file views.py and add there all the logic:
from yourapplication import app @app.route('/') def index(): return 'Hello World!'
Also you can create a global instance of your class and route your rules to it:
class X(object): # Your code here INSTANCE_X = X() # Note that we are not *calling* the methods app.add_url_rule('/x/', view_func=INSTANCE_X.route1) app.add_url_rule('/y/', view_func=INSTANCE_X.route2)
You can use view_func:
def handle_route2(): return X().route2() app.add_url_rule('/y/', view_func=handle_route2)
app.debug = True.@app.route('/') def root(): register_ip(request.remote_addr) return redirect(url_for('static', filename='resume.html'))
url_for(folder, file) will return the url for that file in that folder.