Skip to content

Instantly share code, notes, and snippets.

@rudyryk
Last active August 29, 2015 14:07
Show Gist options
  • Save rudyryk/1ad3e6c694acb47efa60 to your computer and use it in GitHub Desktop.
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
# 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)
@rudyryk
Copy link
Author

rudyryk commented Oct 20, 2014

For Python2.x just update the lines below.

Class declaration:

class AuthRequiredMixin(object):
   ...

In StaticPagesView .__init__:

super(StaticPagesView, self).__init__(*args, **kwargs)

@rudyryk
Copy link
Author

rudyryk commented Oct 20, 2014

For both compatible 2.x and 3.x code just use future module.

from future.builtins import super
# and use super().__init__() in 2.x!

And class AuthRequiredMixin(object) declaration is valid in Python 3.x as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment