Welcome to dokomoforms’s documentation!

Contents:

dokomoforms package

Subpackages

dokomoforms.handlers package

Subpackages
dokomoforms.handlers.api package
Subpackages
dokomoforms.handlers.api.v0 package
Submodules
dokomoforms.handlers.api.v0.base module

The base class of the TornadoResource classes in the api module.

class dokomoforms.handlers.api.v0.base.BaseResource(*args, **kwargs)[source]

Bases: restless.tnd.TornadoResource

Set up the basics for the model resource.

BaseResource does some basic configuration for the restless resources. - sets the base request handler class which is used by the resources - providing reference to the ORM session via request handler - inserting a serializer for dokomo Models - setting up authentication

build_response(data, status=200)

Finish the Tornado response.

This takes into account non-JSON content-types.

content_type

The format specified in the request.

current_user

The handler’s current_user.

current_user_model

The handler’s current_user_model.

default_sort_column_name

The default ORDER BY column name for list responses.

delete(model_id)

Set the deleted attribute to True. Does not destroy the instance.

detail(model_id)

Return a single instance of a model.

handle_error(err)

Generate a serialized error message.

If the error came from Tornado, pass it along as such. Otherwise, turn certain expected errors into 400 BAD REQUEST instead of 500 INTERNAL SERVER ERROR.

is_authenticated(admin_only=True)

Return whether the request has been authenticated.

list(where=None)

Return a list of instances of this model.

Given a model class, build up the ORM query based on query params and return the query result.

objects_key

The key for list responses.

query_modifiers_applied

Whether there were any modifiers applied to the query.

resource_type

The model class for the resource.

serializer = <dokomoforms.handlers.api.v0.serializer.ModelJSONSerializer object>
session

The handler’s session.

update(model_id)

Update a model.

wrap_list_response(data)

Wrap a list response in a dict.

Takes a list of data & wraps it in a dictionary (within the objects key). For security in JSON responses, it’s better to wrap the list results in an object (due to the way the Array constructor can be attacked in Javascript). See http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ & similar for details. Overridable to allow for modifying the key names, adding data (or just insecurely return a plain old list if that’s your thing). :param data: A list of data about to be serialized :type data: list :returns: A wrapping dict :rtype: dict

dokomoforms.handlers.api.v0.nodes module

TornadoResource class for dokomoforms.models.node.Node subclasses.

class dokomoforms.handlers.api.v0.nodes.NodeResource(*args, **kwargs)[source]

Bases: dokomoforms.handlers.api.v0.base.BaseResource

Restless resource for Nodes.

BaseResource sets the serializer, which uses the dokomo models’ ModelJSONEncoder for json conversion.

create()

Create a new node.

default_sort_column_name = 'last_update_time'
objects_key = 'nodes'
resource_type

alias of Node

dokomoforms.handlers.api.v0.photos module

TornadoResource class for dokomoforms.models.answer.Photo.

class dokomoforms.handlers.api.v0.photos.PhotoResource(*args, **kwargs)[source]

Bases: dokomoforms.handlers.api.v0.base.BaseResource

Restless resource for Photos.

create()

Create a Photo. Must match an existing PhotoAnswer.

default_sort_column_name = 'created_on'
is_authenticated()

Allow unauthenticated POSTs.

objects_key = 'photos'
resource_type

alias of Photo

dokomoforms.handlers.api.v0.serializer module

The restless Serializer for the models.

class dokomoforms.handlers.api.v0.serializer.ModelJSONSerializer[source]

Bases: restless.serializers.JSONSerializer

Drop-in replacement for the restless-supplied JSONSerializer.

Uses dokomo’s ModelJSONEncoder in order to correctly serialize models to JSON.

serialize(data)

The low-level serialization.

Underpins serialize, serialize_list & serialize_detail. Has no built-in smarts, simply dumps the JSON. :param data: The body for the response :type data: string :returns: A serialized version of the data :rtype: string

dokomoforms.handlers.api.v0.submissions module

TornadoResource class for dokomoforms.models.submission.Submission.

class dokomoforms.handlers.api.v0.submissions.SubmissionResource(*args, **kwargs)[source]

Bases: dokomoforms.handlers.api.v0.base.BaseResource

Restless resource for Submissions.

BaseResource sets the serializer, which uses the dokomo models’ ModelJSONEncoder for json conversion.

create()

Create a new submission.

Uses the current_user_model (i.e. logged-in user) as creator.

default_sort_column_name = 'save_time'
detail(submission_id)

Allow CSV export of a single submission.

is_authenticated()

Allow unauthenticated POSTs under the right circumstances.

objects_key = 'submissions'
resource_type

alias of Submission

wrap_list_response(data)

Allow CSV export of submission data.

This method adds CSV export functionality on top of the JSON list wrapping of BaseResource.wrap_list_response.

dokomoforms.handlers.api.v0.submissions.get_submission_for_handler(tornado_handler, submission_id)[source]

Maybe a handler needs a submission from the API.

dokomoforms.handlers.api.v0.surveys module

TornadoResource class for dokomoforms.models.survey.Survey.

class dokomoforms.handlers.api.v0.surveys.SurveyResource(*args, **kwargs)[source]

Bases: dokomoforms.handlers.api.v0.base.BaseResource

Restless resource for Surveys.

BaseResource sets the serializer, which uses the dokomo models’ ModelJSONEncoder for json conversion.

__init__(*args, **kwargs)

Make submit return 201.

activity(survey_id)

Get activity for a single survey.

activity_all()

Get activity for all surveys.

create()

Create a new survey.

Uses the current_user_model (i.e. logged-in user) as creator.

default_sort_column_name = 'created_on'
detail(survey_id)

Return the given survey.

Public surveys don’t require authentication. Enumerator-only surveys do required authentication, and the user must be one of the survey’s enumerators or an administrator.

http_methods = {'submit': {'POST': 'submit'}, 'stats': {'GET': 'stats'}, 'list': {'DELETE': 'delete_list', 'POST': 'create', 'PUT': 'update_list', 'GET': 'list'}, 'detail': {'DELETE': 'delete', 'POST': 'create_detail', 'PUT': 'update', 'GET': 'detail'}, 'list_submissions': {'GET': 'list_submissions'}, 'activity_all': {'GET': 'activity_all'}, 'activity': {'GET': 'activity'}}
is_authenticated()

GET detail is allowed unauthenticated.

list_submissions(survey_id)

List all submissions for a survey.

objects_key = 'surveys'
resource_type

alias of Survey

stats(survey_id)

Get stats for a survey.

submit(survey_id)

Submit to a survey.

dokomoforms.handlers.api.v0.surveys.get_survey_for_handler(tornado_handler, survey_id)[source]

Maybe a handler needs a survey from the API.

Module contents

Handlers for the API endpoints.

class dokomoforms.handlers.api.v0.ModelJSONSerializer[source]

Bases: restless.serializers.JSONSerializer

Drop-in replacement for the restless-supplied JSONSerializer.

Uses dokomo’s ModelJSONEncoder in order to correctly serialize models to JSON.

serialize(data)

The low-level serialization.

Underpins serialize, serialize_list & serialize_detail. Has no built-in smarts, simply dumps the JSON. :param data: The body for the response :type data: string :returns: A serialized version of the data :rtype: string

class dokomoforms.handlers.api.v0.BaseResource(*args, **kwargs)[source]

Bases: restless.tnd.TornadoResource

Set up the basics for the model resource.

BaseResource does some basic configuration for the restless resources. - sets the base request handler class which is used by the resources - providing reference to the ORM session via request handler - inserting a serializer for dokomo Models - setting up authentication

build_response(data, status=200)

Finish the Tornado response.

This takes into account non-JSON content-types.

content_type

The format specified in the request.

current_user

The handler’s current_user.

current_user_model

The handler’s current_user_model.

default_sort_column_name

The default ORDER BY column name for list responses.

delete(model_id)

Set the deleted attribute to True. Does not destroy the instance.

detail(model_id)

Return a single instance of a model.

handle_error(err)

Generate a serialized error message.

If the error came from Tornado, pass it along as such. Otherwise, turn certain expected errors into 400 BAD REQUEST instead of 500 INTERNAL SERVER ERROR.

is_authenticated(admin_only=True)

Return whether the request has been authenticated.

list(where=None)

Return a list of instances of this model.

Given a model class, build up the ORM query based on query params and return the query result.

objects_key

The key for list responses.

query_modifiers_applied

Whether there were any modifiers applied to the query.

resource_type

The model class for the resource.

