Web Interface Modules

hedwig.web.app

hedwig.web.app.create_web_app(db=None, facility_spec=None, auto_reload_templates=False, without_logger=False, without_auth=False, _test_return_extra=False)

Function to prepare the Flask web application.

Parameters:
  • db – database access object to use. If None then one will be constructed based on the configuration (and facility_spec).

  • facility_spec – facility specification used to construct the facility list (via hedwig.config.get_config()) and database object (if not given, via hedwig.config.get_database()).

  • auto_reload_templates – Configure whether Jinja2 should automatically reload template files. (Only applies with Flask 0.11 or later.)

  • without_logger – if True, do not configure the application’s logger. (Otherwise it is configured to log to the file specified in the configuration file.)

  • without_auth – if True, do not set up the before_request function to check for log in information.

  • _test_return_extra – if true, instead of just returning the application object, return a dictionary of values useful for debugging. (Currently just returns the output of locals().)

hedwig.web.format

hedwig.web.format.format_text(text, format=None, as_inline=False)

Format text, possibly using different formatting schemes.

If “format” is not specified, it defaults to PLAIN unless “text” has attributes “text” and “format”, in which case those are used instead.

The “as_inline” option requests inline formatting elements only, if the format type supports this.

hedwig.web.format.format_text_plain(text)

Format plain text for display as HTML.

The text is broken into paragraphs at double line breaks. Within each paragraph, a line break tag (<br />) is inserted at remaining (single) line breaks.

Returns:

Flask Markup object containing the formatted text

hedwig.web.format.format_text_plain_inline(text)

Format plain text for display as inline HTML.

This is a variation of format_text_plain which only adds line breaks, not paragraphs. This can be used for small pieces of text inside other elements, such as <td>.

Returns:

Flask Markup object containing the formatted text

hedwig.web.format.format_text_rst(text, extract_title_toc=False, start_heading=3)

Format RST for display as HTML.

This applies the hedwig.format.rst.rst_to_html() function.

Parameters:
  • text – text marked up as RST for formatting

  • extract_title_toc – indicate whether to extract title and TOC

  • start_heading – initial heading level

Returns:

Flask Markup object containing the formatted text, unless extract_title_toc is specified, in which case a tuple of the Markup object, a Markup object containing the title, and a list of TOC items.

hedwig.web.format.format_message_text(text, format=None)

Format message text, using different formatting types.

If format is not specified, it defaults to PLAIN unless text has attributes body and format, in which case those are used instead.

hedwig.web.query_encode

hedwig.web.query_encode.decode_query(encoded)

Attempt to convert encoded query data back to the original form.

The first character of the encoded data is inspected to determine the encoding form. The remaining data are converted to binary and passed to the appropriate decoding function.

Currently only Base 64-encoded msgpack is supported, with designator ‘M’.

hedwig.web.query_encode.encode_query(query)

Convert query data (such as a list of parameters) into a form suitable for including in an URL to make a ‘permalink’.

Returns a character identifying the encoding scheme followed by the encoded data.

hedwig.web.query_encode._decode_query_msgpack(query)
hedwig.web.query_encode._encode_query_msgpack(query)

hedwig.web.template_util

hedwig.web.template_util.register_template_utils(app)

Register all of the template utilities with the given Flask app.

These utilities consist of:

  • Global functions.

  • Filters.

  • Tests.

Parameters:

app – Flask application in which to register the utilities.

class hedwig.web.template_util.Counter(start_value)

Counter object for use in Jinja templates.

hedwig.web.util

class hedwig.web.util.CurrentUserFormatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)

Log entry formatter which includes information regarding the current user.

format(record)

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

class hedwig.web.util.HTTPError(*args: Any, **kwargs: Any)

Exception class for raising HTTP errors.

class hedwig.web.util.HTTPForbidden(*args: Any, **kwargs: Any)

Exception class for HTTP forbidden errors.

class hedwig.web.util.HTTPNotFound(*args: Any, **kwargs: Any)

