Skip to content

Application

Dawid Kraczkowski edited this page Oct 15, 2021 · 10 revisions

chocs.Application class is a base block for building your applications. It is always your starting point, application provides features like:

  • register controllers
  • grouping controllers
  • registering middleware
  • dynamically loading modules

Creating new application

import chocs

my_app = chocs.Application()

The above example is the simplest application you can ever create. It does nothing for now, but with it you can now; register controllers, define submodules and load modules on runtime.

Registering a controller

The following code registers new resource within our application, that is available under /hello path and handled by my_controller controller.

import chocs

my_app = chocs.Application()

@my_app.get("/hello")
def my_controller(request:chocs.HttpRequest) -> chocs.HttpResponse:
    return chocs.HttpResponse("Hello!")

Controller is expected to always accept chocs.HttpRequest as input and return chocs.HttpResponse as output.

Grouping controllers

import chocs

my_app = chocs.Application()

with my_app.group("/hello") as hello_group:
    
    @hello_group.get("/john")
    def hello_john(request:chocs.HttpRequest) -> chocs.HttpResponse:
        return chocs.HttpResponse("Hello John!")

    @hello_group.get("/tom")
    def hello_john(request:chocs.HttpRequest) -> chocs.HttpResponse:
        return chocs.HttpResponse("Hello Tom!")

with my_app.group("/goodbye") as goodbye_group:

    @goodbye_group.get("/tom")
    def hello_john(request:chocs.HttpRequest) -> chocs.HttpResponse:
        return chocs.HttpResponse("Goodbye Tom!")

Registering middleware

Middleware can be passed to chocs.Application's initialiser. Consider the following example:

import chocs

my_app = chocs.Application(chocs.middleware.ParsedBodyMiddleware())

More about middleware can be found in the following link

Dynamically loading modules

Application.use is a helper method that allows dynamical module loading, usually you need to load modules which contain controllers definitions only. While using this feature you should keep in mind possible circular dependencies problem, thus it is recommended to keep your application instance in a separate module.

The following example presents how to load multiple sub-modules from base_module.routes module.

import chocs

my_app = chocs.Application()

my_app.use("base_module.routes.*")  # asterisk is used to load all submodules from `/base_module/routes` directory

More examples can be found in /examples/loading_modules directory.