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.exceptionofPyjoyment.Plugin.DefaultHelpersis the first hook in the chain and a call toPyjoyment_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.WSGIandPyjo.Server.Lambda, which do not know when they stop. The event loop no longer runs, and the server runs it until aPyjo.Promisethat 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]¶
Pyjoymentinherits all attributes and methods fromPyjo.Appand 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()onroutes, 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.HTTPobject and emitafter_build_txhook.
- property commands: Pyjoyment_Commands[source]¶
commands = app.commands app.commands = Pyjoyment.Commands.new()
Command line interface for your application, defaults to a
Pyjoyment.Commandsobject.# 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()onroutes, takes the same arguments.
- dispatch(c: Pyjoyment_Controller) None[source]¶
app.dispatch(Pyjoyment.Controller.new())
The heart of every
Pyjoymentapplication, calls thestaticandroutesdispatchers for every request and passes them aPyjoyment.Controllerobject.
- exception_format¶
format = app.exception_format app.exception_format = 'txt'
Format for HTTP exceptions (
html,json, ortxt), defaults tohtml.
- 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()onroutes, 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_dispatchhook 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.DefaultHelpersandPyjoyment.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
Pyjoymentwith 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.Logobject. The level will default to either thePYJO_LOG_LEVELenvironment variable,traceif themodeisdevelopment, orinfootherwise. All messages will be written tosys.stderrby 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 to0will 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 methodsdomorjsonofPyjo.Message.
- property mode: str[source]¶
mode = app.mode app.mode = 'production'
The operating mode for your application, defaults to a value from the
PYJO_MODEenvironment variable ordevelopment.
- 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()onroutes, 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()onroutes, 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
Pyjoymentdistribution seePyjoyment.Plugins.
- plugins: Pyjoyment_Plugins¶
plugins = app.plugins app.plugins = Pyjoyment.Plugins.new()
The plugin manager, defaults to a
Pyjoyment.Pluginsobject. See theplugin()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()onroutes, 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()onroutes, 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()onroutes, takes the same arguments.
- renderer: Pyjoyment_Renderer¶
renderer = app.renderer app.renderer = Pyjoyment.Renderer.new()
Used to render content, defaults to a
Pyjoyment.Rendererobject.# 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.Routesobject. 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
monikerof 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_starthook.
- server_stopped(server: Pyjo_Server) Pyjo_Promise | None[source]¶
promise = app.server_stopped(Pyjo.Server.new())
Emits the
after_server_stophook, 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.Sessionsobject. You can usually leave this alone, seePyjoyment.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,--homeand-m/--mode, which are shared by all commands, will be parsed fromsys.argvwhenPyjoyment.Commandsis imported.# Always start daemon app.start('daemon', '-l', 'http://*:8080')
When the environment variable
PYJO_APP_LOADERis set, asPyjo.Server.Pyjo_Server.load_app()does, the application is kept inPyjo.Server.loaded_appfor 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
publicdirectories, defaults to aPyjoyment.Staticobject.# 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(), seePyjoyment.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.Typesobject.# 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()onroutes, takes the same arguments.
- validator: Pyjoyment_Validator¶
validator = app.validator app.validator = Pyjoyment.Validator.new()
Validate values, defaults to a
Pyjoyment.Validatorobject.# 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_namespacesfor 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()onroutes, takes the same arguments.