API¶
Core¶
View logic is often repetitive, there are standard patterns we repeat over again both within and across projects, and reimplementing the same patterns can be a bore.
These views take some of those patterns and abstract them so you can create views for common tasks quickly without having to write too much code.
Tasks such as rendering a template or redirecting to a new url can be performed by passing parameters at instantiation without defining additional classes.
Views¶
-
class
flask_generic_views.core.View(**kwargs)¶ Bases:
flask.views.ViewThe master class-based base view.
All other generic views inherit from this base class. This class itself inherits from
flask.views.Viewand adds a generic constructor, that will convert any keyword arguments to instance attributes.class GreetingView(View): greeting = 'Hello' def dispatch_request(self): return "{} World!".format(self.greeting) bonjour_view = GreetingView.as_view('bonjour', greeting='Bonjour') app.add_url_rule('/bonjour, view_func=bonjour_view)
The above example shows a generic view that allows us to change the greeting while setting up the URL rule.
-
class
flask_generic_views.core.MethodView(**kwargs)¶ Bases:
flask.views.MethodView,flask_generic_views.core.ViewView class that routes to methods based on HTTP verb.
This view allows us to break down logic based on the HTTP verb used, and avoid conditionals in our code.
class GreetingView(View): greeting = 'Hello' def get(self): return "{} World!".format(self.greeting) def post(self): name = request.form.get('name', 'World') return "{} {}!".format(self.greeting, name) bonjour_view = GreetingView.as_view('bonjour', greeting='Bonjour') app.add_url_rule('/bonjour, view_func=bonjour_view)
The above example will process the request differently depending on wether it was a HTTP POST or GET.
-
class
flask_generic_views.core.TemplateView(**kwargs)¶ Bases:
flask_generic_views.core.TemplateResponseMixin,flask_generic_views.core.ContextMixin,flask_generic_views.core.MethodViewRenders a given template, with the context containing parameters captured by the URL rule.
class AboutView(View): template_name = 'about.html' def get_context_data(self, **kwargs): kwargs['staff'] = ('John Smith', 'Jane Doe') return super(AboutView, self).get_context_data(self, **kwargs) app.add_url_rule('/about', view_func=AboutView.as_view('about'))
The
TemplateViewcan be subclassed to create custom views that render a template.about_view = TemplateView.as_view('about', template_name='about.html') app.add_url_rule('/about', view_func=about_view, defaults={ 'staff': ('John Smith', 'Jane Doe') })
It can also be used directly in a URL rule to avoid having to create additional classes.
-
get(**kwargs)¶ Handle request and return a template response.
Any keyword arguments will be passed to the views context.
Parameters: kwargs (dict) – keyword arguments from url rule Returns: response Return type: werkzeug.wrappers.Response
-
-
class
flask_generic_views.core.RedirectView(**kwargs)¶ Bases:
flask_generic_views.core.ViewRedirects to a given URL.
The given URL may contain dictionary-style format fields which will be interpolated against the keyword arguments captured from the URL rule using the
format()method.An URL rule endpoint may be given instead, which will be passed to
url_for()along with any keyword arguments captured by the URL rule.When no URL can be found a
Goneexception will be raised.class ShortView(RedirectView): permanent = True query_string = True endpoint = 'post-detail' def get_redirect_url(self, **kwargs): post = Post.query.get_or_404(base62.decode(kwargs['code'])) kwargs['slug'] = post.slug return super(ShortView, self).get_redirect_url(**kwargs) short_view = ShortView.as_view('short') app.add_url_rule('/s/<code>', view_func=short_view)
The above example will redirect “short links” where the pk is base62 encoded to the correct url.
google_view = RedirectView.as_view('google', url='http://google.com/') app.add_url_rule('/google', view_func=google_view)
It can also be used directly in a URL rule to avoid having to create additional classes for simple redirects.
-
endpoint= None¶ The name of the endpoint to redirect to. URL generation will be done using the same keyword arguments as are passed in for this view.
-
permanent= False¶ Whether the redirect should be permanent. The only difference here is the HTTP status code returned. When True, then the redirect will use status code 301. When False, then the redirect will use status code 302.
-
query_string= False¶ Whether to pass along the query string to the new location. When True, then the query string is appended to the URL. When False, then the query string is discarded.
-
dispatch_request(**kwargs)¶ Redirect the user to the result of.
get_redirect_url(), when by default it will issue a 302 temporary redirect, except whenpermanentis set to theTrue, then a 301 permanent redirect will be used.When the redirect URL is None, a
Goneexception will be raised.Any keyword arguments will be used to build the URL.
Parameters: kwargs (dict) – keyword arguments from url rule Returns: response Return type: werkzeug.wrappers.Response
-
get_redirect_url(**kwargs)¶ Retrieve URL to redirect to.
When
urlis not None then it is returned after being interpolated with the keyword arguments usingformat().When
urlis None andendpointis not None then it is passed tourl_for()with the keyword arguments, and any query string is removed.The query string from the current request can be added to the new URL by setting
query_stringtoTrue.Parameters: kwargs (dict) – keyword arguments Returns: URL Return type: str
-
-
class
flask_generic_views.core.FormView(**kwargs)¶ Bases:
flask_generic_views.core.TemplateResponseMixin,flask_generic_views.core.BaseFormViewView class to display a
Form. When invalid it shows the form with validation errors, when valid it redirects to a new URL.class ContactForm(Form): email = StringField('Name', [required(), email()]) message = TextAreaField('Message', [required()]) class ContactView(FormView): form_class = ContactForm success_url = '/thanks' template_name = 'contact.html' def form_valid(self, form): message = Message('Contact Form', body=form.message.data, recipients=['contact@example.com'], sender=form.email.data) mail.send(message) super(ContactView).form_valid(form)
The above example will render the template
contact.htmlwith an instance ofContactFormin the context variableview, when the user submits the form with valid data an email will be sent, and the user redirected to/thanks, when the form is submitted with invalid datacontent.htmlwill be rendered again, and the form will contain any error messages.
Helpers¶
-
class
flask_generic_views.core.ContextMixin¶ Bases:
objectDefault handling of view context data any mixins that modifies the views context data should inherit from this class.
class RandomMixin(ContextMixin): def get_context_data(self, **kwargs): kwargs.setdefault('number', random.randrange(1, 100)) return super(RandomMixin, self).get_context_data(**kwargs)
-
get_context_data(**kwargs)¶ Returns a dictionary representing the view context. Any keyword arguments provided will be included in the returned context.
The context of all class-based views will include a
viewvariable that points to theViewinstance.Parameters: kwargs (dict) – context Returns: context Return type: dict
-
-
class
flask_generic_views.core.TemplateResponseMixin¶ Bases:
objectCreates
Responseinstances with a rendered template based on the given context. The choice of template is configurable and can be customised by subclasses.class RandomView(TemplateResponseMixin, MethodView): template_name = 'random.html' def get(self): context = {'number': random.randrange(1, 100)} return self.create_response(context) random_view = RandomView.as_view('random') app.add_url_rule('/random, view_func=random_view)
-
mimetype= None¶ The mime type type to use for the response. The mimetype is passed as a keyword argument to
response_class.
-
response_class= flask.Response¶ The
Responseclass to be returned bycreate_response().
-
template_name= None¶ The string containing the full name of the template to use. Not defining
template_namewill cause the default implementation ofget_template_names()to raise aNotImplementedErrorexception.
-
create_response(context=None, **kwargs)¶ Returns a
response_classinstance containing the rendered template.If any keyword arguments are provided, they will be passed to the constructor of the response class.
Parameters: Returns: response
Return type:
-
get_template_list()¶ Returns a list of template names to use for when rendering the template.
The default implementation will return a list containing
template_name, when not specified aNotImplementedErrorexception will be raised.Returns: template list Return type: list Raises: NotImplementedError – when template_nameis not set
-
-
class
flask_generic_views.core.FormMixin¶ Bases:
flask_generic_views.core.ContextMixinProvides facilities for creating and displaying forms.
-
data= {}¶ A dictionary containing initial data for the form.
-
form_class= None¶ The form class to instantiate.
-
success_url= None¶ The URL to redirect to when the form is successfully processed.
-
prefix= ''¶ The prefix for the generated form.
-
form_invalid(form)¶ Creates a response using the return value of.
Parameters: form (flask_wtf.Form) – form instance Returns: response Return type: werkzeug.wrappers.Response
-
form_valid(form)¶ Redirects to
get_success_url().Parameters: form (flask_wtf.Form) – form instance Returns: response Return type: werkzeug.wrappers.Response
-
get_context_data(**kwargs)¶ Extends the view context with a
formvariable containing the return value ofget_form().Parameters: kwargs (dict) – context Returns: context Return type: dict
-
get_data()¶ Retrieve data to pass to the form.
By default returns a copy of
data.Returns: data Return type: dict
-
get_form()¶ Create a
Forminstance usingget_form_class()usingget_form_kwargs().Returns: form Return type: flask_wtf.Form
-
get_form_class()¶ Retrieve the form class to instantiate.
By default returns
form_class.Returns: form class Return type: type Raises: NotImplementedError – when form_classis not set
-
get_form_kwargs()¶ Retrieve the keyword arguments required to instantiate the form.
The
dataargument is set usingget_data()and theprefixargument is set usingget_prefix(). When the request is a POST or PUT, then theformdataargument will be set usingget_formdata().Returns: keyword arguments Return type: dict
-
get_formdata()¶ Retrieve prefix to pass to the form.
By default returns a
werkzeug.datastructures.CombinedMultiDictcontainingflask.request.formandflask.request.files.Returns: form / file data Return type: werkzeug.datastructures.CombinedMultiDict
-
get_prefix()¶ Retrieve prefix to pass to the form.
By default returns
prefix.Returns: prefix Return type: str
-
get_success_url()¶ Retrive the URL to redirect to when the form is successfully validated.
By default returns
success_url.Returns: URL Return type: str Raises: NotImplementedError – when success_urlis not set
-
-
class
flask_generic_views.core.ProcessFormView(**kwargs)¶ Bases:
flask_generic_views.core.MethodViewProvides basic HTTP GET and POST processing for forms.
This class cannot be used directly and should be used with a suitable mixin.
-
get(**kwargs)¶ Creates a response using the return value of.
get_context_data().Parameters: kwargs (dict) – keyword arguments from url rule Returns: response Return type: werkzeug.wrappers.Response
-
post(**kwargs)¶ Constructs and validates a form.
When the form is valid
form_valid()is called, when the form is invalidform_invalid()is called.Parameters: kwargs (dict) – keyword arguments from url rule Returns: response Return type: werkzeug.wrappers.Response
-
put(**kwargs)¶ Passes all keyword arguments to
post().Parameters: kwargs (dict) – keyword arguments from url rule Returns: response Return type: werkzeug.wrappers.Response
-
-
class
flask_generic_views.core.BaseFormView(**kwargs)¶ Bases:
flask_generic_views.core.FormMixin,flask_generic_views.core.ProcessFormViewView class to process handle forms without response creation.
SQLAlchemy¶
Views logic often relates to retrieving and persisting data in a database, these views cover some of the most common patterns for working with models using the SQLAlchemy library.
Tasks such as displaying, listing, creating, updating, and deleting objects can be performed by passing parameters at instantiation without defining additional classes.
Views¶
-
class
flask_generic_views.sqlalchemy.DetailView(**kwargs)¶ Bases:
flask_generic_views.sqlalchemy.SingleObjectTemplateResponseMixin,flask_generic_views.sqlalchemy.BaseDetailViewRenders a given template,, with the context containing an object retrieved from the database.
class PostDetailView(DetailView): model = Post def context_data(self, **kwargs): kwargs.setdefault('now', datetime.now()) post_detail = PostDetailView.as_view('post_detail') app.add_url_rule('/posts/<pk>', view_func=post_detail)
The above example will render the
post_detail.htmltemplate from a folder named after the current blueprint, when no blueprint is used it will look in the root template folder. The view context will contain the object asobjectand the current date-time asnow.post_detail = DetailView.as_view('post_detail', model=Post) app.add_url_rule('/post/<pk>', view_func=post_detail)
It can also be used directly in a URL rule to avoid having to create additional classes.
{# post_detail.html #} <h1>{{ object.title }}</h1> <p>{{ object.body }}</p> <p>Published: {{ object.published_at }}</p> <p>Date: {{ now }}</p>
-
class
flask_generic_views.sqlalchemy.ListView(**kwargs)¶ Bases:
flask_generic_views.sqlalchemy.MultipleObjectTemplateResponseMixin,flask_generic_views.sqlalchemy.BaseListViewRenders a given template,, with the context containing a list of objects retrieved from the database.
class PostListView(DetailView): model = Post def context_data(self, **kwargs): kwargs.setdefault('now', datetime.now()) post_list = PostDetailView.as_view('post_list') app.add_url_rule('/posts', view_func=post_list)
The above example will render the
post_list.htmltemplate from a folder named after the current blueprint, when no blueprint is used it will look in the root template folder. The view context will contain the list of objects aspost_listand the current date-time asnow.post_list = ListView.as_view('post_list', model=Post) app.add_url_rule('/posts', view_func=post_list)
It can also be used directly in a URL rule to avoid having to create additional classes.
{# post_list.html #} <ul> {% for post in object_list %} <li>{{ post.title }}</li> {% else %} <li>No posts found.</li> {% endfor %} </ul>
-
class
flask_generic_views.sqlalchemy.CreateView(**kwargs)¶ Bases:
flask_generic_views.sqlalchemy.SingleObjectTemplateResponseMixin,flask_generic_views.sqlalchemy.BaseCreateViewView class to display a form for creating an object. When invalid it shows the form with validation errors, when valid it saves a new object to the database and redirects to a new URL.
class PostCreateView(FormView): model = Post fields = ('title', 'body') success_url = '/posts/{id}' post_create = PostCreateView.as_view('post_create') app.add_url_rule('/posts/new', view_func=post_create)
The above example will render the template
post_form.htmlwith an instance offlask_wtf.Formin the context variableformwith fields based onfieldsandModelFormView.model, when the user submits the form with valid data an instance of Post will be saved to the database, and the user redirected to its page, when the form is submitted with invalid datapost_form.htmlwill be rendered again, and the form will contain any error messages.post_create = CreateView.as_view('post_create', model=Post, fields=('title', 'body'), success_url = '/posts/{id}') app.add_url_rule('/posts/new', view_func=post_create)
It can also be used directly in a URL rule to avoid having to create additional classes.
{# post_form.html #} <form action="" method="post"> <p>{{ form.title.label }} {{ form.title }}</p> <p>{{ form.title.label }} {{ form.title }}</p> <input type="submit" value="Save"> </form>
-
template_name_suffix= '_form'¶ The suffix to use when generating a template name from the model class
-
-
class
flask_generic_views.sqlalchemy.UpdateView(**kwargs)¶ Bases:
flask_generic_views.sqlalchemy.SingleObjectTemplateResponseMixin,flask_generic_views.sqlalchemy.BaseUpdateViewView class to display a form for updating an object. When invalid it shows the form with validation errors, when valid it saves the updated object to the database and redirects to a new URL.
class PostUpdateView(FormView): model = Post fields = ('title', 'body') success_url = '/posts/{id}' post_update = PostUpdateView.as_view('post_update') app.add_url_rule('/posts/new', view_func=post_update)
The above example will render the template
post_form.htmlwith an instance offlask_wtf.Formin the context variableformwith fields based onfieldsandModelFormView.model, when the user submits the form with valid data an instance of Post will be updated in the database, and the user redirected to its page, when the form is submitted with invalid datapost_form.htmlwill be rendered again, and the form will contain any error messages.post_update = UpdateView.as_view('post_update', model=Post, fields=('title', 'body'), success_url = '/posts/{id}') app.add_url_rule('/posts/<pk>/edit', view_func=post_update)
It can also be used directly in a URL rule to avoid having to create additional classes.
{# post_form.html #} <form action="" method="post"> <p>{{ form.title.label }} {{ form.title }}</p> <p>{{ form.title.label }} {{ form.title }}</p> <input type="submit" value="Save"> </form>
-
template_name_suffix= '_form'¶ The suffix to use when generating a template name from the model class
-
-
class
flask_generic_views.sqlalchemy.DeleteView(**kwargs)¶ Bases:
flask_generic_views.sqlalchemy.SingleObjectTemplateResponseMixin,flask_generic_views.sqlalchemy.BaseDeleteViewDisplays a confirmation page and deletes an existing object. The object will ve deleted on POST or DELETE requests, for GET requests a conformation page will be shown which should contain a form to POST to the same URL.
class PostDeleteView(DeleteView): model = Post success_url = "/posts" post_delete = PostDeleteView.as_view('post_delete') app.add_url_rule('/posts/<id>', view_func=post_delete)
The above will render
post_delete.htmlwhen accessed by GET request, for a POST or DELETE request an instance will be deleted from the database and the user redirected to/posts.post_delete = DeleteView.as_view('post_delete', model=Post, success_url = '/posts') app.add_url_rule('/posts/<id>/delete', view_func=post_delete)
It can also be used directly in a URL rule to avoid having to create additional classes.
{# post_form.html #} <form action="" method="post"> <p>Are you sure you want to delete "{{ object }}"?</p> <input type="submit" value="Delete"> </form>
-
template_name_suffix= '_delete'¶ The suffix to use when generating a template name from the model class
-
Helpers¶
-
flask_generic_views.sqlalchemy.session¶ A proxy to the current SQLAlchemy session provided by Flask-SQLAlchemy.
-
class
flask_generic_views.sqlalchemy.SingleObjectMixin¶ Bases:
flask_generic_views.core.ContextMixinProvides the ability to retrieve an object based on the current HTTP request.
-
object¶ The the object used by the view.
-
model= None¶ The
Modelclass used to retrieve the object used by this view.This property is a shorthand,
model = Postandquery = Post.queryare functionally identical.
-
slug_field= 'slug'¶ The name of model field that contains the slug
-
slug_view_arg= 'slug'¶ The name of the view keyword argument that contains the slug.
-
pk_view_arg= 'pk'¶ The name of the view keyword argument that contains the primary-key.
-
query_pk_and_slug= False¶ When True
get_object()will filter the query by both primary-key and slug when available.
-
get_context_data(**kwargs)¶ Extends the view context with
object.When
objectis set, anobject`variable containingobjectis added to the context.A variable named with the result of
get_context_object_name()containingobjectwill be added to the context.Parameters: kwargs (dict) – context Returns: context Return type: dict
-
get_context_object_name()¶ Retrieve the context variable name that
objectwill be stored under.By default it will return
context_object_name, falling back to a name based on the model fromqueryormodel, the modelBlogPostwould have the context object nameblog_post.Returns: context object name Return type: str
-
get_model()¶ Retrieve the model used to retrieve the object used by this view.
By default returns the model associated with
querywhen it’s set, otherwise it will returnmodel.Returns: model Return type: flask_sqlalchemy.Model
-
get_object()¶ Retrieve the object used by the view.
The
Queryobject fromget_query()will be used as a base query for the object.When
pk_view_argexists in the current requestsview_argsit will be used to filter the query by primary-key.When
slug_view_argexists in the current requestsview_argsand either no primary-key was found orquery_pk_and_slugisTruethen it will be used to filter the query byslug_field.Returns: object Return type: flask_sqlalchemy.Model Raises: werkzeug.exceptions.NotFound – when no result found
-
get_query()¶ Retrieve the query used to retrieve the object used by this view.
By default returns
querywhen it’s set, otherwise it will return a query formodel.Returns: query Return type: sqlalchemy.orm.query.Query
-
get_slug_field()¶ Retrive the name of model field that contains the slug.
By default it will return
slug_field.Returns: slug field Return type: str
-
-
class
flask_generic_views.sqlalchemy.BaseDetailView(**kwargs)¶ Bases:
flask_generic_views.sqlalchemy.SingleObjectMixin,flask_generic_views.core.MethodViewView class to retrieve an object.
-
get(**kwargs)¶ Set
objectto the result ofget_object()and create a response using the return value ofget_context_data().Parameters: kwargs (dict) – keyword arguments from url rule Returns: response Return type: werkzeug.wrappers.Response
-
-
class
flask_generic_views.sqlalchemy.SingleObjectTemplateResponseMixin¶ Bases:
flask_generic_views.core.TemplateResponseMixinCreates
Responseinstances with a rendered template based on the given context.When no template names are provided, the class will try and generate one based on the model name.
-
get_template_list()¶ Retrives a list of template names to use for when rendering the template.
When no
template_nameis set then the following will be provided instead:- the value of the
template_name_fieldfield on the model when availible. - A template based on
template_name_suffix, the model, and the current blueprint. The modelBlogArticlein blueprintbloggingwould generate the template nameblogging/blog_article_detail.html, no blueprint would generateblog_article_detail.html
Returns: list of template names Return type: list - the value of the
-
-
class
flask_generic_views.sqlalchemy.MultipleObjectMixin¶ Bases:
flask_generic_views.core.ContextMixinProvides the ability to retrieve a list of objects based on the current HTTP request.
If
paginate_byis specified, the object list will be paginated. You can specify the page number in the URL in one of two ways:Pass the page as a view argument in the url rule.
post_list = PostListView.as_view('post_list') app.add_url_rule('/posts/page/<int:page>', view_func=post_list)
Pass the page as a query-string argument in the request url.
/posts?page=5
When no page is provided it defaults to 1.
When
error_outis set, a non numeric page number or empty page (other than the first page) will result in aNotFoundexception.-
model= None¶ The
Modelclass used to retrieve the object used by this view.This property is a shorthand,
model = Postandquery = Post.queryare functionally identical.
-
per_page= None¶ The number of results to return per page, when None pagination will be disabled.
-
context_object_name= None¶ The name of the context variable name to store the
object_listin.
-
pagination_class= flask_sqlalchemy.Pagination¶ The
Paginationclass to be returned byget_pagination().
-
page_arg= 'page'¶ The name of the view / query-string keyword argument that contains the page number.
-
order_by= None¶ A
tupleof criteria to pass to pass to the queryorder_by()method.
-
apply_pagination(object_list, per_page, error_out)¶ Retrieves a 3-item tuple containing (pagination, object_list, is_paginated).
The
paginationfromget_pagination(), Theobject_listpaginated with page fromget_page()andper_page, and wether there is more than one page will be returned.When
error_outis set then aNotFoundexception will be raised when the page number is invalid, or refers to an empty page greater than 1.Parameters: - query (flask_sqlalchemy.BaseQuery) – sqlalchemy query
- per_page (int) – items per page
- error_out (bool) – error out
Returns: pagination instance, object list, is paginated
Return type: Raises: werkzeug.exceptions.NotFound – when page number is invalid
-
get_context_data(**kwargs)¶ Extends the view context with
object.When the return value of
get_per_page()is notNone, thenobject_listwill be paginated withapply_pagination()and the resultingpagination,object_listandis_paginatedwill be stored in the view context. Otherwise the result of executingobject_listwill be stored inobject_list,paginationwill beNone, andis_paginatedwill beFalse.A variable named with the result of
get_context_object_name()containingobject_listwill be added to the context.Parameters: kwargs (dict) – context Returns: context Return type: dict
-
get_context_object_name()¶ Retrieve the context variable name that
objectwill be stored under.By default it will return
context_object_name, falling back to a name based on the model fromqueryormodel, the modelBlogPostwould have the context object nameblog_post_list.Returns: context object name Return type: str
-
get_error_out()¶ Retrive how invalid page numbers or empty pages are handled.
When
Trueawerkzeug.exceptions.NotFoundwill be raised for invalid page numbers or empty pages greater than one.When
Falseinvalid page numbers will default to 1 and empty pages will be rendered with an emptyobject_list.By default returns
error_out.Returns: error out Return type: bool
-
get_model()¶ Retrieve the model used to retrieve the object used by this view.
By default returns the model associated with
querywhen it’s set, otherwise it will returnmodel.Returns: model Return type: flask_sqlalchemy.Model
-
get_order_by()¶ Retrieve a
tupleof criteria to pass to pass to the queryorder_by()method.Returns: list of order by criteria Return type: list
-
get_page(error_out)¶ Retrieve the current page number.
The page is first checked for in the view keyword arguments, and then the query-string arguments using the key from
page_arg.When the value is not a an unsigned integer greater than zero and
error_outisTruethen aNotFoundexception will be raised. WhenFalsethe page will default to 1.Parameters: error_out (bool) – raise error on invalid page number Returns: number of items per page Return type: int
-
get_pagination(query, page, per_page, total, items)¶ Parameters: - query (flask_sqlalchemy.BaseQuery) – sqlalchemy query
- page (int) – page number
- per_page (int) – items per page
- total (int) – total items
- items (list) – list of objects
Returns: pagination instance
Return type:
-
get_per_page()¶ Retrieve the number of items to show per page.
By default returns
per_page.Returns: number of items per page Return type: int
-
get_query()¶ Retrieve the query used to retrieve the object used by this view.
By default returns
querywhen it’s set, otherwise it will return a query formodel.Returns: query Return type: flask_sqlalchemy.BaseQuery
-
class
flask_generic_views.sqlalchemy.BaseListView(**kwargs)¶ Bases:
flask_generic_views.sqlalchemy.MultipleObjectMixin,flask_generic_views.core.MethodViewView class to retrieve a list of objects.
-
get(**kwargs)¶ Set
object_listto the result ofget_query()and create a view from the context.Parameters: kwargs (dict) – keyword arguments from url rule Returns: response Return type: werkzeug.wrappers.Response
-
-
class
flask_generic_views.sqlalchemy.MultipleObjectTemplateResponseMixin¶ Bases:
flask_generic_views.core.TemplateResponseMixin-
template_name_suffix= '_list'¶ The suffix to use when generating a template name from the model class
-
get_template_list()¶ Retrives a list of template names to use for when rendering the template.
When no
template_nameis set then the following will be provided instead:- A template based on
template_name_suffix, the model, and the current blueprint. The modelBlogArticlein blueprintbloggingwould generate the template nameblogging/blog_article_list.html, no blueprint would generateblog_article_list.html
Returns: list of template names Return type: list - A template based on
-
-
class
flask_generic_views.sqlalchemy.ModelFormMixin¶ Bases:
flask_generic_views.core.FormMixin,flask_generic_views.sqlalchemy.SingleObjectMixin-
fields= None¶ A
tupleofstrmapping to the names of column attribute on themodel, these will be added as form fields on the automatically generated form.
-
form_valid(form)¶ Creates or updates
objectfrommodel, persists it to database, and redirects toget_success_url().Parameters: form (flask_wtf.Form) – form instance Returns: response Return type: werkzeug.wrappers.Response
-
get_form_class()¶ Retrieve the form class to instantiate.
When
form_classis not set, a form class will be automatically generated usingmodelandfields.Returns: form class Return type: type
-
-
class
flask_generic_views.sqlalchemy.BaseCreateView(**kwargs)¶ Bases:
flask_generic_views.sqlalchemy.ModelFormMixin,flask_generic_views.core.ProcessFormViewView class for creating an object.
-
class
flask_generic_views.sqlalchemy.BaseUpdateView(**kwargs)¶ Bases:
flask_generic_views.sqlalchemy.ModelFormMixin,flask_generic_views.core.ProcessFormViewView class for updating an object.
-
get(**kwargs)¶ Set
objectto the result ofget_object()and create a response using the return value ofget_context_data().Parameters: kwargs (dict) – keyword arguments from url rule Returns: response Return type: werkzeug.wrappers.Response
-
post(**kwargs)¶ Set
objectto the result ofget_object()and construct and validates a form.When the form is valid
form_valid()is called, when the form is invalidform_invalid()is called.Parameters: kwargs (dict) – keyword arguments from url rule Returns: response Return type: werkzeug.wrappers.Response
-
-
class
flask_generic_views.sqlalchemy.DeletionMixin¶ Bases:
objectHandle the DELETE http method.
-
success_url= None¶ The URL to redirect to after deletion.
-
delete(**kwargs)¶ Set
objectto the result ofget_object(), delete the object from the database, and create a response using the return value ofget_context_data().Parameters: kwargs (dict) – keyword arguments from url rule Returns: response Return type: werkzeug.wrappers.Response
-
get_success_url()¶ Retrive the URL to redirect to when the form is successfully validated.
By default returns
success_urlafter being interpolated with the object attributes usingformat(). So"/posts/{id}"will be populated withself.object.idReturns: URL Return type: str
-
post(**kwargs)¶ Passes all keyword arguments to
delete().Parameters: kwargs (dict) – keyword arguments from url rule Returns: response Return type: werkzeug.wrappers.Response
-
-
class
flask_generic_views.sqlalchemy.BaseDeleteView(**kwargs)¶ Bases:
flask_generic_views.sqlalchemy.DeletionMixin,flask_generic_views.sqlalchemy.BaseDetailViewView class for deleting an object.