Pyjoyment - Real-time web framework

# Application
import Pyjoyment

class MyApp(Pyjoyment.object):

    # Route
    def startup(self):
        self.get('/hello').to('foo#hello')

# Controller
import Pyjoyment.Controller

class MyApp_Controller_Foo(Pyjoyment.Controller.object):

    # Action
    def hello(self):
        self.render(text='Hello World!')

An amazing real-time web framework built on top of the powerful Pyjo web development toolkit, ported from Mojolicious. With support for RESTful routes, plugins, content negotiation, session management, static file server, first class Unicode support and much more for you to discover.

Hooks

Pyjoyment will emit the following hooks in the listed order.

before_command

Emitted right before the application runs a command through the command line interface.

@app.hook('before_command')
def before_command(command, args): ...

Useful for reconfiguring the application before running a command or to modify the behavior of a command. (Passed the command object and the list of the command arguments)

before_server_start

Emitted right before the application server is started, for web servers that support it, which includes all the built-in ones.

@app.hook('before_server_start')
def before_server_start(server, app): ...

Useful for reconfiguring application servers dynamically or collecting server diagnostics information. (Passed the server and application objects)

after_build_tx

Emitted right after the transaction is built and before the HTTP request gets parsed.

@app.hook('after_build_tx')
def after_build_tx(tx, app): ...

This is a very powerful hook and should not be used lightly, it makes some rather advanced features such as upload progress bars possible. Note that this hook will not work for embedded applications, because only the host application gets to build transactions. (Passed the transaction and application objects)

around_dispatch

Emitted right after a new request has been received and wraps around the whole dispatch process, so you have to manually forward to the next hook if you want to continue the chain. Default exception handling with the helper reply.exception of Pyjoyment.Plugin.DefaultHelpers is the first hook in the chain and a call to Pyjoyment_App.dispatch() the last, yours will be in between.

@app.hook('around_dispatch')
def around_dispatch(next, c):
    ...
    next()
    ...

This is a very powerful hook and should not be used lightly, it allows you, for example, to customize application-wide exception handling, consider it the sledgehammer in your toolbox. (Passed a callback leading to the next hook and the default controller object)

before_dispatch

Emitted right before the static file server and router start their work.

@app.hook('before_dispatch')
def before_dispatch(c): ...

Very useful for rewriting incoming requests and other preprocessing tasks. (Passed the default controller object)

after_static

Emitted after a static file response has been generated by the static file server.

@app.hook('after_static')
def after_static(c): ...

Mostly used for post-processing static file responses. (Passed the default controller object)

before_routes

Emitted after the static file server determined if a static file should be served and before the router starts its work.

@app.hook('before_routes')
def before_routes(c): ...

Mostly used for custom dispatchers and collecting metrics. (Passed the default controller object)

around_action

Emitted right before an action gets executed and wraps around it, so you have to manually forward to the next hook if you want to continue the chain. Default action dispatching is the last hook in the chain, yours will run before it.

@app.hook('around_action')
def around_action(next, c, action, last):
    ...
    return next()

This is a very powerful hook and should not be used lightly, it allows you for example to pass additional arguments to actions or handle return values differently. Note that this hook can trigger more than once for the same request if there are nested routes. (Passed a callback leading to the next hook, the current controller object, the action callback and a flag indicating if this action is an endpoint)

before_render

Emitted before content is generated by the renderer. Note that this hook can trigger out of order due to its dynamic nature, and with embedded applications will only work for the application that is rendering.

@app.hook('before_render')
def before_render(c, args): ...

Mostly used for pre-processing arguments passed to the renderer. (Passed the current controller object and the render arguments)

after_render

Emitted after content has been generated by the renderer that will be assigned to the response. Note that this hook can trigger out of order due to its dynamic nature, and with embedded applications will only work for the application that is rendering.

@app.hook('after_render')
def after_render(c, output, format): ...

Mostly used for post-processing dynamically generated content. (Passed the current controller object, a file object with the content and the format)

after_dispatch

Emitted in reverse order after a response has been generated. Note that this hook can trigger out of order due to its dynamic nature, and with embedded applications will only work for the application that is generating the response.

@app.hook('after_dispatch')
def after_dispatch(c): ...

Useful for rewriting outgoing responses and other post-processing tasks. (Passed the current controller object)

after_server_stop

Emitted right after the application server has stopped gracefully, in each process and thread that has run the application, for web servers that support it, which includes all the built-in ones but Pyjo.Server.WSGI and Pyjo.Server.Lambda, which do not know when they stop. The event loop no longer runs, and the server runs it until a Pyjo.Promise that the hook returns is settled.

