Flask-Velox

Flask-Velox is a Flask extension designed to provide ready made View and Mixin classes to help rapidly build Flask applications for both public and admin systems, based on Flasks pluggable MethodView.

Here at SOON_ we use Flask a lot and we wanted a framework we could use across all our products. As our products and requirements grow so will Flask-Velox. It is early days but the absolute basics are there and we would love feedback and help to grow this further.

Todo

  • Unit Tests
  • Flask-Principal integration for Flask-Admin Views

Usage Documentation

Installation

Installation is simple, use your favourite PyPi package installer and install Flask-Velox, for example with pip:

pip install Flask-Velox

Integration with Flask

Next we need to integrate Flask-Velox into your Flask app, all you need to do is import the extenstion, insatiate the Velox class and call init_app with your application object. A simple example:

from flask import Flask
from flask.ext.velox import Velox

app = Flask(__name__)

velox = Velox()
velox.init_app(app)

app.run()

Quickstart

Flask-Velox is designed to be quick to use and easy to extend. Here you will see some basic examples of what Flask-Velox can do.

Concept

The idea behind Flask-Velox was to write a set of classes which can be mixed in together to build easily implimentable Flask MethodView pluggable views which could be used on the public and private admin systems.

See also

In Flask-Velox the mixin classes are king and they do all the hard work and heavy lifting, Views simply implement these mixin classes, you can see a full set of mixin classes in the API Reference.

This approach allows us to easily implement Views of various mixin configuration and create views for admin systems just as quickly.

Template View

The most common task any web application will need is to render a HTML document. The class is TemplateMixin the core class which almost all other views will implement in order to render a page of HTML. The TemplateView class is the simplest view which implements the TemplateMixin as well as the ContextMixin allowing us to pass context to our template.

Take this example:

from flask import Flask
from flask.ext.velox import Velox
from flask.ext.velox.views.template import TemplateView

app = Flask(__name__)

velox = Velox()
velox.init_app(app)

class HomeView(TemplateView):
    template = 'home.html'
    context = {
        'foo': 'bar'
    }

app.add_url_rule('/', view_func=HomeView.as_view('home'))

app.run()

The above example creates a HomeView class which extends the TemplateView which implements the TemplateMixin and ContextMixin. The View defines the template to render and some default context to use when rendering the template. All other bundled views with Flask-Velox follow a similar pattern.

Accessing View Argument

If your view takes keyword arguments these can also be accessed as attributes on the instance. For example, take these route:

app.add_url_rule('/<name>/', view_func=SomeView.as_view('name'))
app.add_url_rule('/<name>/<version>',
                 view_func=SomeView.as_view('name-version'))

The view takes 2 arguments, name and version, these are captured and can be accessed as attributes:

class SomeView(TemplateView):

    def set_context(self):
        self.add_context('name', self.name)
        self.add_context('version', self.version)

        super(TemplateView, self).set_context()

Forms

Rendering forms is another core component of any web application. Flask-Velox provides views which allow us to implement Flask-WTF forms in our views.

Form View

The FormView class allows us to render and process a Flask-WTF form:

from flask.ext.velox.views import forms
from yourapp.forms import FooForm

class MyFormView(forms.FormView):
    template = 'form.html'
    form = FooForm
    redirect_url_rule = 'some.rule'

The view above when called will render the form.html template, this is something you have to make yourself. The view will also pass the following context to the template:

  • form: The instantiated form class
  • submit_url_rule: By default this will be the views current endpoint
  • submit_url: A function to call in the template which generates the url

Remember you are inheriting existing provided functionality which means you can easily customise it by overriding methods, examples below.

Example Template

Here is how you might write a template for the above view. This assumes the current url rule is forms.foo which relates to url /forms/foo.

<form action="{{ submit_url(foo='bar') }}" method="POST">
    <ul>
        {% for field in form %}
        <li>{{ field.label }} {{ field }}</li>
        {% endfor %}
    </ul>
    <button type="submit">Submit</button>
</form>

In the above template the generated submit url would be /forms/foo?foo=bar.

Success Callback

If a form has successfully validated a call back function will be called. By default all this function does is issue a redirect. If you wish to alter this behaviour you can simply override the method:

class MyFormView(forms.FormView):
    ...

    def success_callback(self):
        form = self.get_form()
        # Do what ever you want
Redirect URL

Ofcourse you can also override the method use for generating the redirect_url as well, for example:

class MyFormView(forms.FormView):
    ...

    def success_callback(self):
        form = self.get_form()
        # Do what ever you want
        super(MyFormView, self).success_callback()  # Triggers redirect

    def redirect_url(self, **kwargs):
        return url_for('some.rule', foo='bar')

Multi Form View

Sometimes you want to render multiple forms on a page, this can be done with Flask-Velox by extending the MultiFromView like so:

from flask.ext.velox.views import forms
from yourapp.forms import FooForm, BarForm

class MyFormView(forms.MultiFormView):
    template = 'forms.html'
    forms = [
        ('Foo', FooForm)
        ('Bar', BarForm)
    ]
    redirect_url_rule = 'some.rule'

Here we have defined forms to contain a list of form classes, the rest is the same as a regular FormView.

The following context is returned:

  • forms: Dict of instantiated form classes
  • submit_url_rule: By default this will be the views current endpoint
  • submit_url: A function to call in the template which generates the url.

As with the FormView you can override behaviour by overriding methods:

class MyFormView(forms.MultiFormView):
    ...

    def submit_url(self, **kwargs):
        return url_for('some.rule', foo='bar')
Example Template

When rending a template for multi form views its important to understand what the forms context contains:

{
    'form1': ('Foo', form),
    'form2': ('Bar', form)
}

The forms context variable is a dict where the key represents a form id and the value containing the name of the form and the instantiated form class.

Here is an example template:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
{% for id, data in forms.iteritems() %}
{% set name, form = data %}
<h2>{{ name }}</h2>
<form action="{{ submit_url(foo='bar') }}" method="POST" id="{{ id }}">
    <input type="hidden" name="form" id="form" value="{{ id }}">
    <ul>
        {% for field in form %}
        <li>{{ field.label }} {{ field }}</li>
        {% endfor %}
    </ul>
    <button type="submit">Submit</button>
</form>
{% endform %}

Line 5 is emphasized as we have added a hidden field containing the form id which is generated at run time, its this which is used to determine which form has been submit and therefore which needs to validated.

Success Callback

In a multi form view only one form can be submit at a time, this means the behaviour of the get_form method will have changed, it will now only return the submit form object.

class MyFormView(forms.MultiFormView):
    ...

    def success_callback(self):
        form = self.get_form()  # The submit form and is valid
        # Do what ever you want

SQLAlchemy

Flask-Velox also has integration with SQLAlchemy models.

Note

The followuing packages are required:

  • Flask-SQLAlchemy

Read

Reading SQLAlchemy models in views is simple.

Model List View

The ModelListView allows you to render templates with paginated (or not) lists of model objects.

from flask.ext.velox.views.sqla import read
from yourapp.models import Model

class MyView(read.ModelListView):
    model = Model
    template = 'list.html'

The context returned to the template is as follows:

  • model: The SQLAlchemy model class
  • objects: List of objects returned from query
  • pagination: Pagination object or None
Example Template

Here are some example templates.

Without Pagination
<ul>
    {% for object in objects %}
    <li>{{ object.name }}</li>
    {% endfor %}
</ul>
With Pagination
<ul>
    {% for object in objects %}
    <li>{{ object.name }}</li>
    {% endfor %}
</ul>

{% if objects.has_prev %}<a href="{{ url_for('rule', page=objects.prev_num) }}"><< Newer Objects{% else %}<< Newer Objects{% endif %} |
{% if objects.has_next %}<a href="{{ url_for('rule', page=objects.next_num) }}">Older Objects >></a>{% else %}Older Objects >>{% endif %}
Changing context name

If you do not wish objects to be used as the context name for your object list you can change this be defining a objects_context_name attribute on the class, for example:

from flask.ext.velox.views.sqla import read
from yourapp.models import Model

class MyView(read.ModelListView):
    model = Model
    objects_context_name = 'foos'
    template = 'list.html'

In this case foos will be used instead of objects in the template.

Model Table View

The table model view is almost exactly the same as ModelListView so we won’t tread the same ground.

This view allows us to specify the columns we want to render in our table which relate to field names in the model:

from flask.ext.velox.views.sqla import read
from yourapp.models import Model

class MyView(read.ModelTableView):
    model = Model
    template = 'list.html'
    columns = ['field1', 'field2', 'field3']
    paginate = False

The context returned to the template is as follows:

  • model: The SQLAlchemy model class
  • objects: List of objects returned from query
  • pagination: Pagination object or None
  • columns: List of columns to render
  • column_name: Function to make the column name humanized
  • format_value: Function to format a fields value
Template Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<table>
    <thead>
        <tr>
            {% for column in columns %}
            <th>{{ column_name(column) }}</th>
            {% endfor %}
        </tr>
    </thead>
    <tbody>
        {% for object in objects %}
        <tr>
            {% for column in columns %}
            <tr>{{ format_value(column, object) }}
            {% endfor %}
        </tr>
        {% endfor %}
    </tbody>
</table>

We won’t go into detail about how column_name and format_value work here but you can check the API Reference for more details:

Pagination operates exactly the same as ListModelMixin.

Object View

The ObjectView functions like the list views above however simply returns a single object to the template. Please read the SingleObjectMixin documentation which explains how an object is retreived.

from flask.ext.velox.views.sqla import read
from yourapp.models import Model

class MyView(read.ObjectView):
    model = Model
    template = 'detail.html'

