1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
|
import asyncio
import sys
import warnings
from argparse import ArgumentParser
from collections import MutableMapping
from importlib import import_module
from yarl import URL
from . import (hdrs, web_exceptions, web_reqrep, web_server, web_urldispatcher,
web_ws)
from .abc import AbstractMatchInfo, AbstractRouter
from .helpers import FrozenList, sentinel
from .log import access_logger, web_logger
from .protocol import HttpVersion # noqa
from .signals import PostSignal, PreSignal, Signal
from .web_exceptions import * # noqa
from .web_reqrep import * # noqa
from .web_server import Server
from .web_urldispatcher import * # noqa
from .web_ws import * # noqa
__all__ = (web_reqrep.__all__ +
web_exceptions.__all__ +
web_urldispatcher.__all__ +
web_ws.__all__ +
web_server.__all__ +
('Application', 'HttpVersion', 'MsgType'))
class Application(MutableMapping):
def __init__(self, *, logger=web_logger, loop=None,
router=None,
middlewares=(), debug=...):
if loop is None:
loop = asyncio.get_event_loop()
if router is None:
router = web_urldispatcher.UrlDispatcher()
assert isinstance(router, AbstractRouter), router
router.post_init(self)
if debug is ...:
debug = loop.get_debug()
self._debug = debug
self._router = router
self._secure_proxy_ssl_header = None
self._loop = loop
self.logger = logger
self._middlewares = FrozenList(middlewares)
self._state = {}
self._frozen = False
self._on_pre_signal = PreSignal()
self._on_post_signal = PostSignal()
self._on_response_prepare = Signal(self)
self._on_startup = Signal(self)
self._on_shutdown = Signal(self)
self._on_cleanup = Signal(self)
# MutableMapping API
def __getitem__(self, key):
return self._state[key]
def _check_frozen(self):
if self._frozen:
warnings.warn("Changing state of started or joined "
"application is deprecated",
DeprecationWarning,
stacklevel=3)
def __setitem__(self, key, value):
self._check_frozen()
self._state[key] = value
def __delitem__(self, key):
self._check_frozen()
del self._state[key]
def __len__(self):
return len(self._state)
def __iter__(self):
return iter(self._state)
########
@property
def frozen(self):
return self._frozen
def freeze(self):
if self._frozen:
return
self._frozen = True
self._router.freeze()
self._middlewares.freeze()
self._on_pre_signal.freeze()
self._on_post_signal.freeze()
self._on_response_prepare.freeze()
self._on_startup.freeze()
self._on_shutdown.freeze()
self._on_cleanup.freeze()
@property
def debug(self):
return self._debug
def _reg_subapp_signals(self, subapp):
def reg_handler(signame):
subsig = getattr(subapp, signame)
@asyncio.coroutine
def handler(app):
yield from subsig.send(subapp)
appsig = getattr(self, signame)
appsig.append(handler)
reg_handler('on_startup')
reg_handler('on_shutdown')
reg_handler('on_cleanup')
@property
def on_response_prepare(self):
return self._on_response_prepare
@property
def on_pre_signal(self):
return self._on_pre_signal
@property
def on_post_signal(self):
return self._on_post_signal
@property
def on_startup(self):
return self._on_startup
@property
def on_shutdown(self):
return self._on_shutdown
@property
def on_cleanup(self):
return self._on_cleanup
@property
def router(self):
return self._router
@property
def loop(self):
return self._loop
@property
def middlewares(self):
return self._middlewares
def make_handler(self, *, secure_proxy_ssl_header=None, **kwargs):
debug = kwargs.pop('debug', sentinel)
if debug is not sentinel:
warnings.warn(
"`debug` parameter is deprecated. "
"Use Application's debug mode instead", DeprecationWarning)
if debug != self.debug:
raise ValueError(
"The value of `debug` parameter conflicts with the debug "
"settings of the `Application` instance. The "
"application's debug mode setting should be used instead "
"as a single point to setup a debug mode. For more "
"information please check "
"http://aiohttp.readthedocs.io/en/stable/"
"web_reference.html#aiohttp.web.Application"
)
self.freeze()
self._secure_proxy_ssl_header = secure_proxy_ssl_header
return Server(self._handle, request_factory=self._make_request,
debug=self.debug, loop=self.loop, **kwargs)
@asyncio.coroutine
def startup(self):
"""Causes on_startup signal
Should be called in the event loop along with the request handler.
"""
yield from self.on_startup.send(self)
@asyncio.coroutine
def shutdown(self):
"""Causes on_shutdown signal
Should be called before cleanup()
"""
yield from self.on_shutdown.send(self)
@asyncio.coroutine
def cleanup(self):
"""Causes on_cleanup signal
Should be called after shutdown()
"""
yield from self.on_cleanup.send(self)
@asyncio.coroutine
def finish(self):
"""Finalize an application.
Deprecated alias for .cleanup()
"""
warnings.warn("Use .cleanup() instead", DeprecationWarning)
yield from self.cleanup()
def register_on_finish(self, func, *args, **kwargs):
warnings.warn("Use .on_cleanup.append() instead", DeprecationWarning)
self.on_cleanup.append(lambda app: func(app, *args, **kwargs))
def _make_request(self, message, payload, protocol,
_cls=web_reqrep.Request):
return _cls(
message, payload,
protocol.transport, protocol.reader, protocol.writer,
protocol.time_service, protocol._request_handler,
secure_proxy_ssl_header=self._secure_proxy_ssl_header)
@asyncio.coroutine
def _handle(self, request):
match_info = yield from self._router.resolve(request)
assert isinstance(match_info, AbstractMatchInfo), match_info
match_info.add_app(self)
match_info.freeze()
resp = None
request._match_info = match_info
expect = request.headers.get(hdrs.EXPECT)
if expect:
resp = (
yield from match_info.expect_handler(request))
if resp is None:
handler = match_info.handler
for app in match_info.apps:
for factory in reversed(app.middlewares):
handler = yield from factory(app, handler)
resp = yield from handler(request)
assert isinstance(resp, web_reqrep.StreamResponse), \
("Handler {!r} should return response instance, "
"got {!r} [middlewares {!r}]").format(
match_info.handler, type(resp),
[middleware for middleware in app.middlewares
for app in match_info.apps])
return resp
def __call__(self):
"""gunicorn compatibility"""
return self
def __repr__(self):
return "<Application 0x{:x}>".format(id(self))
def run_app(app, *, host='0.0.0.0', port=None,
shutdown_timeout=60.0, ssl_context=None,
print=print, backlog=128, access_log_format=None,
access_log=access_logger):
"""Run an app locally"""
if port is None:
if not ssl_context:
port = 8080
else:
port = 8443
loop = app.loop
make_handler_kwargs = dict()
if access_log_format is not None:
make_handler_kwargs['access_log_format'] = access_log_format
handler = app.make_handler(access_log=access_log,
**make_handler_kwargs)
loop.run_until_complete(app.startup())
srv = loop.run_until_complete(loop.create_server(handler, host,
port, ssl=ssl_context,
backlog=backlog))
scheme = 'https' if ssl_context else 'http'
url = URL('{}://localhost'.format(scheme))
url = url.with_host(host).with_port(port)
print("======== Running on {} ========\n"
"(Press CTRL+C to quit)".format(url))
try:
loop.run_forever()
except KeyboardInterrupt: # pragma: no cover
pass
finally:
srv.close()
loop.run_until_complete(srv.wait_closed())
loop.run_until_complete(app.shutdown())
loop.run_until_complete(handler.shutdown(shutdown_timeout))
loop.run_until_complete(app.cleanup())
loop.close()
def main(argv):
arg_parser = ArgumentParser(
description="aiohttp.web Application server",
prog="aiohttp.web"
)
arg_parser.add_argument(
"entry_func",
help=("Callable returning the `aiohttp.web.Application` instance to "
"run. Should be specified in the 'module:function' syntax."),
metavar="entry-func"
)
arg_parser.add_argument(
"-H", "--hostname",
help="TCP/IP hostname to serve on (default: %(default)r)",
default="localhost"
)
arg_parser.add_argument(
"-P", "--port",
help="TCP/IP port to serve on (default: %(default)r)",
type=int,
default="8080"
)
args, extra_argv = arg_parser.parse_known_args(argv)
# Import logic
mod_str, _, func_str = args.entry_func.partition(":")
if not func_str or not mod_str:
arg_parser.error(
"'entry-func' not in 'module:function' syntax"
)
if mod_str.startswith("."):
arg_parser.error("relative module names not supported")
try:
module = import_module(mod_str)
except ImportError as ex:
arg_parser.error("unable to import %s: %s" % (mod_str, ex))
try:
func = getattr(module, func_str)
except AttributeError:
arg_parser.error("module %r has no attribute %r" % (mod_str, func_str))
app = func(extra_argv)
run_app(app, host=args.hostname, port=args.port)
arg_parser.exit(message="Stopped\n")
if __name__ == "__main__": # pragma: no branch
main(sys.argv[1:]) # pragma: no cover
|