Routing
Glim has an easy to use powerful routing feature where developers can define routes in seconds. It uses werkzeug's great routing features and exposes all of them. The route definitions reside in app/routes.py
file. The simplest route example would be the following;
# routes.py
urls = {
'/': 'BaseController.hello'
}
The first route definition simply means that BaseController
's hello()
function is mapped to the root route ( / ). Although most of the popular web frameworks allow automatic detection of controller, action, glim doesn't allow for that because of security reasons.
RESTful Routing
There are two ways of RESTful routing in glim. The first one is to define Controllers as resources.
Consider the following route definition;
# routes.py
urls = {
'/users': 'UserController'
}
The second route definition is a typical example of a RESTful
routing in glim. This means that the following http methods are automatically mapped to the functions;
URL | HTTP Method | Function |
---|---|---|
/users | POST | UserController.post() |
/users | PUT | UserController.put() |
/users | GET | UserController.get() |
/users | DELETE | UserController.delete() |
/users | PATCH | UserController.patch() |
Moreover, glim has an option to define routes with single verbs. For instance;
# routes.py
urls = {
'POST /authentication': 'UserController.login'
}
This route will match /authentication endpoint with only POST method to UserController's login function
More examples on routing
Glim has features to validate variables inside the route level as werkzeug provides. A more complex route definition example would be the following;
# routes.py
urls = {
'/feeds/<slug>' : 'FeedController.get'
}
In this example, this route definition will be mapped into FeedController
‘s get(slug)
function.
A GET | POST to /feeds route without variable will result in HTTP 404 - Not found response.
You can also define types of variables in route level. The following example will also match types;
# routes.py
urls = {
'/post/<int:year>' : 'PostController.get'
}
# is mapping to
# app/controllers.py
class PostController(object):
def get(self, year):
# do stuff
In this example, the route will only be mapped for integer typed year variables. The route will be mapped into PostController
‘s get()
function with year only being an integer.
The routing system also allows defining the length of variables. For example;
# routes.py
urls = {
'/index/<string(length=2):lang_code>' : 'HomeController.index'
}
In this definition, the route will be mapped HomeController
‘s index(lang_code)
function with lang_code
being only strings with length of 2.
For mapping any of the routes, <any>
keyword can be used in defining generic routes like the following;
# routes.py
urls = {
'/<any(about, help, imprint):page' : 'PageController.resolve'
}
In this definition, the route will be mapped into PageController‘s resolve(page) function with page variable being about
, help
or imprint
.
Updated less than a minute ago