The context returned to the template is as follows:

  • model: The SQLAlchemy model class
  • object: The object
Example Template
<html>
    <head>
        <meta charset="utf-8" />
        <title>{{ object.name }}</title>
    </head>
    <body>
        {{ object.description }}
    </body>
</html>
Changing context name

As with the list views you can change the context name used for accessing the object in the template by setting an object_context_name attribute on the view class:

from flask.ext.velox.views.sqla import read
from yourapp.models import Model

class MyView(read.ObjectView):
    model = Model
    template = 'detail.html'
    object_context_name = 'foo'

In the above view foo will be returned to the template for accessing the object rather than object.

Forms

Flask-Velox comes with SQLAlchemy form integration to hopefully make those Create / Update tasks as simple as possible.

Note

The following packages must be installed:

  • Flask-SQLAlchemy
  • Flask-WTF
Create View

The CreateModelView allows you to render a form and on successful validation of the form creates a new object and saves to the database. You will ofcourse need to make the form yourself, you could use WTForms-Alchemy to automate this for you, example below:

This view is almost identical to the Form View we have seen before except that the view mixis in the ability to create an object populated with data from the form and save that object. You can see how the success callback function works here:

from flask.ext.wtf import Form
from flask.ext.velox.views.sqla import forms
from wtforms import TextField
from yourapp import db

class MyModel(db.Model):
    field1 = db.Column(db.String(20))
    field2 = db.Column(db.String(128))

class MyForm(Form):
    field1 = TextField()
    field2 = TextField()

class MyCreateView(forms.CreateModelView):
    model = MyModel
    session = db.session
    form = MyForm
    template = 'create.html'

You will ofcourse need a template for rendering the form, see an Example Template in the Form View guide.

As with the Form View you can override the success callback function, redirect url etc.

Update View

The Update View follows the same principle as the Create View except that the form is instantiated with an existing object which you can see documented here:

class MyUpdateView(forms.UpdateModelView):
    model = MyModel
    session = db.session
    form = MyForm
    template = 'update.html'
Multi Form Update View

There can sometimes be the requirement for multiple forms to update a single object which offer different functionality, an example situation is updating a user object where a password change form needs to be seperate from the general user attributes form. This view allows us to do this.

Again it follows the same principles as the Create View and Update View.

See also

from flask.ext.velox.views.sqla import forms
from yourapp import db
from yourapp.forms import UserPasswordForm, UserUpdateForm
from yourapp.models import User

class MyMultiFormView(forms.UpdateModelMultiFormView):
    model = User
    session = db.sesion
    forms = [
        ('Change Password', UserPasswordForm)
        ('Update User', UserUpdateForm)
    ]
    template = 'mutli.html'

You can see an example template here.

Delete

So we can create and update objects but what about deleting them, well we can do that too with Flask-Velox.

Note

The following packages must be installed:

  • Flask-SQLAlchemy
Delete View

Deleting a single object is the most basic form of deletion. Implement a view as follows:

The view sends the following context to the template:

  • model: The SQLAlchemy model
  • object: The object to delete
from flask.ext.velox.views.sqla.delete import DeleteObjectView
from yourapp import db
from yourapp.models import MyModel

class MyView(DeleteObjectView):
    model = MyModel
    session = db.session
    template = 'delete.html'
Confirm or not to Confirm

In most cases you will want to render a confirm dialog to the user before actually deleting an object from the database. By default the Delete View will not delete your object unless a confirm query parameter is found in the url. You can disable this behaviour so the object is deleted straight away without a confirm dialog by setting the confirm attribute on your view to False:

class MyView(DeleteObjectView):
    model = MyModel
    session = db.session
    confirm = False
Example Template

As with other views you need to render the confirm dialog yourself so here is an example to get you going:

<p>Are you sure?</p>
<p>{{ object }}</p>
<a href="{{ url_for(request.url_rule.endpoint, confirm=True) }}">Do it!</a>

The above template will render a confirm dialog with a link using the current endpoint with an extra argument so ?confirm=True is appended to the url.

Multi Delete View

You may also want the ability to delete mulitple objects, this is achived by posting a list of ids of ovbjects to delete to the view.

from flask.ext.velox.views.sqla.delete import MultiDeleteObjectView
from yourapp import db
from yourapp.models import MyModel

class MyView(MultiDeleteObjectView):
    model = MyModel
    session = db.session
    template = 'multi.html'

This view operates almost identically to the Delete View with a couple of exceptions.

  1. This view operates on POST rather GET
  2. objects is returned to the context rather than object.
Example Template
<form action="{{ url_for(request.url_rule.endpoint, confirm=True) }}" method="POST">
    <p>Are you sure?</p>
    <ul>
        {% for object in objects %}
        <li>{{ object }}</li>
        <input type="hidden" name="objects" id="objects" value="{{ object.id }}" />
        {% endfor %}
    </ul>
    <button type="submit">Do it!</button>
</form>

Admin

Flask-Velox also has optional Flask-Admin integration which you can use to build admin systems rapidly.

Note

The following packages must be installed:

  • Flask-SQLAlchemy
  • Flask-Admin
  • Flask-WTF

How you manage authentication is up to you, Flask-Velox simply provides views to perform standard admin tasks.

It is recommended that you view the API Reference to understand the extra attributes you can define on the admin versions of the views.

Example

Using the already existing views and mixins we have created a set of admin view classes and mixins which allow the views to be rendered within a Flask-Admin framework.

Here is a complete example which has create, read, update, delete views:

from flask.ext import admin
from flask.ext.velox.admin.views.sqla import read
from flask.ext.velox.admin.views.sqla import forms
from flask.ext.velox.admin.views.sqla import delete
from flask.ext.velox.formatters import datetime_formatter
from yourapp import db
from yourapp.forms import CreateForm, UpdateForm
from yourapp.models import Model

class AdminView(admin.BaseView):

    @admin.expose_plugview('/')
    class index(read.AdminModelTableView):
        model = Model
        columns = ['title', 'created', 'updated']
        formatters = {
            'created': datetime_formatter,
            'updated': datetime_formatter
        }
        with_selected = {
            'Delete': '.delete_multi',
        }

    @admin.expose_plugview('/create')
    class create(forms.AdminCreateModelView):
        model = Model
        form = CreateForm
        session = db.session

    @admin.expose_plugview('/update/<int:id>')
    class update(forms.AdminUpdateModelView):
        model = Model
        session = db.session
        form = UpdateForm

    @admin.expose_plugview('/delete/<int:id>')
    class delete(delete.AdminDeleteObjectView):
        model = Model
        session = db.session

    @admin.expose_plugview('/delete')
    class delete_multi(delete.AdminMultiDeleteObjectView):
        model = Model
        session = db.session

Reference

API Reference

Use the API Reference to look up how specific provided functionality works and how to extend it.

flask_velox.fields

Fields to help with common functionality, for example Upload fields with WTForms.

Note

The following packages must be installed:

  • Flask-WTF
class flask_velox.fields.UploadFileField(upload_to=None, *args, **kwargs)

Bases: flask_wtf.file.FileField

A django style upload field, allowing files to be uploaded and deleted when changed.

Warning

An application config variable called MEDIA_ROOT needs to be defined. This should be an absolute path to a directory to where uploaded files will be written.

Example

1
2
3
4
5
6
7
8
from flask.ext.velox.fields import UploadFileField
from flask_wtf import Form
from flask_wtf.file import FileAllowed, FileRequired

class MyForm(Form):
    name = UploadFileField('name', validators=[
        FileRequired(),
        FileAllowed(['pdf', ], 'PDF Only')])
absolute_dir_path

Returns the absolute path to the directory in which the file should be written too.

Returns:Path to directory
Return type:str
Raises:NotImplementedError – If MEDIA_ROOT is not defined in app config
delete(relative_path)

Delete an existing file

Parameters:relative (str) – The path to the saved the file to delete
make_paths(obj)

Returns built paths for saving to the file system, storing a relative path in a DB and the secure filename. In the case where the exact same filename exists in the same directory a UNIX timestamp is appended to the end of the filename to ensure no overwrites of existing files occure.

Parameters:obj (obj) – The object being populated by the form
Returns:Realtive path, Absolute path, filename
Return type:tuple
populate_obj(obj, name)

Called when populating an object such as a SQLAlchemy model with field data.

In the case of UploadFileField this method will trigger the proceess of safely saving the file and setting the field data to be a relative path to the file.

Parameters:
  • obj (obj) – Instance of the object
  • name (str) – Name of the field
relative_dir_path

Returns the relative path of the directory, this is used for storing relative paths in a DB rather than absolute ones. By default this will be blank so the relative path for a file names foo.jpg would be foo.jpg

Returns:Relative path to file
Return type:str
save(absolute_path)

Save the file to the file system. In the event the destination directory does not exist it will attempt to create it.

Parameters:absolute_path (str) – The path to save the file too

flask_velox.formatters

Helper functions to assist in formatting data when rendering object data.

flask_velox.formatters.bool_admin_formatter(value)

Render booleans using HTML rather than plain text for the Flask-Admin system using bootstrap markup.

Example

>>> from flask.ext.velox.formatters import bool_admin_formatter
>>> bool_admin_formatter(True)
'<i class="icon-ok"></i>'
>>> bool_admin_formatter(False)
'<i class="icon-remove"></i>'
Parameters:value (bool) – The value to evaluate against
Returns:The html value to use
Return type:str
flask_velox.formatters.bool_formatter(value, true='Yes', false='No')

For rendering True / False values in a human friendly way, by default True = Yes and False = No however this can be overriden by passing true and false keyword args with their respective values.

Example

