Pyjoyment.Plugin.DefaultHelpers - Default helpers plugin

# Pyjoyment
app.plugin('DefaultHelpers')

Pyjoyment.Plugin.DefaultHelpers is a collection of helpers for Pyjoyment.

This is a core plugin, that means it is always enabled and its code a good example for learning to build new plugins, you’re welcome to fork it.

See Pyjoyment.Plugins for a list of plugins that are available by default.

Helpers

Pyjoyment.Plugin.DefaultHelpers implements the following helpers.

accepts

formats = c.accepts()
format = c.accepts('html', 'json', 'txt')

Select best possible representation for resource from format GET/POST parameter, format stash value or Accept request header with Pyjoyment.Renderer.Pyjoyment_Renderer.accepts(), defaults to returning the first extension if no preference could be detected.

# Check if JSON is acceptable
if c.accepts('json'):
    c.render(json={'hello': 'world'})

# Check if JSON was specifically requested
if c.accepts('', 'json'):
    c.render(json={'hello': 'world'})

# Unsupported representation
if not (format := c.accepts('html', 'json')):
    c.render(data=b'', status=204)

# Detected representations to select from
formats = c.accepts()

app

%= app().secrets[0]

Alias for Pyjoyment.Controller.Pyjoyment_Controller.app.

b

%= b(b'Joel is a slug').slugify()

Turn bytes into a Pyjo.String.Bytes object.

c

%= c.c('a', 'b', 'c').shuffle().join()

Turn list into a Pyjo.Collection object. In templates, the variable c is the controller, which hides the helper.

config

%= config('something')

Alias for Pyjo.App.Pyjo_App.config().

content

%= content('foo', begin
  test
% end)
%= content('bar', 'Hello World!')
%= content('foo')
%= content('bar')
%= content()

Store partial rendered content in a named buffer and retrieve it later, defaults to retrieving the named buffer content, which is used by the renderer for the layout and extends features. New content will be ignored if the named buffer is already in use.

content_for

% content_for('foo', begin
  test
% end)
%= content_for('foo')

Same as content, but appends content to named buffers if they are already in use.

% content_for('message', begin
  Hello
% end)
% content_for('message', begin
  world!
% end)
%= content('message')

content_with

% content_with('foo', begin
  test
% end)
%= content_with('foo')

Same as content, but replaces content of named buffers if they are already in use.

% content('message', begin
  world!
% end)
% content_with('message', begin
  Hello <%= content('message') %>
% end)
%= content('message')

csrf_token

%= csrf_token()

Get CSRF token from session, and generate one if none exists. The token is masked with a fresh random value on every call to protect against BREACH attacks.

current_route

% if current_route('login'):
  Welcome to Pyjoyment!
% end
%= current_route()

Check or get name of current route.

dumper

%= dumper({'some': 'data'})

Dump a Python data structure with Pyjo.Util.dumper(), very useful for debugging.

exception_format

format = c.exception_format()
c = c.exception_format('txt')

Format for HTTP exceptions (html, json, or txt), defaults to the value of Pyjoyment.Pyjoyment_App.exception_format.

extends

% extends('blue')
% extends('blue', title='Blue!')

Set extends stash value, all additional keyword arguments get merged into the stash.

flash

foo = c.flash('foo')
c = c.flash({'foo': 'bar'})
c = c.flash(foo='bar')
%= flash('foo')

Data storage persistent only for the next request, stored in the session.

# Show message after redirect
c.flash(message='User created successfully!')
c.redirect_to('show_user', id=23)

inactivity_timeout

c = c.inactivity_timeout(3600)

Use Pyjo.IOLoop.stream() to find the current connection and increase timeout if possible.

# Longer version
Pyjo.IOLoop.stream(c.tx.connection).timeout = 3600

include

%= include('menubar')
%= include('menubar', format='txt')

Alias for Pyjoyment.Controller.Pyjoyment_Controller.render_to_string().

is_fresh

boolean = c.is_fresh()
boolean = c.is_fresh(etag='abc')
boolean = c.is_fresh(etag='W/"def"')
boolean = c.is_fresh(last_modified=epoch)

