Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access app.config in a blueprint?

Tags:

flask

I am trying to access access application configuration inside a blueprint authorisation.py which in a package api. I am initializing the blueprint in __init__.py which is used in authorisation.py.

__init__.py

from flask import Blueprint api_blueprint = Blueprint("xxx.api", __name__, None) from api import authorisation 

authorisation.py

from flask import request, jsonify, current_app  from ..oauth_adapter import OauthAdapter from api import api_blueprint as api  client_id = current_app.config.get('CLIENT_ID') client_secret = current_app.config.get('CLIENT_SECRET') scope = current_app.config.get('SCOPE') callback = current_app.config.get('CALLBACK')  auth = OauthAdapter(client_id, client_secret, scope, callback)   @api.route('/authorisation_url') def authorisation_url():     url = auth.get_authorisation_url()     return str(url) 

I am getting RuntimeError: working outside of application context

I understand why that is but then what is the correct way of accessing those configuration settings?

----Update---- Temporarily, I have done this.

@api.route('/authorisation_url') def authorisation_url():     client_id, client_secret, scope, callback = config_helper.get_config()     auth = OauthAdapter(client_id, client_secret, scope, callback)     url = auth.get_authorisation_url()     return str(url) 
like image 567
Chirdeep Tomar Avatar asked Aug 13 '13 16:08

Chirdeep Tomar


People also ask

What is flask_ ENV?

The environment is used to indicate to Flask, extensions, and other programs, like Sentry, what context Flask is running in. It is controlled with the FLASK_ENV environment variable and defaults to production . Setting FLASK_ENV to development will enable debug mode.

What is the use of blueprint in flask?

Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. Blueprints can greatly simplify how large applications work and provide a central means for Flask extensions to register operations on applications.


2 Answers

Use flask.current_app in place of app in the blueprint view.

from flask import current_app  @api.route("/info") def get_account_num():     num = current_app.config["INFO"] 

The current_app proxy is only available in the context of a request.

like image 105
weihuang Avatar answered Sep 21 '22 03:09

weihuang


Overloading record method seems to be quite easy:

api_blueprint = Blueprint('xxx.api',  __name__, None) api_blueprint.config = {}  @api_blueprint.record def record_params(setup_state):   app = setup_state.app   api_blueprint.config = dict([(key,value) for (key,value) in app.config.iteritems()]) 
like image 38
Ashalynd Avatar answered Sep 17 '22 03:09

Ashalynd