>>> from flask.ext.velox.formatters import bool_formatter
>>> bool_formatter(True)
'Yes'
>>> bool_formatter(False)
'No'
Parameters:
  • value (bool) – The value to evaluate against
  • true (str, optional) – Value to use for True state, defaults to ‘Yes’
  • false (str, optional) – Value to use for False state, defaults to ‘No’
Returns:

The value to use

Return type:

str

flask_velox.formatters.datetime_formatter(value)

Render a sane date time value, for example: dd/mm/yyyy at HH:MM TZ. All values should be UTC.

Example

>>> import datetime
>>> from flask.ext.velox.formatters import datetime_formatter
>>> now = datetime.datetime.utcnow()
>>> datetime_formatter(now)
'11/04/2014 at 10:49AM UTC'
Parameters:value (datetime) – Datetime object to format
Returns:Formatted date time
Return type:str

flask_velox.mixins

This module provides mixin classes to help extend views to add additional functionality. Mixins in Flask-Velox have all the power, flask_velox.views simply implement mixin classes to provide the desired functionality for the view.

Modules
flask_velox.mixins.context

Module provides mixin classes for dealing with updating context passed to templates for rendering.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from flask.ext.velox.mixins.context import ContextMixin
from flask.ext.velox.mixins.template import TemplateMixin

app = Flask(__name__)

class MyView(TemplateMixin, ContextMixin):
    context = {
        'foo': 'bar'
    }

app.add_url_rule('/', view_func=MyView.as_view('myview'))

app.run()
class flask_velox.mixins.context.ContextMixin(*args, **kwargs)

Bases: object

Mixin this class to add context support to template rendering. Default context can be defined by setting the context attribute to contain a dict of key value pairs.

context dict, optional

Default context to use when rendering the template

Example

1
2
3
4
class FooView(ContextMixin):
    context = {
        'foo': 'bar',
    }
add_context(key, val)

Adds a new element to the context.

Parameters:
  • key (str) – The context key name
  • val – The value of the new context item of any type
Returns:

The new context

Return type:

dict

del_context(key)

Removes an element from the context dictionary.

Example

>>> class FooView(ContextMixin):
...     context = {
...         'foo': 'bar',
...     }
...
>>> view = FooView()
>>> view.del_context('foo')
{}
Parameters:key (str) – The context key name
Returns:Success or Failure
Return type:bool
Returns:The new context
Return type:dict
get_context()

Propety method which returns the current context.

Returns:Current context value
Return type:dict
merge_context(subject)

Merge the passed dictionary into the current _context

Parameters:subject (dict) – The dict to merge into _context

Example

>>> class FooView(ContextMixin):
...     context = {
...         'foo': 'bar',
...     }
...
>>> view = FooView()
>>> view.merge_context({'hello': 'world'})
>>> view.get_context()
{
    'hello': 'world',
    'foo': 'bar'
}
Returns:The new context
Return type:dict
set_context()

A method which should be overridden when required to set extra context on a per view basis. This method is not required to be implemented however is the recommended way of setting extra context

update_context(new)

Overwrites the existing context with the provided new context value.

Example

>>> class FooView(ContextMixin):
...     context = {
...         'foo': 'bar',
...     }
...
>>> view = FooView()
>>> view.update_context({'hello': 'world'})
{
    'hello': 'world'
}
Parameters:new (dict) – Value to update context too
Returns:The new context
Return type:dict
flask_velox.mixins.forms

Mixin classes for handeling form rendering and processing.

Note

The following packages must be installed:

  • Flask-WTF
class flask_velox.mixins.forms.BaseFormMixin(*args, **kwargs)

Bases: flask_velox.mixins.context.ContextMixin, flask_velox.mixins.template.TemplateMixin

Base Form Mixin class, defines some standard methods required for both single and multi forms.

redirect_url_rule str

Raw Flask url rule, e.g: some.url.rule

submit_url_rule str, optional

Flask url rule for form submit action e.g: ‘some.url.rule’

flash()

Override this method to call a flask flash method. By default this method does nothing.

Example

class MyView(FromMixin):
    form = Form

    def flash(self):
        flash('Message', 'success')
get_redirect_url_rule()

Returns raw redirect url rule to be used in url_for. The redirect_url_rule must be defined else NotImplementedError will be raised.

Returns:Raw flask url endpoint
Return type:str
Raises:NotImplementedError – If redirect_url_rule is not defined
get_submit_url_rule()

Returns a submit url rule for usage in generating a submit form action url. Defaults to the views current url rule endpoint but can be overridden by defining submit_url_rule on the view class.abs

Returns:Raw flask url rule endpoint
Return type:str
instantiate_form(kls=None, obj=None, prefix='')

Instantiates form if instance does not already exisst. Override this method to tailor form instantiation.

Parameters:
  • kls (class, optional) – Form class to instantiate, defaults to None
  • obj (object, optional) – Object to pass into the form to pre populate with
  • prefix (str, optional) – Add a prefix to the form class
Returns:

Instantiated form

Return type:

object

post(*args, **kwargs)

Handle HTTP POST requets using Flask MethodView rendering a single html template.

Returns:Rendered template
Return type:str
redirect_url(**kwargs)

Returns the url to a redirect endpoint, when the form is valid and the callback is called.

Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url
Return type:str or None
set_context()

Overrides set_context to set extra context variables.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()

Note

Adds the following extra context variables:

  • is_hidden_field: Function for determining is field is hidden
submit_url(**kwargs)

Returns the url to a submit endpoint, this is used to render a link in forms actions:

<form action="{{ submit_url() }}" method="POST">
...
</form>
Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url
Return type:str or None
success_callback()

Called on successful form validation, by default this will perform a redirect if redirect_url_rule is defined. Override this method to perform any custom actions on successful form validation.

Returns:Redirects request to somewhere else
Return type:werkzeug.wrappers.Response
class flask_velox.mixins.forms.FormMixin(*args, **kwargs)

Bases: flask_velox.mixins.forms.BaseFormMixin

Renders and validates a single Form.

Example

1
2
3
4
5
from flask.velox.mixins.forms import FormMixin
from yourapp.forms import MyForm

class MyView(FormMixin):
    form_class = MyForm
form class

An uninstantiated WTForm class

get_form()

Returns an instantiated WTForm class.

Returns:Instantiated form
Return type:object
get_form_class()

Returns defined form_class or riases NotImplementedError

Returns:Uninstantiated WTForm class
Return type:class
Raises:NotImplementedError – If form_class is not defined
set_context()

Overrides set_context to set extra context variables.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()

Note

Adds the following extra context variables:

  • form: Instantiated form object
class flask_velox.mixins.forms.MultiFormMixin(*args, **kwargs)

Bases: flask_velox.mixins.forms.BaseFormMixin

Mixin allows rendering of multiple forms in a single template, each form is submit individually and validated individually but to the same endpoint.

Example

1
2
3
4
5
6
7
8
from flask.velox.mixins.forms import MultiFormMixin
from yourapp.forms import Form1, Form2

class MyView(MultiFormMixin):
    forms = [
        ('Form 1', Form1)
        ('Form 2', Form2)
    ]
get_form()

Get the submit form if one exists else return None, this allows us to get the correctly submit form to validate against and populate objects if required.

A hidden field must be included in each <form> block named form containing the value of the forms prefix. This is the forms uniqie identifier and is used to obtain the submit form.

Returns:Submit form object or None if submit form not found
Return type:obj or None
get_form_classes()

Return list of tuples of form classes, the tuple should contain a human readable name and a form class defined in forms attribute. If not set NotImplementedError is risen.

Returns:Tuples containing human name and form class
Return type:list
Raises:NotImplementedErrorforms attribute is not defined
get_forms()

Instantiates forms set in forms attribute giving each form an individual prefix and storing each form in a dict using its prefix as the key.

Returns:Instantiated forms with form prefix as key and a tuple containing the human readable form name and form object:
{
    'form1': ('Foo Form', <object>),
    'form1': ('Bar Form', <object>)
}
Return type:collections.OrderedDict
is_submit(form, prefix)

If the form has been submit run the validate on submit method and call the success callback if the form is valid.

Parameters:
  • form (object) – Instantiated form object
  • prefix (str) – Form prefix id
Returns:

If the form was submit§

Return type:

bool

set_context()

Updates context to contain extra variables.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()

Note

Adds the following extra context variables:

  • forms: List of forms
flask_velox.mixins.http

Module provides mixins for issuing HTTP Status codes using the Flask View.

class flask_velox.mixins.http.RedirectMixin

Bases: flask.views.View

Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used however this can be overridden using the code attribute.

Example

1
2
3
4
from flask.ext.velox.mixins.http import RedirectMixin
class MyView(RedirectMixin):
    rule = 'some.url.rule'
    code = 301
rule str

Flask URL Rule passed into url_for

code int, optional

Status code to raise, defaults to 302

dispatch_request(*args, **kwargs)

Dispatch the request, returning the redirect.func_closure

Returns:Redirect response
Return type:werkzeug.wrappers.Response
get_url()

Return a generated url from rule attribute.

Returns:Generated url
Return type:str
pre_dispatch(*args, **kwargs)

If you wish to run an arbitrary piece of code before the redirect is dispatched you can override this method which is called before dispatch.

flask_velox.mixins.template

Module provides mixins for rendering templates using Flask MethodView.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from flask import Flask
from flask.ext.velox.mixins.template import TemplateMixin
from flask.views import MethodView

app = Flask(__name__)

class MyView(TemplateMixin):
    template = 'templates/home.html'

app.add_url_rule('/', view_func=MyView.as_view('myview'))

app.run()
class flask_velox.mixins.template.TemplateMixin

Bases: flask.views.MethodView

