Web server¤
For starting, accessing, and manipulating of a web server, ASAB provides asab.web
module together with asab.WebService
and asab.web.WebContainer
.
This module offers an integration of aiohttp
web server. It is possible to run multiple web servers from one application. The configuration for each server is stored in dedicated web container. Web Service registers these containers and runs the servers.
Tip
For a quick start, we recommend reading the official aiohttp
tutorial on how to run a simple web server.
In order to use ASAB Web Service, first make sure that you have aiohttp
module installed:
Handlers, routes, and resources¤
aiohttp
servers use the concept of handlers, routes, and resources. Here we provide a very quick explanation that should help you to get into the terminology.
-
Handler, more precisely "a web request handler", is a function that does the logic when you send an HTTP request to the endpoint. It is a coroutine that accepts
aiohttp.web.Request
instance as its only parameter and returns aaiohttp.web.Response
object. -
Route corresponds to handling HTTP method by calling web handler. Routes are added to the route table that is stored in the Web Application object.
-
Resource is an entry in route table which corresponds to requested URL. Resource in turn has at least one route. When you add a route, the resource object is created under the hood.
Running a simple web server¤
Creating a web server 1: One method does it all!
To build a web server quickly, ASAB provides a method asab.web.create_web_server()
that does all the magic.
- Web server configuration should be prepared during the init-time of the application lifecycle.
asab.web.create_web_server()
creates web server and returns instance ofaiohttp.web.UrlDispatcher
object (which is usually referred to as a "router"). The method takes the argumentapp
which is used as the reference to the baseasab.Application
object, and optional parameters that expand configuration options.- You can easily create a new endpoint by
aiohttp.web.UrlDispatcher.add_route()
method that appends a request handler to the router table. This one is a shortcut for adding a GET handler. - A request handler must be a coroutine that accepts
aiohttp.web.Request
instance as its only parameter and returnsaiohttp.web.Response
instance.
By default, ASAB server runs on 0.0.0.0:8080
.
You can test if your server is working by sending a request to the /hello
endpoint, e.g., via the curl
command:
and you should get the response:
Creating a web server 2: Under the hood.
The code below does exactly the same as in the previous example.
- In order to use
asab.WebService
, first import the correspondingasab.web.Module
... - ...and then locate the Service.
- Creates the Web container, which is instance of
asab.Config.Configurable
object that stores the configuration such as the actual web application. asab.web.WebContainer.WebApp
is instance ofaiohttp.web.Application
object. To create a new endpoint, use methods foraiohttp.web.Application.router
object.- A request handler must be a coroutine that accepts
aiohttp.web.Request
instance as its only parameter and returnsaiohttp.web.Response
instance.
Tip
Resources may also have variable path, see the documentation.
Note
aiohttp
also supports the Flask style for creating web request handlers via decorators. ASAB applications use the Django style way of creating routes, i.e. without decorators.
Web server configuration¤
Configuration is passed to the asab.web.WebContainer
object.
Parameter | Meaning |
---|---|
listen |
The socket address to which the web server will listen |
backlog |
A number of unaccepted connections that the system will allow before refusing new connections, see socket.socket.listen() for details |
rootdir |
The root path for the server. In case of many web containers, each one can implement a different root |
servertokens |
Controls whether 'Server' response header field is included ('full' ) or faked ('prod' ) |
cors |
See Cross-Origin Resource Sharing section |
body_max_size |
Client's maximum size in a request, in bytes. If a POST request exceeds this value, aiohttp.HTTPRequestEntityTooLarge exception is raised. See the documentation for more information |
cors |
Contents of the Access-Control-Allow-Origin header. See the CORS section |
cors_preflight_paths |
Pattern for endpoints that shall return responses to pre-flight requests (OPTIONS). Value must start with "/" . See the CORS section |
The default configuration¤
[web]
listen=0.0.0.0 8080
backlog=128
rootdir=
servertokens=full
cors=
cors_preflight_paths=/openidconnect/*, /test/*
body_max_size=1024**2
Socket addresses¤
The default configuration of the web socket address in asab.web.WebContainer
is the following:
Multiple listening interfaces can be specified:
Multiple listening interfaces, one with HTTPS (TLS/SSL) can be specified:
Multiple interfaces, one with HTTPS (inline):
[web]
listen:
0.0.0.0 8080
:: 8080
0.0.0.0 8443 ssl
# The SSL parameters are inside of the WebContainer section
cert=...
key=...
You can also enable listening on TCP port 8080, IPv4 and IPv6 if applicable:
Reference¤
asab.web.create_web_server(app, section='web', config=None, api=False)
¤
Build the web server with the specified configuration.
It is an user convenience function that simplifies typical way of how the web server is created.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app
|
Application
|
A reference to the ASAB Application. |
required |
section
|
str
|
Configuration section name with which the WebContainer will be created. |
'web'
|
config
|
dict | None
|
Additional server configuration. |
None
|
Returns:
Type | Description |
---|---|
UrlDispatcher
|
Examples:
class MyApplication(asab.Application):
async def initialize(self):
web = asab.web.create_web_server(self)
web.add_get('/hello', self.hello)
async def hello(self, request):
return asab.web.rest.json_response(request, data="Hello, world!
")
Source code in asab/web/__init__.py
asab.web.service.WebService
¤
Bases: Service
Service for running and easy manipulation of the web server. It is used for registering and running the web container as well as initialization of web request metrics.
It should be used together with asab.web.WebContainer
object that handles the web configuration.
Examples:
from asab.web import Module
self.add_module(Module)
web_service = self.get_service("asab.WebService")
container = asab.web.WebContainer(
websvc=web_service,
config_section_name='my:web',
config={"listen": "0.0.0.0:8080"}
)
Source code in asab/web/service.py
asab.web.WebContainer
¤
Bases: Configurable
Configurable object that serves as a backend for asab.WebService
.
It contains everything needed for the web server existence, namely all the configuration and the server Application object.
Source code in asab/web/container.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 |
|
WebApp: aiohttp.web.Application = aiohttp.web.Application(client_max_size=client_max_size)
instance-attribute
¤
The Web Application object. See aiohttp documentation for the details.
It is a dict-like object, so you can use it for sharing data globally by storing arbitrary properties for later access from a handler.
Attributes:
Name | Type | Description |
---|---|---|
WebApp["app"] |
Application
|
Reference to the ASAB Application. |
WebApp["rootdir"] |
StaticDirProvider
|
Reference to the root path specified by |
add_preflight_handlers(preflight_paths)
¤
Add handlers with preflight resources.
Preflight requests are sent by the browser, for some cross domain request (custom header etc.).
Browser sends preflight request first.
It is request on the same endpoint as app demanded request, but of OPTIONS method.
Only when satisfactory response is returned, browser proceeds with sending original request.
Use cors_preflight_paths
option to specify all paths and path prefixes (separated by comma) for which you
want to allow OPTIONS method for preflight requests.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preflight_paths
|
list[str]
|
List of routes that will be provided with OPTIONS handler. |
required |
Source code in asab/web/container.py
get_ports()
¤
Return list of available ports.
Returns:
Type | Description |
---|---|
List[str]
|
(list[str]) List of ports. |