API

This documentation is for Flask-Diamond 0.5.1.

Diamond object

class flask_diamond.Diamond(name=None)[source]

A Diamond application.

Parameters:app (Flask) – a Flask app that you created on your own
Returns:None
facet(extension_name, *args, **kwargs)[source]

initialize an extension

super(extension_name, *args, **kwargs)[source]

invoke the initialization method for the superclass

ex: self.super(“administration”)

teardown(exception)[source]

Remove any persistent connections during application context teardown.

Returns:None

models

models.user

class flask_diamond.models.user.User(**kwargs)[source]

Bases: flask_sqlalchemy.Model, flask_security.core.UserMixin, flask_diamond.mixins.crud.CRUDMixin, flask_diamond.mixins.marshmallow.MarshmallowMixin

active

boolean – whether the user account is active

add_role(role_name)[source]

update a User account so that it includes a new Role

Parameters:role_name (string) – the name of the Role to add
confirm()[source]

update a User account so that login is permitted

Returns:None
confirmed_at

datetime – when the user account was confirmed

current_login_at

datetime – the time of the current login, if any

current_login_ip

string – the IP address of the current login

email

string – email address

id

integer – primary key

last_login_at

datetime – the time of the most recent login

last_login_ip

string – the IP address of the previous login

login_count

integer – the number of times this account been accessed

password

password – the users’s password

classmethod register(email, password, confirmed=False, roles=None)[source]

Create a new user account.

Parameters:
  • email (string) – the email address used to identify the account
  • password (string) – the plaintext password for the account
  • confirmed (boolean) – whether to confirm the account immediately
  • roles (list(string)) – a list containing the names of the Roles for this User
roles
class flask_diamond.models.user.UserSchema(obj=None, extra=None, only=None, exclude=None, prefix=u'', strict=False, many=False, skip_missing=False, context=None)[source]

Bases: flask_marshmallow.Schema

class Meta[source]
additional = ('id', 'email', 'password', 'active', 'last_login_ip', 'current_login_ip', 'login_count')
dateformat = '%F %T %z'

models.role

class flask_diamond.models.role.Role(**kwargs)[source]

Bases: flask_sqlalchemy.Model, flask_security.core.RoleMixin, flask_diamond.mixins.crud.CRUDMixin, flask_diamond.mixins.marshmallow.MarshmallowMixin

For the purpose of access controls, Roles can be used to create collections of users and give them permissions as a group.

classmethod add_default_roles()[source]

Create a basic set of users and roles

Returns:None
description

string – a sentence describing the role

id

integer – primary key

name

string – what the role is called

class flask_diamond.models.role.RoleSchema(obj=None, extra=None, only=None, exclude=None, prefix=u'', strict=False, many=False, skip_missing=False, context=None)[source]

Bases: flask_marshmallow.Schema

class Meta[source]
additional = ('id', 'name', 'description')

mixins

mixins.crud

class flask_diamond.mixins.crud.CRUDMixin[source]

Convenience functions for CRUD operations.

Adapted from flask-kit.

classmethod create(_commit=True, **kwargs)[source]

Create a new object.

Parameters:
  • commit (boolean) – whether to commit the change immediately to the database
  • kwargs (dict) – parameters corresponding to the new values
Returns:

the object that was created

delete(_commit=True)[source]

Delete this object.

Parameters:commit (boolean) – whether to commit the change immediately to the database
Returns:whether the delete was successful
classmethod find(**kwargs)[source]

Find an object in the database with certain properties.

Parameters:kwargs (dict) – the values of the object to find
Returns:the object that was found, or else None
classmethod find_or_create(_commit=True, **kwargs)[source]

Find an object or, if it does not exist, create it.

Parameters:kwargs (dict) – the values of the object to find or create
Returns:the object that was created
classmethod get_by_id(id)[source]

Retrieve an object of this class from the database.

Parameters:id (integer) – the id of the object to be retrieved
Returns:the object that was retrieved
save(_commit=True)[source]

Save this object to the database.

Parameters:commit (boolean) – whether to commit the change immediately to the database
Returns:the object that was saved
update(_commit=True, **kwargs)[source]

Update this object with new values.

Parameters:
  • commit (boolean) – whether to commit the change immediately to the database
  • kwargs (dict) – parameters corresponding to the new values
Returns:

the object that was updated

mixins.marshmallow

class flask_diamond.mixins.marshmallow.MarshmallowMixin[source]
dump()[source]

serialize the Model object as a python object

classmethod dump_all()[source]

write all objects of Model class to an array of python objects

dumpf(file_handle)[source]

write a Model object to file_handle as a JSON string

classmethod dumpf_all(file_handle)[source]

write all objects of Model class to file_handle as JSON

dumps()[source]

serialize the Model object as a JSON string

classmethod dumps_all()[source]

write all objects of Model class to a JSON-encoded array

classmethod load(python_obj)[source]

create a Model object from a python object

classmethod load_all(python_objects)[source]

create objects of Model class from an array of python objects

classmethod loadf(file_handle)[source]

create a Model object from a file_handle pointing to a JSON file

classmethod loadf_all(file_handle)[source]

create objects of Model class from a file containing an array of JSON-encoded objects

classmethod loads(buf)[source]

create a Model object from a JSON-encoded string

classmethod loads_all(buf)[source]

create objects of Model class from a string containing an array of JSON-encoded objects

facets

facets.accounts

