Pyjoyment.Controller - Controller base class

# Controller
from Pyjoyment.Controller import Controller

class MyApp_Controller_Foo(Controller):

    # Action
    def bar(self):
        name = self.param('name')
        self.res.headers.cache_control = 'max-age=1, no-cache'
        self.render(json={'hello': name})

object = MyApp_Controller_Foo

# Or import the module, as in Google Python Style Guide

# Controller
import Pyjoyment.Controller

class MyApp_Controller_Foo(Pyjoyment.Controller.object):

    # Action
    def bar(self):
        name = self.param('name')
        self.res.headers.cache_control = 'max-age=1, no-cache'
        self.render(json={'hello': name})

object = MyApp_Controller_Foo

Pyjoyment.Controller is the base class for your Pyjoyment controllers. It is also the default controller class unless you set Pyjoyment.Pyjoyment_App.controller_class.

A controller is a context manager for the callbacks of a delayed response: an exception that the with block does not catch is replied with the helper reply.exception of Pyjoyment.Plugin.DefaultHelpers, as an exception that goes on to the event loop would leave the request without a response.

# Exception in a callback of a delayed response
def later(self):
    @Pyjo.IOLoop.next_tick
    def tick(loop):
        with self:
            self.render(text=self.param('name').upper())

Helpers

In addition to the attributes and methods below you can also call helpers provided by app on Pyjoyment.Controller objects. This includes all helpers from Pyjoyment.Plugin.DefaultHelpers and Pyjoyment.Plugin.TagHelpers.

# Call helpers
c.layout('green')
c.title('Welcome!')

# Longer version
c.helpers.layout('green')

See also

Pyjoyment, https://mojolicious.org.

Ported from Mojolicious::Controller of Mojolicious 9.49.

class Pyjoyment.Controller.Pyjoyment_Controller(app: Pyjoyment_App | None = None, match: Pyjoyment_Routes_Match | None = None, stash: dict[str, Any] | None = None, tx: Pyjo_Transaction | None = None)[source]

Pyjoyment.Controller inherits all methods from Pyjo.Base and implements the following new ones.

property app: Pyjoyment_App[source]
app = c.app
c.app = Pyjoyment.new()

A reference back to the application that dispatched to this controller, usually a Pyjoyment object. Note that this attribute is weakened.

# Use application logger
c.app.log.debug('Hello Pyjo')

# Generate path
path = c.app.home.child('templates', 'foo', 'bar.html.ep')
cookie(name: str, /) → str | None[source]
cookie(name: str, value: str, options: dict[str, Any] | None = None, /) → Self
value = c.cookie('foo')
c = c.cookie('foo', 'bar')
c = c.cookie('foo', 'bar', {'path': '/'})

Access request cookie values and create new response cookies. If there are multiple values sharing the same name, and you want to access more than just the last one, you can use every_cookie().

# Create response cookie with domain and expiration date
c.cookie('user', 'sri', {'domain': 'example.com', 'expires': time.time() + 60})

# Create secure response cookie
c.cookie('secret', 'I <3 Pyjoyment', {'secure': True, 'httponly': True})
values = c.every_cookie('foo')

Similar to cookie(), but returns all request cookie values sharing the same name as a list.

# Get first cookie value
first = c.every_cookie('foo')[0]
every_param(name: str) → list[Any][source]
values = c.every_param('foo')

Similar to param(), but returns all values sharing the same name as a list.

# Get first value
first = c.every_param('foo')[0]
values = c.every_signed_cookie('foo')

Similar to signed_cookie(), but returns all signed request cookie values sharing the same name as a list.

# Get first signed cookie value
first = c.every_signed_cookie('foo')[0]
finish(*args: Any) → Self[source]
c = c.finish()
c = c.finish(1000)
c = c.finish(1003, 'Cannot accept data!')
c = c.finish(b'Bye!')

Close WebSocket connection or long poll stream gracefully. This method will automatically respond to WebSocket handshake requests with a 101 response status, to establish the WebSocket connection.

property helpers: Any[source]
helpers = c.helpers

Return a proxy object containing the current controller object and on which helpers provided by app can be called. This includes all helpers from Pyjoyment.Plugin.DefaultHelpers and Pyjoyment.Plugin.TagHelpers.