Check freshness of request by comparing the If-None-Match and If-Modified-Since request headers to the ETag and Last-Modified response headers with Pyjoyment.Static.Pyjoyment_Static.is_fresh().

# Add ETag/Last-Modified headers and check freshness before rendering
if c.is_fresh(etag='abc', last_modified=1424985708):
    c.rendered(304)
else:
    c.render(text='I ♥ Pyjoyment!')

layout

% layout('green')
% layout('green', title='Green!')

Set layout stash value, all additional keyword arguments get merged into the stash.

log

log = c.log()

Alternative to Pyjoyment.Pyjoyment_App.log that includes Pyjo.Message.Request.Pyjo_Message_Request.request_id with every log message, as the field request_id of a message of JSON, see Pyjo.Log.Field.

# Log message with context
c.log().debug('This is a log message with request id')

# Pass logger with context to model
log = c.log()
c.some_model().create({'foo': foo}, log)

param

%= param('foo')

Alias for Pyjoyment.Controller.Pyjoyment_Controller.param().

proxy.get_p

promise = c.proxy.get_p('http://example.com', {'Accept': '*/*'})

Perform non-blocking GET request and forward response as efficiently as possible, takes the same arguments as Pyjo.UserAgent.Pyjo_UserAgent.get and returns a Pyjo.Promise object.

# Forward with exception handling
@c.proxy.get_p('http://mojolicious.org').catch
def catch(err):
    c.log().debug(f'Proxy error: {err}')
    c.render(text='Something went wrong!', status=400)

proxy.post_p

promise = c.proxy.post_p('http://example.com', {'Accept': '*/*'})

Perform non-blocking POST request and forward response as efficiently as possible, takes the same arguments as Pyjo.UserAgent.Pyjo_UserAgent.post and returns a Pyjo.Promise object.

# Forward with exception handling
@c.proxy.post_p('example.com', form={'test': 'pass'}).catch
def catch(err):
    c.log().debug(f'Proxy error: {err}')
    c.render(text='Something went wrong!', status=400)

proxy.start_p

promise = c.proxy.start_p(Pyjo.Transaction.HTTP.new())

Perform non-blocking request for a custom Pyjo.Transaction.HTTP object and forward response as efficiently as possible, returns a Pyjo.Promise object.

# Forward with exception handling
tx = c.ua().build_tx('GET', 'http://mojolicious.org')

@c.proxy.start_p(tx).catch
def catch(err):
    c.log().debug(f'Proxy error: {err}')
    c.render(text='Something went wrong!', status=400)

# Forward with custom request and response headers
headers = c.req.headers.clone().dehop()
headers.header('X-Proxy', 'Pyjo')
tx = c.ua().build_tx('GET', 'http://example.com', headers.to_dict())
c.proxy.start_p(tx)
tx.res.content.once('body', lambda content: c.res.headers.header('X-Proxy', 'Pyjo'))

redirect_to

c = c.redirect_to('named', foo='bar')
c = c.redirect_to('named', {'foo': 'bar'})
c = c.redirect_to('/index.html')
c = c.redirect_to('http://example.com/index.html')

Prepare a 302 (if the status code is not already 3xx) redirect response with Location header, takes the same arguments as url_for.

# Moved Permanently
c.res.code = 301
c.redirect_to('some_route')

# Temporary Redirect
c.res.code = 307
c.redirect_to('some_route')

reply.asset

c.reply.asset(Pyjo.Asset.File.new())

Reply with a Pyjo.Asset.File or Pyjo.Asset.Memory object using Pyjoyment.Static.Pyjoyment_Static.serve_asset(), and perform content negotiation with Range, If-Modified-Since and If-None-Match headers.

# Serve asset with custom modification time
asset = Pyjo.Asset.Memory.new()
asset.add_chunk(b'Hello World!').mtime = 784111777
c.res.headers.content_type = 'text/plain'
c.reply.asset(asset)

# Serve static file if it exists
if asset := c.app.static.file('images/logo.png'):
    c.res.headers.content_type = 'image/png'
    c.reply.asset(asset)

reply.exception

c = c.reply.exception('Oops!')
c = c.reply.exception(Pyjo.Exception.new())