@app.hook('after_server_stop')
def after_server_stop(server, app): ...

Useful for cleaning up what the application has started for the server, as the connections of a pool. (Passed the server and application objects)

Helpers

In addition to the attributes and methods below you can also call helpers on Pyjoyment objects. This includes all helpers from Pyjoyment.Plugin.DefaultHelpers and Pyjoyment.Plugin.TagHelpers. Note that application helpers are always called with a new default controller object, so they can’t depend on or change controller state, which includes request, response and stash.

# Call helper
print(app.dumper({'foo': 'bar'}))

# Longer version
print(app.build_controller().helpers.dumper({'foo': 'bar'}))

See also

Pyjo, https://mojolicious.org.

Ported from Mojolicious of Mojolicious 9.53.

class Pyjoyment.Pyjoyment_App(attrs: dict[str, Any] | None = None, /, **kwargs: Any)[source]

Pyjoyment inherits all attributes and methods from Pyjo.App and implements the following new ones.

any(*args: Any, **constraints: Constraint) → Pyjoyment_Routes_Route[source]
route = app.any('/:foo', lambda c: ...)

Generate route with Pyjoyment.Routes.Route.Pyjoyment_Routes_Route.any() on routes, takes the same arguments.

build_controller(tx: Any = None) → Pyjoyment_Controller[source]
c = app.build_controller()
c = app.build_controller(Pyjo.Transaction.HTTP.new())
c = app.build_controller(Pyjoyment.Controller.new())

Build default controller object with controller_class.

# Render template from application
foo = app.build_controller().render_to_string(template='foo')
build_tx() → Pyjo_Transaction_HTTP[source]
tx = app.build_tx()

Build Pyjo.Transaction.HTTP object and emit after_build_tx hook.

property commands: Pyjoyment_Commands[source]
commands = app.commands
app.commands = Pyjoyment.Commands.new()

Command line interface for your application, defaults to a Pyjoyment.Commands object.

# Add another namespace to load commands from
app.commands.namespaces.append('MyApp.Command')
controller_class: type[Pyjoyment_Controller] | str
cls = app.controller_class
app.controller_class = Pyjoyment.Controller.object

Class to be used for the default controller, defaults to Pyjoyment.Controller.

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

Default values for Pyjoyment.Controller.Pyjoyment_Controller.stash(), assigned for every new request.

# Remove value
foo = app.defaults().pop('foo')

# Assign multiple values at once
app.defaults(foo='test', bar=23)
delete(*args: Any, **constraints: Constraint) → Pyjoyment_Routes_Route[source]
route = app.delete('/:foo', lambda c: ...)

Generate route with Pyjoyment.Routes.Route.Pyjoyment_Routes_Route.delete() on routes, takes the same arguments.

dispatch(c: Pyjoyment_Controller) → None[source]
app.dispatch(Pyjoyment.Controller.new())

The heart of every Pyjoyment application, calls the static and routes dispatchers for every request and passes them a Pyjoyment.Controller object.

exception_format
format = app.exception_format
app.exception_format = 'txt'

Format for HTTP exceptions (html, json, or txt), defaults to html.

get(*args: Any, **constraints: Constraint) → Pyjoyment_Routes_Route[source]
route = app.get('/:foo', lambda c: ...)

Generate route with Pyjoyment.Routes.Route.Pyjoyment_Routes_Route.get() on routes, takes the same arguments.

handler(tx: Any) → None[source]
app.handler(Pyjo.Transaction.HTTP.new())
app.handler(Pyjoyment.Controller.new())

Sets up the default controller and emits the around_dispatch hook for every request.

helper(name: str, cb: None = None) → Callable[[F], F][source]
helper(name: str, cb: F) → F
app.helper('foo', lambda c, *args: ...)

@app.helper('foo')
def foo(c, *args): ...

Add or replace a helper that will be available as a method of the controller object and the application object. For a full list of helpers that are available by default see Pyjoyment.Plugin.DefaultHelpers and Pyjoyment.Plugin.TagHelpers.

# Helper
cache = {}
app.helper('cache', lambda c: cache)

# Application
app.cache()['foo'] = 'bar'
result = app.cache()['foo']

# Controller
c.cache()['foo'] = 'bar'
result = c.cache()['foo']
hook(name: str, cb: Callable[[...], Any] | None = None) → Any[source]
app.hook('after_dispatch', lambda c: ...)

@app.hook('after_dispatch')
def after_dispatch(c): ...

Extend Pyjoyment with hooks, which allow code to be shared with all requests indiscriminately, for a full list of available hooks see the hooks above.