# Make sure to use the "title" helper and not the controller method
c.helpers.title('Welcome!')

# Use a nested helper instead of the "reply" controller method
c.helpers.reply.not_found()
property match: Pyjoyment_Routes_Match[source]
m = c.match
c.match = Pyjoyment.Routes.Match.new()

Router results for the current request, defaults to a Pyjoyment.Routes.Match object.

# Introspect
name = c.match.endpoint.name
foo = c.match.endpoint.pattern.defaults['foo']
action = c.match.stack[-1]['action']
on(name: str, cb: None = None) → Callable[[Callable[[...], Any]], Callable[[...], Any]][source]
on(name: str, cb: Callable[[...], Any]) → Callable[[...], Any]
cb = c.on('finish', lambda c: ...)

@c.on('finish')
def cb(c): ...

Subscribe to events of tx, which is usually a Pyjo.Transaction.HTTP or Pyjo.Transaction.WebSocket object. This method will automatically respond to WebSocket handshake requests with a 101 response status, to establish the WebSocket connection.

# Do something after the transaction has been finished
@c.on('finish')
def finish(c):
    c.app.log.debug('All data has been sent')

# Receive WebSocket message
@c.on('message')
def message(c, msg):
    c.app.log.debug(f'Message: {msg}')

# Receive JSON object via WebSocket message
@c.on('json')
def json(c, hash):
    c.app.log.debug(f'Test: {hash["test"]}')

# Receive WebSocket "Binary" message
@c.on('binary')
def binary(c, data):
    c.app.log.debug(f'Received {len(data)} bytes')
param(name: str, /) → Any[source]
param(name: str, value: Any, /, *values: Any) → Self
value = c.param('foo')
c = c.param('foo', 'ba;r')
c = c.param('foo', 'ba;r', 'baz')
c = c.param('foo', ['ba;r', 'baz'])

Access route placeholder values that are not reserved stash values, 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, in that order. If there are multiple values sharing the same name, and you want to access more than just the last one, you can use every_param(). 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.

# Get first value
first = c.every_param('foo')[0]

For more control you can also access request information directly.

# Only GET parameters
foo = c.req.query_params.param('foo')

# Only POST parameters
foo = c.req.body_params.param('foo')

# Only GET and POST parameters
foo = c.req.param('foo')

# Only file uploads
foo = c.req.upload('foo')
proceed() → None[source]
c.proceed()

Continue dispatch chain from an intermediate destination with Pyjoyment.Routes.Pyjoyment_Routes.proceed(). continue_ is an alias, the name of Mojolicious with an underscore.

render(template: str | None = None, /, **args: Any) → Any[source]
boolean = c.render()
boolean = c.render(foo='bar', baz=23)
boolean = c.render(template='foo/index')
boolean = c.render(template='index', format='html')
boolean = c.render(data=data)
boolean = c.render(text='Hello!')
boolean = c.render(json={'foo': 'bar'})
boolean = c.render(yaml={'foo': 'bar'})
boolean = c.render(toml={'foo': 'bar'})
boolean = c.render(handler='something')
boolean = c.render('foo/index')

Render content with Pyjoyment.Pyjoyment_App.renderer and emit hooks before_render as well as after_render, or raises an exception if no response could be generated. All additional keyword arguments get merged into the stash().

# Render characters
c.render(text='I ♥ Pyjoyment!')

# Render characters (alternative)
c.stash(text='I ♥ Pyjoyment!').render()

# Render binary data
from Pyjo.JSON import encode_json
c.render(data=encode_json({'test': 'I ♥ Pyjoyment!'}))

# Render JSON
c.render(json={'test': 'I ♥ Pyjoyment!'})

# Render YAML, in the style of index.yaml of a chart repository of Helm
c.render(yaml={'entries': {'test': [{'version': '1.0.0'}]}})

# Render TOML, of a table
c.render(toml={'server': {'workers': 4}})

# Render inline template
c.render(inline='<%= 1 + 1 %>')

# Render template "foo/bar.html.ep"
c.render(template='foo/bar', format='html', handler='ep')

# Render template "test.*.*" with arbitrary values "foo" and "bar"
c.render(template='test', foo='test', bar=23)

