app.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from flask import Flask
  2. from flask_sqlalchemy import SQLAlchemy
  3. from sqlalchemy.ext.hybrid import hybrid_property
  4. import flask_admin as admin
  5. from flask_admin.contrib import sqla
  6. # Create application
  7. app = Flask(__name__)
  8. # Create dummy secrey key so we can use sessions
  9. app.config['SECRET_KEY'] = '123456790'
  10. # Create in-memory database
  11. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sample_db_2.sqlite'
  12. app.config['SQLALCHEMY_ECHO'] = True
  13. db = SQLAlchemy(app)
  14. # Flask views
  15. @app.route('/')
  16. def index():
  17. return '<a href="/admin/">Click me to get to Admin!</a>'
  18. class Screen(db.Model):
  19. __tablename__ = 'screen'
  20. id = db.Column(db.Integer, primary_key=True)
  21. width = db.Column(db.Integer, nullable=False)
  22. height = db.Column(db.Integer, nullable=False)
  23. @hybrid_property
  24. def number_of_pixels(self):
  25. return self.width * self.height
  26. class ScreenAdmin(sqla.ModelView):
  27. """ Flask-admin can not automatically find a hybrid_property yet. You will
  28. need to manually define the column in list_view/filters/sorting/etc."""
  29. column_list = ['id', 'width', 'height', 'number_of_pixels']
  30. column_sortable_list = ['id', 'width', 'height', 'number_of_pixels']
  31. # Flask-admin can automatically detect the relevant filters for hybrid properties.
  32. column_filters = ('number_of_pixels', )
  33. # Create admin
  34. admin = admin.Admin(app, name='Example: SQLAlchemy2', template_mode='bootstrap3')
  35. admin.add_view(ScreenAdmin(Screen, db.session))
  36. if __name__ == '__main__':
  37. # Create DB
  38. db.create_all()
  39. # Start app
  40. app.run(debug=True)