Renders a template on HTTP GET request as long as the template attribute is defined.

template str

Relative template path, e.g: templates/home.html

Example

1
2
class MyView(TemplateMixin):
    template = 'templates/home.html'
__getattr__(name)

Overriding this allows us to access request view args as attributes on view instances.

Returns:Attribute value
Return type:anything
Raises:AttributeError – If attribute does not exist
_template

Returns the defined template which should be set using the template attribute on classes inheriting this view.

Returns:Relative template path, e.g: templates/home.html
Return type:str
Raises:NotImplementedError – If self.template attribute is not defined
get(*args, **kwargs)

Handle HTTP GET requets using Flask MethodView rendering a single html template.

Returns:Rendered template
Return type:str
render()

Renders a template. This method will attempt to pass context to the template but if the context attribute does not exist then an empty dict will be passed to the render_template method.

Returns:Rendered template
Return type:str
flask_velox.mixins.sqla

This module provides mixin classes which extend the default flask_velox.mixins functionality but add support for Flask-SQLAlchemy models.

Modules
flask_velox.mixins.sqla.read

Module provides mixin classes for dealing with SQLALchemy models

Note

The following packages must be installed:

  • Flask SQLAlchemy

Example

1
2
3
4
5
6
7
8
9
from flask.ext.velox.mixins.sqla.model import ModelMixin
from yourapp import db
from yourapp.models import SomeModel

app = Flask(__name__)

class MyView(ModelMixin):
    session = db.session
    model = SomeModel
class flask_velox.mixins.sqla.read.ListModelMixin(*args, **kwargs)

Bases: flask_velox.mixins.sqla.object.BaseModelMixin

Mixin provides ability to list multiple instances of a SQLAlchemy model.

As well as attributes supported by the classes this mixin inherits from other attributes are supported as well.

Example

1
2
3
4
5
6
from flask.ext.velox.mixins.sqla.model import ListModelMixin
from yourapp.models import SomeModel

class MyView(ListModelMixin):
    model = SomeModel
    base_query = SomeModel.query.filter(foo='bar')
base_query object, optional

A SQLAlchemy base query object, if defined this will be used instead of self.model.query.all()

objects_context_name str, optional

Instead of using object you can set the context variable name to use for the object, defaults to object

paginate bool, optional

Paginate the records using SQLAlchemy query.paginate, defaults True

per_page int, optional

If paginate is True customise the number of records to show per page, defaults to 30

get_basequery()

Returns SQLAlchemy base query object instance, if base_query is declared this will be used as the base query, else self.model.query.all() will be used which would get all model objects.

Returns:A flask BaseQuery object instance
Return type:flask_sqlalchemy.BaseQuery
get_objects()

Returns a list of objects and pagination object if paginate is True, else None will be returned when paginate is not set or False.

Returns:List of model object instances, Pagination object or None
Return type:tuple
get_objects_context_name()

Returns the context name to use when returning the objects to the template, defaults to objects.

Returns:Name to use for context variable
Return type:str
get_page()

Attempt to get the current page number, assumes a HTTP GET query param called page is availible in flask.request.args which holds the page number.

get_per_page()

Returns the number of records to show per page for paginated result sets. Defaults to 30

Returns:Number of records per page
Return type:int
set_context()

Adds extra context to SQLAlchemy based list views.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()

Note

Adds the following context variables.

  • objects: List of model objects
  • pagination: Pagination object or None
Returns:Rendered template
Return type:str
class flask_velox.mixins.sqla.read.ObjectMixin(*args, **kwargs)

Bases: flask_velox.mixins.sqla.object.SingleObjectMixin

Mixin for returning a single object.

get_object_context_name()

Returns the context name to use for returning the object to the template, defaults to object.

Returns:Context name to use for object in template
Return type:str
set_context()

Set the context for a Object view.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()

Note

Adds the following context variables.

  • object: List of columns
class flask_velox.mixins.sqla.read.TableModelMixin(*args, **kwargs)

Bases: flask_velox.mixins.sqla.read.ListModelMixin

Mixin extends the default ListModelMixin behaviour adding attributes for rendering lists in tables.

Example

1
2
3
4
5
6
from flask.ext.velox.mixins.sqla.model import TableModelMixin
from yourapp.models import SomeModel

class MyView(TableModelMixin):
    model = SomeModel
    columns = ['field1', 'field2', 'field3']
columns list

A list of columns to render, this should map to model fields

formatters dict

A dict of key value pairs mapping a field name (key) to a method which formats the fields data, for example:

formatters = {
    'field1': fmt_bool
    'field1': fmt_datetime
}
column_name(name)

Attempts to get a human friendly name for the column. First it will look for an info attribute on the model field, if present will then return label value of the info dict. If not present this method will replace underscore characters with spaces and simply title case the individual words.

An example model with an info attribute, this is the same behaviour as WTForms-Alchemy:

class MyModel(db.Model):
    field = db.Column(db.Unicode, info={
        'label' = 'My Field'
    })
Parameters:name (str) – The column name mapping to a model field attribute
Returns:Human friendly field name
Return type:str
format_value(field, instance)

Format a given field name and instance with defined formatter if a formatter is defined for the specific field. This method is added to the context for use in a template, for example:

{% for object in objects %}
    {% for column in columns %}
        {{ format_value(column, object) }}
    {% endfor %}
{% endfor %}
Parameters:
  • field (str) – Field name on model
  • instance (obj) – Instance of model
Returns:

Formatted value

Return type:

anything

get_columns()

Returns the list of columns defined for the View using this Mixin.

Returns:List of strings of model field names
Return type:list
Raises:NotImplementedError – If columns is not defined
get_formatters()

Return formatters defined for the View using this Mixin.

Returns:Returns defined formatters or None
Return type:dict or None
set_context()

Adds extra context to SQLAlchemy table based list views.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()

Note

Adds the following context variables.

  • columns: List of columns
  • column_name: column_name function
  • format_value: format_value function
flask_velox.mixins.sqla.forms

Mixin classes for helping build forms with WTForms populating SQLAlchemy objects.

Note

The following packages must be installed:

  • Flask-WTF
  • Flask-SQLAlchemy
class flask_velox.mixins.sqla.forms.BaseCreateUpdateMixin

Bases: object

Base Mixin for Creating or Updating a object with SQLAlchemy.

Warning

This mixin cannot be used on it’s own and should be used inconjunction with others, such as ModelFormMixin.

success_callback()

Overrides success_callback creating new model objects. This method is called on successful form validations. It first obtains the current db session and the instantiated form. A blank object is obtained from the model and then populated with the form data.

        session = self.get_session()
        form = self.get_form()
        obj = self.get_object()

        form.populate_obj(obj)

        session.add(obj)
        session.commit()
Returns:Redirects request to somewhere else
Return type:werkzeug.wrappers.Response
class flask_velox.mixins.sqla.forms.CreateModelFormMixin(*args, **kwargs)

Bases: flask_velox.mixins.sqla.object.SingleObjectMixin, flask_velox.mixins.sqla.forms.BaseCreateUpdateMixin, flask_velox.mixins.forms.FormMixin

Handles creating objects after form validation has completed and was successful.

flash()

Flash created message to user.

class flask_velox.mixins.sqla.forms.UpdateModelFormMixin(*args, **kwargs)

Bases: flask_velox.mixins.sqla.object.SingleObjectMixin, flask_velox.mixins.sqla.forms.BaseCreateUpdateMixin, flask_velox.mixins.forms.FormMixin

Handels updating a single existing object after form validation has completed and was successful.

flash()

Flash updated message to user.

instantiate_form(**kwargs)

Overrides form instantiation so object instance can be passed to the form.

        obj = self.get_object()

        return super(UpdateModelFormMixin, self).instantiate_form(
            obj=obj,
            **kwargs)
Returns:Instantiated form
Return type:object
class flask_velox.mixins.sqla.forms.UpdateModelMultiFormMixin(*args, **kwargs)

Bases: flask_velox.mixins.sqla.object.SingleObjectMixin, flask_velox.mixins.sqla.forms.BaseCreateUpdateMixin, flask_velox.mixins.forms.MultiFormMixin

Mixin for building mutli forms with a single SQAlachemy object

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from flask.ext.velox.mixins.sqla.forms import ModelFormMixin
from yourapp.forms import MyForm1, MyForm2
from yourapp.models import MyModel

class MyView(UpdateModelMultiFormMixin):
    model = MyModel
    forms = [
        'Form 1': MyForm1
        'Form 2': MyForm2
    ]
flask_velox.mixins.sqla.delete

Mixin classes for deleting SQLAlchemy objects from the Database.

Note

The following packages must be installed:

  • Flask-SQLAlchemy
class flask_velox.mixins.sqla.delete.DeleteObjectMixin(*args, **kwargs)

Bases: flask_velox.mixins.sqla.object.SingleObjectMixin, flask_velox.mixins.context.ContextMixin, flask_velox.mixins.template.TemplateMixin

Deletes a single SQLAlchemy object from the Database.

Example

1
2
3
4
5
6
7
8
form flask.ext.velox.mixins.sqla.delete import DeleteObjectMixin
from yourapp import db
from yourapp.models import MyModel

class DeleteMyModel(DeleteObjectMixin):
    template = 'delete.html'
    model = MyModel
    session = db.sesion
confirm bool, optional

Ensure a confirmed flag is required when processing the view, defaults to True

can_delete

Propery function which returns a bool. If confirm attribute is set to False on the class this will return True else it will only return True if the confirmed query string is present.

Returns:Ok to delete the object or not
Return type:bool
delete()

Deletes the object, only if can_delete() returns True.

flash()

Flashes a success message to the user.

set_context()

Adds extra context variables to be used in delete view templates.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()

Note

Adds the following context variables:

  • object: The object to be deleted
  • cancel_url: Function for retrieving cancel url in template
success_callback()

Success callback called after object has been deleted. Override this to customise what happens after an object is delted

Raises:werkzeug.routing.RequestRedirect – When object is deleted to force a redirect to another View
class flask_velox.mixins.sqla.delete.MultiDeleteObjectMixin(*args, **kwargs)

Bases: flask_velox.mixins.sqla.delete.DeleteObjectMixin

Mixin provides functionality to delete mutliple objects of the same model.

delete()

Override default delete functionality adding the ability to delete multiple objects of the same model but only if can_delete() is True.

flash()

Flashes a success message to the user.

get_objects()

Returns a set of objects set for deletion. List of objects is retrived from a HTTP POST list called objects.

Returns:Set of objects to delete
Return type:set
methods = ['GET', 'POST']

Allowed HTTP Methods

post(*args, **kwargs)

Handle HTTP POST requests rendering a template.

set_context()

Override context to add objects rather than object to the context.

flask_velox.mixins.sqla.object

Mixin classes for obtaining object of an SQLAlchemy model.

Note

The following packages must be installed:

  • Flask-SQLAlchemy
class flask_velox.mixins.sqla.object.BaseModelMixin(*args, **kwargs)

Bases: flask_velox.mixins.context.ContextMixin

Mixin provides SQLAlchemy model integration.

model class

SQLAlchemy un-instanciated model class

session object

SQLAlchemy session instance

pk_field str, optional

The primary key field name, defaults to id

get_model()

Returns the Model to perform queries against.

Example

>>> from flask.ext.velox.mixins.sqla.model import BaseModelMixin
>>> from yourapp.models import SomeModel
>>> class MyView(BaseModelMixin):
...     model = SomeModel
>>> view = MyView()
>>> view.get_model()
yourapp.models.SomeModel
Raises:NotImplementedError – If model has not been declared on the class
get_pk_field()

Returns the primary key field name. If pk_field is not declared return value defaults to id.

Example

>>> from flask.ext.velox.mixins.sqla.model import BaseModelMixin
>>> class MyView(BaseModelMixin):
...     pk_field = 'foo'
>>> view = MyView()
>>> view.get_pk_field()
'foo'
Returns:Primary key field name
Return type:str
get_session()

Returns the SQLAlchemy db session instance.

Example

>>> from flask.ext.velox.mixins.sqla.model import BaseModelMixin
>>> from yourapp import db
>>> class MyView(BaseModelMixin):
...     session = db.session
>>> view = MyView()
>>> view.get_session()
<sqlalchemy.orm.scoping.scoped_session at 0x104c88dd0>
Raises:NotImplementedError – If session has not been declared on the class
set_context()

Overrides set_context to set extra context variables.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()
class flask_velox.mixins.sqla.object.SingleObjectMixin(*args, **kwargs)

Bases: flask_velox.mixins.sqla.object.BaseModelMixin

Mixin handles retrieving a single object from an SQLAlchemy model. This is done by defining a field query.

The value to use in the query is obtained by trying different request attributes for the data:

  1. request.view_args - Data passed as part of a uri
  2. request.args - Data passed as part of aquery string
  3. self - An attribute defined on the view class

The field used for the lookup is also the name of the value passed in the request, for example if lookup_field is set to foo then request.view_args / request.args should have an element named foo containing the data or an attribute on the class named foo.

Examples

1
2
3
4
5
from flask.ext.velox.mixins.sqla.object import SingleObjectMixin
from yourapp.models import MyModel

class MyView(SingleObjectMixin):
    model = MyModel
get_lookup_field()

Returns the field to lookup objects against, if lookup_field is not defined id will be returned by default.

Returns:Field to use for lookup, defaults to id
Return type:str
get_lookup_value()

Attempt to get the value to use for looking up the object in the database, this is usually an id number but could technically be anything.

Returns:Value to use in the lookup query
Return type:anything
get_object()

Returns an object from the database or a blank object if no lookup value is provided.

Returns:Populated or blank model object
Return type:object

flask_velox.views

Views simply impliment mixins provided in flask_velox.mixins. These views provide the basics to enable you to build simple pages such as lists, templates and form rendering / validation.

Modules
flask_velox.views.forms

Module provides views for basic form rendering and processing.

Note

The following packages must be installed:

  • Flask-WTF
class flask_velox.views.forms.FormView(*args, **kwargs)

Bases: flask_velox.mixins.forms.FormMixin

Class implements flask_velox.mixins.forms.FormMixin allowing rendering of Flask-WTF forms.

Note

Context pased to template:

  • form: The instantiated form class
  • submit_url_rule: Raw flask url rule
  • submit_url: Function to call to generate the submit url for the form

Example

from flask.ext.velox.views.forms import FormView
from yourapp.forms import MyForm

class MyView(FormView):
    template = 'form.html'
    form = MyForm
__delattr__

x.__delattr__(‘name’) <==> del x.name

__format__()

default object formatter

__getattribute__

x.__getattribute__(‘name’) <==> x.name

__hash__

x.__hash__() <==> hash(x)

__reduce__()

helper for pickle

__reduce_ex__()

helper for pickle

__repr__

x.__repr__() <==> repr(x)

__setattr__

x.__setattr__(‘name’, value) <==> x.name = value

__sizeof__() → int

size of object in memory, in bytes

__str__

x.__str__() <==> str(x)

add_context(key, val)

Adds a new element to the context.

Parameters:
  • key (str) – The context key name
  • val – The value of the new context item of any type
Returns:

The new context

Return type:

dict

classmethod as_view(name, *class_args, **class_kwargs)

Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the View on each request and call the dispatch_request() method on it.

The arguments passed to as_view() are forwarded to the constructor of the class.

del_context(key)

Removes an element from the context dictionary.

Example

>>> class FooView(ContextMixin):
...     context = {
...         'foo': 'bar',
...     }
...
>>> view = FooView()
>>> view.del_context('foo')
{}
Parameters:key (str) – The context key name
Returns:Success or Failure
Return type:bool
Returns:The new context
Return type:dict
flash()

Override this method to call a flask flash method. By default this method does nothing.

Example

class MyView(FromMixin):
    form = Form

    def flash(self):
        flash('Message', 'success')
get(*args, **kwargs)

Handle HTTP GET requets using Flask MethodView rendering a single html template.

Returns:Rendered template
Return type:str
get_context()

Propety method which returns the current context.

Returns:Current context value
Return type:dict
get_form()

Returns an instantiated WTForm class.

Returns:Instantiated form
Return type:object
get_form_class()

Returns defined form_class or riases NotImplementedError

Returns:Uninstantiated WTForm class
Return type:class
Raises:NotImplementedError – If form_class is not defined
get_redirect_url_rule()

Returns raw redirect url rule to be used in url_for. The redirect_url_rule must be defined else NotImplementedError will be raised.

Returns:Raw flask url endpoint
Return type:str
Raises:NotImplementedError – If redirect_url_rule is not defined
get_submit_url_rule()

Returns a submit url rule for usage in generating a submit form action url. Defaults to the views current url rule endpoint but can be overridden by defining submit_url_rule on the view class.abs

Returns:Raw flask url rule endpoint
Return type:str
instantiate_form(kls=None, obj=None, prefix='')

Instantiates form if instance does not already exisst. Override this method to tailor form instantiation.

Parameters:
  • kls (class, optional) – Form class to instantiate, defaults to None
  • obj (object, optional) – Object to pass into the form to pre populate with
  • prefix (str, optional) – Add a prefix to the form class
Returns:

Instantiated form

Return type:

object

merge_context(subject)

Merge the passed dictionary into the current _context

Parameters:subject (dict) – The dict to merge into _context

Example

>>> class FooView(ContextMixin):
...     context = {
...         'foo': 'bar',
...     }
...
>>> view = FooView()
>>> view.merge_context({'hello': 'world'})
>>> view.get_context()
{
    'hello': 'world',
    'foo': 'bar'
}
Returns:The new context
Return type:dict
post(*args, **kwargs)

Handle HTTP POST requets using Flask MethodView rendering a single html template.

Returns:Rendered template
Return type:str
redirect_url(**kwargs)

Returns the url to a redirect endpoint, when the form is valid and the callback is called.

Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url
Return type:str or None
render()

Renders a template. This method will attempt to pass context to the template but if the context attribute does not exist then an empty dict will be passed to the render_template method.

Returns:Rendered template
Return type:str
set_context()

Overrides set_context to set extra context variables.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()

Note

Adds the following extra context variables:

  • form: Instantiated form object
submit_url(**kwargs)

Returns the url to a submit endpoint, this is used to render a link in forms actions:

<form action="{{ submit_url() }}" method="POST">
...
</form>
Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url
Return type:str or None
success_callback()

Called on successful form validation, by default this will perform a redirect if redirect_url_rule is defined. Override this method to perform any custom actions on successful form validation.

Returns:Redirects request to somewhere else
Return type:werkzeug.wrappers.Response
update_context(new)

Overwrites the existing context with the provided new context value.

Example

>>> class FooView(ContextMixin):
...     context = {
...         'foo': 'bar',
...     }
...
>>> view = FooView()
>>> view.update_context({'hello': 'world'})
{
    'hello': 'world'
}
Parameters:new (dict) – Value to update context too
Returns:The new context
Return type:dict
class flask_velox.views.forms.MultiFormView(*args, **kwargs)

Bases: flask_velox.mixins.forms.MultiFormMixin

Class implements flask_velox.mixins.forms.MultiFormMixin allowing rendering of multiple Flask-WTF forms.

Note

Context pased to template:

  • forms: The instantiated form classes
  • submit_url_rule: Raw flask url rule
  • submit_url: Function to call to generate the submit url for the form

Example

from flask.ext.velox.views.forms import MultiFormView
from yourapp.forms import FooForm, BarForm

class MyView(MultiFormView):
    template = 'forms.html'
    forms = [FooForm, BarForm]
__delattr__

x.__delattr__(‘name’) <==> del x.name

__format__()

default object formatter

__getattribute__

x.__getattribute__(‘name’) <==> x.name

__hash__

x.__hash__() <==> hash(x)

__reduce__()

helper for pickle

__reduce_ex__()

helper for pickle

__repr__

x.__repr__() <==> repr(x)

__setattr__

x.__setattr__(‘name’, value) <==> x.name = value

__sizeof__() → int

size of object in memory, in bytes

__str__

x.__str__() <==> str(x)

add_context(key, val)

Adds a new element to the context.

Parameters:
  • key (str) – The context key name
  • val – The value of the new context item of any type
Returns:

The new context

Return type:

dict

classmethod as_view(name, *class_args, **class_kwargs)

Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the View on each request and call the dispatch_request() method on it.

The arguments passed to as_view() are forwarded to the constructor of the class.

del_context(key)

Removes an element from the context dictionary.

Example

>>> class FooView(ContextMixin):
...     context = {
...         'foo': 'bar',
...     }
...
>>> view = FooView()
>>> view.del_context('foo')
{}
Parameters:key (str) – The context key name
Returns:Success or Failure
Return type:bool
Returns:The new context
Return type:dict
flash()

Override this method to call a flask flash method. By default this method does nothing.

Example

class MyView(FromMixin):
    form = Form

    def flash(self):
        flash('Message', 'success')
get(*args, **kwargs)

Handle HTTP GET requets using Flask MethodView rendering a single html template.

Returns:Rendered template
Return type:str
get_context()

Propety method which returns the current context.

Returns:Current context value
Return type:dict
get_form()

Get the submit form if one exists else return None, this allows us to get the correctly submit form to validate against and populate objects if required.

A hidden field must be included in each <form> block named form containing the value of the forms prefix. This is the forms uniqie identifier and is used to obtain the submit form.

Returns:Submit form object or None if submit form not found
Return type:obj or None
get_form_classes()

Return list of tuples of form classes, the tuple should contain a human readable name and a form class defined in forms attribute. If not set NotImplementedError is risen.

Returns:Tuples containing human name and form class
Return type:list
Raises:NotImplementedErrorforms attribute is not defined
get_forms()

Instantiates forms set in forms attribute giving each form an individual prefix and storing each form in a dict using its prefix as the key.

Returns:Instantiated forms with form prefix as key and a tuple containing the human readable form name and form object:
{
    'form1': ('Foo Form', <object>),
    'form1': ('Bar Form', <object>)
}
Return type:collections.OrderedDict
get_redirect_url_rule()

Returns raw redirect url rule to be used in url_for. The redirect_url_rule must be defined else NotImplementedError will be raised.

Returns:Raw flask url endpoint
Return type:str
Raises:NotImplementedError – If redirect_url_rule is not defined
get_submit_url_rule()

Returns a submit url rule for usage in generating a submit form action url. Defaults to the views current url rule endpoint but can be overridden by defining submit_url_rule on the view class.abs

Returns:Raw flask url rule endpoint
Return type:str
instantiate_form(kls=None, obj=None, prefix='')

Instantiates form if instance does not already exisst. Override this method to tailor form instantiation.

Parameters:
  • kls (class, optional) – Form class to instantiate, defaults to None
  • obj (object, optional) – Object to pass into the form to pre populate with
  • prefix (str, optional) – Add a prefix to the form class
Returns:

Instantiated form

Return type:

object

is_submit(form, prefix)

If the form has been submit run the validate on submit method and call the success callback if the form is valid.

Parameters:
  • form (object) – Instantiated form object
  • prefix (str) – Form prefix id
Returns:

If the form was submit§

Return type:

bool

merge_context(subject)

Merge the passed dictionary into the current _context

Parameters:subject (dict) – The dict to merge into _context

Example

>>> class FooView(ContextMixin):
...     context = {
...         'foo': 'bar',
...     }
...
>>> view = FooView()
>>> view.merge_context({'hello': 'world'})
>>> view.get_context()
{
    'hello': 'world',
    'foo': 'bar'
}
Returns:The new context
Return type:dict
post(*args, **kwargs)

Handle HTTP POST requets using Flask MethodView rendering a single html template.

Returns:Rendered template
Return type:str
redirect_url(**kwargs)

Returns the url to a redirect endpoint, when the form is valid and the callback is called.

Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url
Return type:str or None
render()

Renders a template. This method will attempt to pass context to the template but if the context attribute does not exist then an empty dict will be passed to the render_template method.

Returns:Rendered template
Return type:str
set_context()

Updates context to contain extra variables.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()

Note

Adds the following extra context variables:

  • forms: List of forms
submit_url(**kwargs)

Returns the url to a submit endpoint, this is used to render a link in forms actions:

<form action="{{ submit_url() }}" method="POST">
...
</form>
Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url
Return type:str or None
success_callback()

Called on successful form validation, by default this will perform a redirect if redirect_url_rule is defined. Override this method to perform any custom actions on successful form validation.

Returns:Redirects request to somewhere else
Return type:werkzeug.wrappers.Response
update_context(new)

Overwrites the existing context with the provided new context value.

Example

>>> class FooView(ContextMixin):
...     context = {
...         'foo': 'bar',
...     }
...
>>> view = FooView()
>>> view.update_context({'hello': 'world'})
{
    'hello': 'world'
}
Parameters:new (dict) – Value to update context too
Returns:The new context
Return type:dict
flask_velox.views.http

Module provides views for issuing HTTP status codes using Flask MethodView.

class flask_velox.views.http.RedirectView

Bases: flask_velox.mixins.http.RedirectMixin

View for raising a HTTP 3XX Response. By default this View will raise a HTTP 302 however this can be overridden by defining a code attribute.

Example

1
2
3
4
from flask.ext.velox.views.http import RedirectView
class MyView(RedirectMixin):
    rule = 'some.url.rule'
    code = 301
flask_velox.views.template

Module provides classes for rendering templates using Flask MethodView.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from flask import Flask
from flask.ext.velox.views.template import TemplateView
from flask.views import MethodView

app = Flask(__name__)

class HomeView(TemplateView):
    template = 'templates/home.html'
    context = {
        'hello': 'word'
    }

app.add_url_rule('/', view_func=HomeView.as_view('home'))

app.run()
class flask_velox.views.template.TemplateView(*args, **kwargs)

Bases: flask_velox.mixins.context.ContextMixin, flask_velox.mixins.template.TemplateMixin

Renders a template with optionl context.

template str

Relative template path, e.g: templates/home.html

context dict, optional

Default context to use when rendering the template

Example

1
2
3
4
5
class HomeView(TemplateView):
    template = 'templates/home.html'
    context = {
        'hello': 'word'
    }
__delattr__

x.__delattr__(‘name’) <==> del x.name

__format__()

default object formatter

__getattribute__

x.__getattribute__(‘name’) <==> x.name

__hash__

x.__hash__() <==> hash(x)

__reduce__()

helper for pickle

__reduce_ex__()

helper for pickle

__repr__

x.__repr__() <==> repr(x)

__setattr__

x.__setattr__(‘name’, value) <==> x.name = value

__sizeof__() → int

size of object in memory, in bytes

__str__

x.__str__() <==> str(x)

add_context(key, val)

Adds a new element to the context.

Parameters:
  • key (str) – The context key name
  • val – The value of the new context item of any type
Returns:

The new context

Return type:

dict

classmethod as_view(name, *class_args, **class_kwargs)

Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the View on each request and call the dispatch_request() method on it.

The arguments passed to as_view() are forwarded to the constructor of the class.

del_context(key)

Removes an element from the context dictionary.

Example

>>> class FooView(ContextMixin):
...     context = {
...         'foo': 'bar',
...     }
...
>>> view = FooView()
>>> view.del_context('foo')
{}
Parameters:key (str) – The context key name
Returns:Success or Failure
Return type:bool
Returns:The new context
Return type:dict
get(*args, **kwargs)

Handle HTTP GET requets using Flask MethodView rendering a single html template.

Returns:Rendered template
Return type:str
get_context()

Propety method which returns the current context.

Returns:Current context value
Return type:dict
merge_context(subject)

Merge the passed dictionary into the current _context

Parameters:subject (dict) – The dict to merge into _context

Example

>>> class FooView(ContextMixin):
...     context = {
...         'foo': 'bar',
...     }
...
>>> view = FooView()
>>> view.merge_context({'hello': 'world'})
>>> view.get_context()
{
    'hello': 'world',
    'foo': 'bar'
}
Returns:The new context
Return type:dict
render()

Renders a template. This method will attempt to pass context to the template but if the context attribute does not exist then an empty dict will be passed to the render_template method.

Returns:Rendered template
Return type:str
set_context()

A method which should be overridden when required to set extra context on a per view basis. This method is not required to be implemented however is the recommended way of setting extra context

update_context(new)

Overwrites the existing context with the provided new context value.

Example

>>> class FooView(ContextMixin):
...     context = {
...         'foo': 'bar',
...     }
...
>>> view = FooView()
>>> view.update_context({'hello': 'world'})
{
    'hello': 'world'
}
Parameters:new (dict) – Value to update context too
Returns:The new context
Return type:dict
flask_velox.views.sqla