serializer = <dokomoforms.handlers.api.v0.serializer.ModelJSONSerializer object>
session

The handler’s session.

update(model_id)

Update a model.

wrap_list_response(data)

Wrap a list response in a dict.

Takes a list of data & wraps it in a dictionary (within the objects key). For security in JSON responses, it’s better to wrap the list results in an object (due to the way the Array constructor can be attacked in Javascript). See http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ & similar for details. Overridable to allow for modifying the key names, adding data (or just insecurely return a plain old list if that’s your thing). :param data: A list of data about to be serialized :type data: list :returns: A wrapping dict :rtype: dict

class dokomoforms.handlers.api.v0.SurveyResource(*args, **kwargs)[source]

Bases: dokomoforms.handlers.api.v0.base.BaseResource

Restless resource for Surveys.

BaseResource sets the serializer, which uses the dokomo models’ ModelJSONEncoder for json conversion.

__init__(*args, **kwargs)

Make submit return 201.

activity(survey_id)

Get activity for a single survey.

activity_all()

Get activity for all surveys.

create()

Create a new survey.

Uses the current_user_model (i.e. logged-in user) as creator.

default_sort_column_name = 'created_on'
detail(survey_id)

Return the given survey.

Public surveys don’t require authentication. Enumerator-only surveys do required authentication, and the user must be one of the survey’s enumerators or an administrator.

http_methods = {'submit': {'POST': 'submit'}, 'stats': {'GET': 'stats'}, 'list': {'DELETE': 'delete_list', 'POST': 'create', 'PUT': 'update_list', 'GET': 'list'}, 'detail': {'DELETE': 'delete', 'POST': 'create_detail', 'PUT': 'update', 'GET': 'detail'}, 'list_submissions': {'GET': 'list_submissions'}, 'activity_all': {'GET': 'activity_all'}, 'activity': {'GET': 'activity'}}
is_authenticated()

GET detail is allowed unauthenticated.

list_submissions(survey_id)

List all submissions for a survey.

objects_key = 'surveys'
resource_type

alias of Survey

stats(survey_id)

Get stats for a survey.

submit(survey_id)

Submit to a survey.

dokomoforms.handlers.api.v0.get_survey_for_handler(tornado_handler, survey_id)[source]

Maybe a handler needs a survey from the API.

class dokomoforms.handlers.api.v0.SubmissionResource(*args, **kwargs)[source]

Bases: dokomoforms.handlers.api.v0.base.BaseResource

Restless resource for Submissions.

BaseResource sets the serializer, which uses the dokomo models’ ModelJSONEncoder for json conversion.

create()

Create a new submission.

Uses the current_user_model (i.e. logged-in user) as creator.

default_sort_column_name = 'save_time'
detail(submission_id)

Allow CSV export of a single submission.

is_authenticated()

Allow unauthenticated POSTs under the right circumstances.

objects_key = 'submissions'
resource_type

alias of Submission

wrap_list_response(data)

Allow CSV export of submission data.

This method adds CSV export functionality on top of the JSON list wrapping of BaseResource.wrap_list_response.

dokomoforms.handlers.api.v0.get_submission_for_handler(tornado_handler, submission_id)[source]

Maybe a handler needs a submission from the API.

class dokomoforms.handlers.api.v0.UserResource(*args, **kwargs)[source]

Bases: dokomoforms.handlers.api.v0.base.BaseResource

Restless resource for Users.

create()

Create a new user.

default_sort_column_name = 'name'
objects_key = 'users'
resource_type

alias of User

update(user_id)

Update a user.

class dokomoforms.handlers.api.v0.NodeResource(*args, **kwargs)[source]

Bases: dokomoforms.handlers.api.v0.base.BaseResource

Restless resource for Nodes.

BaseResource sets the serializer, which uses the dokomo models’ ModelJSONEncoder for json conversion.

create()

Create a new node.

default_sort_column_name = 'last_update_time'
objects_key = 'nodes'
resource_type

alias of Node

class dokomoforms.handlers.api.v0.PhotoResource(*args, **kwargs)[source]

Bases: dokomoforms.handlers.api.v0.base.BaseResource

Restless resource for Photos.

create()

Create a Photo. Must match an existing PhotoAnswer.

default_sort_column_name = 'created_on'
is_authenticated()

Allow unauthenticated POSTs.

objects_key = 'photos'
resource_type

alias of Photo

dokomoforms.handlers.user package
Submodules
dokomoforms.handlers.user.admin module

Admin view handlers.

class dokomoforms.handlers.user.admin.AdminHomepageHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The endpoint for the main Administrator interface.

get()

GET the admin interface.

class dokomoforms.handlers.user.admin.ViewSubmissionHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The endpoint for viewing a submission.

get(submission_id: str)

GET the visualization page.

class dokomoforms.handlers.user.admin.ViewSurveyDataHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The endpoint for getting a single survey’s data page.

get(survey_id: str)

GET the data page.

class dokomoforms.handlers.user.admin.ViewSurveyHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The endpoint for getting a single survey’s admin page.

get(survey_id: str)

GET the admin page for a survey.

class dokomoforms.handlers.user.admin.ViewUserAdminHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The endpoint for getting the user administration admin page.

get()

GET the user admin page.

dokomoforms.handlers.user.enumerate module

Survey view handler.