Exception class for HTTP not found errors.

class hedwig.web.util.HTTPRedirect(*args: Any, **kwargs: Any)

Exception class requesting a temporary (“See Other”) HTTP redirect.

code = 303
class hedwig.web.util.HTTPRedirectWithReferrer(*args: Any, **kwargs: Any)

Exception class for HTTP redirect with added “referrer” URL argument.

This class extends HTTPRedirect, overriding the constructor to add a “referrer” URL argument giving the relative URL of the current request.

exception hedwig.web.util.ErrorPage(fmt_string, *fmt_args, **kwargs)

Exception class where an error page should be shown.

hedwig.web.util.ascii_safe(value)

Convert value to a form which is safe for inclusion in HTTP headers.

hedwig.web.util.flash(message, *args)

Add a message to the list of messages to be flashed on the next page viewied.

The message can include string formatting and the remaining arguments taken as arguments for string formatting.

hedwig.web.util.get_logger()

Get the logger of the current Flask application.

(Returned as a FormattedLogger instance supporting string formatting.)

hedwig.web.util.make_enum_converter(enum_class)

Make a Werkzeug routing converter for a Hedwig enum-style class.

The given class must have support for URL paths: it should have methods get_url_paths, by_url_path and url_path. Such a class can be constructed by defining an url_path attribute and inheriting from the hedwig.type.base.EnumURLPath mix-in.

hedwig.web.util.mangle_email_address(email_address)

Mangles an email address by turning it into a JSON-encoded list of HTML character entities.

The unmangle.js script can be used to reconstruct such addresses when they are placed in the mangled data attribute of a span of class mangled_address, e.g.:

<span class="mangled_address" data-mangled="{{ email_address | mangle_email_address }}">&nbsp;</span>
hedwig.web.util.parse_datetime(date_and_time)

Parses date and time strings as received from a form.

The intention is that this function is used in conjunction with format_datetime() to pass datetimes to and from forms. The values from a form (which will be strings) are read into a DateAndTime tuple. This tuple can be returned to the form (in the event of parsing errors) to allow the user to make corrections. Otherwise it is parsed by this function to obtain a datetime object. For the reverse process — populating an edit form with existing data — format_datetime() is used to convert a datetime object to a DateAndTime tuple which the form template can use for default values.

Parameters:

date_time_pair – a DateAndTime tuple of strings.

Returns:

combined datetime object.

Raises:

UserError – if the date or time can not be parsed.

hedwig.web.util.format_datetime(value)

Converts datetime object to date and time string pair.

If the object is None, returns a pair of empty strings.

Please see parse_datetime() for a description of the intended usage of this function.

Parameters:

valuedatetime object.

Returns:

a DateAndTime tuple containing formatted strings.

hedwig.web.util.register_error_handlers(app)

Register error handlers with the given Flask app.

Parameters:

app – Flask application with which to register error handlers.

hedwig.web.util.require_admin(f)

Decorator to require that the user has administrative access.

Simply checks that the user is logged in and has administrative privileges enabled – i.e. that the current_user.is_admin flag is set.

hedwig.web.util.require_auth(require_person=True, require_person_admin=False, require_institution=False, allow_unverified=False, register_user_only=False, record_referrer=False)

Decorator to require that the user is authenticated.

Parameters:
  • require_person – require the user to have a profile, which must be verified unless allow_verified is specified.

  • require_person_admin – also check that the person record in the current_user has the admin flag. (This is not the same as the current_user.is_admin flag – use require_admin() for that.)

  • require_institution – require the user to have an institution associated with thir profile.

  • allow_unverified – when requiring a person profile, do not require that profile to be verified.

  • register_user_only – used when we want the user to log in or create a user account but not to complete a profile before proceeding. This is to support accepting invitation tokens.

  • record_referrer – if specified then the referrer is passed to the log in page as an argument if log in is required.

Note