This module provides views classes which extend the default flask_velox.views functionality but add support for Flask-SQLAlchemy models implimenting mixin classes.

Modules
flask_velox.views.sqla.read

Module provides classes for rendering views for SQLAlchemy based models.

Note

The following packages must be installed:

  • Flask SQLAlchemy
class flask_velox.views.sqla.read.ModelListView(*args, **kwargs)

Bases: flask_velox.mixins.sqla.read.ListModelMixin, flask_velox.mixins.context.ContextMixin, flask_velox.mixins.template.TemplateMixin

Handles rendering templates which list out model objects.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.velox.views.sqla.model import ModelListView
from yourapp.models import SomeModel

app = Flask(__name__)
db = SQLAlchemy(app)

class MyListView(ModelListView):
    template = 'templates/list.html'
    session = db.session
    model = SomeModel

app.add_url_rule('/', view_func=MyListView.as_view('list'))

app.run()
class flask_velox.views.sqla.read.ObjectView(*args, **kwargs)

Bases: flask_velox.mixins.sqla.read.ObjectMixin, flask_velox.mixins.template.TemplateMixin

View for rendering a single SQLALchemy object within a template.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.velox.views.sqla.read import ObjectView
from yourapp.models import SomeModel

app = Flask(__name__)
db = SQLAlchemy(app)

class MyObjectView(ObjectView):
    template = 'templates/object.html'
    session = db.session
    model = SomeModel

app.add_url_rule('/', view_func=MyObjectView.as_view('object'))

app.run()
class flask_velox.views.sqla.read.TableModelView(*args, **kwargs)

Bases: flask_velox.mixins.sqla.read.TableModelMixin, flask_velox.views.sqla.read.ModelListView

View renders model lists in a table extending ModelListView adding extra attributes to configure the table output.

flask_velox.views.sqla.forms

Module provides Views for handling CRUD actions on SQLAlchemy models using Flask-WTForms.

Note

Requires the following packages are installed:

  • Flask-SQLAlchemy
  • Flask-WTF
class flask_velox.views.sqla.forms.CreateModelView(*args, **kwargs)

Bases: flask_velox.mixins.sqla.forms.CreateModelFormMixin

View for creating new model objects.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from flask.ext.velox.views.sqla.forms import CreateModelView
from yourapp import db
from yourapp.forms import MyForm
from yourapp.models import MyModel

class MyView(CreateModelView):
    template = 'create.html'
    session = db.session
    model = MyModel
    form = MyForm
class flask_velox.views.sqla.forms.UpdateModelFormView(*args, **kwargs)

Bases: flask_velox.mixins.sqla.forms.UpdateModelFormMixin

View for updating model objects.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from flask.ext.velox.views.sqla.forms import UpdateModelView
from yourapp import db
from yourapp.forms import MyForm
from yourapp.models import MyModel

class MyView(UpdateModelView):
    template = 'update.html'
    session = db.session
    model = MyModel
    form = MyForm
class flask_velox.views.sqla.forms.UpdateModelMultiFormView(*args, **kwargs)

Bases: flask_velox.mixins.sqla.forms.UpdateModelMultiFormMixin

View for rendering mutliple forms for a single object.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from flask.ext.velox.views.sqla.forms import UpdateModelView
from yourapp import db
from yourapp.forms import FooForm, BarForm
from yourapp.models import MyModel

class MyView(UpdateModelView):
    template = 'update.html'
    session = db.session
    model = MyModel
    forms = [
        ('Foo Form', FooForm),
        ('Bar Form', BarForm)
    ]
flask_velox.views.sqla.delete

Views for deleting objects from databases using SQLAlchemy

Note

The following packages must be installed:

  • Flask-SQLAlchemy
class flask_velox.views.sqla.delete.DeleteObjectView(*args, **kwargs)

Bases: flask_velox.mixins.sqla.delete.DeleteObjectMixin

View for deleting single objects from databases using SQLAlchemy.

Example

1
2
3
4
5
6
7
8
from flask.ext.velox.views.sqla.delete import DeleteObjectView
from yourapp import db
from yourapp.models import MyModel

class MyView(DeleteObjectView):
    template = 'delete.html'
    model = MyModel
    session = db.session
class flask_velox.views.sqla.delete.MultiDeleteObjectView(*args, **kwargs)

Bases: flask_velox.mixins.sqla.delete.MultiDeleteObjectMixin

View for deleting multiple objects from databases using SQLAlchemy.

Example

1
2
3
4
5
6
7
8
from flask.ext.velox.views.sqla.delete import MultiDeleteObjectView
form yourapp import db
from yourapp.models import MyModel

class MyView(MultiDeleteObjectView):
    template = 'delete.html'
    model = MyModel
    session = db.session

flask_velox.admin

This module provides Flas-Admin integration with Flask-Velox.

Modules
flask_velox.admin.mixins

Extends the default mixins to work with Flask-Admin.

Modules
flask_velox.admin.mixins.forms

Mixin classes for forms specific to Flask-Admin and Flask-WTForms

Note

The following packages must be installed.

  • Flask-WTF
  • Flask-Admin
class flask_velox.admin.mixins.forms.AdminBaseFormMixin(*args, **kwargs)

Bases: flask_velox.mixins.context.ContextMixin, flask_velox.admin.mixins.template.AdminTemplateMixin

Base Admin Form Mixin.

Warning

Use this mixin inconjunction with other mixins, cannot be used on its own.

cancel_url_rule str, optional

Flask url rule for cancel link, defaults to .index

cancel_url(**kwargs)

Returns the url to a cancel endpoint, this is used to render a link in forms to exit:

<a href="{{ cancel_url() }}">Cancel</a>

The cancel_url_rule must be defined.

Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url
Return type:str or None
delete_url(**kwargs)

Returns the url to a delete endpoint, this is used to render a link in forms to delete an object:

<a href="{{ delete_url(id=object.id) }}">Cancel</a>

If delete_url_rule is not defined this method will not be called.

Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url
Return type:str or None
get_cancel_url_rule()

Returns the cancel_url_rule or raises NotImplementedError if not defined.

Returns:Defined cancel_url_rule
Return type:str
get_delete_url_rule()

Returns the delete_url_rule or None if not defined.

Returns:Defined delete_url_rule
Return type:str or None
get_redirect_url_rule()

Returns raw redirect url rule to be used in url_for. If the redirect_url_rule is not defined then .index will be returned.

Returns:Raw flask url endpoint
Return type:str
post(admin, *args, **kwargs)

Hadnle HTTP POST requests. Overrides default post behaviour allowing the view on POST reqeuests to be processed by Flask-Admin

See also

  • flask_velox.views.forms.BaseModelView.post()
Returns:Rendered template
Return type:str
set_context()

Adds extra context variables.

Note

Adds the following extra context variables:

  • cancel_url_rule: str
  • cancel_url: func

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()
class flask_velox.admin.mixins.forms.AdminFormMixin(*args, **kwargs)

Bases: flask_velox.admin.mixins.forms.AdminBaseFormMixin, flask_velox.mixins.forms.FormMixin

Admin form mixin class provides the ability to render forms within the Flask-Admin System for an SQLAlchemy model.

class flask_velox.admin.mixins.forms.AdminMultiFormMixin(*args, **kwargs)

Bases: flask_velox.admin.mixins.forms.AdminBaseFormMixin, flask_velox.mixins.forms.MultiFormMixin

Admin form mixin class provides the ability to render multiple forms within the Flask-Admin System for an SQLAlchemy model.

flask_velox.admin.mixins.template

Module provides mixin classes for integrating Flask-Velox Views with Flask-Admin.

class flask_velox.admin.mixins.template.AdminTemplateMixin

Bases: flask_velox.mixins.template.TemplateMixin

Overrides default TemplateMixin methods to provide admin rendering functionality.

Note

get(admin, *args, **kwargs)

Handles HTTP GET requests to View. Also sets self._admin which contains the passed admin view.

Parameters:admin (obj) – The current admin view
get_admin()

Returns the current admin system to render templates within the Flask-Admin system.

Returns:Current admin view
Return type:obj
render()

Renders template within the Flask-Admin system.

flask_velox.admin.mixins.sqla

This module provides mixin classes for Flask-SQLAlchemy allowing integration with Flask-Admin.

Modules
flask_velox.admin.mixins.sqla.delete

Provides mixin classes to delete SQLAlchemy objects from within a Flask-Admin interface.

Note

The following packages must be installed:

  • Flask-SQLAlchemy
  • Flask-Admin
class flask_velox.admin.mixins.sqla.delete.AdminDeleteBaseMixin

Bases: object

Base mixin class to be used inconjunction with other mixin classes.

cancel_url(**kwargs)

Returns the url to a cancel endpoint, this is used to render a link in forms to exit:

<a href="{{ cancel_url() }}">Cancel</a>

The cancel_url_rule must be defined.

Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url
Return type:str or None
get_cancel_url_rule()

Returns the cancel_url_rule or if not defined returns default value of .index.

Returns:Defined cancel_url_rule
Return type:str
get_redirect_url_rule()

Returns raw redirect url rule to be used in url_for. If the redirect_url_rule is not defined then .index will be returned.

Returns:Raw flask url endpoint
Return type:str
redirect_url(**kwargs)

Returns the url to a redirect endpoint, when the form is valid and the callback is called.

Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url
Return type:str or None
set_context()

Adds extra context variables to be used in delete view templates.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()

Note

Adds the following context variables:

  • object: The object to be deleted
  • cancel_url: Function for retrieving cancel url in template
class flask_velox.admin.mixins.sqla.delete.AdminDeleteObjectMixin(*args, **kwargs)