flask_diamond.facets.accounts.init_accounts(self, user=None, role=None, *args, **kwargs)[source]

Initialize Security for application.

Parameters:kwargs (dict) – parameters that will be passed through to Flask-Security
Returns:None

A number of common User account operations are provided by Flask- Security. This function is responsible for associating User models in the database with the Security object.

In case you need to override a Flask-Security form (as is the case with implementing CAPTCHA) then you must use super() from within your application and provide any arguments destined for Flask-Security.

>>> result = self.super("accounts", user=User, role=Role,
>>>    confirm_register_form=ExtendedRegisterForm)

facets.administration

flask_diamond.facets.administration.init_administration(self, index_view=None, user=None, role=None)[source]

Initialize the Administrative GUI.

Parameters:index_view (AdminIndexView) – the View that will act as the index page of the admin GUI.
Returns:None

The administration GUI is substantially derived from Flask-Admin. When this function is called, it will instantiate blueprints so the application serves the admin GUI via the URL http://localhost/admin.

Typically, you will want to call this function even if you override it. The following example illustrates using super() to invoke this administration() function from within your own application.

>>> admin = super(MyApp, self).administration(
>>>     index_view=MyApp.modelviews.RedirectView(name="Home")
>>> )

facets.blueprints

flask_diamond.facets.blueprints.init_blueprints(self)[source]

Initialize blueprints.

Returns:None

By default, this function does nothing. Your application needs to overload this function in order to implement your View functionality. More information about blueprints can be found in the Flask documentation.

facets.configuration

flask_diamond.facets.configuration.init_configuration(self)[source]

Load the application configuration from the SETTINGS environment variable.

Returns:None

SETTINGS must contain a filename that points to the configuration file.

facets.database

flask_diamond.facets.database.init_database(self)[source]

Initialize database

Returns:None

Flask-Diamond assumes you are modelling your solution using an Entity- Relationship framework, and that the application will use a relational database (e.g. MySQL, Postgres, or SQlite3) for model persistence. Thus, SQLAlchemy and Flask- SQLalchemy are used for database operations.

Typically, this just works as long as SQLALCHEMY_DATABASE_URI is set correctly in the application configuration.

facets.debugger

flask_diamond.facets.debugger.init_debugger(self)[source]

Initialize the DebugToolbar

Returns:None

The DebugToolbar is a handy utility for debugging your application during development.

This function obeys the DEBUG_TOOLBAR configuration setting. Only if this value is explicitly set to True will the Debug Toolbarr run.

facets.email

flask_diamond.facets.email.init_email(self)[source]

Initialize email facilities.

Returns:None

Flask-Mail is a useful tool for creating and sending emails from within a Flask application. There are a number of configuration settings beginning with MAIL_ that permit control over the SMTP credentials used to send email.

facets.forms

flask_diamond.facets.forms.add_helpers(app)[source]

Create any Jinja2 helpers needed.

flask_diamond.facets.forms.init_forms(self)[source]

WTForms helpers

Returns:None

WTForms is a great library for using forms and Flask-WTF provides good integration with it. WTForms helpers enable you to add custom filters and other custom behaviours.

facets.handlers

flask_diamond.facets.handlers.init_error_handlers(self)[source]

Initialize handlers for HTTP error events

Returns:None

Flask is able to respond to HTTP error codes with custom behaviours. By default, it will redirect error 403 (forbidden) to the login page.

flask_diamond.facets.handlers.init_request_handlers(self)[source]

request handlers

Returns:None

Flask handles requests for URLs by scanning the URL path. Typically, any serious functionality will be collected into Views. However, this function is a chance to define a few simple utility URLs.

If in your application you want to disable the default handlers in Flask-Diamond, you can override them like this.

>>> def request_handlers(self):
>>>     pass

facets.logs

flask_diamond.facets.logs.init_logs(self)[source]

Initialize a log file to collect messages.

Returns:None

This file may be written to using

>>> flask.current_app.logger.info("message")

facets.marshalling

flask_diamond.facets.marshalling.init_marshalling(self)[source]

Initialize Marshmallow.

Returns:None

facets.rest

flask_diamond.facets.rest.init_rest(self, api_map=None)[source]

Initialize REST API.

Returns:None

By default, this function does nothing. Your application needs to overload this function in order to implement your REST API. More information about REST can be found in the documentation.

api_map is an optional function that can be responsible for setting up the API. This is usually accomplished with a series of add_resource() invocations. api_map must take one parameter, which is the Flask-Restful object managed by Flask-Diamond.

You will end up writing something like this in your application:

class PlanetResource(Resource):
def get(self, name):

planet = Planet.find(name=name) if planet:

return(planet.dump())
def api_map(rest_extension):
rest_extension.add_resource(PlanetResource, ‘/api/planet/<string:name>’)
def create_app():
application.facet(“rest”, api_map=api_map)

facets.signals

flask_diamond.facets.signals.init_signals(self)[source]

Initialize Flask signal handlers

Returns:None

Flask provides a number of signals corresponding to things that happen during the operation of the application, which can also be thought of as events. It is possible to create signal handlers that will respond to these events with some behaviour.

facets.task_queue

flask_diamond.facets.task_queue.init_task_queue(self)[source]

Initialize celery.

facets.webassets

flask_diamond.facets.webassets.init_webassets(self, asset_map=None)[source]

Initialize web assets.

Returns:None

webassets make it simpler to process and bundle CSS and Javascript assets. This can be baked into a Flask application using Flask-Assets