| 1 |
import asyncio |
| 2 |
import logging |
| 3 |
import socket |
| 4 |
from abc import ABC, abstractmethod |
| 5 |
from collections.abc import Sized |
| 6 |
from http.cookies import BaseCookie, Morsel |
| 7 |
from typing import ( |
| 8 |
TYPE_CHECKING, |
| 9 |
Any, |
| 10 |
Awaitable, |
| 11 |
Callable, |
| 12 |
Dict, |
| 13 |
Generator, |
| 14 |
Iterable, |
| 15 |
List, |
| 16 |
Optional, |
| 17 |
Tuple, |
| 18 |
TypedDict, |
| 19 |
) |
| 20 |
|
| 21 |
from multidict import CIMultiDict |
| 22 |
from yarl import URL |
| 23 |
|
| 24 |
from .typedefs import LooseCookies |
| 25 |
|
| 26 |
if TYPE_CHECKING: |
| 27 |
from .web_app import Application |
| 28 |
from .web_exceptions import HTTPException |
| 29 |
from .web_request import BaseRequest, Request |
| 30 |
from .web_response import StreamResponse |
| 31 |
else: |
| 32 |
BaseRequest = Request = Application = StreamResponse = None |
| 33 |
HTTPException = None |
| 34 |
|
| 35 |
|
| 36 |
class AbstractRouter(ABC): |
| 37 |
def __init__(self) -> None: |
| 38 |
self._frozen = False |
| 39 |
|
| 40 |
def post_init(self, app: Application) -> None: |
| 41 |
"""Post init stage. |
| 42 |
|
| 43 |
Not an abstract method for sake of backward compatibility, |
| 44 |
but if the router wants to be aware of the application |
| 45 |
it can override this. |
| 46 |
""" |
| 47 |
|
| 48 |
@property |
| 49 |
def frozen(self) -> bool: |
| 50 |
return self._frozen |
| 51 |
|
| 52 |
def freeze(self) -> None: |
| 53 |
"""Freeze router.""" |
| 54 |
self._frozen = True |
| 55 |
|
| 56 |
@abstractmethod |
| 57 |
async def resolve(self, request: Request) -> "AbstractMatchInfo": |
| 58 |
"""Return MATCH_INFO for given request""" |
| 59 |
|
| 60 |
|
| 61 |
class AbstractMatchInfo(ABC): |
| 62 |
@property # pragma: no branch |
| 63 |
@abstractmethod |
| 64 |
def handler(self) -> Callable[[Request], Awaitable[StreamResponse]]: |
| 65 |
"""Execute matched request handler""" |
| 66 |
|
| 67 |
@property |
| 68 |
@abstractmethod |
| 69 |
def expect_handler( |
| 70 |
self, |
| 71 |
) -> Callable[[Request], Awaitable[Optional[StreamResponse]]]: |
| 72 |
"""Expect handler for 100-continue processing""" |
| 73 |
|
| 74 |
@property # pragma: no branch |
| 75 |
@abstractmethod |
| 76 |
def http_exception(self) -> Optional[HTTPException]: |
| 77 |
"""HTTPException instance raised on router's resolving, or None""" |
| 78 |
|
| 79 |
@abstractmethod # pragma: no branch |
| 80 |
def get_info(self) -> Dict[str, Any]: |
| 81 |
"""Return a dict with additional info useful for introspection""" |
| 82 |
|
| 83 |
@property # pragma: no branch |
| 84 |
@abstractmethod |
| 85 |
def apps(self) -> Tuple[Application, ...]: |
| 86 |
"""Stack of nested applications. |
| 87 |
|
| 88 |
Top level application is left-most element. |
| 89 |
|
| 90 |
""" |
| 91 |
|
| 92 |
@abstractmethod |
| 93 |
def add_app(self, app: Application) -> None: |
| 94 |
"""Add application to the nested apps stack.""" |
| 95 |
|
| 96 |
@abstractmethod |
| 97 |
def freeze(self) -> None: |
| 98 |
"""Freeze the match info. |
| 99 |
|
| 100 |
The method is called after route resolution. |
| 101 |
|
| 102 |
After the call .add_app() is forbidden. |
| 103 |
|
| 104 |
""" |
| 105 |
|
| 106 |
|
| 107 |
class AbstractView(ABC): |
| 108 |
"""Abstract class based view.""" |
| 109 |
|
| 110 |
def __init__(self, request: Request) -> None: |
| 111 |
self._request = request |
| 112 |
|
| 113 |
@property |
| 114 |
def request(self) -> Request: |
| 115 |
"""Request instance.""" |
| 116 |
return self._request |
| 117 |
|
| 118 |
@abstractmethod |
| 119 |
def __await__(self) -> Generator[Any, None, StreamResponse]: |
| 120 |
"""Execute the view handler.""" |
| 121 |
|
| 122 |
|
| 123 |
class ResolveResult(TypedDict): |
| 124 |
"""Resolve result. |
| 125 |
|
| 126 |
This is the result returned from an AbstractResolver's |
| 127 |
resolve method. |
| 128 |
|
| 129 |
:param hostname: The hostname that was provided. |
| 130 |
:param host: The IP address that was resolved. |
| 131 |
:param port: The port that was resolved. |
| 132 |
:param family: The address family that was resolved. |
| 133 |
:param proto: The protocol that was resolved. |
| 134 |
:param flags: The flags that were resolved. |
| 135 |
""" |
| 136 |
|
| 137 |
hostname: str |
| 138 |
host: str |
| 139 |
port: int |
| 140 |
family: int |
| 141 |
proto: int |
| 142 |
flags: int |
| 143 |
|
| 144 |
|
| 145 |
class AbstractResolver(ABC): |
| 146 |
"""Abstract DNS resolver.""" |
| 147 |
|
| 148 |
@abstractmethod |
| 149 |
async def resolve( |
| 150 |
self, host: str, port: int = 0, family: socket.AddressFamily = socket.AF_INET |
| 151 |
) -> List[ResolveResult]: |
| 152 |
"""Return IP address for given hostname""" |
| 153 |
|
| 154 |
@abstractmethod |
| 155 |
async def close(self) -> None: |
| 156 |
"""Release resolver""" |
| 157 |
|
| 158 |
|
| 159 |
if TYPE_CHECKING: |
| 160 |
IterableBase = Iterable[Morsel[str]] |
| 161 |
else: |
| 162 |
IterableBase = Iterable |
| 163 |
|
| 164 |
|
| 165 |
ClearCookiePredicate = Callable[["Morsel[str]"], bool] |
| 166 |
|
| 167 |
|
| 168 |
class AbstractCookieJar(Sized, IterableBase): |
| 169 |
"""Abstract Cookie Jar.""" |
| 170 |
|
| 171 |
def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: |
| 172 |
self._loop = loop or asyncio.get_running_loop() |
| 173 |
|
| 174 |
@abstractmethod |
| 175 |
def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None: |
| 176 |
"""Clear all cookies if no predicate is passed.""" |
| 177 |
|
| 178 |
@abstractmethod |
| 179 |
def clear_domain(self, domain: str) -> None: |
| 180 |
"""Clear all cookies for domain and all subdomains.""" |
| 181 |
|
| 182 |
@abstractmethod |
| 183 |
def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None: |
| 184 |
"""Update cookies.""" |
| 185 |
|
| 186 |
@abstractmethod |
| 187 |
def filter_cookies(self, request_url: URL) -> "BaseCookie[str]": |
| 188 |
"""Return the jar's cookies filtered by their attributes.""" |
| 189 |
|
| 190 |
|
| 191 |
class AbstractStreamWriter(ABC): |
| 192 |
"""Abstract stream writer.""" |
| 193 |
|
| 194 |
buffer_size = 0 |
| 195 |
output_size = 0 |
| 196 |
length: Optional[int] = 0 |
| 197 |
|
| 198 |
@abstractmethod |
| 199 |
async def write(self, chunk: bytes) -> None: |
| 200 |
"""Write chunk into stream.""" |
| 201 |
|
| 202 |
@abstractmethod |
| 203 |
async def write_eof(self, chunk: bytes = b"") -> None: |
| 204 |
"""Write last chunk.""" |
| 205 |
|
| 206 |
@abstractmethod |
| 207 |
async def drain(self) -> None: |
| 208 |
"""Flush the write buffer.""" |
| 209 |
|
| 210 |
@abstractmethod |
| 211 |
def enable_compression(self, encoding: str = "deflate") -> None: |
| 212 |
"""Enable HTTP body compression""" |
| 213 |
|
| 214 |
@abstractmethod |
| 215 |
def enable_chunking(self) -> None: |
| 216 |
"""Enable HTTP chunked mode""" |
| 217 |
|
| 218 |
@abstractmethod |
| 219 |
async def write_headers( |
| 220 |
self, status_line: str, headers: "CIMultiDict[str]" |
| 221 |
) -> None: |
| 222 |
"""Write HTTP headers""" |
| 223 |
|
| 224 |
|
| 225 |
class AbstractAccessLogger(ABC): |
| 226 |
"""Abstract writer to access log.""" |
| 227 |
|
| 228 |
def __init__(self, logger: logging.Logger, log_format: str) -> None: |
| 229 |
self.logger = logger |
| 230 |
self.log_format = log_format |
| 231 |
|
| 232 |
@abstractmethod |
| 233 |
def log(self, request: BaseRequest, response: StreamResponse, time: float) -> None: |
| 234 |
"""Emit log to logger.""" |