# Dispatchers will not run if there's already a response code defined
@app.hook('before_dispatch')
def before_dispatch(c):
    if re.search(r'do_not_dispatch', c.req.url.path.to_route()):
        c.render(text='Skipped static file server and router!')
property log: Pyjo_Log[source]
log = app.log
app.log = Pyjo.Log.new()

The logging layer of your application, defaults to a Pyjo.Log object. The level will default to either the PYJO_LOG_LEVEL environment variable, trace if the mode is development, or info otherwise. All messages will be written to sys.stderr by default.

# Log debug message
app.log.debug('It works')
max_request_size: int | None
max = app.max_request_size
app.max_request_size = 16777216

Maximum request size in bytes, defaults to the value of Pyjo.Message.Pyjo_Message.max_message_size. Setting the value to 0 will allow requests of indefinite size. Note that increasing this value can also drastically increase memory usage, should you for example attempt to parse an excessively large request body with the methods dom or json of Pyjo.Message.

property mode: str[source]
mode = app.mode
app.mode = 'production'

The operating mode for your application, defaults to a value from the PYJO_MODE environment variable or development.

options(*args: Any, **constraints: Constraint) → Pyjoyment_Routes_Route[source]
route = app.options('/:foo', lambda c: ...)

Generate route with Pyjoyment.Routes.Route.Pyjoyment_Routes_Route.options() on routes, takes the same arguments.

patch(*args: Any, **constraints: Constraint) → Pyjoyment_Routes_Route[source]
route = app.patch('/:foo', lambda c: ...)

Generate route with Pyjoyment.Routes.Route.Pyjoyment_Routes_Route.patch() on routes, takes the same arguments.

plugin(name: str, conf: dict[str, Any] | None = None, /, **values: Any) → Any[source]
app.plugin('some_thing')
app.plugin('some_thing', foo=23)
app.plugin('some_thing', {'foo': 23})
app.plugin('SomeThing')
app.plugin('SomeThing', foo=23)
app.plugin('SomeThing', {'foo': 23})
app.plugin('MyApp.Plugin.SomeThing')
app.plugin('MyApp.Plugin.SomeThing', foo=23)
app.plugin('MyApp.Plugin.SomeThing', {'foo': 23})

Load a plugin, for a full list of example plugins included in the Pyjoyment distribution see Pyjoyment.Plugins.

plugins: Pyjoyment_Plugins
plugins = app.plugins
app.plugins = Pyjoyment.Plugins.new()

The plugin manager, defaults to a Pyjoyment.Plugins object. See the plugin() method below if you want to load a plugin.

# Add another namespace to load plugins from
app.plugins.namespaces.append('MyApp.Plugin')
post(*args: Any, **constraints: Constraint) → Pyjoyment_Routes_Route[source]
route = app.post('/:foo', lambda c: ...)

Generate route with Pyjoyment.Routes.Route.Pyjoyment_Routes_Route.post() on routes, takes the same arguments.

preload_namespaces: list[str]
namespaces = app.preload_namespaces
app.preload_namespaces = ['MyApp.Controller']

Namespaces to preload classes from during application startup.

put(*args: Any, **constraints: Constraint) → Pyjoyment_Routes_Route[source]
route = app.put('/:foo', lambda c: ...)

Generate route with Pyjoyment.Routes.Route.Pyjoyment_Routes_Route.put() on routes, takes the same arguments.

query(*args: Any, **constraints: Constraint) → Pyjoyment_Routes_Route[source]
route = app.query('/:foo', lambda c: ...)

Generate route with Pyjoyment.Routes.Route.Pyjoyment_Routes_Route.query() on routes, takes the same arguments.

renderer: Pyjoyment_Renderer
renderer = app.renderer
app.renderer = Pyjoyment.Renderer.new()

Used to render content, defaults to a Pyjoyment.Renderer object.

# Enable compression
app.renderer.compress = True

# Add another "templates" directory
app.renderer.paths.append('/home/sri/templates')

# Add another "templates" directory with higher precedence
app.renderer.paths.insert(0, '/home/sri/themes/blue/templates')

# Add another class with templates in DATA section
app.renderer.classes.append('Pyjoyment.Plugin.Fun')
routes: Pyjoyment_Routes
routes = app.routes
app.routes = Pyjoyment.Routes.new()

The router, defaults to a Pyjoyment.Routes object. You use this in your startup method to define the url endpoints for your application.

# Add routes
r = app.routes
r.get('/foo/bar').to('test#foo', title='Hello Pyjo!')
r.post('/baz').to('test#baz')

