API

alliance_platform.pdf.decorators.view_as_pdf(optional=True, query_param_test='pdf', request_headers=None, extra_headers=None, url_path=None, **render_options)[source]

Decorator that can wrap a django view, and return the view html as a PDF if a given URL parameter is present in the request. E.g.

@view_as_pdf(pass_through=True):
def my_view(request):
    return HttpResponse('Some content')

This will return the normal view response unless pdf=<something truthy> is present in the query parameters, in which case it will return the same content rendered as a PDF.

Parameters:
  • optional (bool) – If not True then will always render as PDF otherwise will only render as PDF if query_param_test check passes.

  • query_param_test (str | Callable[[HttpRequest], bool]) – If a string is passed, it will be interpreted as a query parameter, and if that query parameter is present and truthy (using strtobool) the view will be rendered as a PDF. If more control is needed, you can pass a function here that takes the request as an argument and returns a bool to indicate whether to render as PDF (if the predicate returns True) or return the normal view response (if the predicate returns False).

  • request_headers (dict[str, str] | None) – The complete set of headers to pass through on network requests triggered by pdf rendering (if you just want to add/override certain request headers, use extra_headers instead). If you set this to an empty dictionary, this implies that NO headers will be sent.

  • extra_headers (dict[str, str | None] | None) – Additional headers that will override/add to the existing request headers on network requests triggered by pdf rendering. Any header set to None here will be removed from the request.

  • url_path (str | None) –

    Optional path to override the request url path. This can be useful when rendering a view that returns a single page app, and you want to control the route that is seen by the SPA. E.g.

    view_as_pdf(optional=False, location='/admin/users/')(
        django_site.views.FrontendView.as_view(
            site=admin_site,
            basename='admin',
            entry_point='admin',
        )
    )
    

    Will render the frontend template for admin site, and the SPA will see the route as /admin/users/ and render that page accordingly.

  • **render_options – The remaining options are passed through to render_pdf()

alliance_platform.pdf.render.render_pdf(url=None, html=None, request_headers=None, request_handlers=None, pass_through=False, run_as_subprocess=True, page_done_flag='window.__PAGE_RENDERING_FINISHED', page_done_timeout_msecs=10000, pdf_options={'height': '297mm', 'print_background': True, 'width': '210mm'})[source]

Render a PDF from either a URL or directly from HTML

Parameters:
  • url (str | None) – A url to render as a pdf. If the html argument is supplied, this argument will control the url that chromium sees as the ‘source url’, but the content will be determined by the html argument.

  • html (str | None) – HTML content to render as a pdf. If url is also supplied, the html content will appear to originate from the supplied url.

  • request_headers (dict[str, str] | None) – A dictionary of headers which are then passed through on network requests triggered when rendering the pdf.

  • request_handlers (list[RequestHandler] | None) – A list of RequestHandler’s that will handle network requests triggered when rendering the pdf. Note that the order of these handlers is important: handlers are attempted in order until one returns a response or throws an error. If not specified uses return value of get_default_handlers().

  • pass_through (bool) – If True, requests that aren’t handled by any other request handler will be handled by the client. If False, requests that aren’t handled by any other request handler will raise an exception.

  • run_as_subprocess (bool) – Default is to run the playwright script as a subprocess. Set this to False to run it in the current process. This is only used to support running tests currently.

  • page_done_flag (str | None) – Set this to an in-page variable that is used (in addition to waiting for page load and no more active network requests) that flags when a page has finished rendering. The script will wait up to page_done_timeout_msecs milliseconds for this flag to become truthy, and then continue rendering regardless. Set it to None to avoid this extra delay.

  • page_done_timeout_msecs (int) – Set this to the maximum time to wait for the page_done_flag to become truthy.

  • pdf_options – kwargs to be passed directly to Page.pdf(). the_default_options_are { 'width': "210_mm", 'height': '297_mm', 'print_background': true }.

alliance_platform.pdf.render.get_default_handlers()[source]

Returns the default request handlers to use

Includes StaticHttpRequestHandler, MediaHttpRequestHandler, DjangoRequestHandler and WhitelistDomainRequestHandler.

WhitelistDomainRequestHandler will use domains in the WHITELIST_DOMAINS setting and, when DEBUG=True, also include the Vite dev server URL as extracted from the stats file.

Return type:

list[RequestHandler]

Request Handlers

class alliance_platform.pdf.request_handlers.RequestHandler[source]

Base RequestHandler class

A RequestHandler tells the renderer how to handle network requests that occur during the rendering process.

classmethod deserialize(data=None)[source]

Construct an instance of this class from the serialized data

handle_request(request)[source]

Handle request and return the response

Parameters:

request (Request)

Return type:

RequestHandlerResponse | None

log(*args, sep=' ', end='\n', file=None, flush=False)[source]

Prints the values to a stream, or to sys.stdout by default.

sep

string inserted between values, default a space.

end

string appended after the last value, default a newline.

file

a file-like object (stream); defaults to the current sys.stdout.

flush

whether to forcibly flush the stream.

serialize()[source]

Serialize handler data so can be reconstructed in a different process

This always includes path which is used to identify the class to construct.

deserialize is used to construct a new instance of the class from the serialized data.

class alliance_platform.pdf.request_handlers.RequestHandlerResponse(status, payload=None)[source]
Parameters:

status (RequestHandlerResponseStatus)

class alliance_platform.pdf.request_handlers.RequestHandlerResponseStatus(value)[source]
class alliance_platform.pdf.request_handlers.DjangoRequestHandler[source]

Handle requests that should be processed by django.

class alliance_platform.pdf.request_handlers.StaticHttpRequestHandler[source]

Handle static files.

Any request that has a URL starting with the sites static URL will be handled.

class alliance_platform.pdf.request_handlers.WhitelistDomainRequestHandler(domains)[source]

Allow requests from the specified domains

Parameters:

domains (list[str])

__init__(domains)[source]
Parameters:

domains (list[str]) – List of domains that are allowed

class alliance_platform.pdf.request_handlers.PassThroughRequestHandler[source]

This handler will pass through all requests to be handled by the client.

class alliance_platform.pdf.request_handlers.MediaHttpRequestHandler[source]

Handle media files, both S3 buckets and local storage.

Any request that has a URL starting with the sites medial URL will be handled

class alliance_platform.pdf.request_handlers.CustomRequestHandler(routes)[source]

Handle requests to specific urls with custom html, e.g.

CustomRequestHandler({
    'http://foo.com/bar/': {
        'body': '<html><body>Content</body></html>',
        'status': 201, (200 is the default)
        'headers': {
            'X-Some-Header: 'foo',
        },
    }
})

Note that urls are normalized with regard to trailing slash, so if you set http://foo.com/bar/ as the url, it will match to http://foo.com/bar/ or http://foo.com/bar. However the full url (scheme, netloc, etc.) is required in order to match.