This needs to be the outermost route decorator, because under certain circumstances (namely requiring the user to authenticate from a POST request) it needs to be able to write a response directly.

To help ensure this, it sets an attribute _hedwig_require_auth on the decorated function which other decorators can use to detect the problem.

hedwig.web.util.require_not_auth(f)

Decorator to require that the user is not authenticated.

Warning

ErrorPage can not be raised here because this decorator is normally applied outside of the “templated” decorator.

hedwig.web.util.require_session_option(option)

Decorator to require that a certain session option is set.

hedwig.web.util.send_file(fixed_type=None, **send_file_kwargs)

Decorator for route functions which send files.

If there is a fixed MIME type, it can be set in the decorator argument as a string, FileTypeInfo object or FigureType value and the function just returns the data. Otherwise the function must return a ProposalFigure (data, type, filename) tuple where the type is a value from FigureType.

Parameters:
  • fixed_type – fixed MIME type, if appropriate (see above).

  • allow_cache – if enabled, HTTP headers will be added to enable caching. In this case it is assumed that the caller will ensure the resource hasn’t changed, e.g. by including a checksum in the URL.

  • cache_max_age – specify how long to allow the user’s browser to cache the file. (Default is one day.)

  • cache_private – unless set to False assume the file is part of a proposal, or other private information, so request no public caching.

Raises:

Exception – if applied to a function with an attribute _hedwig_require_auth because require_auth() should be the outermost decorator.

hedwig.web.util._make_file_response(data, type_, filename=None, allow_cache=False, cache_max_age=86400, cache_private=True)

Prepare Flask response when sending a file.

hedwig.web.util.send_json(allow_cache=False, cache_max_age=86400, cache_private=True)

Decorator for route functions which return JSON.

Raises:

Exception – if applied to a function with an attribute _hedwig_require_auth because require_auth() should be the outermost decorator.

hedwig.web.util._set_response_caching(response, max_age, private)
hedwig.web.util.templated(template, section=False)

Template application decorator.

Based on the templating decorator example in the Flask documentation.

The ErrorPage exception is caught, and rendered using the _error_page_response() method.

Parameters:
  • template – the template(s) to use.

  • section – enable “section” mode: the response should be a list where each entry is either a template context dictionary or a (MIME type, data) pair. Some kind of multi-part response (as defined by _make_multipart_response()) will be returned.

Raises:

Exception – if applied to a function with an attribute _hedwig_require_auth because require_auth should be the outermost decorator.

hedwig.web.util.with_current_user(f)

Decorator to provided current_user object.

hedwig.web.util._error_page_response(err)

Prepare flask response for an error page.

Parameters:

err – the ErrorPage exception object.

hedwig.web.util._make_response(template, result, status=None)

Prepare flask repsonse via a template.

Parameters:
  • template – the file name of the template to use

  • result – the template context dictionary

  • status – the HTTP response status

Raises:

HTTPError – if the view function returns None.

hedwig.web.util.check_current_user(db)

Check the user’s session for log in information.

This function sets the current_user entry in the Flask g variable to an instance of CurrentUser. This will have user None if the user is not logged in or person None if they do not have a registered profile.

This is invoked at the start of each request, as it is registered with Flask as a before_request function by the create_web_app() function. It should run before the require_admin() and require_auth() functions examine the session.

hedwig.web.util._url_manipulation(f)

Decorator to assist in URL manipulation.

The URL is “parsed” by url_parse before being passed to the decorated function and the return value is then reconstructed by url_unparse afterwards.

hedwig.web.util.url_add_args(url, **kwargs)

Add keyword arguments to the given URL as query parameters.

hedwig.web.util.url_relative(url)

Convert an URL to relative form, by removing the scheme and location.

hedwig.web.util._make_multipart_response(parts)

Make a multipart response.

The current implementation uses pickle for simplicity.

hedwig.web.util.parse_multipart_response(data)

Parse a multipart response.

This should be used to parse the response constructed by _make_multipart_response().