Last active
August 29, 2015 14:07
-
-
Save rudyryk/1ad3e6c694acb47efa60 to your computer and use it in GitHub Desktop.
Flask-Admin simple helpers: require login mixing, serving protected static pages. Snippet is written for Python 3.x
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
# No Rights Reserved | |
# http://creativecommons.org/publicdomain/zero/1.0/ | |
""" | |
Flask-Admin simple helpers | |
========================== | |
Just copy and paste to some of your helpers or base classes module, import and use. | |
You'll also need to install Flask-Login for using authentication. | |
Example for `AuthRequiredMixin` is `StaticPagesView` class itself. | |
Example for `StaticPagesView`:: | |
# ... Flask admin setup ... | |
docs_home_dir = '/home/user/project/docs' | |
admin.add_view(StaticPagesView(name='Docs', url='docs', home=docs_home_dir)) | |
Cheers! | |
""" | |
from werkzeug.exceptions import NotFound | |
from flask import send_from_directory | |
from flask.ext import admin | |
from flask.ext import login | |
class AuthRequiredMixin: | |
""" Mixin for Flask-Admin views to require login. | |
""" | |
def is_accessible(self): | |
return login.current_user.is_authenticated() | |
class StaticPagesView(AuthRequiredMixin, admin.BaseView): | |
""" Flask-Admin view to serve protected static pages. | |
""" | |
def __init__(self, *args, **kwargs): | |
self.home = kwargs.pop('home').rstrip('/') | |
super().__init__(*args, **kwargs) | |
@admin.expose('/') | |
def index(self): | |
return self.pages('') | |
@admin.expose('/<path:page>') | |
def pages(self, page): | |
if not page or page.endswith('/'): | |
index_file = page and ('%s/index.html' % page.strip('/')) or 'index.html' | |
return send_from_directory(self.home, index_file) | |
else: | |
return send_from_directory(self.home, page) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For both compatible 2.x and 3.x code just use future module.
And
class AuthRequiredMixin(object)
declaration is valid in Python 3.x as well.