# Render template "test.xml.*"
c.render(template='test', format='xml')

# Render template "test.xml.*" (alternative)
c.render('test', format='xml')
render_later() → Self[source]
c = c.render_later()

Disable automatic rendering to delay response generation, only necessary if automatic rendering would result in a response.

# Delayed rendering
c.render_later()
Pyjo.IOLoop.timer(2, lambda loop: c.render(text='Delayed by 2 seconds!'))
render_maybe(template: str | None = None, /, **args: Any) → Any[source]
boolean = c.render_maybe()
boolean = c.render_maybe(foo='bar', baz=23)
boolean = c.render_maybe('foo/index', format='html')

Try to render content, but do not call Pyjoyment.Plugin.DefaultHelpers() reply.not_found if no response could be generated, all arguments get localized automatically and are only available during this render operation, takes the same arguments as render().

# Render template "index_local" only if it exists
c.render_maybe('index_local') or c.render('index')
render_to_string(template: str | None = None, /, **args: Any) → Pyjo_String_HTML | Pyjo_String_Bytes | None[source]
output = c.render_to_string('foo/index', format='pdf')

Try to render content and return it wrapped in a Pyjo.String.HTML object, markup that templates do not escape, or a Pyjo.String.Bytes object or return None, all arguments get localized automatically and are only available during this render operation, takes the same arguments as render().

# Render inline template
two = c.render_to_string(inline='<%= 1 + 1 %>')
rendered(status: int | str | None = None) → Self[source]
c = c.rendered()
c = c.rendered(302)

Finalize response and emit hook after_dispatch, defaults to using a 200 response code.

# Custom response
c.res.headers.content_type = 'text/plain'
c.res.body = b'Hello World!'
c.rendered(200)
property req: Pyjo_Message_Request[source]
req = c.req

Get Pyjo.Message.Request object from tx.

# Longer version
req = c.tx.req

# Extract request information
id = c.req.request_id
method = c.req.method
url = c.req.url.to_abs()
info = c.req.url.to_abs().userinfo
host = c.req.url.to_abs().host
agent = c.req.headers.user_agent
custom = c.req.headers.header('Custom-Header')
data = c.req.body
string = c.req.text
hash = c.req.params.to_dict()
all = c.req.uploads
value = c.req.json()
foo = c.req.json('/23/foo')
dom = c.req.dom()
bar = c.req.dom('div.bar').first().text
property res: Pyjo_Message_Response[source]
res = c.res

Get Pyjo.Message.Response object from tx.

# Longer version
res = c.tx.res

# Force file download by setting a response header
c.res.headers.content_disposition = 'attachment; filename=foo.png;'

# Use a custom response header
c.res.headers.header('Custom-Header', 'whatever')

# Make sure response is cached correctly
c.res.headers.cache_control = 'public, max-age=300'
c.res.headers.append('Vary', 'Accept-Encoding')
send(msg: Any, cb: Callable[[Self], Any] | None = None) → Self[source]
c = c.send({'binary': data})
c = c.send({'text': data})
c = c.send({'json': {'test': [1, 2, 3]}})
c = c.send([fin, rsv1, rsv2, rsv3, op, payload])
c = c.send(chars)
c = c.send(chars, lambda c: ...)

Send message or frame non-blocking via WebSocket, the optional drain callback will be executed once all data has been written. This method will automatically respond to WebSocket handshake requests with a 101 response status, to establish the WebSocket connection.

# Send "Text" message
c.send('I ♥ Pyjoyment!')

# Send JSON object as "Text" message
c.send({'json': {'test': 'I ♥ Pyjoyment!'}})

# Send JSON object as "Binary" message
from Pyjo.JSON import encode_json
c.send({'binary': encode_json({'test': 'I ♥ Pyjoyment!'})})

# Send "Ping" frame
from Pyjo.WebSocket import WS_PING
c.send([1, 0, 0, 0, WS_PING, b'Hello World!'])

# Make sure the first message has been written before continuing
c.send('First message!', lambda c: c.send('Second message!'))

For mostly idle WebSockets you might also want to increase the inactivity timeout with the helper inactivity_timeout of Pyjoyment.Plugin.DefaultHelpers, which usually defaults to 30 seconds.

