How to share object between blueprint in Flask

flask

Solution

The `g` object is only available between requests.

The quick and dirty way to solve this, is to add your `api` object into the global space where the Flask `app` is defined and then importing the `api` object from there.

Keep in mind that with multiple servers and concurrency, this object can get out of sync fairly quickly and should remain stateless.

See this project on github for an example

The preferred solution for this is to use a database that fits the needs of your object. Redis, MongoDB and PostgreSQL are some of the more common ones.

Problem

I have two blueprints, such as `auth` and `sprints`, the structure is as follows: ``` auth __init__.py views.py forms.py sprints __init__.py views.py forms.py ``` I want to share `api` object after login successfully ``` @auth.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): try: jira_url = app.config["JIRA_URL"] app_id = app.config["JIRA_APPID"] api = GreenHopper(options={"server": jira_url, "appid": 37}, basic_auth=(form.username.data, form.password.data)) g.api = api except JIRAError: api = None ... ... return redirect(request.args.get('next') or url_for('scrumworks.index')) return render_template('auth/login.html', form=form) ``` On the `sprints` blueprint, I want to get the `api` object like codes below: ``` @scrumworks.route("/sprints") @login_required def show_sprints(): if current_user.admin: sprints = g.api.sprints(37) return render_template("scrumworks/sprints.html") else: flash("Only admin users can access this page") return redirect(url_for(".index")) ``` When the codes run, it will complain AttributeError: '_AppCtxGlobals' object has no attribute 'api'. It seems the life cycle of `g` is per request, not global, so I can't store `api` in `g` Another choice is `session`, but the `api` object cannot be serializable, so it can't be stored in `session`, what should I do next? Any ideas? Thanks :-)

Original source