-
Notifications
You must be signed in to change notification settings - Fork 3
Routing
Chocs is shipped with a built-in routing library. The easiest way to register new route is by utilising chocs.Application
instance which provides a simple API where each function is a decorator corresponding to an HTTP method.
import chocs
http = chocs.Application()
@http.get("/hello")
def hello(req: chocs.HttpRequest) -> chocs.HttpResponse:
...
The above example will assign the hello function to handle a GET /hello
request.
Available methods:
delete
get
head
options
patch
post
put
trace
Routes can contain parameterised parts. Parameters must be enclosed within {
and }
.
from chocs import Application
http = Application()
@http.get("/pet/{id}")
def hello():
...
Will match the following URIs:
/pet/1
/pet/abc
/pet/abc1
Asterisks (*
) can be used in the route's pattern to match any possible combination. Keep in mind that routes which
do not contain wildcards are prioritised over routes with wildcards.
from chocs import Application
http = Application()
@http.get("/pet/*", id)
def hello():
...
The above example will match following URIs:
/pet/a
/pet/a/b/c
/pet/12jd/fds
Chocs supports route groups. Route groups is implemented through context lib interface. If you need to split your application in smaller chunks with standalone req/res handlers consider the following example:
from threading import Thread
from chocs.wsgi import serve
from chocs import Application
from chocs import HttpRequest
from chocs import HttpResponse
main_app = Application()
with main_app.group("/users/{id}") as user_module:
@user_module.post("/profile_picture") # POST /users/{id}/profile_pictures
def create_profile_picture(request: HttpRequest) -> HttpResponse:
...
@user_module.get("/profile_picture") # GET /users/{id}/profile_pictures
def get_profile_picture(request: HttpRequest) -> HttpResponse:
...
@user_module.get("/badges") # GET /users/{id}/badges
def badges(request: HttpRequest) -> HttpResponse:
...
with main_app.group("/payments") as payment_module:
@payment_module.get("/analytics") # GET /payments/analytics
def get_analytics(request: HttpRequest) -> HttpResponse:
...
if __name__ == '__main__':
def wsgi_user_module():
serve(user_module, port=8081)
def wsgi_payment_module():
serve(payment_module, port=8082)
Thread(target=wsgi_user_module).start()
payment_module()
The above example shows how to run two different modules, which support their own routes on two different ports in the one process.
- Creating new application
- Registering a controller
- Grouping controllers
- Registering middleware
- Dynamically loading modules
TBA
TBA
- Reading request's body
- Accessing request's parsed body
- Accessing request's headers
- Accessing path's parameters
- Reading client cookies
- Comparing requests objects
- API