# Increase inactivity timeout for connection to 300 seconds
c.inactivity_timeout(300)
session() → dict[str, Any][source]
session(name: str, /) → Any
session(values: dict[str, Any], /) → Self
session(**values: Any) → Self
session = c.session()
foo = c.session('foo')
c = c.session({'foo': 'bar'})
c = c.session(foo='bar')

Persistent data storage for the next few requests, all session data gets serialized with Pyjo.JSON and stored Base64 encoded in HMAC-SHA256 signed cookies, to prevent tampering. Note that cookies usually have a 4096 byte (4KiB) limit, depending on browser.

# Manipulate session
c.session()['foo'] = 'bar'
foo = c.session()['foo']
del c.session()['foo']

# Expiration date in seconds from now (persists between requests)
c.session(expiration=604800)

# Expiration date as absolute epoch time (only valid for one request)
c.session(expires=time.time() + 604800)

# Delete whole session by setting an expiration date in the past
c.session(expires=1)
signed_cookie(name: str, value: str, options: dict[str, Any] | None = None, /) → Self
value = c.signed_cookie('foo')
c = c.signed_cookie('foo', 'bar')
c = c.signed_cookie('foo', 'bar', {'path': '/'})

Access signed request cookie values and create new signed response cookies. If there are multiple values sharing the same name, and you want to access more than just the last one, you can use every_signed_cookie(). Cookies are cryptographically signed with HMAC-SHA256, to prevent tampering, and the ones failing signature verification will be automatically discarded.

stash() → dict[str, Any][source]
stash(name: str, /) → Any
stash(values: dict[str, Any], /) → Self
stash(**values: Any) → Self
hash = c.stash()
foo = c.stash('foo')
c = c.stash({'foo': 'bar', 'baz': 23})
c = c.stash(foo='bar', baz=23)

Non-persistent data storage and exchange for the current request, application wide default values can be set with Pyjoyment.Pyjoyment_App.defaults(). Some stash values have a special meaning and are reserved, the full list is currently action, app, cb, controller, data, extends, format, handler, inline, json, layout, namespace, path, status, template, text, toml, variant and yaml. Note that all stash values with a mojo.* prefix are reserved for internal use.

# Remove value
foo = c.stash().pop('foo')

# Assign multiple values at once
c.stash(foo='test', bar=23)
property tx: Pyjo_Transaction | None[source]
tx = c.tx
c.tx = Pyjo.Transaction.HTTP.new()

The transaction that is currently being processed, usually a Pyjo.Transaction.HTTP or Pyjo.Transaction.WebSocket object. Note that this attribute is weakened. So the object needs to be referenced elsewhere as well when you’re performing non-blocking operations and the underlying connection might get closed early.

# Check peer information
address = c.tx.remote_address
port = c.tx.remote_port

# Increase size limit for WebSocket messages to 16MiB
if c.tx.is_websocket:
    c.tx.max_websocket_size = 16777216

# Perform non-blocking operation without knowing the connection status
tx = c.tx
Pyjo.IOLoop.timer(2, lambda loop: c.app.log.debug('Finished' if tx.is_finished else 'In progress'))
url_for(target: str | dict[str, Any] | Pyjo_URL | None = None, /, *args: dict[str, Any], **values: Any) → Pyjo_URL[source]
url = c.url_for()
url = c.url_for(name='sebastian')
url = c.url_for({'name': 'sebastian'})
url = c.url_for('test', name='sebastian')
url = c.url_for('test', {'name': 'sebastian'})
url = c.url_for('/index.html')
url = c.url_for('//example.com/index.html')
url = c.url_for('http://example.com/index.html')
url = c.url_for('mailto:sri@example.com')
url = c.url_for('#whatever')

Generate a portable Pyjo.URL object with base for a path, URL or route.

# Rebuild URL for the current route
c.url_for()

# Rebuild URL for the current route, but replace the "name" placeholder value
c.url_for(name='sebastian')

# Absolute URL for the current route
c.url_for().to_abs()

# Build URL for route "test" with two placeholder values
c.url_for('test', name='sebastian', foo='bar')

# "http://127.0.0.1:3000/index.html" if application was started with Pyjo.Server.Reload
c.url_for('/index.html').to_abs()