# Add another namespace to load controllers from
app.routes.namespaces.append('MyApp.MyController')
property secrets: list[str][source]
secrets = app.secrets
app.secrets = [passphrase]

Secret passphrases used for signed cookies and the like, defaults to the moniker of this application, which is not very secure, so you should change it!!! As long as you are using the insecure default there will be debug messages in the log file reminding you to change your passphrase. Only the first passphrase is used to create new signatures, but all of them for verification. So you can increase security without invalidating all your existing signed cookies by rotating passphrases, just add new ones to the front and remove old ones from the back.

# Rotate passphrases
app.secrets = ['new_passw0rd', 'old_passw0rd', 'very_old_passw0rd']
server(server: Pyjo_Server) → None[source]
app.server(Pyjo.Server.new())

Emits the before_server_start hook.

server_stopped(server: Pyjo_Server) → Pyjo_Promise | None[source]
promise = app.server_stopped(Pyjo.Server.new())

Emits the after_server_stop hook, and returns a promise of the promises that its callbacks return.

sessions: Pyjoyment_Sessions
sessions = app.sessions
app.sessions = Pyjoyment.Sessions.new()

Signed cookie based session manager, defaults to a Pyjoyment.Sessions object. You can usually leave this alone, see Pyjoyment.Controller.Pyjoyment_Controller.session() for more information about working with session data.

# Change name of cookie used for all sessions
app.sessions.cookie_name = 'mysession'

# Disable SameSite feature
app.sessions.samesite = None
start(*args: str) → Any[source]
app.start()
app.start(*sys.argv[1:])

Start the command line interface for your application. For a full list of commands that are available by default see Pyjoyment.Commands. Note that the options -h/--help, --home and -m/--mode, which are shared by all commands, will be parsed from sys.argv when Pyjoyment.Commands is imported.

# Always start daemon
app.start('daemon', '-l', 'http://*:8080')

When the environment variable PYJO_APP_LOADER is set, as Pyjo.Server.Pyjo_Server.load_app() does, the application is kept in Pyjo.Server.loaded_app for the server instead.

startup() → None[source]
app.startup()

This is your main hook into the application, it will be called at application startup. Meant to be overloaded in a subclass.

def startup(self): ...
static: Pyjoyment_Static
static = app.static
app.static = Pyjoyment.Static.new()

For serving static files from your public directories, defaults to a Pyjoyment.Static object.

# Serve static files only with a "/static" prefix
app.static.prefix = '/static'

# Add another "public" directory
app.static.paths.append('/home/sri/public')

# Add another "public" directory with higher precedence
app.static.paths.insert(0, '/home/sri/themes/blue/public')

# Add another class with static files in DATA section
app.static.classes.append('Pyjoyment.Plugin.Fun')

# Remove built-in favicon
del app.static.extra['favicon.ico']
template(name: str, cb: None = None) → Callable[[F], F][source]
template(name: str, cb: F) → F
app.template('index.html', lambda c: t('<p>Hello!</p>'))

@app.template('index.html')
def index(c): ...

Add or replace a template of a function, which gets the controller and the values of the stash that it names and returns a template string, with Pyjoyment.Renderer.Pyjoyment_Renderer.add_template(), see Pyjoyment.Plugin.PyRenderer.

# Template
@app.template('hello.html')
def hello(c, name):
    return t('<p>Hello {name}!</p>')

# Controller
c.render('hello', name='Joe')
types: Pyjoyment_Types
types = app.types
app.types = Pyjoyment.Types.new()

Responsible for connecting file extensions with MIME types, defaults to a Pyjoyment.Types object.

# Add custom MIME type
app.types.type('twt', 'text/tweet')
under(*args: Any, **constraints: Constraint) → Pyjoyment_Routes_Route[source]
route = app.under('/:foo', lambda c: ...)

Generate route with Pyjoyment.Routes.Route.Pyjoyment_Routes_Route.under() on routes, takes the same arguments.

validator: Pyjoyment_Validator
validator = app.validator
app.validator = Pyjoyment.Validator.new()

Validate values, defaults to a Pyjoyment.Validator object.

# Add validation check
app.validator.add_check('foo', lambda v, name, value: value != 'foo')

# Add validation filter
app.validator.add_filter('quotemeta', lambda v, name, value: re.escape(value))
warmup() → None[source]
app.warmup()

Preload classes from preload_namespaces for future use.

websocket(*args: Any, **constraints: Constraint) → Pyjoyment_Routes_Route[source]
route = app.websocket('/:foo', lambda c: ...)

Generate route with Pyjoyment.Routes.Route.Pyjoyment_Routes_Route.websocket() on routes, takes the same arguments.