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.
Installation is simple, use your favourite PyPi package installer and install Flask-Velox, for example with pip:
pip install Flask-Velox
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()
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.
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.
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.
See also
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.
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()
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.
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:
Remember you are inheriting existing provided functionality which means you can easily customise it by overriding methods, examples below.
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.
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
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')
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:
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')
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.
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
Flask-Velox also has integration with SQLAlchemy models.
Note
The followuing packages are required:
Reading SQLAlchemy models in views is simple.
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:
Flask-SQLAlchemy gives us pagination if we want it, by default paginate is True and the number of records is limited to 30, but this can all be changed and configured.
class MyView(read.ModelListView):
model = Model
template = 'list.html'
paginate = False
class MyView(read.ModelListView):
model = Model
template = 'list.html'
per_page = 10
Here are some example templates.
<ul>
{% for object in objects %}
<li>{{ object.name }}</li>
{% endfor %}
</ul>
<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 %}
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.
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:
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.
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:
<html>
<head>
<meta charset="utf-8" />
<title>{{ object.name }}</title>
</head>
<body>
{{ object.description }}
</body>
</html>
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.
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:
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.
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'
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.
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:
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:
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'
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
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.
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.
<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>
Flask-Velox also has optional Flask-Admin integration which you can use to build admin systems rapidly.
Note
The following packages must be installed:
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.
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
Use the API Reference to look up how specific provided functionality works and how to extend it.
Fields to help with common functionality, for example Upload fields with WTForms.
Note
The following packages must be installed:
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')])
|
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 an existing file
Parameters: | relative (str) – The path to the saved the file to delete |
---|
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 |
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: |
|
---|
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 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 |
---|
Helper functions to assist in formatting data when rendering object data.
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 |
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: |
|
---|---|
Returns: | The value to use |
Return type: | str |
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 |
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.
See also
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()
|
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.
Default context to use when rendering the template
Example
1 2 3 4 | class FooView(ContextMixin):
context = {
'foo': 'bar',
}
|
Adds a new element to the context.
Parameters: |
|
---|---|
Returns: | The new context |
Return type: | dict |
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 |
Propety method which returns the current context.
Returns: | Current context value |
---|---|
Return type: | dict |
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 |
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
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 |
Mixin classes for handeling form rendering and processing.
Note
The following packages must be installed:
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.
Raw Flask url rule, e.g: some.url.rule
Flask url rule for form submit action e.g: ‘some.url.rule’
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')
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 |
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 |
Instantiates form if instance does not already exisst. Override this method to tailor form instantiation.
Parameters: |
|
---|---|
Returns: | Instantiated form |
Return type: | object |
Handle HTTP POST requets using Flask MethodView rendering a single html template.
Returns: | Rendered template |
---|---|
Return type: | str |
Returns the url to a redirect endpoint, when the form is valid and the callback is called.
See also
Parameters: | **kwargs – Arbitrary keyword arguments passed to Flask.url_for |
---|---|
Returns: | Generated url |
Return type: | str or None |
Overrides set_context to set extra context variables.
See also
Note
Adds the following extra context variables:
Returns the url to a submit endpoint, this is used to render a link in forms actions:
<form action="{{ submit_url() }}" method="POST">
...
</form>
See also
Parameters: | **kwargs – Arbitrary keyword arguments passed to Flask.url_for |
---|---|
Returns: | Generated url |
Return type: | str or None |
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 |
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
|
An uninstantiated WTForm class
Returns an instantiated WTForm class.
Returns: | Instantiated form |
---|---|
Return type: | object |
Returns defined form_class or riases NotImplementedError
Returns: | Uninstantiated WTForm class |
---|---|
Return type: | class |
Raises: | NotImplementedError – If form_class is not defined |
Overrides set_context to set extra context variables.
See also
Note
Adds the following extra context variables:
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 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 |
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: | NotImplementedError – forms attribute is not defined |
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 |
If the form has been submit run the validate on submit method and call the success callback if the form is valid.
Parameters: |
|
---|---|
Returns: | If the form was submit§ |
Return type: | bool |
Updates context to contain extra variables.
See also
Note
Adds the following extra context variables:
Module provides mixins for issuing HTTP Status codes using the Flask View.
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
|
Flask URL Rule passed into url_for
Status code to raise, defaults to 302
Dispatch the request, returning the redirect.func_closure
Returns: | Redirect response |
---|---|
Return type: | werkzeug.wrappers.Response |
Return a generated url from rule attribute.
Returns: | Generated url |
---|---|
Return type: | str |
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.
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()
|
Bases: flask.views.MethodView
Renders a template on HTTP GET request as long as the template attribute is defined.
Relative template path, e.g: templates/home.html
Example
1 2 | class MyView(TemplateMixin):
template = 'templates/home.html'
|
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 |
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 |
Handle HTTP GET requets using Flask MethodView rendering a single html template.
Returns: | Rendered template |
---|---|
Return type: | str |
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 |
This module provides mixin classes which extend the default flask_velox.mixins functionality but add support for Flask-SQLAlchemy models.
See also
Module provides mixin classes for dealing with SQLALchemy models
Note
The following packages must be installed:
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
|
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')
|
A SQLAlchemy base query object, if defined this will be used instead of self.model.query.all()
Instead of using object you can set the context variable name to use for the object, defaults to object
Paginate the records using SQLAlchemy query.paginate, defaults True
If paginate is True customise the number of records to show per page, defaults to 30
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 |
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 |
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 |
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.
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 |
Adds extra context to SQLAlchemy based list views.
See also
Note
Adds the following context variables.
Returns: | Rendered template |
---|---|
Return type: | str |
Bases: flask_velox.mixins.sqla.object.SingleObjectMixin
Mixin for returning a single object.
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 the context for a Object view.
See also
Note
Adds the following context variables.
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']
|
A list of columns to render, this should map to model fields
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
}
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 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: |
|
---|---|
Returns: | Formatted value |
Return type: | anything |
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 |
Return formatters defined for the View using this Mixin.
Returns: | Returns defined formatters or None |
---|---|
Return type: | dict or None |
Adds extra context to SQLAlchemy table based list views.
See also
Note
Adds the following context variables.
Mixin classes for helping build forms with WTForms populating SQLAlchemy objects.
Note
The following packages must be installed:
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.
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 |
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 created message to user.
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 updated message to user.
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)
See also
Returns: | Instantiated form |
---|---|
Return type: | object |
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
]
|
Mixin classes for deleting SQLAlchemy objects from the Database.
Note
The following packages must be installed:
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
|
Ensure a confirmed flag is required when processing the view, defaults to True
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 |
Deletes the object, only if can_delete() returns True.
Flashes a success message to the user.
Adds extra context variables to be used in delete view templates.
See also
Note
Adds the following context variables:
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 |
---|
Bases: flask_velox.mixins.sqla.delete.DeleteObjectMixin
Mixin provides functionality to delete mutliple objects of the same model.
Override default delete functionality adding the ability to delete multiple objects of the same model but only if can_delete() is True.
Flashes a success message to the user.
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 |
Allowed HTTP Methods
Handle HTTP POST requests rendering a template.
Override context to add objects rather than object to the context.
Mixin classes for obtaining object of an SQLAlchemy model.
Note
The following packages must be installed:
Bases: flask_velox.mixins.context.ContextMixin
Mixin provides SQLAlchemy model integration.
SQLAlchemy un-instanciated model class
SQLAlchemy session instance
The primary key field name, defaults to id
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 |
---|
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 |
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 |
---|
Overrides set_context to set extra context variables.
See also
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:
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
|
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 |
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 |
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 |
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.
See also
Module provides views for basic form rendering and processing.
Note
The following packages must be installed:
Bases: flask_velox.mixins.forms.FormMixin
Class implements flask_velox.mixins.forms.FormMixin allowing rendering of Flask-WTF forms.
Note
Context pased to template:
Example
from flask.ext.velox.views.forms import FormView
from yourapp.forms import MyForm
class MyView(FormView):
template = 'form.html'
form = MyForm
x.__delattr__(‘name’) <==> del x.name
default object formatter
x.__getattribute__(‘name’) <==> x.name
x.__hash__() <==> hash(x)
helper for pickle
helper for pickle
x.__repr__() <==> repr(x)
x.__setattr__(‘name’, value) <==> x.name = value
size of object in memory, in bytes
x.__str__() <==> str(x)
Adds a new element to the context.
Parameters: |
|
---|---|
Returns: | The new context |
Return type: | dict |
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.
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 |
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')
Handle HTTP GET requets using Flask MethodView rendering a single html template.
Returns: | Rendered template |
---|---|
Return type: | str |
Propety method which returns the current context.
Returns: | Current context value |
---|---|
Return type: | dict |
Returns an instantiated WTForm class.
Returns: | Instantiated form |
---|---|
Return type: | object |
Returns defined form_class or riases NotImplementedError
Returns: | Uninstantiated WTForm class |
---|---|
Return type: | class |
Raises: | NotImplementedError – If form_class is not defined |
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 |
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 |
Instantiates form if instance does not already exisst. Override this method to tailor form instantiation.
Parameters: |
|
---|---|
Returns: | Instantiated form |
Return type: | object |
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 |
Handle HTTP POST requets using Flask MethodView rendering a single html template.
Returns: | Rendered template |
---|---|
Return type: | str |
Returns the url to a redirect endpoint, when the form is valid and the callback is called.
See also
Parameters: | **kwargs – Arbitrary keyword arguments passed to Flask.url_for |
---|---|
Returns: | Generated url |
Return type: | str or None |
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 |
Overrides set_context to set extra context variables.
See also
Note
Adds the following extra context variables:
Returns the url to a submit endpoint, this is used to render a link in forms actions:
<form action="{{ submit_url() }}" method="POST">
...
</form>
See also
Parameters: | **kwargs – Arbitrary keyword arguments passed to Flask.url_for |
---|---|
Returns: | Generated url |
Return type: | str or None |
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 |
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 |
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:
Example
from flask.ext.velox.views.forms import MultiFormView
from yourapp.forms import FooForm, BarForm
class MyView(MultiFormView):
template = 'forms.html'
forms = [FooForm, BarForm]
x.__delattr__(‘name’) <==> del x.name
default object formatter
x.__getattribute__(‘name’) <==> x.name
x.__hash__() <==> hash(x)
helper for pickle
helper for pickle
x.__repr__() <==> repr(x)
x.__setattr__(‘name’, value) <==> x.name = value
size of object in memory, in bytes
x.__str__() <==> str(x)
Adds a new element to the context.
Parameters: |
|
---|---|
Returns: | The new context |
Return type: | dict |
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.
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 |
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')
Handle HTTP GET requets using Flask MethodView rendering a single html template.
Returns: | Rendered template |
---|---|
Return type: | str |
Propety method which returns the current context.
Returns: | Current context value |
---|---|
Return type: | dict |
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 |
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: | NotImplementedError – forms attribute is not defined |
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 |
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 |
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 |
Instantiates form if instance does not already exisst. Override this method to tailor form instantiation.
Parameters: |
|
---|---|
Returns: | Instantiated form |
Return type: | object |
If the form has been submit run the validate on submit method and call the success callback if the form is valid.
Parameters: |
|
---|---|
Returns: | If the form was submit§ |
Return type: | bool |
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 |
Handle HTTP POST requets using Flask MethodView rendering a single html template.
Returns: | Rendered template |
---|---|
Return type: | str |
Returns the url to a redirect endpoint, when the form is valid and the callback is called.
See also
Parameters: | **kwargs – Arbitrary keyword arguments passed to Flask.url_for |
---|---|
Returns: | Generated url |
Return type: | str or None |
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 |
Updates context to contain extra variables.
See also
Note
Adds the following extra context variables:
Returns the url to a submit endpoint, this is used to render a link in forms actions:
<form action="{{ submit_url() }}" method="POST">
...
</form>
See also
Parameters: | **kwargs – Arbitrary keyword arguments passed to Flask.url_for |
---|---|
Returns: | Generated url |
Return type: | str or None |
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 |
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 |
Module provides views for issuing HTTP status codes using Flask MethodView.
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
|
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()
|
Bases: flask_velox.mixins.context.ContextMixin, flask_velox.mixins.template.TemplateMixin
Renders a template with optionl context.
Relative template path, e.g: templates/home.html
Default context to use when rendering the template
Example
1 2 3 4 5 | class HomeView(TemplateView):
template = 'templates/home.html'
context = {
'hello': 'word'
}
|
x.__delattr__(‘name’) <==> del x.name
default object formatter
x.__getattribute__(‘name’) <==> x.name
x.__hash__() <==> hash(x)
helper for pickle
helper for pickle
x.__repr__() <==> repr(x)
x.__setattr__(‘name’, value) <==> x.name = value
size of object in memory, in bytes
x.__str__() <==> str(x)
Adds a new element to the context.
Parameters: |
|
---|---|
Returns: | The new context |
Return type: | dict |
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.
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 |
Handle HTTP GET requets using Flask MethodView rendering a single html template.
Returns: | Rendered template |
---|---|
Return type: | str |
Propety method which returns the current context.
Returns: | Current context value |
---|---|
Return type: | dict |
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 |
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 |
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
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 |
This module provides views classes which extend the default flask_velox.views functionality but add support for Flask-SQLAlchemy models implimenting mixin classes.
Module provides classes for rendering views for SQLAlchemy based models.
Note
The following packages must be installed:
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()
|
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()
|
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.
Module provides Views for handling CRUD actions on SQLAlchemy models using Flask-WTForms.
Note
Requires the following packages are installed:
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
|
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
|
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)
]
|
Views for deleting objects from databases using SQLAlchemy
Note
The following packages must be installed:
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
|
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
|
This module provides Flas-Admin integration with Flask-Velox.
See also
Extends the default mixins to work with Flask-Admin.
See also
Mixin classes for forms specific to Flask-Admin and Flask-WTForms
Note
The following packages must be installed.
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.
Flask url rule for cancel link, defaults to .index
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.
See also
Parameters: | **kwargs – Arbitrary keyword arguments passed to Flask.url_for |
---|---|
Returns: | Generated url |
Return type: | str or None |
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.
See also
Parameters: | **kwargs – Arbitrary keyword arguments passed to Flask.url_for |
---|---|
Returns: | Generated url |
Return type: | str or None |
Returns the cancel_url_rule or raises NotImplementedError if not defined.
Returns: | Defined cancel_url_rule |
---|---|
Return type: | str |
Returns the delete_url_rule or None if not defined.
Returns: | Defined delete_url_rule |
---|---|
Return type: | str or None |
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 |
Hadnle HTTP POST requests. Overrides default post behaviour allowing the view on POST reqeuests to be processed by Flask-Admin
See also
Returns: | Rendered template |
---|---|
Return type: | str |
Adds extra context variables.
Note
Adds the following extra context variables:
See also
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.
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.
Module provides mixin classes for integrating Flask-Velox Views with Flask-Admin.
Bases: flask_velox.mixins.template.TemplateMixin
Overrides default TemplateMixin methods to provide admin rendering functionality.
Note
Handles HTTP GET requests to View. Also sets self._admin which contains the passed admin view.
Parameters: | admin (obj) – The current admin view |
---|
Note
Returns the current admin system to render templates within the Flask-Admin system.
Returns: | Current admin view |
---|---|
Return type: | obj |
Renders template within the Flask-Admin system.
Note
Overrides: flask_velox.mixins.template.TemplateMixin.render()
This module provides mixin classes for Flask-SQLAlchemy allowing integration with Flask-Admin.
Provides mixin classes to delete SQLAlchemy objects from within a Flask-Admin interface.
Note
The following packages must be installed:
Bases: object
Base mixin class to be used inconjunction with other mixin classes.
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.
See also
Parameters: | **kwargs – Arbitrary keyword arguments passed to Flask.url_for |
---|---|
Returns: | Generated url |
Return type: | str or None |
Returns the cancel_url_rule or if not defined returns default value of .index.
Returns: | Defined cancel_url_rule |
---|---|
Return type: | str |
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 |
Returns the url to a redirect endpoint, when the form is valid and the callback is called.
See also
Parameters: | **kwargs – Arbitrary keyword arguments passed to Flask.url_for |
---|---|
Returns: | Generated url |
Return type: | str or None |
Adds extra context variables to be used in delete view templates.
See also
Note
Adds the following context variables:
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.
Raw flask url to send users on success, defaults to .index
Raw flask url to send users on cancel, defaults to .index
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.
Raw flask url to send users on success, defaults to .index
Raw flask url to send users on cancel, defaults to .index
Overrides post method in order to capture admin view for rendering within admin system.
Mixin classes specific to Flask-Admin and Flask-SQLAlchemy based views.
Note
The following packages must be installed:
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')
Flask url rule for linkinging to create views for the model, defaults to .create
Flask url rule for linkinging to update views for the model, defaults to .update
Flask url rule for linkinging to delete views for the model, defaults to .delete
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.
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 |
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 |
Returns the create_url_rule or None if not defined.
Returns: | Defined create_url_rule or None |
---|---|
Return type: | str or None |
Returns the delete_url_rule or None if not defined.
Returns: | Defined delete_url_rule or None |
---|---|
Return type: | str or None |
Returns the update_url_rule or None if not defined.
Returns: | Defined update_url_rule or None |
---|---|
Return type: | str or None |
Just returns the value of with_selected or None of not defined.
Returns: | Values of with_selcted |
---|---|
Return type: | dict or None |
Adds extra context to Admin Table Views for Flask-Admin systems
See also
Note
Adds the following context variables.
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 |
Extends the default views to work with Flask-Admin.
See also
Module provides classes for integrating Flask-Velox Form Views with Flask-Admin.
Note
The following packages must be installed:
Bases: flask_velox.mixins.forms.FormMixin, flask_velox.admin.mixins.template.AdminTemplateMixin
Renders a normal form within a Flask-Admin view.
Module provides classes for integrating Flask-Velox Views with Flask-Admin.
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()
|
This module provides View classes for implementing Flask-SQLAlchemy with Flask-Admin.
See also
Module provides classes for rendering views / forms for SQLAlchemy based models within Flask-Admin systems.
Note
The following packages must be installed:
Bases: flask_velox.mixins.sqla.forms.CreateModelFormMixin, flask_velox.admin.mixins.forms.AdminFormMixin
Implements CreateModelFormMixin for Flask-Admin.
Relative template path, defaults to admin/forms/create.html
Bases: flask_velox.mixins.sqla.forms.UpdateModelFormMixin, flask_velox.admin.mixins.forms.AdminFormMixin
Implements UpdateModelFormMixin for Flask-Admin.
Relative template path, defaults to admin/forms/update.html
Set extra context variables specific to Flask-Admin update views.
See also
Bases: flask_velox.mixins.sqla.forms.UpdateModelMultiFormMixin, flask_velox.admin.mixins.forms.AdminMultiFormMixin
Implements UpdateModelFormMixin for Flask-Admin with multiple forms.
Relative template path, defaults to admin/forms/update.html
Set extra context variables specific to Flask-Admin update views.
See also
Module provides classes for rendering views for SQLAlchemy based models within Flask-Admin systems.
Note
The following packages must be installed.
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
Provides views for delete SQLAlchemy objects from within a Flask-Admin interface.
Note
The following packages must be installed:
Bases: flask_velox.admin.mixins.sqla.delete.AdminDeleteObjectMixin
Admin View for deleting a single SQL Alchemy object. Defines default template.
Bases: flask_velox.admin.mixins.sqla.delete.AdminMultiDeleteObjectMixin
Admin view for SQLAlchemy multi object deletion. Defines default template and implements HTTP POST request handling.
Thanks to these guys Flask-Velox would not be possible :)