Integration with flask

Since Pony 0.7.4 we added support for comfortable using PonyORM with Flask. With pony.flask.Pony you can wrap your flask’s application’s request with db_session automatically right way.

  1. from flask import Flask
  2. from pony.flask import Pony
  3. app = Flask(__name__)
  4. Pony(app)

With this code each of view function you will define will be wrapped with db_session so you should not care about them.

Flask-Login

Also you can easily use Flask-Login extension.

Example

  1. from flask import Flask, render_template
  2. from flask_login import LoginManager, UserMixin, login_required
  3. from pony.flask import Pony
  4. from pony.orm import Database, Required, Optional
  5. from datetime import datetime
  6. app = Flask(__name__)
  7. app.config.update(dict(
  8. DEBUG = False,
  9. SECRET_KEY = 'secret_xxx',
  10. PONY = {
  11. 'provider': 'sqlite',
  12. 'filename': 'db.db3',
  13. 'create_db': True
  14. }
  15. ))
  16. db = Database()
  17. class User(db.Entity, UserMixin):
  18. login = Required(str, unique=True)
  19. password = Required(str)
  20. last_login = Optional(datetime)
  21. db.bind(**app.config['PONY'])
  22. db.generate_mapping(create_tables=True)
  23. Pony(app)
  24. login_manager = LoginManager(app)
  25. login_manager.login_view = 'login'
  26. @login_manager.user_loader
  27. def load_user(user_id):
  28. return db.User.get(id=user_id)

You can use LoginManager.current_user as User instance.

  1. @app.route('/friends')
  2. @login_required
  3. def friends():
  4. return render_template('friends.html', friends=current_user.friends)

You can run another example to check it

  1. python -m pony.flask.example