Bases: flask_velox.admin.mixins.sqla.delete.AdminDeleteBaseMixin, flask_velox.mixins.sqla.delete.DeleteObjectMixin, flask_velox.admin.mixins.template.AdminTemplateMixin

Mixin provides object deletion support from within a Flask-Admin system.

redirect_url_rule str, optional

Raw flask url to send users on success, defaults to .index

cancel_url_rule str, optional

Raw flask url to send users on cancel, defaults to .index

class flask_velox.admin.mixins.sqla.delete.AdminMultiDeleteObjectMixin(*args, **kwargs)

Bases: flask_velox.admin.mixins.sqla.delete.AdminDeleteBaseMixin, flask_velox.mixins.sqla.delete.MultiDeleteObjectMixin, flask_velox.admin.mixins.template.AdminTemplateMixin

Mixin provides multi object deletion support from within a Flask-Admin system.

redirect_url_rule str, optional

Raw flask url to send users on success, defaults to .index

cancel_url_rule str, optional

Raw flask url to send users on cancel, defaults to .index

post(admin, *args, **kwargs)

Overrides post method in order to capture admin view for rendering within admin system.

flask_velox.admin.mixins.sqla.read

Mixin classes specific to Flask-Admin and Flask-SQLAlchemy based views.

Note

The following packages must be installed:

  • Flask-Admin
  • Flask-SQLAlchemy
class flask_velox.admin.mixins.sqla.read.AdminTableModelMixin(*args, **kwargs)

Bases: flask_velox.mixins.sqla.read.TableModelMixin

Extends the default functionality of flask_velox.mixins.sqla.model.TableModelMixin adding admin specific functionality, for example the ability to add CRUD urls so the table can render links to other views.

Example

1
2
3
4
5
6
from yourapp.models import MyModel
class MyView(AdminTableModelMixin):
    model = MyModel
    with_selected = {
       'Delete': 'admin.mymodel.delete',
    }

Note

The Flask URL Rules shown above are dependant on how the admin class is registered. In this case it would be registered with an endpoint key word argument, for example:

MyView(
    name='My Model',
    url='mymodel',
    endpoint='admin.mymodel')
create_url_rule str, optional

Flask url rule for linkinging to create views for the model, defaults to .create

update_url_rule str, optional

Flask url rule for linkinging to update views for the model, defaults to .update

delete_url_rule str, optional

Flask url rule for linkinging to delete views for the model, defaults to .delete

with_selected dict, optional

Dictionary containg a human name as the key and a Flask url rule as the value. In the example below Delete is the name which will appear in the With Selected with the url being the destination of the link.

create_url(**kwargs)

Returns the url to a create endpoint, this is used to render a link in admin table views with the destination of this url, should be added to view context and called in the template:

<a href="{{ create_url() }}">Create New</a>

The create_url_rule must be defined otherwise None will be returned.

Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url or None
Return type:str or None
delete_url(**kwargs)

Returns the url for deleting a specific record, this method needs to be passed to the context of the view so it can be used in the template, for example:

{% for object in objects %}
    <a href="{{ delete_url(id=object.id) }}">Delete</a>
{% endfor %}

If delete_url_rule is not defined None will be returned.

Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url or None
Return type:str or None
get_create_url_rule()

Returns the create_url_rule or None if not defined.

Returns:Defined create_url_rule or None
Return type:str or None
get_delete_url_rule()

Returns the delete_url_rule or None if not defined.

Returns:Defined delete_url_rule or None
Return type:str or None
get_update_url_rule()

Returns the update_url_rule or None if not defined.

Returns:Defined update_url_rule or None
Return type:str or None
get_with_selected()

Just returns the value of with_selected or None of not defined.

Returns:Values of with_selcted
Return type:dict or None
set_context()

Adds extra context to Admin Table Views for Flask-Admin systems

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()

Note

Adds the following context variables.

  • create_url_rule: The raw url rule or None
  • create_url: Create url method
  • update_url_rule: The raw url rule or None
  • update_url: Update url method
  • delete_url_rule: The raw url rule or None
  • delete_url: Delete url method
  • with_selcted: With selcted values
update_url(**kwargs)

Returns the url for updating a specific record, this method needs to be passed to the context of the view so it can be used in the template, for example:

{% for object in objects %}
    <a href="{{ update_url(id=object.id) }}">Update</a>
{% endfor %}

If update_url_rule is not defined None will be returned.

Parameters:**kwargs – Arbitrary keyword arguments passed to Flask.url_for
Returns:Generated url or None
Return type:str or None
flask_velox.admin.views

Extends the default views to work with Flask-Admin.

Modules
flask_velox.admin.views.forms

Module provides classes for integrating Flask-Velox Form Views with Flask-Admin.

Note

The following packages must be installed:

  • Flask-Admin
  • Flask-WTForms
class flask_velox.admin.views.forms.AdminFormView(*args, **kwargs)

Bases: flask_velox.mixins.forms.FormMixin, flask_velox.admin.mixins.template.AdminTemplateMixin

Renders a normal form within a Flask-Admin view.

flask_velox.admin.views.template

Module provides classes for integrating Flask-Velox Views with Flask-Admin.

class flask_velox.admin.views.template.AdminTemplateView(*args, **kwargs)

Bases: flask_velox.views.template.TemplateView, flask_velox.admin.mixins.template.AdminTemplateMixin

Overrides default TemplateView methods to provide admin render functionality.

Note

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from flask import Flask
from flask.ext.admin import Admin, BaseView, expose_pluggable
from flask.ext.velox.admin.views import AdminTemplateView

app = Flask(__name__)
admin = Admin(app)

class AdminIndexView(BaseView):

    @expose_pluggable('/')
    class index(AdminTemplateView):
        template = 'admin/index.html'

admin.add_view(AdminIndexView(name='index'))
app.run()
flask_velox.admin.views.sqla

This module provides View classes for implementing Flask-SQLAlchemy with Flask-Admin.

Modules
flask_velox.admin.views.sqla.forms

Module provides classes for rendering views / forms for SQLAlchemy based models within Flask-Admin systems.

Note

The following packages must be installed:

  • Flask-SQLAlchemy
  • Flask-WTForms
  • Flask-Admin
class flask_velox.admin.views.sqla.forms.AdminCreateModelView(*args, **kwargs)

Bases: flask_velox.mixins.sqla.forms.CreateModelFormMixin, flask_velox.admin.mixins.forms.AdminFormMixin

Implements CreateModelFormMixin for Flask-Admin.

template str

Relative template path, defaults to admin/forms/create.html

class flask_velox.admin.views.sqla.forms.AdminUpdateModelView(*args, **kwargs)

Bases: flask_velox.mixins.sqla.forms.UpdateModelFormMixin, flask_velox.admin.mixins.forms.AdminFormMixin

Implements UpdateModelFormMixin for Flask-Admin.

template str

Relative template path, defaults to admin/forms/update.html

set_context()

Set extra context variables specific to Flask-Admin update views.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()
class flask_velox.admin.views.sqla.forms.AdminUpdateMultiFormView(*args, **kwargs)

Bases: flask_velox.mixins.sqla.forms.UpdateModelMultiFormMixin, flask_velox.admin.mixins.forms.AdminMultiFormMixin

Implements UpdateModelFormMixin for Flask-Admin with multiple forms.

template str

Relative template path, defaults to admin/forms/update.html

set_context()

Set extra context variables specific to Flask-Admin update views.

See also

  • from flask_velox.mixins.context.ContextMixin.set_context()
flask_velox.admin.views.sqla.read

Module provides classes for rendering views for SQLAlchemy based models within Flask-Admin systems.

Note

The following packages must be installed.

  • Flask-SQLAlchemy
  • Flask-Admin
class flask_velox.admin.views.sqla.read.AdminModelTableView(*args, **kwargs)

Bases: flask_velox.admin.mixins.template.AdminTemplateMixin, flask_velox.admin.mixins.sqla.read.AdminTableModelMixin, flask_velox.views.sqla.read.TableModelView

Extends the flask_velox.views.sqla.model.TableModelView view injecting an admin specific mixin extending the functionality of the view.

See also

  • flask_velox.admin.mixins.sqla.model.AdminTableModelMixin
flask_velox.admin.views.sqla.delete

Provides views for delete SQLAlchemy objects from within a Flask-Admin interface.

Note

The following packages must be installed:

  • Flask-SQLAlchemy
  • Flask-Admin
class flask_velox.admin.views.sqla.delete.AdminDeleteObjectView(*args, **kwargs)

Bases: flask_velox.admin.mixins.sqla.delete.AdminDeleteObjectMixin

Admin View for deleting a single SQL Alchemy object. Defines default template.

class flask_velox.admin.views.sqla.delete.AdminMultiDeleteObjectView(*args, **kwargs)

Bases: flask_velox.admin.mixins.sqla.delete.AdminMultiDeleteObjectMixin

Admin view for SQLAlchemy multi object deletion. Defines default template and implements HTTP POST request handling.

Change Log

2014.04.25

  • Feature: ObjectView and ObjectMixin for rendering single objects
  • Feature: request.view_args can now be accessed as view instance attributes for accessing in other methods
  • Feature: Ability to customise context name for objects / object within SQLAlchemy read views.

2014.04.24.2

  • Hotfix: Templates not included in MANIFEST.in resulting in missing from build.

2014.04.24.1

  • Hotfix: Fixed issue with BaseFormMixin where get_redirect_url_rule would look for an incorrect attribute resulting in NotImplementedError being risen.

Initial Release - 2014.04.24

  • Initial release and feature set

Authors

Thanks to these guys Flask-Velox would not be possible :)

  • Chris Reeves / @krak3n
  • Greg Reed / @peeklondon

Indices and tables