class dokomoforms.handlers.user.enumerate.Enumerate(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

View and submit to a survey.

get(survey_id)

GET the main survey view.

Render survey page for given survey id, embed JSON into to template so browser can cache survey in HTML.

Raises tornado http error.

@survey_id: Requested survey id.

class dokomoforms.handlers.user.enumerate.EnumerateHomepageHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The endpoint for the main Enumerator interface.

get()

GET the enumerate interface.

class dokomoforms.handlers.user.enumerate.EnumerateTitle(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

View and submit to a survey identified by title.

get(title)

GET the main survey view.

Render survey page for given survey title, embed JSON into to template so browser can cache survey in HTML.

Checks for Survey.url_slug

Raises tornado http error.

Module contents

The handlers for view pages.

Submodules
dokomoforms.handlers.auth module

Authentication handlers.

class dokomoforms.handlers.auth.CheckLoginStatus(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

An endpoint for the application to check login status.

post()

2xx good, 5xx bad.

class dokomoforms.handlers.auth.GenerateToken(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

GET your token here. GETting twice resets the token.

get()

Set a new token for the logged in user and return the token.

class dokomoforms.handlers.auth.Login(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

POST here to verify the assertion generated by Mozilla Persona.

post()

POST to Mozilla’s verifier service.

Accepts: { “assertion”: <assertion> }

Then, POSTS to https://verifier.login.persona.org/verify to verify that the assertion is valid. If so, attempts to log the user in by e-mail.

Responds with: 200 OK { “email”: <e-mail address> }

Raises:tornado.web.HTTPError – 400 Bad Request if the assertion is not verified 422 Unprocessable Entity if the e-mail address is not associated with a user account.
class dokomoforms.handlers.auth.Logout(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

POST here to log out.

post()

Delete the “user” cookie.

Note that this can’t be done in JavaScript because the user cookie is httponly.

dokomoforms.handlers.debug module

Pages pertaining to debug-specific functionality.

class dokomoforms.handlers.debug.DebugLoginHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

Use this page to log in as any existing user.

get(email='test@test_email.com', created=False)

Log in by supplying an e-mail address.

class dokomoforms.handlers.debug.DebugLogoutHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

Log out by visiting this page.

get()

Clear the ‘user’ cookie.

class dokomoforms.handlers.debug.DebugPersonaHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

For testing purposes there’s no need to hit the real URL.

No need for this...

post()

The test user has logged in.

class dokomoforms.handlers.debug.DebugRevisitHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

For testing purposes there’s no need to hit Revisit proper.

Debug endpoint.

get()

Get dummy facilities.

post()

Add a facility.

class dokomoforms.handlers.debug.DebugToggleRevisitHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

For turning the fake Revisit endpoint off and on.

get()

Toggle the ‘online’ state of the GET endpoint.

class dokomoforms.handlers.debug.DebugToggleRevisitSlowModeHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

For toggling slow mode.

get()

Toggle the ‘slow’ state of the GET endpoint.

class dokomoforms.handlers.debug.DebugUserCreationHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

Use this page to create a user.

get(email='test@test_email.com')

Log in for any user (creating one if necessary).

dokomoforms.handlers.debug.revisit_debug()[source]
dokomoforms.handlers.root module

Administrative handlers.

class dokomoforms.handlers.root.Index(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The root URL.

get(msg='')

GET /.

class dokomoforms.handlers.root.NotFound(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

This is the “default” handler according to Tornado.

prepare()

Raise a 404 for any URL without an explicitly defined handler.

Raises:tornado.web.HTTPError – 404 Not Found
write_error(*args, **kwargs)

Serve the custom 404 page.

dokomoforms.handlers.util module

Useful reusable functions for handlers, plus the BaseHandler.

class dokomoforms.handlers.util.BaseAPIHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The Tornado handler class for API resource classes.

api_root_path

The API URL up to the version number.

api_version

The API version.

Do not check XSRF for an API request (usually).

class dokomoforms.handlers.util.BaseHandler(application, request, **kwargs)[source]

Bases: tornado.web.RequestHandler

The base class for handlers.

Makes the database session and current user available.

current_user_model

Return the current logged in User, or None.

get(*args, **kwargs)

404 unless this method is overridden.

The presence of this GET method means that endpoints which only accept POST are hidden from browsers.

Raises:tornado.web.HTTPError – 404 Not Found
get_current_user() → str

Make current_user accessible.

You probably shouldn’t override this method. It makes {{ current_user }} accessible to templates and self.current_user accessible to handlers.

Returns:a string containing the user name.
get_template_namespace()

Template functions.

TODO: Find a way to get rid of this. @jmwohl

num_surveys_for_menu = 20
prepare()

Default behavior before any HTTP method.

By default, just sets up the XSRF token.

session

The SQLAlchemy session for interacting with the models.

Returns:the SQLAlchemy session
set_default_headers()

Add some security-flavored headers.

https://news.ycombinator.com/item?id=10143082

user_default_language

Return the logged-in User’s default language, or None.

user_survey_language(survey)

Return the logged-in User’s selected language for the given survey, or None if they do not have one.

write_error(status_code, **kwargs)

Deal with 404 errors.

dokomoforms.handlers.util.auth_redirect(self)[source]

The URL redirect logic extracted from tornado.web.authenticated.

dokomoforms.handlers.util.authenticated_admin(method)[source]

A copy of tornado.web.authenticated for Administrator access.

Module contents

All the Tornado RequestHandlers used in Dokomo Forms.

class dokomoforms.handlers.Index(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The root URL.

get(msg='')

GET /.

class dokomoforms.handlers.NotFound(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

This is the “default” handler according to Tornado.

prepare()

Raise a 404 for any URL without an explicitly defined handler.

Raises:tornado.web.HTTPError – 404 Not Found
write_error(*args, **kwargs)

Serve the custom 404 page.

class dokomoforms.handlers.Login(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

POST here to verify the assertion generated by Mozilla Persona.

post()

POST to Mozilla’s verifier service.

Accepts: { “assertion”: <assertion> }

Then, POSTS to https://verifier.login.persona.org/verify to verify that the assertion is valid. If so, attempts to log the user in by e-mail.

Responds with: 200 OK { “email”: <e-mail address> }

Raises:tornado.web.HTTPError – 400 Bad Request if the assertion is not verified 422 Unprocessable Entity if the e-mail address is not associated with a user account.
class dokomoforms.handlers.Logout(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

POST here to log out.

post()

Delete the “user” cookie.

Note that this can’t be done in JavaScript because the user cookie is httponly.

class dokomoforms.handlers.GenerateToken(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

GET your token here. GETting twice resets the token.

get()

Set a new token for the logged in user and return the token.

class dokomoforms.handlers.AdminHomepageHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The endpoint for the main Administrator interface.

get()

GET the admin interface.

class dokomoforms.handlers.CheckLoginStatus(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

An endpoint for the application to check login status.

post()

2xx good, 5xx bad.

class dokomoforms.handlers.ViewSurveyHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The endpoint for getting a single survey’s admin page.

get(survey_id: str)

GET the admin page for a survey.

class dokomoforms.handlers.ViewSurveyDataHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The endpoint for getting a single survey’s data page.

get(survey_id: str)

GET the data page.

class dokomoforms.handlers.ViewUserAdminHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The endpoint for getting the user administration admin page.

get()

GET the user admin page.

class dokomoforms.handlers.ViewSubmissionHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The endpoint for viewing a submission.

get(submission_id: str)

GET the visualization page.

class dokomoforms.handlers.EnumerateHomepageHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

The endpoint for the main Enumerator interface.

get()

GET the enumerate interface.

class dokomoforms.handlers.Enumerate(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

View and submit to a survey.

get(survey_id)

GET the main survey view.

Render survey page for given survey id, embed JSON into to template so browser can cache survey in HTML.

Raises tornado http error.

@survey_id: Requested survey id.

class dokomoforms.handlers.EnumerateTitle(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

View and submit to a survey identified by title.

get(title)

GET the main survey view.

Render survey page for given survey title, embed JSON into to template so browser can cache survey in HTML.

Checks for Survey.url_slug

Raises tornado http error.

class dokomoforms.handlers.DebugUserCreationHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

Use this page to create a user.

get(email='test@test_email.com')

Log in for any user (creating one if necessary).

class dokomoforms.handlers.DebugLoginHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

Use this page to log in as any existing user.

get(email='test@test_email.com', created=False)

Log in by supplying an e-mail address.

class dokomoforms.handlers.DebugLogoutHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

Log out by visiting this page.

get()

Clear the ‘user’ cookie.

class dokomoforms.handlers.DebugPersonaHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

For testing purposes there’s no need to hit the real URL.

No need for this...

post()

The test user has logged in.

class dokomoforms.handlers.DebugRevisitHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

For testing purposes there’s no need to hit Revisit proper.

Debug endpoint.

get()

Get dummy facilities.

post()

Add a facility.

class dokomoforms.handlers.DebugToggleRevisitHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

For turning the fake Revisit endpoint off and on.

get()

Toggle the ‘online’ state of the GET endpoint.

class dokomoforms.handlers.DebugToggleRevisitSlowModeHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

For toggling slow mode.

get()

Toggle the ‘slow’ state of the GET endpoint.

class dokomoforms.handlers.DemoUserCreationHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

Use this page to log in as the demo user.

get()

Create the demo account (if necessary) and log in.

class dokomoforms.handlers.DemoLogoutHandler(application, request, **kwargs)[source]

Bases: dokomoforms.handlers.util.BaseHandler

Log out by visiting this page.

get()

Clear the ‘user’ cookie.

dokomoforms.models package

Submodules
dokomoforms.models.answer module

Answer models.

class dokomoforms.models.answer.Answer(**kwargs)[source]

Bases: dokomoforms.models.util.Base

An Answer is a response to a SurveyNode.

An Answer can be one of an answer, an “other” response or a “don’t know” response. Answer.response abstracts over these 3 possibilites.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer

The answer. Could be the same as main_answer in simple cases.

This property is the most useful representation available of the answer. In the simplest case it is just a synonym for main_answer. It could otherwise be a dictionary or another model.

answer_metadata
answer_number
answer_type
deleted
dont_know

A text field containing “don’t know” responses.

id
last_update_time
main_answer

The representative part of a provided answer.

The main_answer is the only answer for simple types (integer, text, etc.) and for other types is the part of the answer that is most important. In practice, the main_answer is special only in that all Answer models have it, which is necessary for certain constraints and for the response property.

other

A text field containing “other” responses.

question_id
question_title
repeatable
response = OrderedDict([('type_constraint', <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7f6b541a03b8>), ('response_type', 'answer'), ('response', <property object at 0x7f6b54182ae8>)])
save_time
submission_id
survey_containing_id
survey_id
survey_node
survey_node_containing_survey_id
survey_node_id
type_constraint
class dokomoforms.models.answer.DateAnswer(**kwargs)[source]

Bases: dokomoforms.models.answer._AnswerMixin, dokomoforms.models.answer.Answer

A DATE answer.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer
answer_metadata
answer_number
answer_type
deleted
dont_know
id
last_update_time
main_answer
other
question_id
question_title
repeatable
save_time
submission_id
survey_containing_id
survey_id
survey_node
survey_node_containing_survey_id
survey_node_id
the_allow_dont_know
the_allow_other
type_constraint
class dokomoforms.models.answer.DecimalAnswer(**kwargs)[source]

Bases: dokomoforms.models.answer._AnswerMixin, dokomoforms.models.answer.Answer

A NUMERIC answer.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer
answer_metadata
answer_number
answer_type
deleted
dont_know
id
last_update_time
main_answer
other
question_id
question_title
repeatable
save_time
submission_id
survey_containing_id
survey_id
survey_node
survey_node_containing_survey_id
survey_node_id
the_allow_dont_know
the_allow_other
type_constraint
class dokomoforms.models.answer.FacilityAnswer(**kwargs)[source]

Bases: dokomoforms.models.answer._AnswerMixin, dokomoforms.models.answer.Answer

A facility answer (a la Revisit).

FacilityAnswer.answer is a dictionary with 4 keys: facility_location, facility_id, facility_name, facility_sector

facility_location accepts input in the form {

‘lng’: <longitude>, ‘lat’: <latitude>

} and outputs a GeoJSON.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer = OrderedDict([('facility_location', <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7f6b54126678>), ('facility_id', <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7f6b54134c50>), ('facility_name', <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7f6b54134d00>), ('facility_sector', <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7f6b54134db0>)])
answer_metadata
answer_number
answer_type
deleted
dont_know
facility_id
facility_name
facility_sector
geo_json
id
last_update_time
main_answer
other
question_id
question_title
repeatable
save_time
submission_id
survey_containing_id
survey_id
survey_node
survey_node_containing_survey_id
survey_node_id
the_allow_dont_know
the_allow_other
type_constraint
class dokomoforms.models.answer.IntegerAnswer(**kwargs)[source]

Bases: dokomoforms.models.answer._AnswerMixin, dokomoforms.models.answer.Answer

An INTEGER answer (signed 4 byte).

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer
answer_metadata
answer_number
answer_type
deleted
dont_know
id
last_update_time
main_answer
other
question_id
question_title
repeatable
save_time
submission_id
survey_containing_id
survey_id
survey_node
survey_node_containing_survey_id
survey_node_id
the_allow_dont_know
the_allow_other
type_constraint
class dokomoforms.models.answer.LocationAnswer(**kwargs)[source]

Bases: dokomoforms.models.answer._AnswerMixin, dokomoforms.models.answer.Answer

A GEOMETRY(‘POINT’, 4326) answer.

Accepts input in the form {

‘lng’: <longitude>, ‘lat’: <latitude>

}

The output is a GeoJSON.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer
answer_metadata
answer_number
answer_type
deleted
dont_know
geo_json
id
last_update_time
main_answer
other
question_id
question_title
repeatable
save_time
submission_id
survey_containing_id
survey_id
survey_node
survey_node_containing_survey_id
survey_node_id
the_allow_dont_know
the_allow_other
type_constraint
class dokomoforms.models.answer.MultipleChoiceAnswer(**kwargs)[source]

Bases: dokomoforms.models.answer._AnswerMixin, dokomoforms.models.answer.Answer

A Choice answer.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer
answer_metadata
answer_number
answer_type
choice
deleted
dont_know
id
last_update_time
main_answer
other
question_id
question_title
repeatable
save_time
submission_id
survey_containing_id
survey_id
survey_node
survey_node_containing_survey_id
survey_node_id
the_allow_dont_know
the_allow_other
the_question_id
the_submission_id
the_survey_node_id
type_constraint
class dokomoforms.models.answer.Photo(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A BYTEA holding an image.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

created_on
deleted
id
image
mime_type
class dokomoforms.models.answer.PhotoAnswer(**kwargs)[source]

Bases: dokomoforms.models.answer._AnswerMixin, dokomoforms.models.answer.Answer

A photo answer (the id of a Photo).

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

actual_photo_id
allow_dont_know
allow_multiple
allow_other
answer
answer_metadata
answer_number
answer_type
deleted
dont_know
id
last_update_time
main_answer
other
photo
question_id
question_title
repeatable
save_time
submission_id
survey_containing_id
survey_id
survey_node
survey_node_containing_survey_id
survey_node_id
the_allow_dont_know
the_allow_other
type_constraint
class dokomoforms.models.answer.TextAnswer(**kwargs)[source]

Bases: dokomoforms.models.answer._AnswerMixin, dokomoforms.models.answer.Answer

A TEXT answer.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer
answer_metadata
answer_number
answer_type
deleted
dont_know
id
last_update_time
main_answer
other
question_id
question_title
repeatable
save_time
submission_id
survey_containing_id
survey_id
survey_node
survey_node_containing_survey_id
survey_node_id
the_allow_dont_know
the_allow_other
type_constraint
class dokomoforms.models.answer.TimeAnswer(**kwargs)[source]

Bases: dokomoforms.models.answer._AnswerMixin, dokomoforms.models.answer.Answer

A TIME WITH TIME ZONE answer.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer
answer_metadata
answer_number
answer_type
deleted
dont_know
id
last_update_time
main_answer
other
question_id
question_title
repeatable
save_time
submission_id
survey_containing_id
survey_id
survey_node
survey_node_containing_survey_id
survey_node_id
the_allow_dont_know
the_allow_other
type_constraint
class dokomoforms.models.answer.TimestampAnswer(**kwargs)[source]

Bases: dokomoforms.models.answer._AnswerMixin, dokomoforms.models.answer.Answer

A TIMESTAMP WITH TIME ZONE answer.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer
answer_metadata
answer_number
answer_type
deleted
dont_know
id
last_update_time
main_answer
other
question_id
question_title
repeatable
save_time
submission_id
survey_containing_id
survey_id
survey_node
survey_node_containing_survey_id
survey_node_id
the_allow_dont_know
the_allow_other
type_constraint
dokomoforms.models.answer.add_new_photo_to_session(session, *, id, **kwargs)[source]

Create a new Photo and update the referenced PhotoAnswer.

dokomoforms.models.answer.construct_answer(*, type_constraint: str, **kwargs) → dokomoforms.models.answer.Answer[source]

Return a subclass of dokomoforms.models.answer.Answer.

The subclass is determined by the type_constraint parameter. This utility function makes it easy to create an instance of an Answer subclass based on external input.

See http://stackoverflow.com/q/30518484/1475412

Parameters:
  • type_constraint – the type of the answer. Must be one of the keys of dokomoforms.models.answer.ANSWER_TYPES
  • kwargs – the keyword arguments to pass to the constructor
Returns:

an instance of one of the Answer subtypes

Raies:

dokomoforms.exc.NotAnAnswerTypeError

dokomoforms.models.column_properties module

Extra properties for models.

These could not be defined inline with the models do to import issues. See http://docs.sqlalchemy.org/en/rel_1_0/orm/mapped_sql_expr.html #using-column-property

dokomoforms.models.column_properties.answer_avg(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the average of the answers.

dokomoforms.models.column_properties.answer_max(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the maximum answer.

dokomoforms.models.column_properties.answer_min(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the minimum answer.

dokomoforms.models.column_properties.answer_mode(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the mode of the answers.

dokomoforms.models.column_properties.answer_stddev_pop(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the population standard deviation of the answers.

dokomoforms.models.column_properties.answer_stddev_samp(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the sample standard deviation of the answers.

dokomoforms.models.column_properties.answer_sum(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the sum of the answers.

dokomoforms.models.column_properties.generate_question_stats(survey)[source]

Get answer statistics for the nodes in a survey.

dokomoforms.models.node module

A Node is either a note or a question and is independent of a Survey.

class dokomoforms.models.node.Choice(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A choice for a MultipleChoiceQuestion.

Models a choice for a dokomoforms.models.survey.MultipleChoiceQuestion.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

choice_number
choice_text
deleted
id
last_update_time
question_id
question_languages
class dokomoforms.models.node.DateQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A date question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.node.DecimalQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A decimal question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.node.FacilityQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A facility question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.node.IntegerQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A integer question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.node.LocationQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A location question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.node.MultipleChoiceQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A multiple_choice question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
choices
deleted
hint
id
languages
last_update_time
logic
node_languages
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.node.Node(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A node is a Note or Question independent of any Survey.

A node is its own entity. A node can be a dokomoforms.models.survey.Note or a dokomoforms.models.survey.Question.

You can use this class for querying, e.g.
session.query(Node).filter_by(title=’Some Title’)

To create the specific kind of Node you want, use dokomoforms.models.survey.node.construct_node.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

deleted
hint
id
languages
last_update_time
logic
title
type_constraint
class dokomoforms.models.node.Note(**kwargs)[source]

Bases: dokomoforms.models.node.Node

Notes provide information interspersed with survey questions.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

deleted
hint
id
languages
last_update_time
logic
the_type_constraint
title
type_constraint
class dokomoforms.models.node.PhotoQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A photo question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.node.Question(**kwargs)[source]

Bases: dokomoforms.models.node.Node

A Question has a response type associated with it.

A Question has a type constraint associated with it (integer, date, text...). Only a dokomoforms.models.survey.MultipleChoiceQuestion has a list of dokomoforms.models.survey.Choice instances.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.node.TextQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A text question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.node.TimeQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A time (with time zone) question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.node.TimestampQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A timestamp (with time zone) question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
dokomoforms.models.node.construct_node(*, type_constraint: str, **kwargs) → dokomoforms.models.node.Node[source]

Return a subclass of dokomoforms.models.node.Node.

The subclass is determined by the type_constraint parameter. This utility function makes it easy to create an instance of a Node or Question subclass based on external input.

See http://stackoverflow.com/q/30518484/1475412

Parameters:
  • type_constraint – the type constraint of the node. Must be one of the keys of dokomoforms.models.survey.NODE_TYPES
  • kwargs – the keyword arguments to pass to the constructor
Returns:

an instance of one of the Node subtypes

Raises:

dokomoforms.exc.NoSuchNodeTypeError

dokomoforms.models.submission module

Submission models.

class dokomoforms.models.submission.EnumeratorOnlySubmission(**kwargs)[source]

Bases: dokomoforms.models.submission.Submission

An EnumeratorOnlySubmission must have an enumerator.

Use an EnumeratorOnlySubmission for an EnumeratorOnlySurvey.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

answers
deleted
enumerator
enumerator_user_id
id
last_update_time
save_time
start_time
submission_time
submission_type
submitter_email
submitter_name
survey_containing_id
survey_default_language
survey_id
survey_title
survey_type
the_survey_id
class dokomoforms.models.submission.PublicSubmission(**kwargs)[source]

Bases: dokomoforms.models.submission.Submission

A PublicSubmission might have an enumerator.

Use a PublicSubmission for a Survey.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

answers
deleted
enumerator
enumerator_user_id
id
last_update_time
save_time
start_time
submission_time
submission_type
submitter_email
submitter_name
survey_containing_id
survey_default_language
survey_id
survey_title
survey_type
class dokomoforms.models.submission.Submission(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A Submission references a Survey and has a list of Answers.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

answers
deleted
id
last_update_time
save_time
start_time
submission_time
submission_type
submitter_email
submitter_name
survey_containing_id
survey_default_language
survey_id
survey_title
survey_type
dokomoforms.models.submission.construct_submission(*, submission_type: str, **kwargs) → dokomoforms.models.submission.Submission[source]

Return a subclass of dokomoforms.models.submission.Submission.

The subclass is determined by the submission_type parameter. This utility function makes it easy to create an instance of a Submission subclass based on external input.

See http://stackoverflow.com/q/30518484/1475412

Parameters:
  • submission_type – the type of submission. Must be either ‘public_submission’ or ‘enumerator_only_submission’
  • kwargs – the keyword arguments to pass to the constructor
Returns:

an instance of one of the Node subtypes

Raises:

dokomoforms.exc.NoSuchSubmissionTypeError

dokomoforms.models.submission.most_recent_submissions(session, user_id, limit=None)[source]

Get an administrator’s surveys’ most recent submissions.

dokomoforms.models.survey module

Survey models.

class dokomoforms.models.survey.AnswerableSurveyNode(**kwargs)[source]

Bases: dokomoforms.models.survey.SurveyNode

Contains a Node which is answerable (.e.g, a Question).

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer_count
answers
containing_survey_id
deleted
id
last_update_time
logic
node
node_id
node_languages
node_number
non_null_repeatable
required
root_survey_id
root_survey_languages
sub_survey_id
sub_survey_repeatable
sub_surveys
survey_node_answerable
the_containing_survey_id
the_node
the_node_id
the_node_languages
the_root_survey_languages
the_sub_survey_repeatable
the_type_constraint
type_constraint
class dokomoforms.models.survey.Bucket(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A Bucket determines how to arrive at a SubSurvey.

A Bucket can be a range or a Choice.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

bucket

The bucket is a range or Choice.

Buckets for a given SubSurvey cannot overlap.

bucket_type
deleted
id
last_update_time
sub_survey_id
sub_survey_parent_node_id
sub_survey_parent_survey_node_id
sub_survey_parent_type_constraint
class dokomoforms.models.survey.DateBucket(**kwargs)[source]

Bases: dokomoforms.models.survey._RangeBucketMixin, dokomoforms.models.survey.Bucket

DATERANGE bucket.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

bucket
bucket_type
deleted
id
last_update_time
sub_survey_id
sub_survey_parent_node_id
sub_survey_parent_survey_node_id
sub_survey_parent_type_constraint
the_survey_node_id
class dokomoforms.models.survey.DecimalBucket(**kwargs)[source]

Bases: dokomoforms.models.survey._RangeBucketMixin, dokomoforms.models.survey.Bucket

NUMRANGE bucket.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

bucket
bucket_type
deleted
id
last_update_time
sub_survey_id
sub_survey_parent_node_id
sub_survey_parent_survey_node_id
sub_survey_parent_type_constraint
the_survey_node_id
class dokomoforms.models.survey.EnumeratorOnlySurvey(**kwargs)[source]

Bases: dokomoforms.models.survey.Survey

Only enumerators (designated Users) can submit to this.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

administrators
containing_id
created_on
creator_id
default_language
deleted
earliest_submission_time
enumerators
id
languages
last_update_time
latest_submission_time
nodes
num_submissions
submissions
survey_metadata
survey_type
title
url_slug
version
class dokomoforms.models.survey.IntegerBucket(**kwargs)[source]

Bases: dokomoforms.models.survey._RangeBucketMixin, dokomoforms.models.survey.Bucket

INT4RANGE bucket.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

bucket
bucket_type
deleted
id
last_update_time
sub_survey_id
sub_survey_parent_node_id
sub_survey_parent_survey_node_id
sub_survey_parent_type_constraint
the_survey_node_id
class dokomoforms.models.survey.MultipleChoiceBucket(**kwargs)[source]

Bases: dokomoforms.models.survey.Bucket

Choice id bucket.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

bucket
bucket_type
choice_id
deleted
id
last_update_time
parent_node_id
parent_survey_node_id
sub_survey_id
sub_survey_parent_node_id
sub_survey_parent_survey_node_id
sub_survey_parent_type_constraint
the_sub_survey_id
class dokomoforms.models.survey.NonAnswerableSurveyNode(**kwargs)[source]

Bases: dokomoforms.models.survey.SurveyNode

Contains a Node which is not answerable (e.g., a Note).

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

containing_survey_id
deleted
id
last_update_time
logic
node
node_id
node_languages
node_number
non_null_repeatable
root_survey_id
root_survey_languages
sub_survey_id
sub_survey_repeatable
survey_node_answerable
the_node
the_node_id
the_type_constraint
type_constraint
class dokomoforms.models.survey.SubSurvey(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A SubSurvey behaves like a Survey but belongs to a SurveyNode.

The way to arrive at a certain SubSurvey is encoded in its buckets.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

buckets
containing_survey_id
deleted
id
nodes
parent_allow_multiple
parent_node_id
parent_survey_node_id
parent_type_constraint
repeatable
root_survey_languages
sub_survey_number
class dokomoforms.models.survey.Survey(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A Survey has a list of SurveyNodes.

Use an EnumeratorOnlySurvey to restrict submissions to enumerators.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

administrators
containing_id
created_on
creator_id
default_language
deleted
earliest_submission_time
id
languages
last_update_time
latest_submission_time
nodes
num_submissions
submissions
survey_metadata
survey_type
title
url_slug
version
class dokomoforms.models.survey.SurveyNode(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A SurveyNode contains a Node and adds survey-specific metadata.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

containing_survey_id
deleted
id
last_update_time
logic
node

The Node instance.

node_id
node_languages
node_number
non_null_repeatable
root_survey_id
root_survey_languages
sub_survey_id
sub_survey_repeatable
survey_node_answerable
the_node
type_constraint
class dokomoforms.models.survey.TimestampBucket(**kwargs)[source]

Bases: dokomoforms.models.survey._RangeBucketMixin, dokomoforms.models.survey.Bucket

TSTZRANGE bucket.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

bucket
bucket_type
deleted
id
last_update_time
sub_survey_id
sub_survey_parent_node_id
sub_survey_parent_survey_node_id
sub_survey_parent_type_constraint
the_survey_node_id
dokomoforms.models.survey.administrator_filter(user_id)[source]

Filter a query by administrator id.

dokomoforms.models.survey.construct_bucket(*, bucket_type: str, **kwargs) → dokomoforms.models.survey.Bucket[source]

Return a subclass of dokomoforms.models.survey.Bucket.

The subclass is determined by the bucket_type parameter. This utility function makes it easy to create an instance of a Bucket subclass based on external input.

See http://stackoverflow.com/q/30518484/1475412

Parameters:
  • bucket_type – the type of the bucket. Must be one of the keys of dokomoforms.models.survey.BUCKET_TYPES
  • kwargs – the keyword arguments to pass to the constructor
Returns:

an instance of one of the Bucket subtypes

Raises:

dokomoforms.exc.NoSuchBucketTypeError

dokomoforms.models.survey.construct_survey(*, survey_type: str, **kwargs)[source]

Construct either a public or enumerator_only Survey.

dokomoforms.models.survey.construct_survey_node(**kwargs) → dokomoforms.models.survey.SurveyNode[source]

Return a subclass of dokomoforms.models.survey.SurveyNode.

The subclass is determined by the type_constraint parameter. This utility function makes it easy to create an instance of a SurveyNode subclass based on external input.

See http://stackoverflow.com/q/30518484/1475412

Parameters:kwargs – the keyword arguments to pass to the constructor
Returns:an instance of one of the Node subtypes
dokomoforms.models.survey.most_recent_surveys(session, user_id, limit=None)[source]

Get an administrator’s most recent surveys.

dokomoforms.models.survey.skipped_required(survey, answers) → str[source]

Return the id of a skipped AnswerableSurveyNode, or None.

dokomoforms.models.user module

User models.

class dokomoforms.models.user.Administrator(**kwargs)[source]

Bases: dokomoforms.models.user.User

A User who can create Surveys and add Users.

Regular users can answer surveys, but only Administrator instances can create surveys.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

deleted
emails
id
last_update_time
name
preferences
role
surveys
token
token_expiration
class dokomoforms.models.user.Email(**kwargs)[source]

Bases: dokomoforms.models.util.Base

Models an e-mail address.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

address
deleted
id
last_update_time
user_id
class dokomoforms.models.user.User(**kwargs)[source]

Bases: dokomoforms.models.util.Base

Models a user. A user has at least one e-mail address.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

deleted
emails
id
last_update_time
name
preferences
role
dokomoforms.models.user.construct_user(*, role: str, **kwargs)[source]

Construct either an enumerator or an administrator.

dokomoforms.models.util module

Useful reusable functions for models.

Models should inherit from dokomforms.models.util.Base, and should almost certainly make use of the dokomoforms.models.util.pk and dokomoforms.models.util.last_update_time

The SQLAlchemy documentation suggests setting those columns in the base class or using class mixins, but it makes it less explicit which columns exist when looking at the models’ definitions.

class dokomoforms.models.util.Base(**kwargs)[source]

Bases: abc.Base

The base class for all Dokomo Forms models.

deleted = Column(None, Boolean(), table=None, nullable=False, server_default=DefaultClause('false', for_update=False))
class dokomoforms.models.util.ModelJSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

This JSONEncoder handles the models in dokomoforms.models.

To use it manually, call:

json.dumps(
model, cls=dokomoforms.models.util.ModelJSONEncoder, **kwargs

)

default(obj)

Handle special types for json.dumps.

If obj is a model from dokomoforms.models, return a dictionary representation.

If obj is a datetime.date or datetime.time, return an ISO 8601 representation string.

If obj is a psycpg2 Range, return its string representation.

Otherwise, throw a TypeError.

See https://docs.python.org/3/library/json.html#json.JSONEncoder.default

Modify a query to search a column’s values (JSONB or TEXT).

TODO: document this

Parameters:
  • query – a
  • model_cls – aa
  • column – b
  • search_term – c
  • language – d
  • regex – r
Returns:

The modified query.

dokomoforms.models.util.create_engine(pool_size: int=None, max_overflow: int=None, echo: bool=None) → sqlalchemy.engine.base.Engine[source]

Get a connection to the database.

Return a sqlalchemy.engine.Engine configured with the options set in dokomoforms.options.options

Returns:a SQLAlchemy engine
dokomoforms.models.util.fk(column_name: str) → sqlalchemy.sql.schema.Column[source]

A foreign key with ONUPDATE CASCADE and ONDELETE CASCADE.

Return a foreign key of type UUID for use in models.

The relationship CASCADEs on UPDATE and DELETE.

Parameters:column_name – the name of the referenced column
Returns:a SQLAlchemy Column for a UUID primary key.
dokomoforms.models.util.get_fields_subset(model: dokomoforms.models.util.Base, fields: list) → collections.OrderedDict[source]

Return the given fields for the model’s dictionary representation.

dokomoforms.models.util.get_model(session, model_cls, model_id, exception=None)[source]

Throw an error if session.query.get(model_id) returns None.

dokomoforms.models.util.json_column(column_name: str, *, default=None) → sqlalchemy.sql.schema.Column[source]

A JSONB column.

Return a column of type JSONB for use in models. Use this for entries like

<language>: <text>
Parameters:
  • column_name – the name of the column
  • default – the column default (default value None, meaning no column default)
Returns:

a SQLAlchemy Column for a non-null JSONB type.

dokomoforms.models.util.jsonify(obj, *, raise_exception=False) → object[source]

Convert the given object to something JSON can handle.

dokomoforms.models.util.languages_column(column_name) → sqlalchemy.sql.schema.Column[source]

A TEXT[] column of length > 0.

Return an ARRAY(TEXT, as_tuple=True) column.

Parameters:column_name – the name of the column
Returns:a SQLAlchemy Column for a non-null ARRAY(TEXT, as_tuple=True) type.
dokomoforms.models.util.languages_constraint(column_name, languages_column_name) → sqlalchemy.sql.schema.Constraint[source]

CHECK CONSTRAINT for a translatable column.

Checks that all of the languages in the languages column exist as keys in the translatable column.

Parameters:
  • column_name – the name of the translatable column
  • languages_column_name – the name of the TEXT[] column containing the languages.
Returns:

a SQLAlchemy Constraint to ensure that all the required translations are available.

dokomoforms.models.util.last_update_time() → sqlalchemy.sql.schema.Column[source]

A timestamp column set to CURRENT_TIMESTAMP on update.

Return a column containing the time that a record was last updated.

Returns:a SQLAlchemy Column for a datetime with time zone auto-updating column
dokomoforms.models.util.pk(*foreign_key_column_names: str) → sqlalchemy.sql.schema.Column[source]

A UUID primary key.

Return a standard primary key of type UUID for use in models. If the any foreign_key_column_names are supplied, the primary key will reference the given columns.

Parameters:foreign_key_column_names – column names of the referenced foreign keys (should be ‘table_name.column_name’)
Returns:a SQLAlchemy Column for a UUID primary key.
Module contents

All the models used in Dokomo Forms.

class dokomoforms.models.Base(**kwargs)[source]

Bases: abc.Base

The base class for all Dokomo Forms models.

deleted = Column(None, Boolean(), table=None, nullable=False, server_default=DefaultClause('false', for_update=False))
dokomoforms.models.create_engine(pool_size: int=None, max_overflow: int=None, echo: bool=None) → sqlalchemy.engine.base.Engine[source]

Get a connection to the database.

Return a sqlalchemy.engine.Engine configured with the options set in dokomoforms.options.options

Returns:a SQLAlchemy engine
dokomoforms.models.jsonify(obj, *, raise_exception=False) → object[source]

Convert the given object to something JSON can handle.

dokomoforms.models.get_model(session, model_cls, model_id, exception=None)[source]

Throw an error if session.query.get(model_id) returns None.

class dokomoforms.models.ModelJSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

This JSONEncoder handles the models in dokomoforms.models.

To use it manually, call:

json.dumps(
model, cls=dokomoforms.models.util.ModelJSONEncoder, **kwargs

)

default(obj)

Handle special types for json.dumps.

If obj is a model from dokomoforms.models, return a dictionary representation.

If obj is a datetime.date or datetime.time, return an ISO 8601 representation string.

If obj is a psycpg2 Range, return its string representation.

Otherwise, throw a TypeError.

See https://docs.python.org/3/library/json.html#json.JSONEncoder.default

class dokomoforms.models.User(**kwargs)[source]

Bases: dokomoforms.models.util.Base

Models a user. A user has at least one e-mail address.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

deleted
emails
id
last_update_time
name
preferences
role
class dokomoforms.models.Administrator(**kwargs)[source]

Bases: dokomoforms.models.user.User

A User who can create Surveys and add Users.

Regular users can answer surveys, but only Administrator instances can create surveys.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

deleted
emails
id
last_update_time
name
preferences
role
surveys
token
token_expiration
class dokomoforms.models.Email(**kwargs)[source]

Bases: dokomoforms.models.util.Base

Models an e-mail address.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

address
deleted
id
last_update_time
user_id
dokomoforms.models.construct_user(*, role: str, **kwargs)[source]

Construct either an enumerator or an administrator.

class dokomoforms.models.Node(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A node is a Note or Question independent of any Survey.

A node is its own entity. A node can be a dokomoforms.models.survey.Note or a dokomoforms.models.survey.Question.

You can use this class for querying, e.g.
session.query(Node).filter_by(title=’Some Title’)

To create the specific kind of Node you want, use dokomoforms.models.survey.node.construct_node.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

deleted
hint
id
languages
last_update_time
logic
title
type_constraint
class dokomoforms.models.Question(**kwargs)[source]

Bases: dokomoforms.models.node.Node

A Question has a response type associated with it.

A Question has a type constraint associated with it (integer, date, text...). Only a dokomoforms.models.survey.MultipleChoiceQuestion has a list of dokomoforms.models.survey.Choice instances.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
dokomoforms.models.construct_node(*, type_constraint: str, **kwargs) → dokomoforms.models.node.Node[source]

Return a subclass of dokomoforms.models.node.Node.

The subclass is determined by the type_constraint parameter. This utility function makes it easy to create an instance of a Node or Question subclass based on external input.

See http://stackoverflow.com/q/30518484/1475412

Parameters:
  • type_constraint – the type constraint of the node. Must be one of the keys of dokomoforms.models.survey.NODE_TYPES
  • kwargs – the keyword arguments to pass to the constructor
Returns:

an instance of one of the Node subtypes

Raises:

dokomoforms.exc.NoSuchNodeTypeError

class dokomoforms.models.Note(**kwargs)[source]

Bases: dokomoforms.models.node.Node

Notes provide information interspersed with survey questions.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

deleted
hint
id
languages
last_update_time
logic
the_type_constraint
title
type_constraint
class dokomoforms.models.TextQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A text question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.PhotoQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A photo question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.IntegerQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A integer question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.DecimalQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A decimal question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.DateQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A date question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.TimeQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A time (with time zone) question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.TimestampQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A timestamp (with time zone) question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.LocationQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A location question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.FacilityQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A facility question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
deleted
hint
id
languages
last_update_time
logic
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.MultipleChoiceQuestion(**kwargs)[source]

Bases: dokomoforms.models.node._QuestionMixin, dokomoforms.models.node.Question

A multiple_choice question.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_multiple
allow_other
choices
deleted
hint
id
languages
last_update_time
logic
node_languages
the_languages
the_type_constraint
title
type_constraint
class dokomoforms.models.Choice(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A choice for a MultipleChoiceQuestion.

Models a choice for a dokomoforms.models.survey.MultipleChoiceQuestion.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

choice_number
choice_text
deleted
id
last_update_time
question_id
question_languages
class dokomoforms.models.Survey(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A Survey has a list of SurveyNodes.

Use an EnumeratorOnlySurvey to restrict submissions to enumerators.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

administrators
containing_id
created_on
creator_id
default_language
deleted
earliest_submission_time
id
languages
last_update_time
latest_submission_time
nodes
num_submissions
submissions
survey_metadata
survey_type
title
url_slug
version
class dokomoforms.models.EnumeratorOnlySurvey(**kwargs)[source]

Bases: dokomoforms.models.survey.Survey

Only enumerators (designated Users) can submit to this.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

administrators
containing_id
created_on
creator_id
default_language
deleted
earliest_submission_time
enumerators
id
languages
last_update_time
latest_submission_time
nodes
num_submissions
submissions
survey_metadata
survey_type
title
url_slug
version
class dokomoforms.models.SubSurvey(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A SubSurvey behaves like a Survey but belongs to a SurveyNode.

The way to arrive at a certain SubSurvey is encoded in its buckets.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

buckets
containing_survey_id
deleted
id
nodes
parent_allow_multiple
parent_node_id
parent_survey_node_id
parent_type_constraint
repeatable
root_survey_languages
sub_survey_number
class dokomoforms.models.SurveyNode(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A SurveyNode contains a Node and adds survey-specific metadata.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

containing_survey_id
deleted
id
last_update_time
logic
node

The Node instance.

node_id
node_languages
node_number
non_null_repeatable
root_survey_id
root_survey_languages
sub_survey_id
sub_survey_repeatable
survey_node_answerable
the_node
type_constraint
dokomoforms.models.construct_survey(*, survey_type: str, **kwargs)[source]

Construct either a public or enumerator_only Survey.

class dokomoforms.models.NonAnswerableSurveyNode(**kwargs)[source]

Bases: dokomoforms.models.survey.SurveyNode

Contains a Node which is not answerable (e.g., a Note).

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

containing_survey_id
deleted
id
last_update_time
logic
node
node_id
node_languages
node_number
non_null_repeatable
root_survey_id
root_survey_languages
sub_survey_id
sub_survey_repeatable
survey_node_answerable
the_node
the_node_id
the_type_constraint
type_constraint
class dokomoforms.models.AnswerableSurveyNode(**kwargs)[source]

Bases: dokomoforms.models.survey.SurveyNode

Contains a Node which is answerable (.e.g, a Question).

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer_count
answers
containing_survey_id
deleted
id
last_update_time
logic
node
node_id
node_languages
node_number
non_null_repeatable
required
root_survey_id
root_survey_languages
sub_survey_id
sub_survey_repeatable
sub_surveys
survey_node_answerable
the_containing_survey_id
the_node
the_node_id
the_node_languages
the_root_survey_languages
the_sub_survey_repeatable
the_type_constraint
type_constraint
dokomoforms.models.construct_survey_node(**kwargs) → dokomoforms.models.survey.SurveyNode[source]

Return a subclass of dokomoforms.models.survey.SurveyNode.

The subclass is determined by the type_constraint parameter. This utility function makes it easy to create an instance of a SurveyNode subclass based on external input.

See http://stackoverflow.com/q/30518484/1475412

Parameters:kwargs – the keyword arguments to pass to the constructor
Returns:an instance of one of the Node subtypes
dokomoforms.models.construct_bucket(*, bucket_type: str, **kwargs) → dokomoforms.models.survey.Bucket[source]

Return a subclass of dokomoforms.models.survey.Bucket.

The subclass is determined by the bucket_type parameter. This utility function makes it easy to create an instance of a Bucket subclass based on external input.

See http://stackoverflow.com/q/30518484/1475412

Parameters:
  • bucket_type – the type of the bucket. Must be one of the keys of dokomoforms.models.survey.BUCKET_TYPES
  • kwargs – the keyword arguments to pass to the constructor
Returns:

an instance of one of the Bucket subtypes

Raises:

dokomoforms.exc.NoSuchBucketTypeError

dokomoforms.models.skipped_required(survey, answers) → str[source]

Return the id of a skipped AnswerableSurveyNode, or None.

dokomoforms.models.administrator_filter(user_id)[source]

Filter a query by administrator id.

dokomoforms.models.most_recent_surveys(session, user_id, limit=None)[source]

Get an administrator’s most recent surveys.

class dokomoforms.models.Submission(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A Submission references a Survey and has a list of Answers.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

answers
deleted
id
last_update_time
save_time
start_time
submission_time
submission_type
submitter_email
submitter_name
survey_containing_id
survey_default_language
survey_id
survey_title
survey_type
class dokomoforms.models.EnumeratorOnlySubmission(**kwargs)[source]

Bases: dokomoforms.models.submission.Submission

An EnumeratorOnlySubmission must have an enumerator.

Use an EnumeratorOnlySubmission for an EnumeratorOnlySurvey.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

answers
deleted
enumerator
enumerator_user_id
id
last_update_time
save_time
start_time
submission_time
submission_type
submitter_email
submitter_name
survey_containing_id
survey_default_language
survey_id
survey_title
survey_type
the_survey_id
class dokomoforms.models.PublicSubmission(**kwargs)[source]

Bases: dokomoforms.models.submission.Submission

A PublicSubmission might have an enumerator.

Use a PublicSubmission for a Survey.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

answers
deleted
enumerator
enumerator_user_id
id
last_update_time
save_time
start_time
submission_time
submission_type
submitter_email
submitter_name
survey_containing_id
survey_default_language
survey_id
survey_title
survey_type
dokomoforms.models.construct_submission(*, submission_type: str, **kwargs) → dokomoforms.models.submission.Submission[source]

Return a subclass of dokomoforms.models.submission.Submission.

The subclass is determined by the submission_type parameter. This utility function makes it easy to create an instance of a Submission subclass based on external input.

See http://stackoverflow.com/q/30518484/1475412

Parameters:
  • submission_type – the type of submission. Must be either ‘public_submission’ or ‘enumerator_only_submission’
  • kwargs – the keyword arguments to pass to the constructor
Returns:

an instance of one of the Node subtypes

Raises:

dokomoforms.exc.NoSuchSubmissionTypeError

dokomoforms.models.most_recent_submissions(session, user_id, limit=None)[source]

Get an administrator’s surveys’ most recent submissions.

class dokomoforms.models.Answer(**kwargs)[source]

Bases: dokomoforms.models.util.Base

An Answer is a response to a SurveyNode.

An Answer can be one of an answer, an “other” response or a “don’t know” response. Answer.response abstracts over these 3 possibilites.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

allow_dont_know
allow_multiple
allow_other
answer

The answer. Could be the same as main_answer in simple cases.

This property is the most useful representation available of the answer. In the simplest case it is just a synonym for main_answer. It could otherwise be a dictionary or another model.

answer_metadata
answer_number
answer_type
deleted
dont_know

A text field containing “don’t know” responses.

id
last_update_time
main_answer

The representative part of a provided answer.

The main_answer is the only answer for simple types (integer, text, etc.) and for other types is the part of the answer that is most important. In practice, the main_answer is special only in that all Answer models have it, which is necessary for certain constraints and for the response property.

other

A text field containing “other” responses.

question_id
question_title
repeatable
response = OrderedDict([('type_constraint', <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7f6b541a03b8>), ('response_type', 'answer'), ('response', <property object at 0x7f6b54182ae8>)])
save_time
submission_id
survey_containing_id
survey_id
survey_node
survey_node_containing_survey_id
survey_node_id
type_constraint
class dokomoforms.models.Photo(**kwargs)[source]

Bases: dokomoforms.models.util.Base

A BYTEA holding an image.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

created_on
deleted
id
image
mime_type
dokomoforms.models.construct_answer(*, type_constraint: str, **kwargs) → dokomoforms.models.answer.Answer[source]

Return a subclass of dokomoforms.models.answer.Answer.

The subclass is determined by the type_constraint parameter. This utility function makes it easy to create an instance of an Answer subclass based on external input.

See http://stackoverflow.com/q/30518484/1475412

Parameters:
  • type_constraint – the type of the answer. Must be one of the keys of dokomoforms.models.answer.ANSWER_TYPES
  • kwargs – the keyword arguments to pass to the constructor
Returns:

an instance of one of the Answer subtypes

Raies:

dokomoforms.exc.NotAnAnswerTypeError

dokomoforms.models.add_new_photo_to_session(session, *, id, **kwargs)[source]

Create a new Photo and update the referenced PhotoAnswer.

dokomoforms.models.answer_min(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the minimum answer.

dokomoforms.models.answer_max(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the maximum answer.

dokomoforms.models.answer_sum(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the sum of the answers.

dokomoforms.models.answer_avg(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the average of the answers.

dokomoforms.models.answer_mode(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the mode of the answers.

dokomoforms.models.answer_stddev_pop(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the population standard deviation of the answers.

dokomoforms.models.answer_stddev_samp(survey_node: dokomoforms.models.survey.AnswerableSurveyNode)[source]

Get the sample standard deviation of the answers.

dokomoforms.models.generate_question_stats(survey)[source]

Get answer statistics for the nodes in a survey.

Submodules

dokomoforms.exc module

The base exception class is DokomoError.

exception dokomoforms.exc.DokomoError[source]

Bases: Exception

The base class for all exceptions used in Dokomo Forms.

exception dokomoforms.exc.InvalidTypeForOperation[source]

Bases: dokomoforms.exc.DokomoError

Invalid type for the selected aggregation function.

For instance, you can’t find the maximum of a text answer.

exception dokomoforms.exc.NoSuchBucketTypeError[source]

Bases: dokomoforms.exc.DokomoError

Invalid type_constraint for construct_bucket.

Raised when dokomoforms.models.survey.construct_bucket is called with an invalid type_constraint.

The valid type_constraints are the keys of dokomoforms.models.survey.BUCKET_TYPES.

exception dokomoforms.exc.NoSuchNodeTypeError[source]

Bases: dokomoforms.exc.DokomoError

Invalid type_constraint for construct_node.

Raised when dokomoforms.models.node.construct_node is called with an invalid type_constraint.

The valid type_constraints are the keys of dokomoforms.models.node.NODE_TYPES.

exception dokomoforms.exc.NoSuchSubmissionTypeError[source]

Bases: dokomoforms.exc.DokomoError

Invalid submission_type for construct_submission.

Raised when dokomoforms.models.submission.construct_submission is called with an invalid submission_type.

The valid types are ‘unathenticated’ and ‘enumerator_only_submission’

exception dokomoforms.exc.NotAResponseTypeError[source]

Bases: dokomoforms.exc.DokomoError

Invalid response_type Answer.response.setter.

Raised when trying to set the response field on an Answer with an invalid response_type.

The valid response_types are ‘answer’, ‘other’, and ‘dont_know’.

exception dokomoforms.exc.NotAnAnswerTypeError[source]

Bases: dokomoforms.exc.DokomoError

Invalid type_constraint for construct_answer.

Raised when dokomoforms.models.node.construct_answer is called with an invalid type_constraint.

The valid type_constraints are the keys of dokomoforms.models.answer.ANSWER_TYPES.

exception dokomoforms.exc.NotJSONifiableError[source]

Bases: dokomoforms.exc.DokomoError

The jsonify function encountered a strange object.

exception dokomoforms.exc.PhotoIdDoesNotExistError[source]

Bases: dokomoforms.exc.DokomoError

The submitted photo ID does not exist in the database.

exception dokomoforms.exc.RequiredQuestionSkipped[source]

Bases: dokomoforms.exc.DokomoError

A submission has no answer for a required question.

exception dokomoforms.exc.SurveyAccessForbidden[source]

Bases: dokomoforms.exc.DokomoError

The logged-in user does not have access to the survey.

exception dokomoforms.exc.UserRequiresEmailError[source]

Bases: dokomoforms.exc.DokomoError

A user must have at least one e-mail address.

dokomoforms.options module

All the application options are defined here.

If you need to inject options at runtime (for testing, etc...):

from dokomoforms.options import parse_options

parse_options(name1=value1, name2=value2, ...)

Module contents

Top level module for Dokomo Forms.

All of the application code for Dokomoforms (outside of the webapp.py script) lives in this module.

webapp module

Main Dokomo Forms entry point.

Execute this script to start the Tornado server and WSGI container. It will ensure that the proper tables and extensions exist in the specified schema of the PostgreSQL database.

The application looks for gettext translation files like locale/{locale}/LC_MESSAGES/dokomoforms.mo

class webapp.Application(session=None, options=<tornado.options.OptionParser object>)[source]

Bases: tornado.web.Application

The tornado.web.Application for Dokomo Forms.

__init__(session=None, options=<tornado.options.OptionParser object>)

Set up the application with handlers and a db connection.

Defines the URLs (with associated handlers) and settings for the application, drops the database schema (if the user selected that option), then prepares the database and creates a session.

webapp.api_url(path, *args, **kwargs)[source]

Prepend the API path to API URLs.

webapp.ensure_that_user_wants_to_drop_schema()[source]

Check that user asked to drop the schema intentionally.

Interrogates the user to make sure that the schema specified by options.schema should be dropped. If the user decides against it, exits the application.

Return the secret from the cookie_secret file.

The cookie secret is in the file <project_directory>/cookie_secret. If the file doesn’t exist, the script will exit with code 1 and tell the user how to generate it.

Returns:the cookie secret as bytes
webapp.main(msg=None)[source]

Start the Tornado web server.

webapp.modify_text(text: str, modifier: str) → str[source]

Modify text for printing to the command line.

Parameters:
  • text – the string to modify
  • modifier – the escape sequence that marks the modifier
Returns:

the modified string

webapp.setup_file_loggers(log_level: str)[source]

Handles application, Tornado, and SQLAlchemy logging configuration.

webapp.start_http_server(http_server, port)[source]

Start the server, with the option to kill anything using the port.

Indices and tables