Render an exception response in the appropriate format by delegating to more specific exception helpers.

reply.file

c.reply.file('/etc/passwd')

Reply with a static file from an absolute path anywhere on the file system using Pyjoyment.Pyjoyment_App.static.

# Longer version
c.reply.asset(Pyjo.Asset.File.new(path='/etc/passwd'))

# Serve file from an absolute path with a custom content type
c.res.headers.content_type = 'application/myapp'
c.reply.file('/home/sri/foo.txt')

# Serve file from a secret application directory
c.reply.file(c.app.home.child('secret', 'file.txt'))

reply.html_exception

c = c.reply.html_exception('Oops!')
c = c.reply.html_exception(Pyjo.Exception.new())

Render the exception template exception.$mode.$format.* or exception.$format.* and set the response status code to 500. Also sets the stash values exception to a Pyjo.Exception object and snapshot to a copy of the stash for use in the templates.

reply.html_not_found

c = c.reply.html_not_found()

Render the not found template not_found.$mode.$format.* or not_found.$format.* and set the response status code to 404. Also sets the stash value snapshot to a copy of the stash for use in the templates.

reply.json_exception

c = c.reply.json_exception('Oops!')
c = c.reply.json_exception(Pyjo.Exception.new())

Render a JSON response and set the response status to 500.

reply.json_not_found

c = c.reply.json_not_found()

Render a JSON response and set the response status to 404.

reply.not_found

c = c.reply.not_found()

Render a not found response in the appropriate format by delegating to more specific exception helpers.

reply.static

c.reply.static('images/logo.png')
c.reply.static('../lib/MyApp.py')

Reply with a static file using Pyjoyment.Pyjoyment_App.static, usually from the public directories or DATA sections of your application. Note that this helper uses a relative path, but does not protect from traversing to parent directories.

# Serve file from a relative path with a custom content type
c.res.headers.content_type = 'application/myapp'
c.reply.static('foo.txt')

reply.txt_exception

c = c.reply.txt_exception('Oops!')
c = c.reply.txt_exception(Pyjo.Exception.new())

Render a plain text response and set the response status to 500.

reply.txt_not_found

c = c.reply.txt_not_found()

Render a plain text response and set the response status to 404.

request_timeout

c = c.request_timeout(120)

The most time in seconds from now to the end of the response, as for a request that waits for a model of language, which the value request_timeout of the stash of a route sets before its first action. When it passes, the actions that are coroutine functions are cancelled where they wait, with the requests of Pyjo.UserAgent that they wait for, and the request gets an empty 504 response, or the connection closes when the response has started already, as a stream. A later call replaces the time.

# A route whose response has two minutes at most
app.routes.post('/chat', {'request_timeout': 120}).to('chat#reply')

respond_to

c = c.respond_to(json={'json': {'message': 'Welcome!'}}, html={'template': 'welcome'}, any=lambda c: ...)

Automatically select best possible representation for resource from format GET/POST parameter, format stash value or Accept request header, defaults to Pyjoyment.Renderer.Pyjoyment_Renderer.default_format or rendering an empty 204 response. Each representation can be handled with a callback or a dict containing arguments to be passed to Pyjoyment.Controller.Pyjoyment_Controller.render().

# Everything else than "json" and "xml" gets a 204 response
c.respond_to(
    json=lambda c: c.render(json={'just': 'works'}),
    xml={'text': '<just>works</just>'},
    any={'data': b'', 'status': 204},
)

For more advanced negotiation logic you can also use accepts.

session

%= session('foo')

Alias for Pyjoyment.Controller.Pyjoyment_Controller.session().

stash

%= stash('foo')
% stash(foo='bar')

Alias for Pyjoyment.Controller.Pyjoyment_Controller.stash().

%= stash('name') or 'Somebody'

timing.begin

c.timing.begin('foo')

Create named timestamp for timing.elapsed.

timing.elapsed

elapsed = c.timing.elapsed('foo')

Return fractional amount of time in seconds since named timstamp has been created with timing.begin or None if no such timestamp exists.

# Log timing information
c.timing.begin('database_stuff')
...
elapsed = c.timing.elapsed('database_stuff')
c.app.log.debug(f'Database stuff took {elapsed} seconds')

timing.rps

rps = c.timing.rps(0.001)

Return fractional number of requests that could be performed in one second if every singe one took the given amount of time in seconds or None if the number is too low.

# Log more timing information
c.timing.begin('web_stuff')
...
elapsed = c.timing.elapsed('web_stuff')
rps = c.timing.rps(elapsed)
c.app.log.debug(f'Web stuff took {elapsed} seconds ({rps} per second)')

timing.server_timing

c.timing.server_timing('metric')
c.timing.server_timing('metric', 'Some Description')
c.timing.server_timing('metric', 'Some Description', 0.001)

Create Server-Timing header with optional description and duration.

# "Server-Timing: miss"
c.timing.server_timing('miss')

# "Server-Timing: dc;desc=atl"
c.timing.server_timing('dc', 'atl')

# "Server-Timing: db;desc=Database;dur=0.0001"
c.timing.begin('database_stuff')
...
elapsed = c.timing.elapsed('database_stuff')
c.timing.server_timing('db', 'Database', elapsed)

# "Server-Timing: miss, dc;desc=atl"
c.timing.server_timing('miss')
c.timing.server_timing('dc', 'atl')

title

%= title()
% title('Welcome!')
% title('Welcome!', foo='bar')

Get or set title stash value, all additional keyword arguments get merged into the stash.

ua

%= ua().get('mojolicious.org').result.dom().at('title').text

Alias for Pyjo.App.Pyjo_App.ua.

url_for

%= url_for('named', foo='bar', baz='yada')

Alias for Pyjoyment.Controller.Pyjoyment_Controller.url_for().

%= url_for('/index.html').set(query={'foo': 'bar'})

url_for_asset

%= url_for_asset('/app.js')

Alias for Pyjoyment.Controller.Pyjoyment_Controller.url_for_asset().

url_for_file

%= url_for_file('/index.html')

Alias for Pyjoyment.Controller.Pyjoyment_Controller.url_for_file().

url_with

%= url_with('named', foo='bar', baz='yada')

Does the same as url_for, but inherits query parameters from the current request.

%= url_with().set(query={'page': 2})

validation

v = c.validation()

Get Pyjoyment.Validator.Validation object for current request to validate file uploads as well as GET and POST parameters extracted from the query string and application/x-www-form-urlencoded or multipart/form-data message body. Parts of the request body need to be loaded into memory to parse POST parameters, so you have to make sure it is not excessively large. There’s a 16MiB limit for requests by default.

# Validate GET/POST parameter
v = c.validation()
v.required('title', 'trim').size(3, 50)
title = v.param('title')

# Validate file upload
v = c.validation()
v.required('tarball').upload().size(1, 1048576)
tarball = v.param('tarball')

See also

Pyjoyment, https://mojolicious.org.

Ported from Mojolicious::Plugin::DefaultHelpers of Mojolicious 9.49.

class Pyjoyment.Plugin.DefaultHelpers.Helpers[source]

The types of the helpers of Pyjoyment.Plugin.DefaultHelpers, for type checkers and editors, which Pyjoyment.Controller and Pyjoyment have, while the helpers themselves are found in the renderer of the application at run time. See Pyjoyment.Controller.Helper.

class Pyjoyment.Plugin.DefaultHelpers.ProxyHelpers[source]

The types of the nested helpers proxy.*, for type checkers.

class Pyjoyment.Plugin.DefaultHelpers.Pyjoyment_Plugin_DefaultHelpers[source]

Pyjoyment.Plugin.DefaultHelpers inherits all methods from Pyjoyment.Plugin and implements the following new ones.

register(app: Pyjoyment_App, conf: dict[str, Any] | None = None) → None[source]
plugin.register(Pyjoyment.new())

Register helpers in Pyjoyment application.

class Pyjoyment.Plugin.DefaultHelpers.ReplyHelpers[source]

The types of the nested helpers reply.*, for type checkers.

class Pyjoyment.Plugin.DefaultHelpers.TimingHelpers[source]

The types of the nested helpers timing.*, for type checkers.