# "https://127.0.0.1:443/index.html" if application was started with Pyjo.Server.Reload
c.url_for('/index.html').to_abs().set(scheme='https', port=443)

# "/index.html?foo=bar" if application is deployed under "/"
c.url_for('/index.html').set(query={'foo': 'bar'})

# "/myapp/index.html?foo=bar" if application is deployed under "/myapp"
c.url_for('/index.html').set(query={'foo': 'bar'})

You can also use the helper url_with of Pyjoyment.Plugin.DefaultHelpers to inherit query parameters from the current request.

# "/list?q=mojo&page=2" if current request was for "/list?q=mojo&page=1"
c.url_with().set(query={'page': 2})
url_for_asset(asset: str) → Pyjo_URL[source]
url = c.url_for_asset('/app.js')

Generate a portable Pyjo.URL object with base for a static asset.

url_for_file(file: str) → Pyjo_URL[source]
url = c.url_for_file('/index.html')

Generate a portable Pyjo.URL object with base for a static file.

write(chunk: bytes | None = None, cb: Callable[[Self], Any] | None = None) → Self[source]
c = c.write()
c = c.write(b'')
c = c.write(data)
c = c.write(data, lambda c: ...)

Write dynamic content non-blocking, the optional drain callback will be executed once all data has been written. Calling this method without a chunk of data will finalize the response headers and allow for dynamic content to be written later.

# Keep connection alive (with Content-Length header)
c.res.headers.content_length = 6
c.write(b'Hel', lambda c: c.write(b'lo!'))

# Close connection when finished (without Content-Length header)
c.write(b'Hel', lambda c: c.write(b'lo!', lambda c: c.finish()))

You can call finish() or write an empty chunk of data at any time to end the stream.

HTTP/1.1 200 OK
Date: Sat, 13 Sep 2014 16:48:29 GMT
Content-Length: 6
Server: Pyjoyment (Python)

Hello!

HTTP/1.1 200 OK
Connection: close
Date: Sat, 13 Sep 2014 16:48:29 GMT
Server: Pyjoyment (Python)

Hello!

For Comet (long polling) you might also want to increase the inactivity timeout with the helper inactivity_timeout of Pyjoyment.Plugin.DefaultHelpers, which usually defaults to 30 seconds.

# Increase inactivity timeout for connection to 300 seconds
c.inactivity_timeout(300)
write_chunk(chunk: bytes | None = None, cb: Callable[[Self], Any] | None = None) → Self[source]
c = c.write_chunk()
c = c.write_chunk(b'')
c = c.write_chunk(data)
c = c.write_chunk(data, lambda c: ...)

Write dynamic content non-blocking with chunked transfer encoding, the optional drain callback will be executed once all data has been written. Calling this method without a chunk of data will finalize the response headers and allow for dynamic content to be written later.

# Make sure previous chunk has been written before continuing
c.write_chunk(b'H', lambda c: c.write_chunk(b'ell', lambda c: c.finish(b'o!')))

You can call finish() or write an empty chunk of data at any time to end the stream.

HTTP/1.1 200 OK
Date: Sat, 13 Sep 2014 16:48:29 GMT
Transfer-Encoding: chunked
Server: Pyjoyment (Python)

1
H
3
ell
2
o!
0
write_sse(event: dict[str, Any] | None = None, cb: Callable[[Self], Any] | None = None) → Self[source]
c = c.write_sse()
c = c.write_sse(event)
c = c.write_sse(event, lambda c: ...)

Write Server-Sent Event (SSE) non-blocking, the optional drain callback will be executed once all data has been written. Calling this method without an event will finalize the response headers and allow for events to be written later. Note that this method is EXPERIMENTAL and might change without warning!

# Send event with default "message" type
c.write_sse({'text': 'Hello World!'})

# You can send comments in regular intervals to keep the connection alive
c.write_sse({'comment': 'Keep connection alive!'})

# Make sure previous event has been written before continuing (id and type are optional)
c.write_sse(
    {'id': 23, 'type': 'greeting', 'text': 'Hello World!'},
    lambda c: c.write_sse({'id': 24, 'type': 'farewell', 'text': 'Goodbye World!'}, lambda c: c.finish()),
)