"""app.views.database==================Admin page initialized with models for reading and writing."""from__future__importannotationsfromflaskimportFlaskfromflask_adminimportAdmin,AdminIndexView,exposefromflask_admin.contribimportsqlafromflask_loginimportcurrent_user,login_requiredfromwerkzeugimportResponsefromapp.extensionsimportdbfromapp.modelsimportMessage,Notification,Post,Task,Userfromapp.views.securityimportadmin_required_INDEX="index"class_MyModelView(sqla.ModelView):def__init__(self,model:db.Model,session:db.session# type: ignore)->None:super().__init__(model,session)self.endpoint=f"{model.__table__}s"defis_accessible(self)->None:"""Only allow access if user is logged in as admin."""returncurrent_user.is_authenticatedandcurrent_user.admin
[docs]classMyAdminIndexView(AdminIndexView):"""Custom index view that handles login / registration."""
[docs]@expose("/")@login_required@admin_requireddefindex(self)->str|Response:"""Requires user be logged in as admin. :return: Admin index page. """returnsuper().index()
[docs]definit_app(app:Flask)->None:"""Add models to admin view. Not consistent with the application factory pattern for ``Flask`` extensions, however, the ``Admin`` object does not integrate into the application well as a global singleton. While running ``pytest``, ``Admin`` will be called multiple times and the following will be raised: ValueError: The name 'user' is already registered for a different blueprint. Use 'name=' to provide a unique name. See https://stackoverflow.com/questions/18002750 :param app: Application object. """admin=Admin(app,index_view=MyAdminIndexView(endpoint="database",url="/database"),base_template="/database.html",template_mode="bootstrap4",)admin.add_view(_MyModelView(User,db.session))admin.add_view(_MyModelView(Post,db.session))admin.add_view(_MyModelView(Message,db.session))admin.add_view(_MyModelView(Notification,db.session))admin.add_view(_MyModelView(Task,db.session))