Commit 1e0c4211 authored by Serge S. Koval's avatar Serge S. Koval

Documentation and style changes.

parent ba6af781
# -*- coding: utf-8 -*-
#
# flask-adminex documentation build configuration file, created by
# sphinx-quickstart on Tue Nov 01 18:35:30 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'flask-adminex'
copyright = u'2012, Serge S. Koval'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.0.1'
# The full version, including alpha/beta/rc tags.
release = '0.0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'flask-adminex'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'flask-adminex', u'Flask-AdminEx documentation',
u'Serge S. Koval', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'flask-adminex', u'Flask-AdminEx documentation',
[u'Serge S. Koval'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'flask-adminex', u'Flask-AdminEx documentation',
u'Serge S. Koval', 'Flask-AdminEx', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}
Flask-AdminEx
=============
Flask-AdminEx is simple and extensible administrative interface framework for `Flask <http://flask.pocoo.org/>`_.
Topics
------
.. toctree::
:maxdepth: 2
quickstart
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
Quick Start
===========
This page gives quick introduction to Flask-AdminEx library. It is assumed that reader has some prior
knowledge of Flask framework.
Introduction
------------
While developing the library, I had set of goals which should make it very easy to use and won't
require monkey patching to achieve desired functionality. Here they are:
1. It should be flexible
2. It should be reusable
3. It should look nice
Library uses one simple, but powerful concept - administrative pieces are grouped by functionality
into classes with their own view methods.
Here is absolutely valid administrative piece::
class MyAdminView(BaseView):
@expose('/')
def index(self):
return render_template('admin/myindex.html', view=self)
@expose('/test/')
def test(self):
return render_template('admin/test.html', view=self)
With this approach, all of OOP concepts apply. You can derive, you can modify behavior, you can do
whatever you want.
Initialization
--------------
You must create `Admin` class and associate it with the `Flask` application::
from flask import Flask
from flask.ext.adminex import Admin
app = Flask(__name__)
admin = Admin()
admin.setup_app(app)
app.run()
If you will run this application and will navigate to `http://localhost:5000/admin/ <http://localhost:5000/admin/`_,
you should see lonely Home page with a navigation bar on top.
Adding first view
-----------------
Now, lets add custom view::
from flask import Flask
from flask.ext.adminex import Admin, BaseView
class MyView(BaseView):
@expose('/')
def index(self):
return self.render('index.html')
app = Flask(__name__)
admin = Admin()
admin.add_view(MyView(name='Hello'))
admin.setup_app(app)
app.run()
If you will run this example, you will see that menu has two items: Home and Hello. If you click on the Hello menu
item, application will crash, as you did not create 'index.html' template.
Create templates directory and create new index.html file with following contents::
{% extends 'admin/master.html' %}
{% block body %}
Hello World from MyView!
{% endblock %}
All administrative pages should derive from the 'admin/master.html' to maintain same look and feel.
If you will refresh 'Hello' administrative page again you should see greeting in the content section.
Authentication
--------------
By default, administrative interface will be visible to everyone, as Flask-AdminEx does not make
any assumptions about authentication system you're using.
If you want to control who can access administrative views and who can not, derive from the
administrative view class and implement `is_accessible` method::
class MyView(BaseView):
def is_accessible(self):
return login.current_user.is_authenticated()
Menu is generated dynamically, so you can implement policy based security, so some users will see
some of the administrative interface, others won't be able to, etc.
Generating URLs
---------------
Internally, these view classes work on top of Flask blueprints, so you can use `url_for` with a dot
prefix to get URL to a local view::
class MyView(BaseView):
@expose('/')
def index(self)
# Get URL for the `test` view method
url = url_for('.test')
return self.render('index.html', url=url)
@expose('/test/')
def test(self):
return self.render('test.html')
If you want to generate URL to the particular view method from outside, following rules apply:
1. You have ability to override endpoint name by passing `endpoint` parameter to the view class
constructor::
admin = Admin()
admin.add_view(MyView(endpoint='testadmin'))
admin.setup_app(app)
In this case, you can generate links by concatenating view method name with a endpoint::
url_for('testadmin.index')
2. If you don't override endpoint name, it will use lower case class name. For previous example,
code to get URL will look like::
url_for('myview.index')
3. For model-based views rule is different - it will take model class name, if endpoint name
is not provided. Model-based views will be explained in the next section.
Model Views
-----------
Flask-AdminEx comes with built-in SQLAlchemy model administrative interface. It is very easy to use it::
from flask.ext.adminex.ext.sqlamodel import ModelBase
from flask.ext.sqlalchemy import db
# Flask and Flask-SQLAlchemy initialization here
admin = Admin()
admin.add_view(ModelBase(User, db.session, name='Users'))
admin.setup_app(app)
This will create administrative interface for `User` model with default settings.
If you want to customize model views, you have two options:
1. Change behavior by overriding public properties that control how these views work
2. Change behavior by overriding view methods
For example, if you want to disable model creation, show only 'login' and 'email' columns in the list view,
you can do something like this::
class UserView(ModelBase):
# Disable model creation
can_create = False
# Override displayed fields
list_columns = ('login', 'email')
def __init__(self, session):
__super__(MyView, self).__init__(User, session)
admin = Admin()
admin.add_view(UserView(db.session))
admin.setup_app(app)
It is very easy to add support for different database backends (Mongo, etc) by inheriting from `BaseModelView`
class and implementing database-related methods.
Examples
--------
Flask-AdminEx comes with three samples:
- Simple administrative interface with custom administrative views
- Sample model view interface
- Flask-Login integration sample
......@@ -7,17 +7,17 @@ from flask.ext import adminex
class MyAdminView(adminex.BaseView):
@adminex.expose('/')
def index(self):
return render_template('myadmin.html', view=self)
return self.render('myadmin.html')
class AnotherAdminView(adminex.BaseView):
@adminex.expose('/')
def index(self):
return render_template('anotheradmin.html', view=self)
return self.render('anotheradmin.html')
@adminex.expose('/test/')
def test(self):
return render_template('test.html', view=self)
return self.render('test.html')
# Create flask app
......@@ -35,7 +35,7 @@ if __name__ == '__main__':
admin = adminex.Admin()
admin.add_view(MyAdminView(category='Test'))
admin.add_view(AnotherAdminView(category='Test'))
admin.apply(app)
admin.setup_app(app)
# Start app
app.debug = True
......
......@@ -76,7 +76,7 @@ if __name__ == '__main__':
admin.add_view(PostAdmin(db.session))
# Associate with an app
admin.apply(app)
admin.setup_app(app)
# Create DB
db.create_all()
......
......@@ -146,6 +146,20 @@ class BaseView(object):
return self.blueprint
def render(self, template, **kwargs):
"""
Render template
`template`
Template path to render
`kwargs`
Template arguments
"""
# Store
kwargs['admin_view'] = self
return render_template(template, **kwargs)
def _prettify_name(self, name):
"""
Prettify class name by splitting name by capital characters. So, 'MySuperClass' will look like 'My Super Class'
......@@ -195,7 +209,7 @@ class AdminIndexView(BaseView):
@expose('/')
def index(self):
return render_template('admin/index.html', view=self)
return self.render('admin/index.html')
class MenuItem(object):
......
from flask import request, url_for, render_template, redirect
from flask import request, url_for, redirect
from .base import BaseView, expose
......@@ -426,8 +426,7 @@ class BaseModelView(BaseView):
def get_value(obj, field):
return getattr(obj, field, None)
return render_template(self.list_template,
view=self,
return self.render(self.list_template,
data=data,
# List
list_columns=self._list_columns,
......@@ -461,7 +460,7 @@ class BaseModelView(BaseView):
if self.create_model(form):
return redirect(return_url or url_for('.index_view'))
return render_template(self.create_template, view=self, form=form)
return self.render(self.create_template, form=form)
@expose('/edit/<int:id>/', methods=('GET', 'POST'))
def edit_view(self, id):
......@@ -484,8 +483,7 @@ class BaseModelView(BaseView):
if self.update_model(form, model):
return redirect(return_url or url_for('.index_view'))
return render_template(self.edit_template,
view=self,
return self.render(self.edit_template,
form=form,
return_url=return_url or url_for('.index_view'))
......
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% if view.category %}{{ view.category }} - {% endif %}{{ view.name }} - {{ view.admin.name }}{% endblock %}</title>
<title>{% block title %}{% if admin_view.category %}{{ admin_view.category }} - {% endif %}{{ admin_view.name }} - {{ admin_view.admin.name }}{% endblock %}</title>
{% block head_meta %}
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
......@@ -20,9 +20,9 @@
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<span class="brand">{{ view.admin.name }}</span>
<span class="brand">{{ admin_view.admin.name }}</span>
<ul class="nav">
{% for item in view.admin.menu() %}
{% for item in admin_view.admin.menu() %}
{% if item.is_category() %}
{% set children = item.get_children() %}
{% if children %}
......
......@@ -9,7 +9,7 @@
{% set column = 0 %}
{% for c, name in list_columns %}
<th>
{% if view.is_sortable(c) %}
{% if admin_.is_sortable(c) %}
{% if sort_column == column %}
<a href="{{ sort_url(column, True) }}">
{{ name }}
......@@ -33,12 +33,12 @@
{% for row in data %}
<tr>
<td>
{%- if view.can_edit -%}
{%- if admin_.can_edit -%}
<a href="{{ url_for('.edit_view', id=row.id, return=return_url) }}">
<i class="icon-pencil"></i>
</a>
{%- endif -%}
{%- if view.can_delete -%}
{%- if admin_.can_delete -%}
<a href="{{ url_for('.delete_view', id=row.id, return=return_url) }}" onclick="return confirm('You sure you want to delete this item?')">
<i class="icon-remove"></i>
</a>
......@@ -51,7 +51,7 @@
{% endfor %}
</table>
{{ lib.pager(page, num_pages, pager_url) }}
{% if view.can_create %}
{% if admin_.can_create %}
<a class="btn btn-primary btn-large" href="{{ url_for('.create_view', return=return_url) }}">Create New</a>
{% endif %}
{% endblock %}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment