Created
September 20, 2016 17:47
-
-
Save doobeh/2c46ad525bed2a92bf4581d74fda674d to your computer and use it in GitHub Desktop.
Context scopes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from flask import Flask, current_app, render_template_string | |
| from flask_sqlalchemy import SQLAlchemy | |
| app = Flask(__name__) | |
| db = SQLAlchemy(app) | |
| app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' | |
| class Example(db.Model): | |
| id = db.Column(db.Integer, primary_key=True) | |
| name = db.Column(db.String) | |
| def __repr__(self): | |
| return self.name | |
| @app.before_first_request | |
| def begin(): | |
| db.create_all() | |
| @app.route('/') | |
| def home(): | |
| print("I have an app context called {}".format(current_app.name)) | |
| db.session.add(Example(name='Alice')) | |
| db.session.commit() | |
| do_something() | |
| return render_template_string("{{ examples|join(', ')}}", examples=Example.query.all()) | |
| def do_something(): | |
| print("I still have context ({})".format(current_app.name)) | |
| print(current_app.name) | |
| db.session.add(Example(name='Bob')) | |
| db.session.commit() | |
| if __name__ == '__main__': | |
| app.run(debug=True, port=8882) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment