Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _is_domain_match(domain: str, hostname: str) -> bool:
if hostname == domain:
return True
if not hostname.endswith(domain):
return False
non_matching = hostname[:-len(domain)]
if not non_matching.endswith... | [
"Implements domain matching adhering to RFC 6265."
] |
Please provide a description of the function:def _is_path_match(req_path: str, cookie_path: str) -> bool:
if not req_path.startswith("/"):
req_path = "/"
if req_path == cookie_path:
return True
if not req_path.startswith(cookie_path):
return False
... | [
"Implements path matching adhering to RFC 6265."
] |
Please provide a description of the function:def _parse_date(cls, date_str: str) -> Optional[datetime.datetime]:
if not date_str:
return None
found_time = False
found_day = False
found_month = False
found_year = False
hour = minute = second = 0
... | [
"Implements date string parsing adhering to RFC 6265."
] |
Please provide a description of the function:def my_protocol_parser(out, buf):
while True:
tp = yield from buf.read(5)
if tp in (MSG_PING, MSG_PONG):
# skip line
yield from buf.skipuntil(b'\r\n')
out.feed_data(Message(tp, None))
elif tp == MSG_STOP:
... | [
"Parser is used with StreamParser for incremental protocol parsing.\n Parser is a generator function, but it is not a coroutine. Usually\n parsers are implemented as a state machine.\n\n more details in asyncio/parsers.py\n existing parsers:\n * HTTP protocol parsers asyncio/http/protocol.py\n ... |
Please provide a description of the function:def set_content_disposition(self,
disptype: str,
quote_fields: bool=True,
**params: Any) -> None:
self._headers[hdrs.CONTENT_DISPOSITION] = content_disposition_he... | [
"Sets ``Content-Disposition`` header."
] |
Please provide a description of the function:def clone(self, *, method: str=sentinel, rel_url: StrOrURL=sentinel,
headers: LooseHeaders=sentinel, scheme: str=sentinel,
host: str=sentinel,
remote: str=sentinel) -> 'BaseRequest':
if self._read_bytes:
... | [
"Clone itself with replacement some attributes.\n\n Creates and returns a new instance of Request object. If no parameters\n are given, an exact copy is returned. If a parameter is not passed, it\n will reuse the one from the current request object.\n\n "
] |
Please provide a description of the function:def forwarded(self) -> Tuple[Mapping[str, str], ...]:
elems = []
for field_value in self._message.headers.getall(hdrs.FORWARDED, ()):
length = len(field_value)
pos = 0
need_separator = False
elem = {} ... | [
"A tuple containing all parsed Forwarded header(s).\n\n Makes an effort to parse Forwarded headers as specified by RFC 7239:\n\n - It adds one (immutable) dictionary per Forwarded 'field-value', ie\n per proxy. The element corresponds to the data in the Forwarded\n field-value added ... |
Please provide a description of the function:def host(self) -> str:
host = self._message.headers.get(hdrs.HOST)
if host is not None:
return host
else:
return socket.getfqdn() | [
"Hostname of the request.\n\n Hostname is resolved in this order:\n\n - overridden value by .clone(host=new_host) call.\n - HOST HTTP header\n - socket.getfqdn() value\n "
] |
Please provide a description of the function:def remote(self) -> Optional[str]:
if isinstance(self._transport_peername, (list, tuple)):
return self._transport_peername[0]
else:
return self._transport_peername | [
"Remote IP of client initiated HTTP request.\n\n The IP is resolved in this order:\n\n - overridden value by .clone(remote=new_remote) call.\n - peername of opened socket\n "
] |
Please provide a description of the function:def _http_date(_date_str: str) -> Optional[datetime.datetime]:
if _date_str is not None:
timetuple = parsedate(_date_str)
if timetuple is not None:
return datetime.datetime(*timetuple[:6],
... | [
"Process a date string, return a datetime object\n "
] |
Please provide a description of the function:def if_modified_since(self) -> Optional[datetime.datetime]:
return self._http_date(self.headers.get(hdrs.IF_MODIFIED_SINCE)) | [
"The value of If-Modified-Since HTTP header, or None.\n\n This header is represented as a `datetime` object.\n "
] |
Please provide a description of the function:def if_unmodified_since(self) -> Optional[datetime.datetime]:
return self._http_date(self.headers.get(hdrs.IF_UNMODIFIED_SINCE)) | [
"The value of If-Unmodified-Since HTTP header, or None.\n\n This header is represented as a `datetime` object.\n "
] |
Please provide a description of the function:def if_range(self) -> Optional[datetime.datetime]:
return self._http_date(self.headers.get(hdrs.IF_RANGE)) | [
"The value of If-Range HTTP header, or None.\n\n This header is represented as a `datetime` object.\n "
] |
Please provide a description of the function:def cookies(self) -> Mapping[str, str]:
raw = self.headers.get(hdrs.COOKIE, '')
parsed = SimpleCookie(raw)
return MappingProxyType(
{key: val.value for key, val in parsed.items()}) | [
"Return request cookies.\n\n A read-only dictionary-like object.\n "
] |
Please provide a description of the function:def http_range(self) -> slice:
rng = self._headers.get(hdrs.RANGE)
start, end = None, None
if rng is not None:
try:
pattern = r'^bytes=(\d*)-(\d*)$'
start, end = re.findall(pattern, rng)[0]
... | [
"The content of Range HTTP header.\n\n Return a slice instance.\n\n "
] |
Please provide a description of the function:def has_body(self) -> bool:
warnings.warn(
"Deprecated, use .can_read_body #2005",
DeprecationWarning, stacklevel=2)
return not self._payload.at_eof() | [
"Return True if request's HTTP BODY can be read, False otherwise."
] |
Please provide a description of the function:async def read(self) -> bytes:
if self._read_bytes is None:
body = bytearray()
while True:
chunk = await self._payload.readany()
body.extend(chunk)
if self._client_max_size:
... | [
"Read request body if present.\n\n Returns bytes object with full request content.\n "
] |
Please provide a description of the function:async def text(self) -> str:
bytes_body = await self.read()
encoding = self.charset or 'utf-8'
return bytes_body.decode(encoding) | [
"Return BODY as text using encoding from .charset."
] |
Please provide a description of the function:async def json(self, *, loads: JSONDecoder=DEFAULT_JSON_DECODER) -> Any:
body = await self.text()
return loads(body) | [
"Return BODY as JSON."
] |
Please provide a description of the function:async def post(self) -> 'MultiDictProxy[Union[str, bytes, FileField]]':
if self._post is not None:
return self._post
if self._method not in self.POST_METHODS:
self._post = MultiDictProxy(MultiDict())
return self._p... | [
"Return POST parameters."
] |
Please provide a description of the function:async def shutdown(self, timeout: Optional[float]=15.0) -> None:
self._force_close = True
if self._keepalive_handle is not None:
self._keepalive_handle.cancel()
if self._waiter:
self._waiter.cancel()
# wait ... | [
"Worker process is about to exit, we need cleanup everything and\n stop accepting requests. It is especially important for keep-alive\n connections."
] |
Please provide a description of the function:def keep_alive(self, val: bool) -> None:
self._keepalive = val
if self._keepalive_handle:
self._keepalive_handle.cancel()
self._keepalive_handle = None | [
"Set keep-alive connection mode.\n\n :param bool val: new state.\n "
] |
Please provide a description of the function:def close(self) -> None:
self._close = True
if self._waiter:
self._waiter.cancel() | [
"Stop accepting new pipelinig messages and close\n connection when handlers done processing messages"
] |
Please provide a description of the function:def force_close(self) -> None:
self._force_close = True
if self._waiter:
self._waiter.cancel()
if self.transport is not None:
self.transport.close()
self.transport = None | [
"Force close connection"
] |
Please provide a description of the function:async def start(self) -> None:
loop = self._loop
handler = self._task_handler
assert handler is not None
manager = self._manager
assert manager is not None
keepalive_timeout = self._keepalive_timeout
resp = Non... | [
"Process incoming request.\n\n It reads request line, request headers and request payload, then\n calls handle_request() method. Subclass has to override\n handle_request(). start() handles various exceptions in request\n or response handling. Connection is being closed always unless\n ... |
Please provide a description of the function:def handle_error(self,
request: BaseRequest,
status: int=500,
exc: Optional[BaseException]=None,
message: Optional[str]=None) -> StreamResponse:
self.log_exception("Error han... | [
"Handle errors.\n\n Returns HTTP response with specific status code. Logs additional\n information. It always closes current connection."
] |
Please provide a description of the function:def run_app(app: Union[Application, Awaitable[Application]], *,
host: Optional[str]=None,
port: Optional[int]=None,
path: Optional[str]=None,
sock: Optional[socket.socket]=None,
shutdown_timeout: float=60.0,
... | [
"Run an app locally"
] |
Please provide a description of the function:def iter_chunked(self, n: int) -> AsyncStreamIterator[bytes]:
return AsyncStreamIterator(lambda: self.read(n)) | [
"Returns an asynchronous iterator that yields chunks of size n.\n\n Python-3.5 available for Python 3.5+ only\n "
] |
Please provide a description of the function:def unread_data(self, data: bytes) -> None:
warnings.warn("unread_data() is deprecated "
"and will be removed in future releases (#3260)",
DeprecationWarning,
stacklevel=2)
if not data... | [
" rollback reading some data from stream, inserting it to buffer head.\n "
] |
Please provide a description of the function:async def readchunk(self) -> Tuple[bytes, bool]:
while True:
if self._exception is not None:
raise self._exception
while self._http_chunk_splits:
pos = self._http_chunk_splits.pop(0)
if... | [
"Returns a tuple of (data, end_of_http_chunk). When chunked transfer\n encoding is used, end_of_http_chunk is a boolean indicating if the end\n of the data corresponds to the end of a HTTP chunk , otherwise it is\n always False.\n "
] |
Please provide a description of the function:def _read_nowait(self, n: int) -> bytes:
chunks = []
while self._buffer:
chunk = self._read_nowait_chunk(n)
chunks.append(chunk)
if n != -1:
n -= len(chunk)
if n == 0:
... | [
" Read not more than n bytes, or whole buffer is n == -1 "
] |
Please provide a description of the function:async def send(self, *args, **kwargs):
if not self.frozen:
raise RuntimeError("Cannot send non-frozen signal.")
for receiver in self:
await receiver(*args, **kwargs) | [
"\n Sends data to all registered receivers.\n "
] |
Please provide a description of the function:def compile_format(self, log_format: str) -> Tuple[str, List[KeyMethod]]:
# list of (key, method) tuples, we don't use an OrderedDict as users
# can repeat the same key more than once
methods = list()
for atom in self.FORMAT_RE.finda... | [
"Translate log_format into form usable by modulo formatting\n\n All known atoms will be replaced with %s\n Also methods for formatting of those atoms will be added to\n _methods in appropriate order\n\n For example we have log_format = \"%a %t\"\n This format will be translated to... |
Please provide a description of the function:def normalize_path_middleware(
*, append_slash: bool=True, remove_slash: bool=False,
merge_slashes: bool=True,
redirect_class: Type[HTTPMove]=HTTPMovedPermanently) -> _Middleware:
correct_configuration = not (append_slash and remove_slash)
... | [
"\n Middleware factory which produces a middleware that normalizes\n the path of a request. By normalizing it means:\n\n - Add or remove a trailing slash to the path.\n - Double slashes are replaced by one.\n\n The middleware returns as soon as it finds a path that resolves\n correctly. Th... |
Please provide a description of the function:def _gen_form_data(self) -> multipart.MultipartWriter:
for dispparams, headers, value in self._fields:
try:
if hdrs.CONTENT_TYPE in headers:
part = payload.get_payload(
value, content_ty... | [
"Encode a list of fields using the multipart/form-data MIME format"
] |
Please provide a description of the function:async def write(self, chunk: bytes,
*, drain: bool=True, LIMIT: int=0x10000) -> None:
if self._on_chunk_sent is not None:
await self._on_chunk_sent(chunk)
if self._compress is not None:
chunk = self._compr... | [
"Writes chunk of data to a stream.\n\n write_eof() indicates end of stream.\n writer can't be used after write_eof() method being called.\n write() return drain future.\n "
] |
Please provide a description of the function:async def write_headers(self, status_line: str,
headers: 'CIMultiDict[str]') -> None:
# status + headers
buf = _serialize_headers(status_line, headers)
self._write(buf) | [
"Write request/response status and headers."
] |
Please provide a description of the function:def netrc_from_env() -> Optional[netrc.netrc]:
netrc_env = os.environ.get('NETRC')
if netrc_env is not None:
netrc_path = Path(netrc_env)
else:
try:
home_dir = Path.home()
except RuntimeError as e: # pragma: no cover
... | [
"Attempt to load the netrc file from the path specified by the env-var\n NETRC or in the default location in the user's home directory.\n\n Returns None if it couldn't be found or fails to parse.\n "
] |
Please provide a description of the function:def parse_mimetype(mimetype: str) -> MimeType:
if not mimetype:
return MimeType(type='', subtype='', suffix='',
parameters=MultiDictProxy(MultiDict()))
parts = mimetype.split(';')
params = MultiDict() # type: MultiDict[str]
... | [
"Parses a MIME type into its components.\n\n mimetype is a MIME type string.\n\n Returns a MimeType object.\n\n Example:\n\n >>> parse_mimetype('text/html; charset=utf-8')\n MimeType(type='text', subtype='html', suffix='',\n parameters={'charset': 'utf-8'})\n\n "
] |
Please provide a description of the function:def content_disposition_header(disptype: str,
quote_fields: bool=True,
**params: str) -> str:
if not disptype or not (TOKEN > set(disptype)):
raise ValueError('bad content disposition type {!r}'
... | [
"Sets ``Content-Disposition`` header.\n\n disptype is a disposition type: inline, attachment, form-data.\n Should be valid extension token (see RFC 2183)\n\n params is a dict with disposition params.\n "
] |
Please provide a description of the function:def decode(cls, auth_header: str, encoding: str='latin1') -> 'BasicAuth':
try:
auth_type, encoded_credentials = auth_header.split(' ', 1)
except ValueError:
raise ValueError('Could not parse authorization header.')
if... | [
"Create a BasicAuth object from an Authorization HTTP header."
] |
Please provide a description of the function:def from_url(cls, url: URL,
*, encoding: str='latin1') -> Optional['BasicAuth']:
if not isinstance(url, URL):
raise TypeError("url should be yarl.URL instance")
if url.user is None:
return None
return ... | [
"Create BasicAuth from url."
] |
Please provide a description of the function:def encode(self) -> str:
creds = ('%s:%s' % (self.login, self.password)).encode(self.encoding)
return 'Basic %s' % base64.b64encode(creds).decode(self.encoding) | [
"Encode credentials."
] |
Please provide a description of the function:def content_type(self) -> str:
raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore
if self._stored_content_type != raw:
self._parse_content_type(raw)
return self._content_type | [
"The value of content part for Content-Type HTTP header."
] |
Please provide a description of the function:def charset(self) -> Optional[str]:
raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore
if self._stored_content_type != raw:
self._parse_content_type(raw)
return self._content_dict.get('charset') | [
"The value of charset part for Content-Type HTTP header."
] |
Please provide a description of the function:def content_length(self) -> Optional[int]:
content_length = self._headers.get(hdrs.CONTENT_LENGTH) # type: ignore
if content_length is not None:
return int(content_length)
else:
return None | [
"The value of Content-Length HTTP header."
] |
Please provide a description of the function:def request(
method: str,
url: StrOrURL, *,
params: Optional[Mapping[str, str]]=None,
data: Any=None,
json: Any=None,
headers: LooseHeaders=None,
skip_auto_headers: Optional[Iterable[str]]=None,
auth: Optional[B... | [
"Constructs and sends a request. Returns response object.\n method - HTTP method\n url - request url\n params - (optional) Dictionary or bytes to be sent in the query\n string of the new request\n data - (optional) Dictionary, bytes, or file-like object to\n send in the body of the request\n ... |
Please provide a description of the function:def request(self,
method: str,
url: StrOrURL,
**kwargs: Any) -> '_RequestContextManager':
return _RequestContextManager(self._request(method, url, **kwargs)) | [
"Perform HTTP request."
] |
Please provide a description of the function:def ws_connect(
self,
url: StrOrURL, *,
method: str=hdrs.METH_GET,
protocols: Iterable[str]=(),
timeout: float=10.0,
receive_timeout: Optional[float]=None,
autoclose: bool=True,
a... | [
"Initiate websocket connection."
] |
Please provide a description of the function:def _prepare_headers(
self,
headers: Optional[LooseHeaders]) -> 'CIMultiDict[str]':
# Convert headers to MultiDict
result = CIMultiDict(self._default_headers)
if headers:
if not isinstance(headers, (MultiDi... | [
" Add default headers and transform it to CIMultiDict\n "
] |
Please provide a description of the function:def get(self, url: StrOrURL, *, allow_redirects: bool=True,
**kwargs: Any) -> '_RequestContextManager':
return _RequestContextManager(
self._request(hdrs.METH_GET, url,
allow_redirects=allow_redirects,
... | [
"Perform HTTP GET request."
] |
Please provide a description of the function:def options(self, url: StrOrURL, *, allow_redirects: bool=True,
**kwargs: Any) -> '_RequestContextManager':
return _RequestContextManager(
self._request(hdrs.METH_OPTIONS, url,
allow_redirects=allow_redir... | [
"Perform HTTP OPTIONS request."
] |
Please provide a description of the function:def head(self, url: StrOrURL, *, allow_redirects: bool=False,
**kwargs: Any) -> '_RequestContextManager':
return _RequestContextManager(
self._request(hdrs.METH_HEAD, url,
allow_redirects=allow_redirects,
... | [
"Perform HTTP HEAD request."
] |
Please provide a description of the function:def post(self, url: StrOrURL,
*, data: Any=None, **kwargs: Any) -> '_RequestContextManager':
return _RequestContextManager(
self._request(hdrs.METH_POST, url,
data=data,
**kwargs)) | [
"Perform HTTP POST request."
] |
Please provide a description of the function:def put(self, url: StrOrURL,
*, data: Any=None, **kwargs: Any) -> '_RequestContextManager':
return _RequestContextManager(
self._request(hdrs.METH_PUT, url,
data=data,
**kwargs)) | [
"Perform HTTP PUT request."
] |
Please provide a description of the function:def patch(self, url: StrOrURL,
*, data: Any=None, **kwargs: Any) -> '_RequestContextManager':
return _RequestContextManager(
self._request(hdrs.METH_PATCH, url,
data=data,
**kwargs... | [
"Perform HTTP PATCH request."
] |
Please provide a description of the function:def delete(self, url: StrOrURL, **kwargs: Any) -> '_RequestContextManager':
return _RequestContextManager(
self._request(hdrs.METH_DELETE, url,
**kwargs)) | [
"Perform HTTP DELETE request."
] |
Please provide a description of the function:async def close(self) -> None:
if not self.closed:
if self._connector is not None and self._connector_owner:
await self._connector.close()
self._connector = None | [
"Close underlying connector.\n\n Release all acquired resources.\n "
] |
Please provide a description of the function:def requote_redirect_url(self, val: bool) -> None:
warnings.warn("session.requote_redirect_url modification "
"is deprecated #2778",
DeprecationWarning,
stacklevel=2)
self._requote_red... | [
"Do URL requoting on redirection handling."
] |
Please provide a description of the function:async def resolve(self, host: str,
port: int, family: int) -> List[Dict[str, Any]]:
| [
"Return IP address for given hostname"
] |
Please provide a description of the function:async def next(self) -> Any:
item = await self.stream.next()
if self.stream.at_eof():
await self.release()
return item | [
"Emits next multipart reader object."
] |
Please provide a description of the function:async def read(self, *, decode: bool=False) -> Any:
if self._at_eof:
return b''
data = bytearray()
while not self._at_eof:
data.extend((await self.read_chunk(self.chunk_size)))
if decode:
return sel... | [
"Reads body part data.\n\n decode: Decodes data following by encoding\n method from Content-Encoding header. If it missed\n data remains untouched\n "
] |
Please provide a description of the function:async def read_chunk(self, size: int=chunk_size) -> bytes:
if self._at_eof:
return b''
if self._length:
chunk = await self._read_chunk_from_length(size)
else:
chunk = await self._read_chunk_from_stream(size... | [
"Reads body part content chunk of the specified size.\n\n size: chunk size\n "
] |
Please provide a description of the function:async def readline(self) -> bytes:
if self._at_eof:
return b''
if self._unread:
line = self._unread.popleft()
else:
line = await self._content.readline()
if line.startswith(self._boundary):
... | [
"Reads body part by line by line."
] |
Please provide a description of the function:async def release(self) -> None:
if self._at_eof:
return
while not self._at_eof:
await self.read_chunk(self.chunk_size) | [
"Like read(), but reads all the data to the void."
] |
Please provide a description of the function:async def text(self, *, encoding: Optional[str]=None) -> str:
data = await self.read(decode=True)
# see https://www.w3.org/TR/html5/forms.html#multipart/form-data-encoding-algorithm # NOQA
# and https://dvcs.w3.org/hg/xhr/raw-file/tip/Overvie... | [
"Like read(), but assumes that body part contains text data."
] |
Please provide a description of the function:async def json(self, *, encoding: Optional[str]=None) -> Any:
data = await self.read(decode=True)
if not data:
return None
encoding = encoding or self.get_charset(default='utf-8')
return json.loads(data.decode(encoding)) | [
"Like read(), but assumes that body parts contains JSON data."
] |
Please provide a description of the function:async def form(self, *,
encoding: Optional[str]=None) -> List[Tuple[str, str]]:
data = await self.read(decode=True)
if not data:
return []
if encoding is not None:
real_encoding = encoding
el... | [
"Like read(), but assumes that body parts contains form\n urlencoded data.\n "
] |
Please provide a description of the function:def decode(self, data: bytes) -> bytes:
if CONTENT_TRANSFER_ENCODING in self.headers:
data = self._decode_content_transfer(data)
if CONTENT_ENCODING in self.headers:
return self._decode_content(data)
return data | [
"Decodes data according the specified Content-Encoding\n or Content-Transfer-Encoding headers value.\n "
] |
Please provide a description of the function:def get_charset(self, default: str) -> str:
ctype = self.headers.get(CONTENT_TYPE, '')
mimetype = parse_mimetype(ctype)
return mimetype.parameters.get('charset', default) | [
"Returns charset parameter from Content-Type header or default."
] |
Please provide a description of the function:def name(self) -> Optional[str]:
_, params = parse_content_disposition(
self.headers.get(CONTENT_DISPOSITION))
return content_disposition_filename(params, 'name') | [
"Returns name specified in Content-Disposition header or None\n if missed or header is malformed.\n "
] |
Please provide a description of the function:def from_response(cls, response: 'ClientResponse') -> Any:
obj = cls.response_wrapper_cls(response, cls(response.headers,
response.content))
return obj | [
"Constructs reader instance from HTTP response.\n\n :param response: :class:`~aiohttp.client.ClientResponse` instance\n "
] |
Please provide a description of the function:async def next(self) -> Any:
# So, if we're at BOF, we need to skip till the boundary.
if self._at_eof:
return
await self._maybe_release_last_part()
if self._at_bof:
await self._read_until_first_boundary()
... | [
"Emits the next multipart body part."
] |
Please provide a description of the function:async def release(self) -> None:
while not self._at_eof:
item = await self.next()
if item is None:
break
await item.release() | [
"Reads all the body parts to the void till the final boundary."
] |
Please provide a description of the function:def _get_part_reader(self, headers: 'CIMultiDictProxy[str]') -> Any:
ctype = headers.get(CONTENT_TYPE, '')
mimetype = parse_mimetype(ctype)
if mimetype.type == 'multipart':
if self.multipart_reader_cls is None:
re... | [
"Dispatches the response by the `Content-Type` header, returning\n suitable reader instance.\n\n :param dict headers: Response headers\n "
] |
Please provide a description of the function:async def _maybe_release_last_part(self) -> None:
if self._last_part is not None:
if not self._last_part.at_eof():
await self._last_part.release()
self._unread.extend(self._last_part._unread)
self._last_par... | [
"Ensures that the last read body part is read completely."
] |
Please provide a description of the function:def _boundary_value(self) -> str:
# Refer to RFCs 7231, 7230, 5234.
#
# parameter = token "=" ( token / quoted-string )
# token = 1*tchar
# quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
# qdtex... | [
"Wrap boundary parameter value in quotes, if necessary.\n\n Reads self.boundary and returns a unicode sting.\n "
] |
Please provide a description of the function:def append_payload(self, payload: Payload) -> Payload:
# compression
encoding = payload.headers.get(CONTENT_ENCODING, '').lower() # type: Optional[str] # noqa
if encoding and encoding not in ('deflate', 'gzip', 'identity'):
rais... | [
"Adds a new body part to multipart writer."
] |
Please provide a description of the function:def append_json(
self,
obj: Any,
headers: Optional['MultiMapping[str]']=None
) -> Payload:
if headers is None:
headers = CIMultiDict()
return self.append_payload(JsonPayload(obj, headers=headers)) | [
"Helper to append JSON part."
] |
Please provide a description of the function:def append_form(
self,
obj: Union[Sequence[Tuple[str, str]],
Mapping[str, str]],
headers: Optional['MultiMapping[str]']=None
) -> Payload:
assert isinstance(obj, (Sequence, Mapping))
if ... | [
"Helper to append form urlencoded part."
] |
Please provide a description of the function:def size(self) -> Optional[int]:
if not self._parts:
return 0
total = 0
for part, encoding, te_encoding in self._parts:
if encoding or te_encoding or part.size is None:
return None
total +... | [
"Size of the payload."
] |
Please provide a description of the function:async def write(self, writer: Any,
close_boundary: bool=True) -> None:
if not self._parts:
return
for part, encoding, te_encoding in self._parts:
await writer.write(b'--' + self._boundary + b'\r\n')
... | [
"Write body."
] |
Please provide a description of the function:def update_host(self, url: URL) -> None:
# get host/port
if not url.host:
raise InvalidURL(url)
# basic auth info
username, password = url.user, url.password
if username:
self.auth = helpers.BasicAuth(... | [
"Update destination host, port and connection type (ssl)."
] |
Please provide a description of the function:def update_version(self, version: Union[http.HttpVersion, str]) -> None:
if isinstance(version, str):
v = [l.strip() for l in version.split('.', 1)]
try:
version = http.HttpVersion(int(v[0]), int(v[1]))
exc... | [
"Convert request version to two elements tuple.\n\n parser HTTP version '1.1' => (1, 1)\n "
] |
Please provide a description of the function:def update_headers(self, headers: Optional[LooseHeaders]) -> None:
self.headers = CIMultiDict() # type: CIMultiDict[str]
# add host
netloc = cast(str, self.url.raw_host)
if helpers.is_ipv6_address(netloc):
netloc = '[{}]... | [
"Update request headers."
] |
Please provide a description of the function:def update_cookies(self, cookies: Optional[LooseCookies]) -> None:
if not cookies:
return
c = SimpleCookie()
if hdrs.COOKIE in self.headers:
c.load(self.headers.get(hdrs.COOKIE, ''))
del self.headers[hdrs.... | [
"Update request cookies header."
] |
Please provide a description of the function:def update_content_encoding(self, data: Any) -> None:
if not data:
return
enc = self.headers.get(hdrs.CONTENT_ENCODING, '').lower()
if enc:
if self.compress:
raise ValueError(
'comp... | [
"Set request content encoding."
] |
Please provide a description of the function:def update_transfer_encoding(self) -> None:
te = self.headers.get(hdrs.TRANSFER_ENCODING, '').lower()
if 'chunked' in te:
if self.chunked:
raise ValueError(
'chunked can not be set '
... | [
"Analyze transfer-encoding header."
] |
Please provide a description of the function:def update_auth(self, auth: Optional[BasicAuth]) -> None:
if auth is None:
auth = self.auth
if auth is None:
return
if not isinstance(auth, helpers.BasicAuth):
raise TypeError('BasicAuth() tuple is require... | [
"Set basic auth."
] |
Please provide a description of the function:async def write_bytes(self, writer: AbstractStreamWriter,
conn: 'Connection') -> None:
# 100 response
if self._continue is not None:
await writer.drain()
await self._continue
protocol = conn.... | [
"Support coroutines that yields bytes objects."
] |
Please provide a description of the function:async def start(self, connection: 'Connection') -> 'ClientResponse':
self._closed = False
self._protocol = connection.protocol
self._connection = connection
with self._timer:
while True:
# read response
... | [
"Start response processing."
] |
Please provide a description of the function:async def read(self) -> bytes:
if self._body is None:
try:
self._body = await self.content.read()
for trace in self._traces:
await trace.send_response_chunk_received(self._body)
exce... | [
"Read response payload."
] |
Please provide a description of the function:async def text(self,
encoding: Optional[str]=None, errors: str='strict') -> str:
if self._body is None:
await self.read()
if encoding is None:
encoding = self.get_encoding()
return self._body.decod... | [
"Read response payload and decode."
] |
Please provide a description of the function:async def json(self, *, encoding: str=None,
loads: JSONDecoder=DEFAULT_JSON_DECODER,
content_type: Optional[str]='application/json') -> Any:
if self._body is None:
await self.read()
if content_type:
... | [
"Read and decodes JSON response."
] |
Please provide a description of the function:def enable_chunked_encoding(self, chunk_size: Optional[int]=None) -> None:
self._chunked = True
if hdrs.CONTENT_LENGTH in self._headers:
raise RuntimeError("You can't enable chunked encoding when "
"a conte... | [
"Enables automatic chunked transfer encoding."
] |
Please provide a description of the function:def enable_compression(self,
force: Optional[Union[bool, ContentCoding]]=None
) -> None:
# Backwards compatibility for when force was a bool <0.17.
if type(force) == bool:
force = Cont... | [
"Enables response compression encoding."
] |
Please provide a description of the function:def set_cookie(self, name: str, value: str, *,
expires: Optional[str]=None,
domain: Optional[str]=None,
max_age: Optional[Union[int, str]]=None,
path: str='/',
secure: Optional[str... | [
"Set or update response cookie.\n\n Sets new cookie or updates existent with new value.\n Also updates only those params which are not None.\n "
] |
Please provide a description of the function:def del_cookie(self, name: str, *,
domain: Optional[str]=None,
path: str='/') -> None:
# TODO: do we need domain/path here?
self._cookies.pop(name, None)
self.set_cookie(name, '', max_age=0,
... | [
"Delete cookie.\n\n Creates new empty expired cookie.\n "
] |
Please provide a description of the function:def last_modified(self) -> Optional[datetime.datetime]:
httpdate = self._headers.get(hdrs.LAST_MODIFIED)
if httpdate is not None:
timetuple = parsedate(httpdate)
if timetuple is not None:
return datetime.dateti... | [
"The value of Last-Modified HTTP header, or None.\n\n This header is represented as a `datetime` object.\n "
] |
Please provide a description of the function:async def _default_expect_handler(request: Request) -> None:
expect = request.headers.get(hdrs.EXPECT)
if request.version == HttpVersion11:
if expect.lower() == "100-continue":
await request.writer.write(b"HTTP/1.1 100 Continue\r\n\r\n")
... | [
"Default handler for Expect header.\n\n Just send \"100 Continue\" to client.\n raise HTTPExpectationFailed if value of header is not \"100-continue\"\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.