id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
172,367
import copyreg import io import functools import types import sys import os from multiprocessing import util from pickle import loads, HIGHEST_PROTOCOL def _rebuild_partial(func, args, keywords): return functools.partial(func, *args, **keywords) def _reduce_partial(p): return _rebuild_partial, (p.func, p.args, p.keywords or {})
null
172,368
import copyreg import io import functools import types import sys import os from multiprocessing import util from pickle import loads, HIGHEST_PROTOCOL _dispatch_table = {} def register(type_, reduce_function): _dispatch_table[type_] = reduce_function register(type(_C().f), _reduce_method) register(type(_C.h), _reduce_method) if not hasattr(sys, "pypy_version_info"): # PyPy uses functions instead of method_descriptors and wrapper_descriptors register(type(list.append), _reduce_method_descriptor) register(type(int.__add__), _reduce_method_descriptor) register(functools.partial, _reduce_partial) try: from joblib.externals import cloudpickle # noqa: F401 DEFAULT_ENV = "cloudpickle" except ImportError: # If cloudpickle is not present, fallback to pickle DEFAULT_ENV = "pickle" ENV_LOKY_PICKLER = os.environ.get("LOKY_PICKLER", DEFAULT_ENV) _LokyPickler = None _loky_pickler_name = None HIGHEST_PROTOCOL: int def import_module(name: Text, package: Optional[Text] = ...) -> types.ModuleType: ... def set_loky_pickler(loky_pickler=None): global _LokyPickler, _loky_pickler_name if loky_pickler is None: loky_pickler = ENV_LOKY_PICKLER loky_pickler_cls = None # The default loky_pickler is cloudpickle if loky_pickler in ["", None]: loky_pickler = "cloudpickle" if loky_pickler == _loky_pickler_name: return if loky_pickler == "cloudpickle": from joblib.externals.cloudpickle import CloudPickler as loky_pickler_cls else: try: from importlib import import_module module_pickle = import_module(loky_pickler) loky_pickler_cls = module_pickle.Pickler except (ImportError, AttributeError) as e: extra_info = ("\nThis error occurred while setting loky_pickler to" f" '{loky_pickler}', as required by the env variable " "LOKY_PICKLER or the function set_loky_pickler.") e.args = (e.args[0] + extra_info,) + e.args[1:] e.msg = e.args[0] raise e util.debug( f"Using '{loky_pickler if loky_pickler else 'cloudpickle'}' for " "serialization." ) class CustomizablePickler(loky_pickler_cls): _loky_pickler_cls = loky_pickler_cls def _set_dispatch_table(self, dispatch_table): for ancestor_class in self._loky_pickler_cls.mro(): dt_attribute = getattr(ancestor_class, "dispatch_table", None) if isinstance(dt_attribute, types.MemberDescriptorType): # Ancestor class (typically _pickle.Pickler) has a # member_descriptor for its "dispatch_table" attribute. Use # it to set the dispatch_table as a member instead of a # dynamic attribute in the __dict__ of the instance, # otherwise it will not be taken into account by the C # implementation of the dump method if a subclass defines a # class-level dispatch_table attribute as was done in # cloudpickle 1.6.0: # https://github.com/joblib/loky/pull/260 dt_attribute.__set__(self, dispatch_table) break # On top of member descriptor set, also use setattr such that code # that directly access self.dispatch_table gets a consistent view # of the same table. self.dispatch_table = dispatch_table def __init__(self, writer, reducers=None, protocol=HIGHEST_PROTOCOL): loky_pickler_cls.__init__(self, writer, protocol=protocol) if reducers is None: reducers = {} if hasattr(self, "dispatch_table"): # Force a copy that we will update without mutating the # any class level defined dispatch_table. loky_dt = dict(self.dispatch_table) else: # Use standard reducers as bases loky_dt = copyreg.dispatch_table.copy() # Register loky specific reducers loky_dt.update(_dispatch_table) # Set the new dispatch table, taking care of the fact that we # need to use the member_descriptor when we inherit from a # subclass of the C implementation of the Pickler base class # with an class level dispatch_table attribute. self._set_dispatch_table(loky_dt) # Register the reducers for type, reduce_func in reducers.items(): self.register(type, reduce_func) def register(self, type, reduce_func): """Attach a reducer function to a given type in the dispatch table. """ self.dispatch_table[type] = reduce_func _LokyPickler = CustomizablePickler _loky_pickler_name = loky_pickler
null
172,369
import copyreg import io import functools import types import sys import os from multiprocessing import util from pickle import loads, HIGHEST_PROTOCOL _loky_pickler_name = None def get_loky_pickler_name(): global _loky_pickler_name return _loky_pickler_name
null
172,370
import copyreg import io import functools import types import sys import os from multiprocessing import util from pickle import loads, HIGHEST_PROTOCOL _LokyPickler = None def get_loky_pickler(): global _LokyPickler return _LokyPickler
null
172,371
import copyreg import io import functools import types import sys import os from multiprocessing import util from pickle import loads, HIGHEST_PROTOCOL _LokyPickler = None def dump(obj, file, reducers=None, protocol=None): '''Replacement for pickle.dump() using _LokyPickler.''' global _LokyPickler _LokyPickler(file, reducers=reducers, protocol=protocol).dump(obj) def dumps(obj, reducers=None, protocol=None): global _LokyPickler buf = io.BytesIO() dump(obj, buf, reducers=reducers, protocol=protocol) return buf.getbuffer()
null
172,372
import warnings def _make_viztracer_initializer_and_initargs(): try: import viztracer tracer = viztracer.get_tracer() if tracer is not None and getattr(tracer, 'enable', False): # Profiler is active: introspect its configuration to # initialize the workers with the same configuration. return _viztracer_init, (tracer.init_kwargs,) except ImportError: # viztracer is not installed: nothing to do pass except Exception as e: # In case viztracer's API evolve, we do not want to crash loky but # we want to know about it to be able to update loky. warnings.warn(f"Unable to introspect viztracer state: {e}") return None, () def _chain_initializers(initializer_and_args): """Convenience helper to combine a sequence of initializers. If some initializers are None, they are filtered out. """ filtered_initializers = [] filtered_initargs = [] for initializer, initargs in initializer_and_args: if initializer is not None: filtered_initializers.append(initializer) filtered_initargs.append(initargs) if not filtered_initializers: return None, () elif len(filtered_initializers) == 1: return filtered_initializers[0], filtered_initargs[0] else: return _ChainedInitializer(filtered_initializers), filtered_initargs def _prepare_initializer(initializer, initargs): if initializer is not None and not callable(initializer): raise TypeError( f"initializer must be a callable, got: {initializer!r}" ) # Introspect runtime to determine if we need to propagate the viztracer # profiler information to the workers: return _chain_initializers([ (initializer, initargs), _make_viztracer_initializer_and_initargs(), ])
null
172,373
from __future__ import with_statement import os import time import pathlib import pydoc import re import functools import traceback import warnings import inspect import weakref from tokenize import open as open_py_source from . import hashing from .func_inspect import get_func_code, get_func_name, filter_args from .func_inspect import format_call from .func_inspect import format_signature from .logger import Logger, format_time, pformat from ._store_backends import StoreBackendBase, FileSystemStoreBackend FIRST_LINE_TEXT = "# first line:" The provided code snippet includes necessary dependencies for implementing the `extract_first_line` function. Write a Python function `def extract_first_line(func_code)` to solve the following problem: Extract the first line information from the function code text if available. Here is the function: def extract_first_line(func_code): """ Extract the first line information from the function code text if available. """ if func_code.startswith(FIRST_LINE_TEXT): func_code = func_code.split('\n') first_line = int(func_code[0][len(FIRST_LINE_TEXT):]) func_code = '\n'.join(func_code[1:]) else: first_line = -1 return func_code, first_line
Extract the first line information from the function code text if available.
172,374
from __future__ import with_statement import os import time import pathlib import pydoc import re import functools import traceback import warnings import inspect import weakref from tokenize import open as open_py_source from . import hashing from .func_inspect import get_func_code, get_func_name, filter_args from .func_inspect import format_call from .func_inspect import format_signature from .logger import Logger, format_time, pformat from ._store_backends import StoreBackendBase, FileSystemStoreBackend _STORE_BACKENDS = {'local': FileSystemStoreBackend} class StoreBackendBase(metaclass=ABCMeta): """Helper Abstract Base Class which defines all methods that a StorageBackend must implement.""" location = None def _open_item(self, f, mode): """Opens an item on the store and return a file-like object. This method is private and only used by the StoreBackendMixin object. Parameters ---------- f: a file-like object The file-like object where an item is stored and retrieved mode: string, optional the mode in which the file-like object is opened allowed valued are 'rb', 'wb' Returns ------- a file-like object """ def _item_exists(self, location): """Checks if an item location exists in the store. This method is private and only used by the StoreBackendMixin object. Parameters ---------- location: string The location of an item. On a filesystem, this corresponds to the absolute path, including the filename, of a file. Returns ------- True if the item exists, False otherwise """ def _move_item(self, src, dst): """Moves an item from src to dst in the store. This method is private and only used by the StoreBackendMixin object. Parameters ---------- src: string The source location of an item dst: string The destination location of an item """ def create_location(self, location): """Creates a location on the store. Parameters ---------- location: string The location in the store. On a filesystem, this corresponds to a directory. """ def clear_location(self, location): """Clears a location on the store. Parameters ---------- location: string The location in the store. On a filesystem, this corresponds to a directory or a filename absolute path """ def get_items(self): """Returns the whole list of items available in the store. Returns ------- The list of items identified by their ids (e.g filename in a filesystem). """ def configure(self, location, verbose=0, backend_options=dict()): """Configures the store. Parameters ---------- location: string The base location used by the store. On a filesystem, this corresponds to a directory. verbose: int The level of verbosity of the store backend_options: dict Contains a dictionary of named parameters used to configure the store backend. """ The provided code snippet includes necessary dependencies for implementing the `register_store_backend` function. Write a Python function `def register_store_backend(backend_name, backend)` to solve the following problem: Extend available store backends. The Memory, MemorizeResult and MemorizeFunc objects are designed to be agnostic to the type of store used behind. By default, the local file system is used but this function gives the possibility to extend joblib's memory pattern with other types of storage such as cloud storage (S3, GCS, OpenStack, HadoopFS, etc) or blob DBs. Parameters ---------- backend_name: str The name identifying the store backend being registered. For example, 'local' is used with FileSystemStoreBackend. backend: StoreBackendBase subclass The name of a class that implements the StoreBackendBase interface. Here is the function: def register_store_backend(backend_name, backend): """Extend available store backends. The Memory, MemorizeResult and MemorizeFunc objects are designed to be agnostic to the type of store used behind. By default, the local file system is used but this function gives the possibility to extend joblib's memory pattern with other types of storage such as cloud storage (S3, GCS, OpenStack, HadoopFS, etc) or blob DBs. Parameters ---------- backend_name: str The name identifying the store backend being registered. For example, 'local' is used with FileSystemStoreBackend. backend: StoreBackendBase subclass The name of a class that implements the StoreBackendBase interface. """ if not isinstance(backend_name, str): raise ValueError("Store backend name should be a string, " "'{0}' given.".format(backend_name)) if backend is None or not issubclass(backend, StoreBackendBase): raise ValueError("Store backend should inherit " "StoreBackendBase, " "'{0}' given.".format(backend)) _STORE_BACKENDS[backend_name] = backend
Extend available store backends. The Memory, MemorizeResult and MemorizeFunc objects are designed to be agnostic to the type of store used behind. By default, the local file system is used but this function gives the possibility to extend joblib's memory pattern with other types of storage such as cloud storage (S3, GCS, OpenStack, HadoopFS, etc) or blob DBs. Parameters ---------- backend_name: str The name identifying the store backend being registered. For example, 'local' is used with FileSystemStoreBackend. backend: StoreBackendBase subclass The name of a class that implements the StoreBackendBase interface.
172,375
from __future__ import with_statement import os import time import pathlib import pydoc import re import functools import traceback import warnings import inspect import weakref from tokenize import open as open_py_source from . import hashing from .func_inspect import get_func_code, get_func_name, filter_args from .func_inspect import format_call from .func_inspect import format_signature from .logger import Logger, format_time, pformat from ._store_backends import StoreBackendBase, FileSystemStoreBackend _STORE_BACKENDS = {'local': FileSystemStoreBackend} import os os.environ.setdefault("KMP_INIT_AT_FORK", "FALSE") class StoreBackendBase(metaclass=ABCMeta): """Helper Abstract Base Class which defines all methods that a StorageBackend must implement.""" location = None def _open_item(self, f, mode): """Opens an item on the store and return a file-like object. This method is private and only used by the StoreBackendMixin object. Parameters ---------- f: a file-like object The file-like object where an item is stored and retrieved mode: string, optional the mode in which the file-like object is opened allowed valued are 'rb', 'wb' Returns ------- a file-like object """ def _item_exists(self, location): """Checks if an item location exists in the store. This method is private and only used by the StoreBackendMixin object. Parameters ---------- location: string The location of an item. On a filesystem, this corresponds to the absolute path, including the filename, of a file. Returns ------- True if the item exists, False otherwise """ def _move_item(self, src, dst): """Moves an item from src to dst in the store. This method is private and only used by the StoreBackendMixin object. Parameters ---------- src: string The source location of an item dst: string The destination location of an item """ def create_location(self, location): """Creates a location on the store. Parameters ---------- location: string The location in the store. On a filesystem, this corresponds to a directory. """ def clear_location(self, location): """Clears a location on the store. Parameters ---------- location: string The location in the store. On a filesystem, this corresponds to a directory or a filename absolute path """ def get_items(self): """Returns the whole list of items available in the store. Returns ------- The list of items identified by their ids (e.g filename in a filesystem). """ def configure(self, location, verbose=0, backend_options=dict()): """Configures the store. Parameters ---------- location: string The base location used by the store. On a filesystem, this corresponds to a directory. verbose: int The level of verbosity of the store backend_options: dict Contains a dictionary of named parameters used to configure the store backend. """ The provided code snippet includes necessary dependencies for implementing the `_store_backend_factory` function. Write a Python function `def _store_backend_factory(backend, location, verbose=0, backend_options=None)` to solve the following problem: Return the correct store object for the given location. Here is the function: def _store_backend_factory(backend, location, verbose=0, backend_options=None): """Return the correct store object for the given location.""" if backend_options is None: backend_options = {} if isinstance(location, pathlib.Path): location = str(location) if isinstance(location, StoreBackendBase): return location elif isinstance(location, str): obj = None location = os.path.expanduser(location) # The location is not a local file system, we look in the # registered backends if there's one matching the given backend # name. for backend_key, backend_obj in _STORE_BACKENDS.items(): if backend == backend_key: obj = backend_obj() # By default, we assume the FileSystemStoreBackend can be used if no # matching backend could be found. if obj is None: raise TypeError('Unknown location {0} or backend {1}'.format( location, backend)) # The store backend is configured with the extra named parameters, # some of them are specific to the underlying store backend. obj.configure(location, verbose=verbose, backend_options=backend_options) return obj elif location is not None: warnings.warn( "Instantiating a backend using a {} as a location is not " "supported by joblib. Returning None instead.".format( location.__class__.__name__), UserWarning) return None
Return the correct store object for the given location.
172,376
from __future__ import with_statement import os import time import pathlib import pydoc import re import functools import traceback import warnings import inspect import weakref from tokenize import open as open_py_source from . import hashing from .func_inspect import get_func_code, get_func_name, filter_args from .func_inspect import format_call from .func_inspect import format_signature from .logger import Logger, format_time, pformat from ._store_backends import StoreBackendBase, FileSystemStoreBackend def _get_func_fullname(func): """Compute the part of part associated with a function.""" modules, funcname = get_func_name(func) modules.append(funcname) return os.path.join(*modules) import os os.environ.setdefault("KMP_INIT_AT_FORK", "FALSE") The provided code snippet includes necessary dependencies for implementing the `_build_func_identifier` function. Write a Python function `def _build_func_identifier(func)` to solve the following problem: Build a roughly unique identifier for the cached function. Here is the function: def _build_func_identifier(func): """Build a roughly unique identifier for the cached function.""" parts = [] if isinstance(func, str): parts.append(func) else: parts.append(_get_func_fullname(func)) # We reuse historical fs-like way of building a function identifier return os.path.join(*parts)
Build a roughly unique identifier for the cached function.
172,377
from __future__ import with_statement import os import time import pathlib import pydoc import re import functools import traceback import warnings import inspect import weakref from tokenize import open as open_py_source from . import hashing from .func_inspect import get_func_code, get_func_name, filter_args from .func_inspect import format_call from .func_inspect import format_signature from .logger import Logger, format_time, pformat from ._store_backends import StoreBackendBase, FileSystemStoreBackend import os os.environ.setdefault("KMP_INIT_AT_FORK", "FALSE") def format_time(t): t = _squeeze_time(t) return "%.1fs, %.1fmin" % (t, t / 60.) The provided code snippet includes necessary dependencies for implementing the `_format_load_msg` function. Write a Python function `def _format_load_msg(func_id, args_id, timestamp=None, metadata=None)` to solve the following problem: Helper function to format the message when loading the results. Here is the function: def _format_load_msg(func_id, args_id, timestamp=None, metadata=None): """ Helper function to format the message when loading the results. """ signature = "" try: if metadata is not None: args = ", ".join(['%s=%s' % (name, value) for name, value in metadata['input_args'].items()]) signature = "%s(%s)" % (os.path.basename(func_id), args) else: signature = os.path.basename(func_id) except KeyError: pass if timestamp is not None: ts_string = "{0: <16}".format(format_time(time.time() - timestamp)) else: ts_string = "" return '[Memory]{0}: Loading {1}'.format(ts_string, str(signature))
Helper function to format the message when loading the results.
172,378
from __future__ import print_function, division, absolute_import import asyncio import concurrent.futures import contextlib import time from uuid import uuid4 import weakref from .parallel import AutoBatchingMixin, ParallelBackendBase, BatchedCalls from .parallel import parallel_backend def is_weakrefable(obj): try: weakref.ref(obj) return True except TypeError: return False
null
172,379
from __future__ import print_function, division, absolute_import import asyncio import concurrent.futures import contextlib import time from uuid import uuid4 import weakref from .parallel import AutoBatchingMixin, ParallelBackendBase, BatchedCalls from .parallel import parallel_backend def _funcname(x): try: if isinstance(x, list): x = x[0][0] except Exception: pass return funcname(x) The provided code snippet includes necessary dependencies for implementing the `_make_tasks_summary` function. Write a Python function `def _make_tasks_summary(tasks)` to solve the following problem: Summarize of list of (func, args, kwargs) function calls Here is the function: def _make_tasks_summary(tasks): """Summarize of list of (func, args, kwargs) function calls""" unique_funcs = {func for func, args, kwargs in tasks} if len(unique_funcs) == 1: mixed = False else: mixed = True return len(tasks), mixed, _funcname(tasks)
Summarize of list of (func, args, kwargs) function calls
172,380
from __future__ import print_function, division, absolute_import import asyncio import concurrent.futures import contextlib import time from uuid import uuid4 import weakref from .parallel import AutoBatchingMixin, ParallelBackendBase, BatchedCalls from .parallel import parallel_backend def _joblib_probe_task(): # Noop used by the joblib connector to probe when workers are ready. pass
null
172,381
from __future__ import print_function import time import sys import os import shutil import logging import pprint from .disk import mkdirp def _squeeze_time(t): def short_format_time(t): t = _squeeze_time(t) if t > 60: return "%4.1fmin" % (t / 60.) else: return " %5.1fs" % (t)
null
172,382
def _mk_exception(exception, name=None): if issubclass(exception, JoblibException): # No need to wrap recursively JoblibException return exception, exception.__name__ # Create an exception inheriting from both JoblibException # and that exception if name is None: name = exception.__name__ this_name = 'Joblib%s' % name if this_name in _exception_mapping: # Avoid creating twice the same exception this_exception = _exception_mapping[this_name] else: if exception is Exception: # JoblibException is already a subclass of Exception. No # need to use multiple inheritance return JoblibException, this_name try: this_exception = type( this_name, (JoblibException, exception), {}) _exception_mapping[this_name] = this_exception except TypeError: # This happens if "Cannot create a consistent method # resolution order", e.g. because 'exception' is a # subclass of JoblibException or 'exception' is not an # acceptable base class this_exception = JoblibException return this_exception, this_name def _mk_common_exceptions(): namespace = dict() import builtins as _builtin_exceptions common_exceptions = filter( lambda x: x.endswith('Error'), dir(_builtin_exceptions)) for name in common_exceptions: obj = getattr(_builtin_exceptions, name) if isinstance(obj, type) and issubclass(obj, BaseException): this_obj, this_name = _mk_exception(obj, name=name) namespace[this_name] = this_obj return namespace
null
172,383
import copy import math import operator import typing as t from contextvars import ContextVar from functools import partial from functools import update_wrapper from operator import attrgetter from .wsgi import ClosingIterator if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment The provided code snippet includes necessary dependencies for implementing the `release_local` function. Write a Python function `def release_local(local: t.Union["Local", "LocalStack"]) -> None` to solve the following problem: Release the data for the current context in a :class:`Local` or :class:`LocalStack` without using a :class:`LocalManager`. This should not be needed for modern use cases, and may be removed in the future. .. versionadded:: 0.6.1 Here is the function: def release_local(local: t.Union["Local", "LocalStack"]) -> None: """Release the data for the current context in a :class:`Local` or :class:`LocalStack` without using a :class:`LocalManager`. This should not be needed for modern use cases, and may be removed in the future. .. versionadded:: 0.6.1 """ local.__release_local__()
Release the data for the current context in a :class:`Local` or :class:`LocalStack` without using a :class:`LocalManager`. This should not be needed for modern use cases, and may be removed in the future. .. versionadded:: 0.6.1
172,384
import copy import math import operator import typing as t from contextvars import ContextVar from functools import partial from functools import update_wrapper from operator import attrgetter from .wsgi import ClosingIterator if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment F = t.TypeVar("F", bound=t.Callable[..., t.Any]) The provided code snippet includes necessary dependencies for implementing the `_l_to_r_op` function. Write a Python function `def _l_to_r_op(op: F) -> F` to solve the following problem: Swap the argument order to turn an l-op into an r-op. Here is the function: def _l_to_r_op(op: F) -> F: """Swap the argument order to turn an l-op into an r-op.""" def r_op(obj: t.Any, other: t.Any) -> t.Any: return op(other, obj) return t.cast(F, r_op)
Swap the argument order to turn an l-op into an r-op.
172,385
import copy import math import operator import typing as t from contextvars import ContextVar from functools import partial from functools import update_wrapper from operator import attrgetter from .wsgi import ClosingIterator T = t.TypeVar("T") def _identity(o: T) -> T: return o
null
172,386
import typing as t from functools import update_wrapper from io import BytesIO from itertools import chain from typing import Union from . import exceptions from .datastructures import FileStorage from .datastructures import Headers from .datastructures import MultiDict from .http import parse_options_header from .sansio.multipart import Data from .sansio.multipart import Epilogue from .sansio.multipart import Field from .sansio.multipart import File from .sansio.multipart import MultipartDecoder from .sansio.multipart import NeedData from .urls import url_decode_stream from .wsgi import _make_chunk_iter from .wsgi import get_content_length from .wsgi import get_input_stream if t.TYPE_CHECKING: import typing as te from _typeshed.wsgi import WSGIEnvironment t_parse_result = t.Tuple[t.IO[bytes], MultiDict, MultiDict] def _exhaust(stream: t.IO[bytes]) -> None: bts = stream.read(64 * 1024) while bts: bts = stream.read(64 * 1024)
null
172,387
import typing as t from functools import update_wrapper from io import BytesIO from itertools import chain from typing import Union from . import exceptions from .datastructures import FileStorage from .datastructures import Headers from .datastructures import MultiDict from .http import parse_options_header from .sansio.multipart import Data from .sansio.multipart import Epilogue from .sansio.multipart import Field from .sansio.multipart import File from .sansio.multipart import MultipartDecoder from .sansio.multipart import NeedData from .urls import url_decode_stream from .wsgi import _make_chunk_iter from .wsgi import get_content_length from .wsgi import get_input_stream if t.TYPE_CHECKING: import typing as te from _typeshed.wsgi import WSGIEnvironment t_parse_result = t.Tuple[t.IO[bytes], MultiDict, MultiDict] class BytesIO(BufferedIOBase, BinaryIO): def __init__(self, initial_bytes: bytes = ...) -> None: ... # BytesIO does not contain a "name" field. This workaround is necessary # to allow BytesIO sub-classes to add this field, as it is defined # as a read-only property on IO[]. name: Any def __enter__(self: _T) -> _T: ... def getvalue(self) -> bytes: ... def getbuffer(self) -> memoryview: ... if sys.version_info >= (3, 7): def read1(self, __size: Optional[int] = ...) -> bytes: ... else: def read1(self, __size: Optional[int]) -> bytes: ... # type: ignore class SpooledTemporaryFile(IO[AnyStr]): # bytes needs to go first, as default mode is to open as bytes if sys.version_info >= (3, 8): def __init__( self: SpooledTemporaryFile[bytes], max_size: int = ..., mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., buffering: int = ..., encoding: Optional[str] = ..., newline: Optional[str] = ..., suffix: Optional[str] = ..., prefix: Optional[str] = ..., dir: Optional[str] = ..., *, errors: Optional[str] = ..., ) -> None: ... def __init__( self: SpooledTemporaryFile[str], max_size: int = ..., mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"] = ..., buffering: int = ..., encoding: Optional[str] = ..., newline: Optional[str] = ..., suffix: Optional[str] = ..., prefix: Optional[str] = ..., dir: Optional[str] = ..., *, errors: Optional[str] = ..., ) -> None: ... def __init__( self, max_size: int = ..., mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., newline: Optional[str] = ..., suffix: Optional[str] = ..., prefix: Optional[str] = ..., dir: Optional[str] = ..., *, errors: Optional[str] = ..., ) -> None: ... def errors(self) -> Optional[str]: ... else: def __init__( self: SpooledTemporaryFile[bytes], max_size: int = ..., mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., buffering: int = ..., encoding: Optional[str] = ..., newline: Optional[str] = ..., suffix: Optional[str] = ..., prefix: Optional[str] = ..., dir: Optional[str] = ..., ) -> None: ... def __init__( self: SpooledTemporaryFile[str], max_size: int = ..., mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"] = ..., buffering: int = ..., encoding: Optional[str] = ..., newline: Optional[str] = ..., suffix: Optional[str] = ..., prefix: Optional[str] = ..., dir: Optional[str] = ..., ) -> None: ... def __init__( self, max_size: int = ..., mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., newline: Optional[str] = ..., suffix: Optional[str] = ..., prefix: Optional[str] = ..., dir: Optional[str] = ..., ) -> None: ... def rollover(self) -> None: ... def __enter__(self: _S) -> _S: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... # These methods are copied from the abstract methods of IO, because # SpooledTemporaryFile implements IO. # See also https://github.com/python/typeshed/pull/2452#issuecomment-420657918. def close(self) -> None: ... def fileno(self) -> int: ... def flush(self) -> None: ... def isatty(self) -> bool: ... def read(self, n: int = ...) -> AnyStr: ... def readline(self, limit: int = ...) -> AnyStr: ... def readlines(self, hint: int = ...) -> List[AnyStr]: ... def seek(self, offset: int, whence: int = ...) -> int: ... def tell(self) -> int: ... def truncate(self, size: Optional[int] = ...) -> int: ... def write(self, s: AnyStr) -> int: ... def writelines(self, iterable: Iterable[AnyStr]) -> None: ... def __iter__(self) -> Iterator[AnyStr]: ... # Other than the following methods, which do not exist on SpooledTemporaryFile def readable(self) -> bool: ... def seekable(self) -> bool: ... def writable(self) -> bool: ... def __next__(self) -> AnyStr: ... def TemporaryFile( mode: Union[bytes, unicode] = ..., bufsize: int = ..., suffix: Union[bytes, unicode] = ..., prefix: Union[bytes, unicode] = ..., dir: Union[bytes, unicode] = ..., ) -> _TemporaryFileWrapper: ... def default_stream_factory( total_content_length: t.Optional[int], content_type: t.Optional[str], filename: t.Optional[str], content_length: t.Optional[int] = None, ) -> t.IO[bytes]: max_size = 1024 * 500 if SpooledTemporaryFile is not None: return t.cast(t.IO[bytes], SpooledTemporaryFile(max_size=max_size, mode="rb+")) elif total_content_length is None or total_content_length > max_size: return t.cast(t.IO[bytes], TemporaryFile("rb+")) return BytesIO()
null
172,388
import typing as t from functools import update_wrapper from io import BytesIO from itertools import chain from typing import Union from . import exceptions from .datastructures import FileStorage from .datastructures import Headers from .datastructures import MultiDict from .http import parse_options_header from .sansio.multipart import Data from .sansio.multipart import Epilogue from .sansio.multipart import Field from .sansio.multipart import File from .sansio.multipart import MultipartDecoder from .sansio.multipart import NeedData from .urls import url_decode_stream from .wsgi import _make_chunk_iter from .wsgi import get_content_length from .wsgi import get_input_stream if t.TYPE_CHECKING: import typing as te from _typeshed.wsgi import WSGIEnvironment t_parse_result = t.Tuple[t.IO[bytes], MultiDict, MultiDict] class FormDataParser: """This class implements parsing of form data for Werkzeug. By itself it can parse multipart and url encoded form data. It can be subclassed and extended but for most mimetypes it is a better idea to use the untouched stream and expose it as separate attributes on a request object. .. versionadded:: 0.8 :param stream_factory: An optional callable that returns a new read and writeable file descriptor. This callable works the same as :meth:`Response._get_file_stream`. :param charset: The character set for URL and url encoded form data. :param errors: The encoding error behavior. :param max_form_memory_size: the maximum number of bytes to be accepted for in-memory stored form data. If the data exceeds the value specified an :exc:`~exceptions.RequestEntityTooLarge` exception is raised. :param max_content_length: If this is provided and the transmitted data is longer than this value an :exc:`~exceptions.RequestEntityTooLarge` exception is raised. :param cls: an optional dict class to use. If this is not specified or `None` the default :class:`MultiDict` is used. :param silent: If set to False parsing errors will not be caught. :param max_form_parts: The maximum number of parts to be parsed. If this is exceeded, a :exc:`~exceptions.RequestEntityTooLarge` exception is raised. """ def __init__( self, stream_factory: t.Optional["TStreamFactory"] = None, charset: str = "utf-8", errors: str = "replace", max_form_memory_size: t.Optional[int] = None, max_content_length: t.Optional[int] = None, cls: t.Optional[t.Type[MultiDict]] = None, silent: bool = True, *, max_form_parts: t.Optional[int] = None, ) -> None: if stream_factory is None: stream_factory = default_stream_factory self.stream_factory = stream_factory self.charset = charset self.errors = errors self.max_form_memory_size = max_form_memory_size self.max_content_length = max_content_length self.max_form_parts = max_form_parts if cls is None: cls = MultiDict self.cls = cls self.silent = silent def get_parse_func( self, mimetype: str, options: t.Dict[str, str] ) -> t.Optional[ t.Callable[ ["FormDataParser", t.IO[bytes], str, t.Optional[int], t.Dict[str, str]], "t_parse_result", ] ]: return self.parse_functions.get(mimetype) def parse_from_environ(self, environ: "WSGIEnvironment") -> "t_parse_result": """Parses the information from the environment as form data. :param environ: the WSGI environment to be used for parsing. :return: A tuple in the form ``(stream, form, files)``. """ content_type = environ.get("CONTENT_TYPE", "") content_length = get_content_length(environ) mimetype, options = parse_options_header(content_type) return self.parse(get_input_stream(environ), mimetype, content_length, options) def parse( self, stream: t.IO[bytes], mimetype: str, content_length: t.Optional[int], options: t.Optional[t.Dict[str, str]] = None, ) -> "t_parse_result": """Parses the information from the given stream, mimetype, content length and mimetype parameters. :param stream: an input stream :param mimetype: the mimetype of the data :param content_length: the content length of the incoming data :param options: optional mimetype parameters (used for the multipart boundary for instance) :return: A tuple in the form ``(stream, form, files)``. """ if ( self.max_content_length is not None and content_length is not None and content_length > self.max_content_length ): # if the input stream is not exhausted, firefox reports Connection Reset _exhaust(stream) raise exceptions.RequestEntityTooLarge() if options is None: options = {} parse_func = self.get_parse_func(mimetype, options) if parse_func is not None: try: return parse_func(self, stream, mimetype, content_length, options) except ValueError: if not self.silent: raise return stream, self.cls(), self.cls() def _parse_multipart( self, stream: t.IO[bytes], mimetype: str, content_length: t.Optional[int], options: t.Dict[str, str], ) -> "t_parse_result": parser = MultiPartParser( self.stream_factory, self.charset, self.errors, max_form_memory_size=self.max_form_memory_size, cls=self.cls, max_form_parts=self.max_form_parts, ) boundary = options.get("boundary", "").encode("ascii") if not boundary: raise ValueError("Missing boundary") form, files = parser.parse(stream, boundary, content_length) return stream, form, files def _parse_urlencoded( self, stream: t.IO[bytes], mimetype: str, content_length: t.Optional[int], options: t.Dict[str, str], ) -> "t_parse_result": if ( self.max_form_memory_size is not None and content_length is not None and content_length > self.max_form_memory_size ): # if the input stream is not exhausted, firefox reports Connection Reset _exhaust(stream) raise exceptions.RequestEntityTooLarge() form = url_decode_stream(stream, self.charset, errors=self.errors, cls=self.cls) return stream, form, self.cls() #: mapping of mimetypes to parsing functions parse_functions: t.Dict[ str, t.Callable[ ["FormDataParser", t.IO[bytes], str, t.Optional[int], t.Dict[str, str]], "t_parse_result", ], ] = { "multipart/form-data": _parse_multipart, "application/x-www-form-urlencoded": _parse_urlencoded, "application/x-url-encoded": _parse_urlencoded, } class MultiDict(TypeConversionDict): """A :class:`MultiDict` is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers. This is necessary because some HTML form elements pass multiple values for the same key. :class:`MultiDict` implements all standard dictionary methods. Internally, it saves all values for a key as a list, but the standard dict access methods will only return the first value for a key. If you want to gain access to the other values, too, you have to use the `list` methods as explained below. Basic Usage: >>> d = MultiDict([('a', 'b'), ('a', 'c')]) >>> d MultiDict([('a', 'b'), ('a', 'c')]) >>> d['a'] 'b' >>> d.getlist('a') ['b', 'c'] >>> 'a' in d True It behaves like a normal dict thus all dict functions will only return the first value when multiple values for one key are found. From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP exceptions. A :class:`MultiDict` can be constructed from an iterable of ``(key, value)`` tuples, a dict, a :class:`MultiDict` or from Werkzeug 0.2 onwards some keyword parameters. :param mapping: the initial value for the :class:`MultiDict`. Either a regular dict, an iterable of ``(key, value)`` tuples or `None`. """ def __init__(self, mapping=None): if isinstance(mapping, MultiDict): dict.__init__(self, ((k, l[:]) for k, l in mapping.lists())) elif isinstance(mapping, dict): tmp = {} for key, value in mapping.items(): if isinstance(value, (tuple, list)): if len(value) == 0: continue value = list(value) else: value = [value] tmp[key] = value dict.__init__(self, tmp) else: tmp = {} for key, value in mapping or (): tmp.setdefault(key, []).append(value) dict.__init__(self, tmp) def __getstate__(self): return dict(self.lists()) def __setstate__(self, value): dict.clear(self) dict.update(self, value) def __iter__(self): # Work around https://bugs.python.org/issue43246. # (`return super().__iter__()` also works here, which makes this look # even more like it should be a no-op, yet it isn't.) return dict.__iter__(self) def __getitem__(self, key): """Return the first data value for this key; raises KeyError if not found. :param key: The key to be looked up. :raise KeyError: if the key does not exist. """ if key in self: lst = dict.__getitem__(self, key) if len(lst) > 0: return lst[0] raise exceptions.BadRequestKeyError(key) def __setitem__(self, key, value): """Like :meth:`add` but removes an existing key first. :param key: the key for the value. :param value: the value to set. """ dict.__setitem__(self, key, [value]) def add(self, key, value): """Adds a new value for the key. .. versionadded:: 0.6 :param key: the key for the value. :param value: the value to add. """ dict.setdefault(self, key, []).append(value) def getlist(self, key, type=None): """Return the list of items for a given key. If that key is not in the `MultiDict`, the return value will be an empty list. Just like `get`, `getlist` accepts a `type` parameter. All items will be converted with the callable defined there. :param key: The key to be looked up. :param type: A callable that is used to cast the value in the :class:`MultiDict`. If a :exc:`ValueError` is raised by this callable the value will be removed from the list. :return: a :class:`list` of all the values for the key. """ try: rv = dict.__getitem__(self, key) except KeyError: return [] if type is None: return list(rv) result = [] for item in rv: try: result.append(type(item)) except ValueError: pass return result def setlist(self, key, new_list): """Remove the old values for a key and add new ones. Note that the list you pass the values in will be shallow-copied before it is inserted in the dictionary. >>> d = MultiDict() >>> d.setlist('foo', ['1', '2']) >>> d['foo'] '1' >>> d.getlist('foo') ['1', '2'] :param key: The key for which the values are set. :param new_list: An iterable with the new values for the key. Old values are removed first. """ dict.__setitem__(self, key, list(new_list)) def setdefault(self, key, default=None): """Returns the value for the key if it is in the dict, otherwise it returns `default` and sets that value for `key`. :param key: The key to be looked up. :param default: The default value to be returned if the key is not in the dict. If not further specified it's `None`. """ if key not in self: self[key] = default else: default = self[key] return default def setlistdefault(self, key, default_list=None): """Like `setdefault` but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items to the list: >>> d = MultiDict({"foo": 1}) >>> d.setlistdefault("foo").extend([2, 3]) >>> d.getlist("foo") [1, 2, 3] :param key: The key to be looked up. :param default_list: An iterable of default values. It is either copied (in case it was a list) or converted into a list before returned. :return: a :class:`list` """ if key not in self: default_list = list(default_list or ()) dict.__setitem__(self, key, default_list) else: default_list = dict.__getitem__(self, key) return default_list def items(self, multi=False): """Return an iterator of ``(key, value)`` pairs. :param multi: If set to `True` the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the first value of each key. """ for key, values in dict.items(self): if multi: for value in values: yield key, value else: yield key, values[0] def lists(self): """Return a iterator of ``(key, values)`` pairs, where values is the list of all values associated with the key.""" for key, values in dict.items(self): yield key, list(values) def values(self): """Returns an iterator of the first value on every key's value list.""" for values in dict.values(self): yield values[0] def listvalues(self): """Return an iterator of all values associated with a key. Zipping :meth:`keys` and this is the same as calling :meth:`lists`: >>> d = MultiDict({"foo": [1, 2, 3]}) >>> zip(d.keys(), d.listvalues()) == d.lists() True """ return dict.values(self) def copy(self): """Return a shallow copy of this object.""" return self.__class__(self) def deepcopy(self, memo=None): """Return a deep copy of this object.""" return self.__class__(deepcopy(self.to_dict(flat=False), memo)) def to_dict(self, flat=True): """Return the contents as regular dict. If `flat` is `True` the returned dict will only have the first item present, if `flat` is `False` all values will be returned as lists. :param flat: If set to `False` the dict returned will have lists with all the values in it. Otherwise it will only contain the first value for each key. :return: a :class:`dict` """ if flat: return dict(self.items()) return dict(self.lists()) def update(self, mapping): """update() extends rather than replaces existing key lists: >>> a = MultiDict({'x': 1}) >>> b = MultiDict({'x': 2, 'y': 3}) >>> a.update(b) >>> a MultiDict([('y', 3), ('x', 1), ('x', 2)]) If the value list for a key in ``other_dict`` is empty, no new values will be added to the dict and the key will not be created: >>> x = {'empty_list': []} >>> y = MultiDict() >>> y.update(x) >>> y MultiDict([]) """ for key, value in iter_multi_items(mapping): MultiDict.add(self, key, value) def pop(self, key, default=_missing): """Pop the first item for a list on the dict. Afterwards the key is removed from the dict, so additional values are discarded: >>> d = MultiDict({"foo": [1, 2, 3]}) >>> d.pop("foo") 1 >>> "foo" in d False :param key: the key to pop. :param default: if provided the value to return if the key was not in the dictionary. """ try: lst = dict.pop(self, key) if len(lst) == 0: raise exceptions.BadRequestKeyError(key) return lst[0] except KeyError: if default is not _missing: return default raise exceptions.BadRequestKeyError(key) from None def popitem(self): """Pop an item from the dict.""" try: item = dict.popitem(self) if len(item[1]) == 0: raise exceptions.BadRequestKeyError(item[0]) return (item[0], item[1][0]) except KeyError as e: raise exceptions.BadRequestKeyError(e.args[0]) from None def poplist(self, key): """Pop the list for a key from the dict. If the key is not in the dict an empty list is returned. .. versionchanged:: 0.5 If the key does no longer exist a list is returned instead of raising an error. """ return dict.pop(self, key, []) def popitemlist(self): """Pop a ``(key, list)`` tuple from the dict.""" try: return dict.popitem(self) except KeyError as e: raise exceptions.BadRequestKeyError(e.args[0]) from None def __copy__(self): return self.copy() def __deepcopy__(self, memo): return self.deepcopy(memo=memo) def __repr__(self): return f"{type(self).__name__}({list(self.items(multi=True))!r})" The provided code snippet includes necessary dependencies for implementing the `parse_form_data` function. Write a Python function `def parse_form_data( environ: "WSGIEnvironment", stream_factory: t.Optional["TStreamFactory"] = None, charset: str = "utf-8", errors: str = "replace", max_form_memory_size: t.Optional[int] = None, max_content_length: t.Optional[int] = None, cls: t.Optional[t.Type[MultiDict]] = None, silent: bool = True, ) -> "t_parse_result"` to solve the following problem: Parse the form data in the environ and return it as tuple in the form ``(stream, form, files)``. You should only call this method if the transport method is `POST`, `PUT`, or `PATCH`. If the mimetype of the data transmitted is `multipart/form-data` the files multidict will be filled with `FileStorage` objects. If the mimetype is unknown the input stream is wrapped and returned as first argument, else the stream is empty. This is a shortcut for the common usage of :class:`FormDataParser`. Have a look at :doc:`/request_data` for more details. .. versionadded:: 0.5 The `max_form_memory_size`, `max_content_length` and `cls` parameters were added. .. versionadded:: 0.5.1 The optional `silent` flag was added. :param environ: the WSGI environment to be used for parsing. :param stream_factory: An optional callable that returns a new read and writeable file descriptor. This callable works the same as :meth:`Response._get_file_stream`. :param charset: The character set for URL and url encoded form data. :param errors: The encoding error behavior. :param max_form_memory_size: the maximum number of bytes to be accepted for in-memory stored form data. If the data exceeds the value specified an :exc:`~exceptions.RequestEntityTooLarge` exception is raised. :param max_content_length: If this is provided and the transmitted data is longer than this value an :exc:`~exceptions.RequestEntityTooLarge` exception is raised. :param cls: an optional dict class to use. If this is not specified or `None` the default :class:`MultiDict` is used. :param silent: If set to False parsing errors will not be caught. :return: A tuple in the form ``(stream, form, files)``. Here is the function: def parse_form_data( environ: "WSGIEnvironment", stream_factory: t.Optional["TStreamFactory"] = None, charset: str = "utf-8", errors: str = "replace", max_form_memory_size: t.Optional[int] = None, max_content_length: t.Optional[int] = None, cls: t.Optional[t.Type[MultiDict]] = None, silent: bool = True, ) -> "t_parse_result": """Parse the form data in the environ and return it as tuple in the form ``(stream, form, files)``. You should only call this method if the transport method is `POST`, `PUT`, or `PATCH`. If the mimetype of the data transmitted is `multipart/form-data` the files multidict will be filled with `FileStorage` objects. If the mimetype is unknown the input stream is wrapped and returned as first argument, else the stream is empty. This is a shortcut for the common usage of :class:`FormDataParser`. Have a look at :doc:`/request_data` for more details. .. versionadded:: 0.5 The `max_form_memory_size`, `max_content_length` and `cls` parameters were added. .. versionadded:: 0.5.1 The optional `silent` flag was added. :param environ: the WSGI environment to be used for parsing. :param stream_factory: An optional callable that returns a new read and writeable file descriptor. This callable works the same as :meth:`Response._get_file_stream`. :param charset: The character set for URL and url encoded form data. :param errors: The encoding error behavior. :param max_form_memory_size: the maximum number of bytes to be accepted for in-memory stored form data. If the data exceeds the value specified an :exc:`~exceptions.RequestEntityTooLarge` exception is raised. :param max_content_length: If this is provided and the transmitted data is longer than this value an :exc:`~exceptions.RequestEntityTooLarge` exception is raised. :param cls: an optional dict class to use. If this is not specified or `None` the default :class:`MultiDict` is used. :param silent: If set to False parsing errors will not be caught. :return: A tuple in the form ``(stream, form, files)``. """ return FormDataParser( stream_factory, charset, errors, max_form_memory_size, max_content_length, cls, silent, ).parse_from_environ(environ)
Parse the form data in the environ and return it as tuple in the form ``(stream, form, files)``. You should only call this method if the transport method is `POST`, `PUT`, or `PATCH`. If the mimetype of the data transmitted is `multipart/form-data` the files multidict will be filled with `FileStorage` objects. If the mimetype is unknown the input stream is wrapped and returned as first argument, else the stream is empty. This is a shortcut for the common usage of :class:`FormDataParser`. Have a look at :doc:`/request_data` for more details. .. versionadded:: 0.5 The `max_form_memory_size`, `max_content_length` and `cls` parameters were added. .. versionadded:: 0.5.1 The optional `silent` flag was added. :param environ: the WSGI environment to be used for parsing. :param stream_factory: An optional callable that returns a new read and writeable file descriptor. This callable works the same as :meth:`Response._get_file_stream`. :param charset: The character set for URL and url encoded form data. :param errors: The encoding error behavior. :param max_form_memory_size: the maximum number of bytes to be accepted for in-memory stored form data. If the data exceeds the value specified an :exc:`~exceptions.RequestEntityTooLarge` exception is raised. :param max_content_length: If this is provided and the transmitted data is longer than this value an :exc:`~exceptions.RequestEntityTooLarge` exception is raised. :param cls: an optional dict class to use. If this is not specified or `None` the default :class:`MultiDict` is used. :param silent: If set to False parsing errors will not be caught. :return: A tuple in the form ``(stream, form, files)``.
172,389
import typing as t from functools import update_wrapper from io import BytesIO from itertools import chain from typing import Union from . import exceptions from .datastructures import FileStorage from .datastructures import Headers from .datastructures import MultiDict from .http import parse_options_header from .sansio.multipart import Data from .sansio.multipart import Epilogue from .sansio.multipart import Field from .sansio.multipart import File from .sansio.multipart import MultipartDecoder from .sansio.multipart import NeedData from .urls import url_decode_stream from .wsgi import _make_chunk_iter from .wsgi import get_content_length from .wsgi import get_input_stream if t.TYPE_CHECKING: import typing as te from _typeshed.wsgi import WSGIEnvironment t_parse_result = t.Tuple[t.IO[bytes], MultiDict, MultiDict] F = t.TypeVar("F", bound=t.Callable[..., t.Any]) def update_wrapper(wrapper: _T, wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> _T: ... The provided code snippet includes necessary dependencies for implementing the `exhaust_stream` function. Write a Python function `def exhaust_stream(f: F) -> F` to solve the following problem: Helper decorator for methods that exhausts the stream on return. Here is the function: def exhaust_stream(f: F) -> F: """Helper decorator for methods that exhausts the stream on return.""" def wrapper(self, stream, *args, **kwargs): # type: ignore try: return f(self, stream, *args, **kwargs) finally: exhaust = getattr(stream, "exhaust", None) if exhaust is not None: exhaust() else: while True: chunk = stream.read(1024 * 64) if not chunk: break return update_wrapper(t.cast(F, wrapper), f)
Helper decorator for methods that exhausts the stream on return.
172,390
import typing as t from functools import update_wrapper from io import BytesIO from itertools import chain from typing import Union from . import exceptions from .datastructures import FileStorage from .datastructures import Headers from .datastructures import MultiDict from .http import parse_options_header from .sansio.multipart import Data from .sansio.multipart import Epilogue from .sansio.multipart import Field from .sansio.multipart import File from .sansio.multipart import MultipartDecoder from .sansio.multipart import NeedData from .urls import url_decode_stream from .wsgi import _make_chunk_iter from .wsgi import get_content_length from .wsgi import get_input_stream if t.TYPE_CHECKING: import typing as te from _typeshed.wsgi import WSGIEnvironment t_parse_result = t.Tuple[t.IO[bytes], MultiDict, MultiDict] The provided code snippet includes necessary dependencies for implementing the `_line_parse` function. Write a Python function `def _line_parse(line: str) -> t.Tuple[str, bool]` to solve the following problem: Removes line ending characters and returns a tuple (`stripped_line`, `is_terminated`). Here is the function: def _line_parse(line: str) -> t.Tuple[str, bool]: """Removes line ending characters and returns a tuple (`stripped_line`, `is_terminated`). """ if line[-2:] == "\r\n": return line[:-2], True elif line[-1:] in {"\r", "\n"}: return line[:-1], True return line, False
Removes line ending characters and returns a tuple (`stripped_line`, `is_terminated`).
172,391
import io import mimetypes import os import pkgutil import re import sys import typing as t import unicodedata from datetime import datetime from time import time from zlib import adler32 from markupsafe import escape from ._internal import _DictAccessorProperty from ._internal import _missing from ._internal import _TAccessorValue from .datastructures import Headers from .exceptions import NotFound from .exceptions import RequestedRangeNotSatisfiable from .security import safe_join from .urls import url_quote from .wsgi import wrap_file _charset_mimetypes = { "application/ecmascript", "application/javascript", "application/sql", "application/xml", "application/xml-dtd", "application/xml-external-parsed-entity", } The provided code snippet includes necessary dependencies for implementing the `get_content_type` function. Write a Python function `def get_content_type(mimetype: str, charset: str) -> str` to solve the following problem: Returns the full content type string with charset for a mimetype. If the mimetype represents text, the charset parameter will be appended, otherwise the mimetype is returned unchanged. :param mimetype: The mimetype to be used as content type. :param charset: The charset to be appended for text mimetypes. :return: The content type. .. versionchanged:: 0.15 Any type that ends with ``+xml`` gets a charset, not just those that start with ``application/``. Known text types such as ``application/javascript`` are also given charsets. Here is the function: def get_content_type(mimetype: str, charset: str) -> str: """Returns the full content type string with charset for a mimetype. If the mimetype represents text, the charset parameter will be appended, otherwise the mimetype is returned unchanged. :param mimetype: The mimetype to be used as content type. :param charset: The charset to be appended for text mimetypes. :return: The content type. .. versionchanged:: 0.15 Any type that ends with ``+xml`` gets a charset, not just those that start with ``application/``. Known text types such as ``application/javascript`` are also given charsets. """ if ( mimetype.startswith("text/") or mimetype in _charset_mimetypes or mimetype.endswith("+xml") ): mimetype += f"; charset={charset}" return mimetype
Returns the full content type string with charset for a mimetype. If the mimetype represents text, the charset parameter will be appended, otherwise the mimetype is returned unchanged. :param mimetype: The mimetype to be used as content type. :param charset: The charset to be appended for text mimetypes. :return: The content type. .. versionchanged:: 0.15 Any type that ends with ``+xml`` gets a charset, not just those that start with ``application/``. Known text types such as ``application/javascript`` are also given charsets.
172,392
import io import mimetypes import os import pkgutil import re import sys import typing as t import unicodedata from datetime import datetime from time import time from zlib import adler32 from markupsafe import escape from ._internal import _DictAccessorProperty from ._internal import _missing from ._internal import _TAccessorValue from .datastructures import Headers from .exceptions import NotFound from .exceptions import RequestedRangeNotSatisfiable from .security import safe_join from .urls import url_quote from .wsgi import wrap_file _filename_ascii_strip_re = re.compile(r"[^A-Za-z0-9_.-]") _windows_device_files = ( "CON", "AUX", "COM1", "COM2", "COM3", "COM4", "LPT1", "LPT2", "LPT3", "PRN", "NUL", ) The provided code snippet includes necessary dependencies for implementing the `secure_filename` function. Write a Python function `def secure_filename(filename: str) -> str` to solve the following problem: r"""Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to :func:`os.path.join`. The filename returned is an ASCII only string for maximum portability. On windows systems the function also makes sure that the file is not named after one of the special device files. >>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename('i contain cool \xfcml\xe4uts.txt') 'i_contain_cool_umlauts.txt' The function might return an empty filename. It's your responsibility to ensure that the filename is unique and that you abort or generate a random filename if the function returned an empty one. .. versionadded:: 0.5 :param filename: the filename to secure Here is the function: def secure_filename(filename: str) -> str: r"""Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to :func:`os.path.join`. The filename returned is an ASCII only string for maximum portability. On windows systems the function also makes sure that the file is not named after one of the special device files. >>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename('i contain cool \xfcml\xe4uts.txt') 'i_contain_cool_umlauts.txt' The function might return an empty filename. It's your responsibility to ensure that the filename is unique and that you abort or generate a random filename if the function returned an empty one. .. versionadded:: 0.5 :param filename: the filename to secure """ filename = unicodedata.normalize("NFKD", filename) filename = filename.encode("ascii", "ignore").decode("ascii") for sep in os.sep, os.path.altsep: if sep: filename = filename.replace(sep, " ") filename = str(_filename_ascii_strip_re.sub("", "_".join(filename.split()))).strip( "._" ) # on nt a couple of special files are present in each folder. We # have to ensure that the target file is not such a filename. In # this case we prepend an underline if ( os.name == "nt" and filename and filename.split(".")[0].upper() in _windows_device_files ): filename = f"_{filename}" return filename
r"""Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to :func:`os.path.join`. The filename returned is an ASCII only string for maximum portability. On windows systems the function also makes sure that the file is not named after one of the special device files. >>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename('i contain cool \xfcml\xe4uts.txt') 'i_contain_cool_umlauts.txt' The function might return an empty filename. It's your responsibility to ensure that the filename is unique and that you abort or generate a random filename if the function returned an empty one. .. versionadded:: 0.5 :param filename: the filename to secure
172,393
import io import mimetypes import os import pkgutil import re import sys import typing as t import unicodedata from datetime import datetime from time import time from zlib import adler32 from markupsafe import escape from ._internal import _DictAccessorProperty from ._internal import _missing from ._internal import _TAccessorValue from .datastructures import Headers from .exceptions import NotFound from .exceptions import RequestedRangeNotSatisfiable from .security import safe_join from .urls import url_quote from .wsgi import wrap_file def redirect( location: str, code: int = 302, Response: t.Optional[t.Type["Response"]] = None ) -> "Response": """Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, 307, and 308. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be a unicode string that is encoded using the :func:`iri_to_uri` function. .. versionadded:: 0.10 The class used for the Response object can now be passed in. :param location: the location the response should redirect to. :param code: the redirect status code. defaults to 302. :param class Response: a Response class to use when instantiating a response. The default is :class:`werkzeug.wrappers.Response` if unspecified. """ if Response is None: from .wrappers import Response # type: ignore display_location = escape(location) if isinstance(location, str): # Safe conversion is necessary here as we might redirect # to a broken URI scheme (for instance itms-services). from .urls import iri_to_uri location = iri_to_uri(location, safe_conversion=True) response = Response( # type: ignore "<!doctype html>\n" "<html lang=en>\n" "<title>Redirecting...</title>\n" "<h1>Redirecting...</h1>\n" "<p>You should be redirected automatically to the target URL: " f'<a href="{escape(location)}">{display_location}</a>. If' " not, click the link.\n", code, mimetype="text/html", ) response.headers["Location"] = location return response The provided code snippet includes necessary dependencies for implementing the `append_slash_redirect` function. Write a Python function `def append_slash_redirect(environ: "WSGIEnvironment", code: int = 308) -> "Response"` to solve the following problem: Redirect to the current URL with a slash appended. If the current URL is ``/user/42``, the redirect URL will be ``42/``. When joined to the current URL during response processing or by the browser, this will produce ``/user/42/``. The behavior is undefined if the path ends with a slash already. If called unconditionally on a URL, it may produce a redirect loop. :param environ: Use the path and query from this WSGI environment to produce the redirect URL. :param code: the status code for the redirect. .. versionchanged:: 2.1 Produce a relative URL that only modifies the last segment. Relevant when the current path has multiple segments. .. versionchanged:: 2.1 The default status code is 308 instead of 301. This preserves the request method and body. Here is the function: def append_slash_redirect(environ: "WSGIEnvironment", code: int = 308) -> "Response": """Redirect to the current URL with a slash appended. If the current URL is ``/user/42``, the redirect URL will be ``42/``. When joined to the current URL during response processing or by the browser, this will produce ``/user/42/``. The behavior is undefined if the path ends with a slash already. If called unconditionally on a URL, it may produce a redirect loop. :param environ: Use the path and query from this WSGI environment to produce the redirect URL. :param code: the status code for the redirect. .. versionchanged:: 2.1 Produce a relative URL that only modifies the last segment. Relevant when the current path has multiple segments. .. versionchanged:: 2.1 The default status code is 308 instead of 301. This preserves the request method and body. """ tail = environ["PATH_INFO"].rpartition("/")[2] if not tail: new_path = "./" else: new_path = f"{tail}/" query_string = environ.get("QUERY_STRING") if query_string: new_path = f"{new_path}?{query_string}" return redirect(new_path, code)
Redirect to the current URL with a slash appended. If the current URL is ``/user/42``, the redirect URL will be ``42/``. When joined to the current URL during response processing or by the browser, this will produce ``/user/42/``. The behavior is undefined if the path ends with a slash already. If called unconditionally on a URL, it may produce a redirect loop. :param environ: Use the path and query from this WSGI environment to produce the redirect URL. :param code: the status code for the redirect. .. versionchanged:: 2.1 Produce a relative URL that only modifies the last segment. Relevant when the current path has multiple segments. .. versionchanged:: 2.1 The default status code is 308 instead of 301. This preserves the request method and body.
172,394
import io import mimetypes import os import pkgutil import re import sys import typing as t import unicodedata from datetime import datetime from time import time from zlib import adler32 from markupsafe import escape from ._internal import _DictAccessorProperty from ._internal import _missing from ._internal import _TAccessorValue from .datastructures import Headers from .exceptions import NotFound from .exceptions import RequestedRangeNotSatisfiable from .security import safe_join from .urls import url_quote from .wsgi import wrap_file if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment from .wrappers.request import Request from .wrappers.response import Response def send_file( path_or_file: t.Union[os.PathLike, str, t.IO[bytes]], environ: "WSGIEnvironment", mimetype: t.Optional[str] = None, as_attachment: bool = False, download_name: t.Optional[str] = None, conditional: bool = True, etag: t.Union[bool, str] = True, last_modified: t.Optional[t.Union[datetime, int, float]] = None, max_age: t.Optional[ t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]] ] = None, use_x_sendfile: bool = False, response_class: t.Optional[t.Type["Response"]] = None, _root_path: t.Optional[t.Union[os.PathLike, str]] = None, ) -> "Response": """Send the contents of a file to the client. The first argument can be a file path or a file-like object. Paths are preferred in most cases because Werkzeug can manage the file and get extra information from the path. Passing a file-like object requires that the file is opened in binary mode, and is mostly useful when building a file in memory with :class:`io.BytesIO`. Never pass file paths provided by a user. The path is assumed to be trusted, so a user could craft a path to access a file you didn't intend. Use :func:`send_from_directory` to safely serve user-provided paths. If the WSGI server sets a ``file_wrapper`` in ``environ``, it is used, otherwise Werkzeug's built-in wrapper is used. Alternatively, if the HTTP server supports ``X-Sendfile``, ``use_x_sendfile=True`` will tell the server to send the given path, which is much more efficient than reading it in Python. :param path_or_file: The path to the file to send, relative to the current working directory if a relative path is given. Alternatively, a file-like object opened in binary mode. Make sure the file pointer is seeked to the start of the data. :param environ: The WSGI environ for the current request. :param mimetype: The MIME type to send for the file. If not provided, it will try to detect it from the file name. :param as_attachment: Indicate to a browser that it should offer to save the file instead of displaying it. :param download_name: The default name browsers will use when saving the file. Defaults to the passed file name. :param conditional: Enable conditional and range responses based on request headers. Requires passing a file path and ``environ``. :param etag: Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead. :param last_modified: The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path. :param max_age: How long the client should cache the file, in seconds. If set, ``Cache-Control`` will be ``public``, otherwise it will be ``no-cache`` to prefer conditional caching. :param use_x_sendfile: Set the ``X-Sendfile`` header to let the server to efficiently send the file. Requires support from the HTTP server. Requires passing a file path. :param response_class: Build the response using this class. Defaults to :class:`~werkzeug.wrappers.Response`. :param _root_path: Do not use. For internal use only. Use :func:`send_from_directory` to safely send files under a path. .. versionchanged:: 2.0.2 ``send_file`` only sets a detected ``Content-Encoding`` if ``as_attachment`` is disabled. .. versionadded:: 2.0 Adapted from Flask's implementation. .. versionchanged:: 2.0 ``download_name`` replaces Flask's ``attachment_filename`` parameter. If ``as_attachment=False``, it is passed with ``Content-Disposition: inline`` instead. .. versionchanged:: 2.0 ``max_age`` replaces Flask's ``cache_timeout`` parameter. ``conditional`` is enabled and ``max_age`` is not set by default. .. versionchanged:: 2.0 ``etag`` replaces Flask's ``add_etags`` parameter. It can be a string to use instead of generating one. .. versionchanged:: 2.0 If an encoding is returned when guessing ``mimetype`` from ``download_name``, set the ``Content-Encoding`` header. """ if response_class is None: from .wrappers import Response response_class = Response path: t.Optional[str] = None file: t.Optional[t.IO[bytes]] = None size: t.Optional[int] = None mtime: t.Optional[float] = None headers = Headers() if isinstance(path_or_file, (os.PathLike, str)) or hasattr( path_or_file, "__fspath__" ): path_or_file = t.cast(t.Union[os.PathLike, str], path_or_file) # Flask will pass app.root_path, allowing its send_file wrapper # to not have to deal with paths. if _root_path is not None: path = os.path.join(_root_path, path_or_file) else: path = os.path.abspath(path_or_file) stat = os.stat(path) size = stat.st_size mtime = stat.st_mtime else: file = path_or_file if download_name is None and path is not None: download_name = os.path.basename(path) if mimetype is None: if download_name is None: raise TypeError( "Unable to detect the MIME type because a file name is" " not available. Either set 'download_name', pass a" " path instead of a file, or set 'mimetype'." ) mimetype, encoding = mimetypes.guess_type(download_name) if mimetype is None: mimetype = "application/octet-stream" # Don't send encoding for attachments, it causes browsers to # save decompress tar.gz files. if encoding is not None and not as_attachment: headers.set("Content-Encoding", encoding) if download_name is not None: try: download_name.encode("ascii") except UnicodeEncodeError: simple = unicodedata.normalize("NFKD", download_name) simple = simple.encode("ascii", "ignore").decode("ascii") quoted = url_quote(download_name, safe="") names = {"filename": simple, "filename*": f"UTF-8''{quoted}"} else: names = {"filename": download_name} value = "attachment" if as_attachment else "inline" headers.set("Content-Disposition", value, **names) elif as_attachment: raise TypeError( "No name provided for attachment. Either set" " 'download_name' or pass a path instead of a file." ) if use_x_sendfile and path is not None: headers["X-Sendfile"] = path data = None else: if file is None: file = open(path, "rb") # type: ignore elif isinstance(file, io.BytesIO): size = file.getbuffer().nbytes elif isinstance(file, io.TextIOBase): raise ValueError("Files must be opened in binary mode or use BytesIO.") data = wrap_file(environ, file) rv = response_class( data, mimetype=mimetype, headers=headers, direct_passthrough=True ) if size is not None: rv.content_length = size if last_modified is not None: rv.last_modified = last_modified # type: ignore elif mtime is not None: rv.last_modified = mtime # type: ignore rv.cache_control.no_cache = True # Flask will pass app.get_send_file_max_age, allowing its send_file # wrapper to not have to deal with paths. if callable(max_age): max_age = max_age(path) if max_age is not None: if max_age > 0: rv.cache_control.no_cache = None rv.cache_control.public = True rv.cache_control.max_age = max_age rv.expires = int(time() + max_age) # type: ignore if isinstance(etag, str): rv.set_etag(etag) elif etag and path is not None: check = adler32(path.encode("utf-8")) & 0xFFFFFFFF rv.set_etag(f"{mtime}-{size}-{check}") if conditional: try: rv = rv.make_conditional(environ, accept_ranges=True, complete_length=size) except RequestedRangeNotSatisfiable: if file is not None: file.close() raise # Some x-sendfile implementations incorrectly ignore the 304 # status code and send the file anyway. if rv.status_code == 304: rv.headers.pop("x-sendfile", None) return rv class NotFound(HTTPException): """*404* `Not Found` Raise if a resource does not exist and never existed. """ code = 404 description = ( "The requested URL was not found on the server. If you entered" " the URL manually please check your spelling and try again." ) def safe_join(directory: str, *pathnames: str) -> t.Optional[str]: """Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory. :param directory: The trusted base directory. :param pathnames: The untrusted path components relative to the base directory. :return: A safe path, otherwise ``None``. """ if not directory: # Ensure we end up with ./path if directory="" is given, # otherwise the first untrusted part could become trusted. directory = "." parts = [directory] for filename in pathnames: if filename != "": filename = posixpath.normpath(filename) if ( any(sep in filename for sep in _os_alt_seps) or os.path.isabs(filename) or filename == ".." or filename.startswith("../") ): return None parts.append(filename) return posixpath.join(*parts) The provided code snippet includes necessary dependencies for implementing the `send_from_directory` function. Write a Python function `def send_from_directory( directory: t.Union[os.PathLike, str], path: t.Union[os.PathLike, str], environ: "WSGIEnvironment", **kwargs: t.Any, ) -> "Response"` to solve the following problem: Send a file from within a directory using :func:`send_file`. This is a secure way to serve files from a folder, such as static files or uploads. Uses :func:`~werkzeug.security.safe_join` to ensure the path coming from the client is not maliciously crafted to point outside the specified directory. If the final path does not point to an existing regular file, returns a 404 :exc:`~werkzeug.exceptions.NotFound` error. :param directory: The directory that ``path`` must be located under. This *must not* be a value provided by the client, otherwise it becomes insecure. :param path: The path to the file to send, relative to ``directory``. This is the part of the path provided by the client, which is checked for security. :param environ: The WSGI environ for the current request. :param kwargs: Arguments to pass to :func:`send_file`. .. versionadded:: 2.0 Adapted from Flask's implementation. Here is the function: def send_from_directory( directory: t.Union[os.PathLike, str], path: t.Union[os.PathLike, str], environ: "WSGIEnvironment", **kwargs: t.Any, ) -> "Response": """Send a file from within a directory using :func:`send_file`. This is a secure way to serve files from a folder, such as static files or uploads. Uses :func:`~werkzeug.security.safe_join` to ensure the path coming from the client is not maliciously crafted to point outside the specified directory. If the final path does not point to an existing regular file, returns a 404 :exc:`~werkzeug.exceptions.NotFound` error. :param directory: The directory that ``path`` must be located under. This *must not* be a value provided by the client, otherwise it becomes insecure. :param path: The path to the file to send, relative to ``directory``. This is the part of the path provided by the client, which is checked for security. :param environ: The WSGI environ for the current request. :param kwargs: Arguments to pass to :func:`send_file`. .. versionadded:: 2.0 Adapted from Flask's implementation. """ path = safe_join(os.fspath(directory), os.fspath(path)) if path is None: raise NotFound() # Flask will pass app.root_path, allowing its send_from_directory # wrapper to not have to deal with paths. if "_root_path" in kwargs: path = os.path.join(kwargs["_root_path"], path) try: if not os.path.isfile(path): raise NotFound() except ValueError: # path contains null byte on Python < 3.8 raise NotFound() from None return send_file(path, environ, **kwargs)
Send a file from within a directory using :func:`send_file`. This is a secure way to serve files from a folder, such as static files or uploads. Uses :func:`~werkzeug.security.safe_join` to ensure the path coming from the client is not maliciously crafted to point outside the specified directory. If the final path does not point to an existing regular file, returns a 404 :exc:`~werkzeug.exceptions.NotFound` error. :param directory: The directory that ``path`` must be located under. This *must not* be a value provided by the client, otherwise it becomes insecure. :param path: The path to the file to send, relative to ``directory``. This is the part of the path provided by the client, which is checked for security. :param environ: The WSGI environ for the current request. :param kwargs: Arguments to pass to :func:`send_file`. .. versionadded:: 2.0 Adapted from Flask's implementation.
172,395
import io import mimetypes import os import pkgutil import re import sys import typing as t import unicodedata from datetime import datetime from time import time from zlib import adler32 from markupsafe import escape from ._internal import _DictAccessorProperty from ._internal import _missing from ._internal import _TAccessorValue from .datastructures import Headers from .exceptions import NotFound from .exceptions import RequestedRangeNotSatisfiable from .security import safe_join from .urls import url_quote from .wsgi import wrap_file if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment from .wrappers.request import Request from .wrappers.response import Response def import_string(import_name: str, silent: bool = False) -> t.Any: """Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If `silent` is True the return value will be `None` if the import fails. :param import_name: the dotted name for the object to import. :param silent: if set to `True` import errors are ignored and `None` is returned instead. :return: imported object """ import_name = import_name.replace(":", ".") try: try: __import__(import_name) except ImportError: if "." not in import_name: raise else: return sys.modules[import_name] module_name, obj_name = import_name.rsplit(".", 1) module = __import__(module_name, globals(), locals(), [obj_name]) try: return getattr(module, obj_name) except AttributeError as e: raise ImportError(e) from None except ImportError as e: if not silent: raise ImportStringError(import_name, e).with_traceback( sys.exc_info()[2] ) from None return None The provided code snippet includes necessary dependencies for implementing the `find_modules` function. Write a Python function `def find_modules( import_path: str, include_packages: bool = False, recursive: bool = False ) -> t.Iterator[str]` to solve the following problem: Finds all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application. Packages are not returned unless `include_packages` is `True`. This can also recursively list modules but in that case it will import all the packages to get the correct load path of that module. :param import_path: the dotted name for the package to find child modules. :param include_packages: set to `True` if packages should be returned, too. :param recursive: set to `True` if recursion should happen. :return: generator Here is the function: def find_modules( import_path: str, include_packages: bool = False, recursive: bool = False ) -> t.Iterator[str]: """Finds all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application. Packages are not returned unless `include_packages` is `True`. This can also recursively list modules but in that case it will import all the packages to get the correct load path of that module. :param import_path: the dotted name for the package to find child modules. :param include_packages: set to `True` if packages should be returned, too. :param recursive: set to `True` if recursion should happen. :return: generator """ module = import_string(import_path) path = getattr(module, "__path__", None) if path is None: raise ValueError(f"{import_path!r} is not a package") basename = f"{module.__name__}." for _importer, modname, ispkg in pkgutil.iter_modules(path): modname = basename + modname if ispkg: if include_packages: yield modname if recursive: yield from find_modules(modname, include_packages, True) else: yield modname
Finds all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application. Packages are not returned unless `include_packages` is `True`. This can also recursively list modules but in that case it will import all the packages to get the correct load path of that module. :param import_path: the dotted name for the package to find child modules. :param include_packages: set to `True` if packages should be returned, too. :param recursive: set to `True` if recursion should happen. :return: generator
172,396
import codecs import os import re import typing as t from ._internal import _check_str_tuple from ._internal import _decode_idna from ._internal import _encode_idna from ._internal import _make_encode_wrapper from ._internal import _to_str def url_unquote( s: t.Union[str, bytes], charset: str = "utf-8", errors: str = "replace", unsafe: str = "", ) -> str: """URL decode a single string with a given encoding. If the charset is set to `None` no decoding is performed and raw bytes are returned. :param s: the string to unquote. :param charset: the charset of the query string. If set to `None` no decoding will take place. :param errors: the error handling for the charset decoding. """ rv = _unquote_to_bytes(s, unsafe) if charset is None: return rv return rv.decode(charset, errors) def _url_unquote_legacy(value: str, unsafe: str = "") -> str: try: return url_unquote(value, charset="utf-8", errors="strict", unsafe=unsafe) except UnicodeError: return url_unquote(value, charset="latin1", unsafe=unsafe)
null
172,397
import codecs import os import re import typing as t from ._internal import _check_str_tuple from ._internal import _decode_idna from ._internal import _encode_idna from ._internal import _make_encode_wrapper from ._internal import _to_str if t.TYPE_CHECKING: from . import datastructures as ds _always_safe = frozenset( bytearray( b"abcdefghijklmnopqrstuvwxyz" b"ABCDEFGHIJKLMNOPQRSTUVWXYZ" b"0123456789" b"-._~" b"$!'()*+,;" # RFC3986 sub-delims set, not including query string delimiters &= ) ) The provided code snippet includes necessary dependencies for implementing the `_make_fast_url_quote` function. Write a Python function `def _make_fast_url_quote( charset: str = "utf-8", errors: str = "strict", safe: t.Union[str, bytes] = "/:", unsafe: t.Union[str, bytes] = "", ) -> t.Callable[[bytes], str]` to solve the following problem: Precompile the translation table for a URL encoding function. Unlike :func:`url_quote`, the generated function only takes the string to quote. :param charset: The charset to encode the result with. :param errors: How to handle encoding errors. :param safe: An optional sequence of safe characters to never encode. :param unsafe: An optional sequence of unsafe characters to always encode. Here is the function: def _make_fast_url_quote( charset: str = "utf-8", errors: str = "strict", safe: t.Union[str, bytes] = "/:", unsafe: t.Union[str, bytes] = "", ) -> t.Callable[[bytes], str]: """Precompile the translation table for a URL encoding function. Unlike :func:`url_quote`, the generated function only takes the string to quote. :param charset: The charset to encode the result with. :param errors: How to handle encoding errors. :param safe: An optional sequence of safe characters to never encode. :param unsafe: An optional sequence of unsafe characters to always encode. """ if isinstance(safe, str): safe = safe.encode(charset, errors) if isinstance(unsafe, str): unsafe = unsafe.encode(charset, errors) safe = (frozenset(bytearray(safe)) | _always_safe) - frozenset(bytearray(unsafe)) table = [chr(c) if c in safe else f"%{c:02X}" for c in range(256)] def quote(string: bytes) -> str: return "".join([table[c] for c in string]) return quote
Precompile the translation table for a URL encoding function. Unlike :func:`url_quote`, the generated function only takes the string to quote. :param charset: The charset to encode the result with. :param errors: How to handle encoding errors. :param safe: An optional sequence of safe characters to never encode. :param unsafe: An optional sequence of unsafe characters to always encode.
172,398
import codecs import os import re import typing as t from ._internal import _check_str_tuple from ._internal import _decode_idna from ._internal import _encode_idna from ._internal import _make_encode_wrapper from ._internal import _to_str def url_parse( url: str, scheme: t.Optional[str] = None, allow_fragments: bool = True ) -> BaseURL: """Parses a URL from a string into a :class:`URL` tuple. If the URL is lacking a scheme it can be provided as second argument. Otherwise, it is ignored. Optionally fragments can be stripped from the URL by setting `allow_fragments` to `False`. The inverse of this function is :func:`url_unparse`. :param url: the URL to parse. :param scheme: the default schema to use if the URL is schemaless. :param allow_fragments: if set to `False` a fragment will be removed from the URL. """ s = _make_encode_wrapper(url) is_text_based = isinstance(url, str) if scheme is None: scheme = s("") netloc = query = fragment = s("") i = url.find(s(":")) if i > 0 and _scheme_re.match(_to_str(url[:i], errors="replace")): # make sure "iri" is not actually a port number (in which case # "scheme" is really part of the path) rest = url[i + 1 :] if not rest or any(c not in s("0123456789") for c in rest): # not a port number scheme, url = url[:i].lower(), rest if url[:2] == s("//"): delim = len(url) for c in s("/?#"): wdelim = url.find(c, 2) if wdelim >= 0: delim = min(delim, wdelim) netloc, url = url[2:delim], url[delim:] if (s("[") in netloc and s("]") not in netloc) or ( s("]") in netloc and s("[") not in netloc ): raise ValueError("Invalid IPv6 URL") if allow_fragments and s("#") in url: url, fragment = url.split(s("#"), 1) if s("?") in url: url, query = url.split(s("?"), 1) result_type = URL if is_text_based else BytesURL return result_type(scheme, netloc, url, query, fragment) def url_quote( string: t.Union[str, bytes], charset: str = "utf-8", errors: str = "strict", safe: t.Union[str, bytes] = "/:", unsafe: t.Union[str, bytes] = "", ) -> str: """URL encode a single string with a given encoding. :param s: the string to quote. :param charset: the charset to be used. :param safe: an optional sequence of safe characters. :param unsafe: an optional sequence of unsafe characters. .. versionadded:: 0.9.2 The `unsafe` parameter was added. """ if not isinstance(string, (str, bytes, bytearray)): string = str(string) if isinstance(string, str): string = string.encode(charset, errors) if isinstance(safe, str): safe = safe.encode(charset, errors) if isinstance(unsafe, str): unsafe = unsafe.encode(charset, errors) safe = (frozenset(bytearray(safe)) | _always_safe) - frozenset(bytearray(unsafe)) rv = bytearray() for char in bytearray(string): if char in safe: rv.append(char) else: rv.extend(_bytetohex[char]) return bytes(rv).decode(charset) def url_quote_plus( string: str, charset: str = "utf-8", errors: str = "strict", safe: str = "" ) -> str: """URL encode a single string with the given encoding and convert whitespace to "+". :param s: The string to quote. :param charset: The charset to be used. :param safe: An optional sequence of safe characters. """ return url_quote(string, charset, errors, safe + " ", "+").replace(" ", "+") def url_unparse(components: t.Tuple[str, str, str, str, str]) -> str: """The reverse operation to :meth:`url_parse`. This accepts arbitrary as well as :class:`URL` tuples and returns a URL as a string. :param components: the parsed URL as tuple which should be converted into a URL string. """ _check_str_tuple(components) scheme, netloc, path, query, fragment = components s = _make_encode_wrapper(scheme) url = s("") # We generally treat file:///x and file:/x the same which is also # what browsers seem to do. This also allows us to ignore a schema # register for netloc utilization or having to differentiate between # empty and missing netloc. if netloc or (scheme and path.startswith(s("/"))): if path and path[:1] != s("/"): path = s("/") + path url = s("//") + (netloc or s("")) + path elif path: url += path if scheme: url = scheme + s(":") + url if query: url = url + s("?") + query if fragment: url = url + s("#") + fragment return url def _to_str( # type: ignore x: None, charset: t.Optional[str] = ..., errors: str = ..., allow_none_charset: bool = ..., ) -> None: ... def _to_str( x: t.Any, charset: t.Optional[str] = ..., errors: str = ..., allow_none_charset: bool = ..., ) -> str: ... def _to_str( x: t.Optional[t.Any], charset: t.Optional[str] = _default_encoding, errors: str = "strict", allow_none_charset: bool = False, ) -> t.Optional[t.Union[str, bytes]]: if x is None or isinstance(x, str): return x if not isinstance(x, (bytes, bytearray)): return str(x) if charset is None: if allow_none_charset: return x return x.decode(charset, errors) # type: ignore The provided code snippet includes necessary dependencies for implementing the `url_fix` function. Write a Python function `def url_fix(s: str, charset: str = "utf-8") -> str` to solve the following problem: r"""Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: >>> url_fix('http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)') 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)' :param s: the string with the URL to fix. :param charset: The target charset for the URL if the url was given as a string. Here is the function: def url_fix(s: str, charset: str = "utf-8") -> str: r"""Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: >>> url_fix('http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)') 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)' :param s: the string with the URL to fix. :param charset: The target charset for the URL if the url was given as a string. """ # First step is to switch to text processing and to convert # backslashes (which are invalid in URLs anyways) to slashes. This is # consistent with what Chrome does. s = _to_str(s, charset, "replace").replace("\\", "/") # For the specific case that we look like a malformed windows URL # we want to fix this up manually: if s.startswith("file://") and s[7:8].isalpha() and s[8:10] in (":/", "|/"): s = f"file:///{s[7:]}" url = url_parse(s) path = url_quote(url.path, charset, safe="/%+$!*'(),") qs = url_quote_plus(url.query, charset, safe=":&%=+$!*'(),") anchor = url_quote_plus(url.fragment, charset, safe=":&%=+$!*'(),") return url_unparse((url.scheme, url.encode_netloc(), path, qs, anchor))
r"""Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: >>> url_fix('http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)') 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)' :param s: the string with the URL to fix. :param charset: The target charset for the URL if the url was given as a string.
172,399
import codecs import os import re import typing as t from ._internal import _check_str_tuple from ._internal import _decode_idna from ._internal import _encode_idna from ._internal import _make_encode_wrapper from ._internal import _to_str if t.TYPE_CHECKING: from . import datastructures as ds _fast_url_quote = _make_fast_url_quote() The provided code snippet includes necessary dependencies for implementing the `_codec_error_url_quote` function. Write a Python function `def _codec_error_url_quote(e: UnicodeError) -> t.Tuple[str, int]` to solve the following problem: Used in :func:`uri_to_iri` after unquoting to re-quote any invalid bytes. Here is the function: def _codec_error_url_quote(e: UnicodeError) -> t.Tuple[str, int]: """Used in :func:`uri_to_iri` after unquoting to re-quote any invalid bytes. """ # the docs state that UnicodeError does have these attributes, # but mypy isn't picking them up out = _fast_url_quote(e.object[e.start : e.end]) # type: ignore return out, e.end # type: ignore
Used in :func:`uri_to_iri` after unquoting to re-quote any invalid bytes.
172,400
import codecs import os import re import typing as t from ._internal import _check_str_tuple from ._internal import _decode_idna from ._internal import _encode_idna from ._internal import _make_encode_wrapper from ._internal import _to_str if t.TYPE_CHECKING: from . import datastructures as ds def _url_decode_impl( pair_iter: t.Iterable[t.AnyStr], charset: str, include_empty: bool, errors: str ) -> t.Iterator[t.Tuple[str, str]]: for pair in pair_iter: if not pair: continue s = _make_encode_wrapper(pair) equal = s("=") if equal in pair: key, value = pair.split(equal, 1) else: if not include_empty: continue key = pair value = s("") yield ( url_unquote_plus(key, charset, errors), url_unquote_plus(value, charset, errors), ) class MultiDict(TypeConversionDict): """A :class:`MultiDict` is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers. This is necessary because some HTML form elements pass multiple values for the same key. :class:`MultiDict` implements all standard dictionary methods. Internally, it saves all values for a key as a list, but the standard dict access methods will only return the first value for a key. If you want to gain access to the other values, too, you have to use the `list` methods as explained below. Basic Usage: >>> d = MultiDict([('a', 'b'), ('a', 'c')]) >>> d MultiDict([('a', 'b'), ('a', 'c')]) >>> d['a'] 'b' >>> d.getlist('a') ['b', 'c'] >>> 'a' in d True It behaves like a normal dict thus all dict functions will only return the first value when multiple values for one key are found. From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP exceptions. A :class:`MultiDict` can be constructed from an iterable of ``(key, value)`` tuples, a dict, a :class:`MultiDict` or from Werkzeug 0.2 onwards some keyword parameters. :param mapping: the initial value for the :class:`MultiDict`. Either a regular dict, an iterable of ``(key, value)`` tuples or `None`. """ def __init__(self, mapping=None): if isinstance(mapping, MultiDict): dict.__init__(self, ((k, l[:]) for k, l in mapping.lists())) elif isinstance(mapping, dict): tmp = {} for key, value in mapping.items(): if isinstance(value, (tuple, list)): if len(value) == 0: continue value = list(value) else: value = [value] tmp[key] = value dict.__init__(self, tmp) else: tmp = {} for key, value in mapping or (): tmp.setdefault(key, []).append(value) dict.__init__(self, tmp) def __getstate__(self): return dict(self.lists()) def __setstate__(self, value): dict.clear(self) dict.update(self, value) def __iter__(self): # Work around https://bugs.python.org/issue43246. # (`return super().__iter__()` also works here, which makes this look # even more like it should be a no-op, yet it isn't.) return dict.__iter__(self) def __getitem__(self, key): """Return the first data value for this key; raises KeyError if not found. :param key: The key to be looked up. :raise KeyError: if the key does not exist. """ if key in self: lst = dict.__getitem__(self, key) if len(lst) > 0: return lst[0] raise exceptions.BadRequestKeyError(key) def __setitem__(self, key, value): """Like :meth:`add` but removes an existing key first. :param key: the key for the value. :param value: the value to set. """ dict.__setitem__(self, key, [value]) def add(self, key, value): """Adds a new value for the key. .. versionadded:: 0.6 :param key: the key for the value. :param value: the value to add. """ dict.setdefault(self, key, []).append(value) def getlist(self, key, type=None): """Return the list of items for a given key. If that key is not in the `MultiDict`, the return value will be an empty list. Just like `get`, `getlist` accepts a `type` parameter. All items will be converted with the callable defined there. :param key: The key to be looked up. :param type: A callable that is used to cast the value in the :class:`MultiDict`. If a :exc:`ValueError` is raised by this callable the value will be removed from the list. :return: a :class:`list` of all the values for the key. """ try: rv = dict.__getitem__(self, key) except KeyError: return [] if type is None: return list(rv) result = [] for item in rv: try: result.append(type(item)) except ValueError: pass return result def setlist(self, key, new_list): """Remove the old values for a key and add new ones. Note that the list you pass the values in will be shallow-copied before it is inserted in the dictionary. >>> d = MultiDict() >>> d.setlist('foo', ['1', '2']) >>> d['foo'] '1' >>> d.getlist('foo') ['1', '2'] :param key: The key for which the values are set. :param new_list: An iterable with the new values for the key. Old values are removed first. """ dict.__setitem__(self, key, list(new_list)) def setdefault(self, key, default=None): """Returns the value for the key if it is in the dict, otherwise it returns `default` and sets that value for `key`. :param key: The key to be looked up. :param default: The default value to be returned if the key is not in the dict. If not further specified it's `None`. """ if key not in self: self[key] = default else: default = self[key] return default def setlistdefault(self, key, default_list=None): """Like `setdefault` but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items to the list: >>> d = MultiDict({"foo": 1}) >>> d.setlistdefault("foo").extend([2, 3]) >>> d.getlist("foo") [1, 2, 3] :param key: The key to be looked up. :param default_list: An iterable of default values. It is either copied (in case it was a list) or converted into a list before returned. :return: a :class:`list` """ if key not in self: default_list = list(default_list or ()) dict.__setitem__(self, key, default_list) else: default_list = dict.__getitem__(self, key) return default_list def items(self, multi=False): """Return an iterator of ``(key, value)`` pairs. :param multi: If set to `True` the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the first value of each key. """ for key, values in dict.items(self): if multi: for value in values: yield key, value else: yield key, values[0] def lists(self): """Return a iterator of ``(key, values)`` pairs, where values is the list of all values associated with the key.""" for key, values in dict.items(self): yield key, list(values) def values(self): """Returns an iterator of the first value on every key's value list.""" for values in dict.values(self): yield values[0] def listvalues(self): """Return an iterator of all values associated with a key. Zipping :meth:`keys` and this is the same as calling :meth:`lists`: >>> d = MultiDict({"foo": [1, 2, 3]}) >>> zip(d.keys(), d.listvalues()) == d.lists() True """ return dict.values(self) def copy(self): """Return a shallow copy of this object.""" return self.__class__(self) def deepcopy(self, memo=None): """Return a deep copy of this object.""" return self.__class__(deepcopy(self.to_dict(flat=False), memo)) def to_dict(self, flat=True): """Return the contents as regular dict. If `flat` is `True` the returned dict will only have the first item present, if `flat` is `False` all values will be returned as lists. :param flat: If set to `False` the dict returned will have lists with all the values in it. Otherwise it will only contain the first value for each key. :return: a :class:`dict` """ if flat: return dict(self.items()) return dict(self.lists()) def update(self, mapping): """update() extends rather than replaces existing key lists: >>> a = MultiDict({'x': 1}) >>> b = MultiDict({'x': 2, 'y': 3}) >>> a.update(b) >>> a MultiDict([('y', 3), ('x', 1), ('x', 2)]) If the value list for a key in ``other_dict`` is empty, no new values will be added to the dict and the key will not be created: >>> x = {'empty_list': []} >>> y = MultiDict() >>> y.update(x) >>> y MultiDict([]) """ for key, value in iter_multi_items(mapping): MultiDict.add(self, key, value) def pop(self, key, default=_missing): """Pop the first item for a list on the dict. Afterwards the key is removed from the dict, so additional values are discarded: >>> d = MultiDict({"foo": [1, 2, 3]}) >>> d.pop("foo") 1 >>> "foo" in d False :param key: the key to pop. :param default: if provided the value to return if the key was not in the dictionary. """ try: lst = dict.pop(self, key) if len(lst) == 0: raise exceptions.BadRequestKeyError(key) return lst[0] except KeyError: if default is not _missing: return default raise exceptions.BadRequestKeyError(key) from None def popitem(self): """Pop an item from the dict.""" try: item = dict.popitem(self) if len(item[1]) == 0: raise exceptions.BadRequestKeyError(item[0]) return (item[0], item[1][0]) except KeyError as e: raise exceptions.BadRequestKeyError(e.args[0]) from None def poplist(self, key): """Pop the list for a key from the dict. If the key is not in the dict an empty list is returned. .. versionchanged:: 0.5 If the key does no longer exist a list is returned instead of raising an error. """ return dict.pop(self, key, []) def popitemlist(self): """Pop a ``(key, list)`` tuple from the dict.""" try: return dict.popitem(self) except KeyError as e: raise exceptions.BadRequestKeyError(e.args[0]) from None def __copy__(self): return self.copy() def __deepcopy__(self, memo): return self.deepcopy(memo=memo) def __repr__(self): return f"{type(self).__name__}({list(self.items(multi=True))!r})" The provided code snippet includes necessary dependencies for implementing the `url_decode` function. Write a Python function `def url_decode( s: t.AnyStr, charset: str = "utf-8", include_empty: bool = True, errors: str = "replace", separator: str = "&", cls: t.Optional[t.Type["ds.MultiDict"]] = None, ) -> "ds.MultiDict[str, str]"` to solve the following problem: Parse a query string and return it as a :class:`MultiDict`. :param s: The query string to parse. :param charset: Decode bytes to string with this charset. If not given, bytes are returned as-is. :param include_empty: Include keys with empty values in the dict. :param errors: Error handling behavior when decoding bytes. :param separator: Separator character between pairs. :param cls: Container to hold result instead of :class:`MultiDict`. .. versionchanged:: 2.0 The ``decode_keys`` parameter is deprecated and will be removed in Werkzeug 2.1. .. versionchanged:: 0.5 In previous versions ";" and "&" could be used for url decoding. Now only "&" is supported. If you want to use ";", a different ``separator`` can be provided. .. versionchanged:: 0.5 The ``cls`` parameter was added. Here is the function: def url_decode( s: t.AnyStr, charset: str = "utf-8", include_empty: bool = True, errors: str = "replace", separator: str = "&", cls: t.Optional[t.Type["ds.MultiDict"]] = None, ) -> "ds.MultiDict[str, str]": """Parse a query string and return it as a :class:`MultiDict`. :param s: The query string to parse. :param charset: Decode bytes to string with this charset. If not given, bytes are returned as-is. :param include_empty: Include keys with empty values in the dict. :param errors: Error handling behavior when decoding bytes. :param separator: Separator character between pairs. :param cls: Container to hold result instead of :class:`MultiDict`. .. versionchanged:: 2.0 The ``decode_keys`` parameter is deprecated and will be removed in Werkzeug 2.1. .. versionchanged:: 0.5 In previous versions ";" and "&" could be used for url decoding. Now only "&" is supported. If you want to use ";", a different ``separator`` can be provided. .. versionchanged:: 0.5 The ``cls`` parameter was added. """ if cls is None: from .datastructures import MultiDict # noqa: F811 cls = MultiDict if isinstance(s, str) and not isinstance(separator, str): separator = separator.decode(charset or "ascii") elif isinstance(s, bytes) and not isinstance(separator, bytes): separator = separator.encode(charset or "ascii") # type: ignore return cls( _url_decode_impl( s.split(separator), charset, include_empty, errors # type: ignore ) )
Parse a query string and return it as a :class:`MultiDict`. :param s: The query string to parse. :param charset: Decode bytes to string with this charset. If not given, bytes are returned as-is. :param include_empty: Include keys with empty values in the dict. :param errors: Error handling behavior when decoding bytes. :param separator: Separator character between pairs. :param cls: Container to hold result instead of :class:`MultiDict`. .. versionchanged:: 2.0 The ``decode_keys`` parameter is deprecated and will be removed in Werkzeug 2.1. .. versionchanged:: 0.5 In previous versions ";" and "&" could be used for url decoding. Now only "&" is supported. If you want to use ";", a different ``separator`` can be provided. .. versionchanged:: 0.5 The ``cls`` parameter was added.
172,401
import codecs import os import re import typing as t from ._internal import _check_str_tuple from ._internal import _decode_idna from ._internal import _encode_idna from ._internal import _make_encode_wrapper from ._internal import _to_str if t.TYPE_CHECKING: from . import datastructures as ds def _url_decode_impl( pair_iter: t.Iterable[t.AnyStr], charset: str, include_empty: bool, errors: str ) -> t.Iterator[t.Tuple[str, str]]: for pair in pair_iter: if not pair: continue s = _make_encode_wrapper(pair) equal = s("=") if equal in pair: key, value = pair.split(equal, 1) else: if not include_empty: continue key = pair value = s("") yield ( url_unquote_plus(key, charset, errors), url_unquote_plus(value, charset, errors), ) class MultiDict(TypeConversionDict): """A :class:`MultiDict` is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers. This is necessary because some HTML form elements pass multiple values for the same key. :class:`MultiDict` implements all standard dictionary methods. Internally, it saves all values for a key as a list, but the standard dict access methods will only return the first value for a key. If you want to gain access to the other values, too, you have to use the `list` methods as explained below. Basic Usage: >>> d = MultiDict([('a', 'b'), ('a', 'c')]) >>> d MultiDict([('a', 'b'), ('a', 'c')]) >>> d['a'] 'b' >>> d.getlist('a') ['b', 'c'] >>> 'a' in d True It behaves like a normal dict thus all dict functions will only return the first value when multiple values for one key are found. From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP exceptions. A :class:`MultiDict` can be constructed from an iterable of ``(key, value)`` tuples, a dict, a :class:`MultiDict` or from Werkzeug 0.2 onwards some keyword parameters. :param mapping: the initial value for the :class:`MultiDict`. Either a regular dict, an iterable of ``(key, value)`` tuples or `None`. """ def __init__(self, mapping=None): if isinstance(mapping, MultiDict): dict.__init__(self, ((k, l[:]) for k, l in mapping.lists())) elif isinstance(mapping, dict): tmp = {} for key, value in mapping.items(): if isinstance(value, (tuple, list)): if len(value) == 0: continue value = list(value) else: value = [value] tmp[key] = value dict.__init__(self, tmp) else: tmp = {} for key, value in mapping or (): tmp.setdefault(key, []).append(value) dict.__init__(self, tmp) def __getstate__(self): return dict(self.lists()) def __setstate__(self, value): dict.clear(self) dict.update(self, value) def __iter__(self): # Work around https://bugs.python.org/issue43246. # (`return super().__iter__()` also works here, which makes this look # even more like it should be a no-op, yet it isn't.) return dict.__iter__(self) def __getitem__(self, key): """Return the first data value for this key; raises KeyError if not found. :param key: The key to be looked up. :raise KeyError: if the key does not exist. """ if key in self: lst = dict.__getitem__(self, key) if len(lst) > 0: return lst[0] raise exceptions.BadRequestKeyError(key) def __setitem__(self, key, value): """Like :meth:`add` but removes an existing key first. :param key: the key for the value. :param value: the value to set. """ dict.__setitem__(self, key, [value]) def add(self, key, value): """Adds a new value for the key. .. versionadded:: 0.6 :param key: the key for the value. :param value: the value to add. """ dict.setdefault(self, key, []).append(value) def getlist(self, key, type=None): """Return the list of items for a given key. If that key is not in the `MultiDict`, the return value will be an empty list. Just like `get`, `getlist` accepts a `type` parameter. All items will be converted with the callable defined there. :param key: The key to be looked up. :param type: A callable that is used to cast the value in the :class:`MultiDict`. If a :exc:`ValueError` is raised by this callable the value will be removed from the list. :return: a :class:`list` of all the values for the key. """ try: rv = dict.__getitem__(self, key) except KeyError: return [] if type is None: return list(rv) result = [] for item in rv: try: result.append(type(item)) except ValueError: pass return result def setlist(self, key, new_list): """Remove the old values for a key and add new ones. Note that the list you pass the values in will be shallow-copied before it is inserted in the dictionary. >>> d = MultiDict() >>> d.setlist('foo', ['1', '2']) >>> d['foo'] '1' >>> d.getlist('foo') ['1', '2'] :param key: The key for which the values are set. :param new_list: An iterable with the new values for the key. Old values are removed first. """ dict.__setitem__(self, key, list(new_list)) def setdefault(self, key, default=None): """Returns the value for the key if it is in the dict, otherwise it returns `default` and sets that value for `key`. :param key: The key to be looked up. :param default: The default value to be returned if the key is not in the dict. If not further specified it's `None`. """ if key not in self: self[key] = default else: default = self[key] return default def setlistdefault(self, key, default_list=None): """Like `setdefault` but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items to the list: >>> d = MultiDict({"foo": 1}) >>> d.setlistdefault("foo").extend([2, 3]) >>> d.getlist("foo") [1, 2, 3] :param key: The key to be looked up. :param default_list: An iterable of default values. It is either copied (in case it was a list) or converted into a list before returned. :return: a :class:`list` """ if key not in self: default_list = list(default_list or ()) dict.__setitem__(self, key, default_list) else: default_list = dict.__getitem__(self, key) return default_list def items(self, multi=False): """Return an iterator of ``(key, value)`` pairs. :param multi: If set to `True` the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the first value of each key. """ for key, values in dict.items(self): if multi: for value in values: yield key, value else: yield key, values[0] def lists(self): """Return a iterator of ``(key, values)`` pairs, where values is the list of all values associated with the key.""" for key, values in dict.items(self): yield key, list(values) def values(self): """Returns an iterator of the first value on every key's value list.""" for values in dict.values(self): yield values[0] def listvalues(self): """Return an iterator of all values associated with a key. Zipping :meth:`keys` and this is the same as calling :meth:`lists`: >>> d = MultiDict({"foo": [1, 2, 3]}) >>> zip(d.keys(), d.listvalues()) == d.lists() True """ return dict.values(self) def copy(self): """Return a shallow copy of this object.""" return self.__class__(self) def deepcopy(self, memo=None): """Return a deep copy of this object.""" return self.__class__(deepcopy(self.to_dict(flat=False), memo)) def to_dict(self, flat=True): """Return the contents as regular dict. If `flat` is `True` the returned dict will only have the first item present, if `flat` is `False` all values will be returned as lists. :param flat: If set to `False` the dict returned will have lists with all the values in it. Otherwise it will only contain the first value for each key. :return: a :class:`dict` """ if flat: return dict(self.items()) return dict(self.lists()) def update(self, mapping): """update() extends rather than replaces existing key lists: >>> a = MultiDict({'x': 1}) >>> b = MultiDict({'x': 2, 'y': 3}) >>> a.update(b) >>> a MultiDict([('y', 3), ('x', 1), ('x', 2)]) If the value list for a key in ``other_dict`` is empty, no new values will be added to the dict and the key will not be created: >>> x = {'empty_list': []} >>> y = MultiDict() >>> y.update(x) >>> y MultiDict([]) """ for key, value in iter_multi_items(mapping): MultiDict.add(self, key, value) def pop(self, key, default=_missing): """Pop the first item for a list on the dict. Afterwards the key is removed from the dict, so additional values are discarded: >>> d = MultiDict({"foo": [1, 2, 3]}) >>> d.pop("foo") 1 >>> "foo" in d False :param key: the key to pop. :param default: if provided the value to return if the key was not in the dictionary. """ try: lst = dict.pop(self, key) if len(lst) == 0: raise exceptions.BadRequestKeyError(key) return lst[0] except KeyError: if default is not _missing: return default raise exceptions.BadRequestKeyError(key) from None def popitem(self): """Pop an item from the dict.""" try: item = dict.popitem(self) if len(item[1]) == 0: raise exceptions.BadRequestKeyError(item[0]) return (item[0], item[1][0]) except KeyError as e: raise exceptions.BadRequestKeyError(e.args[0]) from None def poplist(self, key): """Pop the list for a key from the dict. If the key is not in the dict an empty list is returned. .. versionchanged:: 0.5 If the key does no longer exist a list is returned instead of raising an error. """ return dict.pop(self, key, []) def popitemlist(self): """Pop a ``(key, list)`` tuple from the dict.""" try: return dict.popitem(self) except KeyError as e: raise exceptions.BadRequestKeyError(e.args[0]) from None def __copy__(self): return self.copy() def __deepcopy__(self, memo): return self.deepcopy(memo=memo) def __repr__(self): return f"{type(self).__name__}({list(self.items(multi=True))!r})" def make_chunk_iter( stream: t.Union[t.Iterable[bytes], t.IO[bytes]], separator: bytes, limit: t.Optional[int] = None, buffer_size: int = 10 * 1024, cap_at_buffer: bool = False, ) -> t.Iterator[bytes]: """Works like :func:`make_line_iter` but accepts a separator which divides chunks. If you want newline based processing you should use :func:`make_line_iter` instead as it supports arbitrary newline markers. .. versionadded:: 0.8 .. versionadded:: 0.9 added support for iterators as input stream. .. versionadded:: 0.11.10 added support for the `cap_at_buffer` parameter. :param stream: the stream or iterate to iterate over. :param separator: the separator that divides chunks. :param limit: the limit in bytes for the stream. (Usually content length. Not necessary if the `stream` is otherwise already limited). :param buffer_size: The optional buffer size. :param cap_at_buffer: if this is set chunks are split if they are longer than the buffer size. Internally this is implemented that the buffer size might be exhausted by a factor of two however. """ _iter = _make_chunk_iter(stream, limit, buffer_size) first_item = next(_iter, b"") if not first_item: return _iter = t.cast(t.Iterator[bytes], chain((first_item,), _iter)) if isinstance(first_item, str): separator = _to_str(separator) _split = re.compile(f"({re.escape(separator)})").split _join = "".join else: separator = _to_bytes(separator) _split = re.compile(b"(" + re.escape(separator) + b")").split _join = b"".join buffer: t.List[bytes] = [] while True: new_data = next(_iter, b"") if not new_data: break chunks = _split(new_data) new_buf: t.List[bytes] = [] buf_size = 0 for item in chain(buffer, chunks): if item == separator: yield _join(new_buf) new_buf = [] buf_size = 0 else: buf_size += len(item) new_buf.append(item) if cap_at_buffer and buf_size >= buffer_size: rv = _join(new_buf) while len(rv) >= buffer_size: yield rv[:buffer_size] rv = rv[buffer_size:] new_buf = [rv] buf_size = len(rv) buffer = new_buf if buffer: yield _join(buffer) The provided code snippet includes necessary dependencies for implementing the `url_decode_stream` function. Write a Python function `def url_decode_stream( stream: t.IO[bytes], charset: str = "utf-8", include_empty: bool = True, errors: str = "replace", separator: bytes = b"&", cls: t.Optional[t.Type["ds.MultiDict"]] = None, limit: t.Optional[int] = None, ) -> "ds.MultiDict[str, str]"` to solve the following problem: Works like :func:`url_decode` but decodes a stream. The behavior of stream and limit follows functions like :func:`~werkzeug.wsgi.make_line_iter`. The generator of pairs is directly fed to the `cls` so you can consume the data while it's parsed. :param stream: a stream with the encoded querystring :param charset: the charset of the query string. If set to `None` no decoding will take place. :param include_empty: Set to `False` if you don't want empty values to appear in the dict. :param errors: the decoding error behavior. :param separator: the pair separator to be used, defaults to ``&`` :param cls: an optional dict class to use. If this is not specified or `None` the default :class:`MultiDict` is used. :param limit: the content length of the URL data. Not necessary if a limited stream is provided. .. versionchanged:: 2.0 The ``decode_keys`` and ``return_iterator`` parameters are deprecated and will be removed in Werkzeug 2.1. .. versionadded:: 0.8 Here is the function: def url_decode_stream( stream: t.IO[bytes], charset: str = "utf-8", include_empty: bool = True, errors: str = "replace", separator: bytes = b"&", cls: t.Optional[t.Type["ds.MultiDict"]] = None, limit: t.Optional[int] = None, ) -> "ds.MultiDict[str, str]": """Works like :func:`url_decode` but decodes a stream. The behavior of stream and limit follows functions like :func:`~werkzeug.wsgi.make_line_iter`. The generator of pairs is directly fed to the `cls` so you can consume the data while it's parsed. :param stream: a stream with the encoded querystring :param charset: the charset of the query string. If set to `None` no decoding will take place. :param include_empty: Set to `False` if you don't want empty values to appear in the dict. :param errors: the decoding error behavior. :param separator: the pair separator to be used, defaults to ``&`` :param cls: an optional dict class to use. If this is not specified or `None` the default :class:`MultiDict` is used. :param limit: the content length of the URL data. Not necessary if a limited stream is provided. .. versionchanged:: 2.0 The ``decode_keys`` and ``return_iterator`` parameters are deprecated and will be removed in Werkzeug 2.1. .. versionadded:: 0.8 """ from .wsgi import make_chunk_iter pair_iter = make_chunk_iter(stream, separator, limit) decoder = _url_decode_impl(pair_iter, charset, include_empty, errors) if cls is None: from .datastructures import MultiDict # noqa: F811 cls = MultiDict return cls(decoder)
Works like :func:`url_decode` but decodes a stream. The behavior of stream and limit follows functions like :func:`~werkzeug.wsgi.make_line_iter`. The generator of pairs is directly fed to the `cls` so you can consume the data while it's parsed. :param stream: a stream with the encoded querystring :param charset: the charset of the query string. If set to `None` no decoding will take place. :param include_empty: Set to `False` if you don't want empty values to appear in the dict. :param errors: the decoding error behavior. :param separator: the pair separator to be used, defaults to ``&`` :param cls: an optional dict class to use. If this is not specified or `None` the default :class:`MultiDict` is used. :param limit: the content length of the URL data. Not necessary if a limited stream is provided. .. versionchanged:: 2.0 The ``decode_keys`` and ``return_iterator`` parameters are deprecated and will be removed in Werkzeug 2.1. .. versionadded:: 0.8
172,402
import codecs import os import re import typing as t from ._internal import _check_str_tuple from ._internal import _decode_idna from ._internal import _encode_idna from ._internal import _make_encode_wrapper from ._internal import _to_str if t.TYPE_CHECKING: from . import datastructures as ds def _url_encode_impl( obj: t.Union[t.Mapping[str, str], t.Iterable[t.Tuple[str, str]]], charset: str, sort: bool, key: t.Optional[t.Callable[[t.Tuple[str, str]], t.Any]], ) -> t.Iterator[str]: from .datastructures import iter_multi_items iterable: t.Iterable[t.Tuple[str, str]] = iter_multi_items(obj) if sort: iterable = sorted(iterable, key=key) for key_str, value_str in iterable: if value_str is None: continue if not isinstance(key_str, bytes): key_bytes = str(key_str).encode(charset) else: key_bytes = key_str if not isinstance(value_str, bytes): value_bytes = str(value_str).encode(charset) else: value_bytes = value_str yield f"{_fast_url_quote_plus(key_bytes)}={_fast_url_quote_plus(value_bytes)}" def _to_str( # type: ignore x: None, charset: t.Optional[str] = ..., errors: str = ..., allow_none_charset: bool = ..., ) -> None: ... def _to_str( x: t.Any, charset: t.Optional[str] = ..., errors: str = ..., allow_none_charset: bool = ..., ) -> str: ... def _to_str( x: t.Optional[t.Any], charset: t.Optional[str] = _default_encoding, errors: str = "strict", allow_none_charset: bool = False, ) -> t.Optional[t.Union[str, bytes]]: if x is None or isinstance(x, str): return x if not isinstance(x, (bytes, bytearray)): return str(x) if charset is None: if allow_none_charset: return x return x.decode(charset, errors) # type: ignore The provided code snippet includes necessary dependencies for implementing the `url_encode` function. Write a Python function `def url_encode( obj: t.Union[t.Mapping[str, str], t.Iterable[t.Tuple[str, str]]], charset: str = "utf-8", sort: bool = False, key: t.Optional[t.Callable[[t.Tuple[str, str]], t.Any]] = None, separator: str = "&", ) -> str` to solve the following problem: URL encode a dict/`MultiDict`. If a value is `None` it will not appear in the result string. Per default only values are encoded into the target charset strings. :param obj: the object to encode into a query string. :param charset: the charset of the query string. :param sort: set to `True` if you want parameters to be sorted by `key`. :param separator: the separator to be used for the pairs. :param key: an optional function to be used for sorting. For more details check out the :func:`sorted` documentation. .. versionchanged:: 2.0 The ``encode_keys`` parameter is deprecated and will be removed in Werkzeug 2.1. .. versionchanged:: 0.5 Added the ``sort``, ``key``, and ``separator`` parameters. Here is the function: def url_encode( obj: t.Union[t.Mapping[str, str], t.Iterable[t.Tuple[str, str]]], charset: str = "utf-8", sort: bool = False, key: t.Optional[t.Callable[[t.Tuple[str, str]], t.Any]] = None, separator: str = "&", ) -> str: """URL encode a dict/`MultiDict`. If a value is `None` it will not appear in the result string. Per default only values are encoded into the target charset strings. :param obj: the object to encode into a query string. :param charset: the charset of the query string. :param sort: set to `True` if you want parameters to be sorted by `key`. :param separator: the separator to be used for the pairs. :param key: an optional function to be used for sorting. For more details check out the :func:`sorted` documentation. .. versionchanged:: 2.0 The ``encode_keys`` parameter is deprecated and will be removed in Werkzeug 2.1. .. versionchanged:: 0.5 Added the ``sort``, ``key``, and ``separator`` parameters. """ separator = _to_str(separator, "ascii") return separator.join(_url_encode_impl(obj, charset, sort, key))
URL encode a dict/`MultiDict`. If a value is `None` it will not appear in the result string. Per default only values are encoded into the target charset strings. :param obj: the object to encode into a query string. :param charset: the charset of the query string. :param sort: set to `True` if you want parameters to be sorted by `key`. :param separator: the separator to be used for the pairs. :param key: an optional function to be used for sorting. For more details check out the :func:`sorted` documentation. .. versionchanged:: 2.0 The ``encode_keys`` parameter is deprecated and will be removed in Werkzeug 2.1. .. versionchanged:: 0.5 Added the ``sort``, ``key``, and ``separator`` parameters.
172,403
import codecs import os import re import typing as t from ._internal import _check_str_tuple from ._internal import _decode_idna from ._internal import _encode_idna from ._internal import _make_encode_wrapper from ._internal import _to_str if t.TYPE_CHECKING: from . import datastructures as ds def _url_encode_impl( obj: t.Union[t.Mapping[str, str], t.Iterable[t.Tuple[str, str]]], charset: str, sort: bool, key: t.Optional[t.Callable[[t.Tuple[str, str]], t.Any]], ) -> t.Iterator[str]: from .datastructures import iter_multi_items iterable: t.Iterable[t.Tuple[str, str]] = iter_multi_items(obj) if sort: iterable = sorted(iterable, key=key) for key_str, value_str in iterable: if value_str is None: continue if not isinstance(key_str, bytes): key_bytes = str(key_str).encode(charset) else: key_bytes = key_str if not isinstance(value_str, bytes): value_bytes = str(value_str).encode(charset) else: value_bytes = value_str yield f"{_fast_url_quote_plus(key_bytes)}={_fast_url_quote_plus(value_bytes)}" def _to_str( # type: ignore x: None, charset: t.Optional[str] = ..., errors: str = ..., allow_none_charset: bool = ..., ) -> None: ... def _to_str( x: t.Any, charset: t.Optional[str] = ..., errors: str = ..., allow_none_charset: bool = ..., ) -> str: ... def _to_str( x: t.Optional[t.Any], charset: t.Optional[str] = _default_encoding, errors: str = "strict", allow_none_charset: bool = False, ) -> t.Optional[t.Union[str, bytes]]: if x is None or isinstance(x, str): return x if not isinstance(x, (bytes, bytearray)): return str(x) if charset is None: if allow_none_charset: return x return x.decode(charset, errors) # type: ignore The provided code snippet includes necessary dependencies for implementing the `url_encode_stream` function. Write a Python function `def url_encode_stream( obj: t.Union[t.Mapping[str, str], t.Iterable[t.Tuple[str, str]]], stream: t.Optional[t.IO[str]] = None, charset: str = "utf-8", sort: bool = False, key: t.Optional[t.Callable[[t.Tuple[str, str]], t.Any]] = None, separator: str = "&", ) -> None` to solve the following problem: Like :meth:`url_encode` but writes the results to a stream object. If the stream is `None` a generator over all encoded pairs is returned. :param obj: the object to encode into a query string. :param stream: a stream to write the encoded object into or `None` if an iterator over the encoded pairs should be returned. In that case the separator argument is ignored. :param charset: the charset of the query string. :param sort: set to `True` if you want parameters to be sorted by `key`. :param separator: the separator to be used for the pairs. :param key: an optional function to be used for sorting. For more details check out the :func:`sorted` documentation. .. versionchanged:: 2.0 The ``encode_keys`` parameter is deprecated and will be removed in Werkzeug 2.1. .. versionadded:: 0.8 Here is the function: def url_encode_stream( obj: t.Union[t.Mapping[str, str], t.Iterable[t.Tuple[str, str]]], stream: t.Optional[t.IO[str]] = None, charset: str = "utf-8", sort: bool = False, key: t.Optional[t.Callable[[t.Tuple[str, str]], t.Any]] = None, separator: str = "&", ) -> None: """Like :meth:`url_encode` but writes the results to a stream object. If the stream is `None` a generator over all encoded pairs is returned. :param obj: the object to encode into a query string. :param stream: a stream to write the encoded object into or `None` if an iterator over the encoded pairs should be returned. In that case the separator argument is ignored. :param charset: the charset of the query string. :param sort: set to `True` if you want parameters to be sorted by `key`. :param separator: the separator to be used for the pairs. :param key: an optional function to be used for sorting. For more details check out the :func:`sorted` documentation. .. versionchanged:: 2.0 The ``encode_keys`` parameter is deprecated and will be removed in Werkzeug 2.1. .. versionadded:: 0.8 """ separator = _to_str(separator, "ascii") gen = _url_encode_impl(obj, charset, sort, key) if stream is None: return gen # type: ignore for idx, chunk in enumerate(gen): if idx: stream.write(separator) stream.write(chunk) return None
Like :meth:`url_encode` but writes the results to a stream object. If the stream is `None` a generator over all encoded pairs is returned. :param obj: the object to encode into a query string. :param stream: a stream to write the encoded object into or `None` if an iterator over the encoded pairs should be returned. In that case the separator argument is ignored. :param charset: the charset of the query string. :param sort: set to `True` if you want parameters to be sorted by `key`. :param separator: the separator to be used for the pairs. :param key: an optional function to be used for sorting. For more details check out the :func:`sorted` documentation. .. versionchanged:: 2.0 The ``encode_keys`` parameter is deprecated and will be removed in Werkzeug 2.1. .. versionadded:: 0.8
172,404
import base64 import codecs import mimetypes import os import re from collections.abc import Collection from collections.abc import MutableSet from copy import deepcopy from io import BytesIO from itertools import repeat from os import fspath from . import exceptions from ._internal import _missing from . import http def is_immutable(self): raise TypeError(f"{type(self).__name__!r} objects are immutable")
null
172,405
import base64 import codecs import mimetypes import os import re from collections.abc import Collection from collections.abc import MutableSet from copy import deepcopy from io import BytesIO from itertools import repeat from os import fspath from . import exceptions from ._internal import _missing class UpdateDictMixin(dict): """Makes dicts call `self.on_update` on modifications. .. versionadded:: 0.5 :private: """ on_update = None def setdefault(self, key, default=None): modified = key not in self rv = super().setdefault(key, default) if modified and self.on_update is not None: self.on_update(self) return rv def pop(self, key, default=_missing): modified = key in self if default is _missing: rv = super().pop(key) else: rv = super().pop(key, default) if modified and self.on_update is not None: self.on_update(self) return rv __setitem__ = _calls_update("__setitem__") __delitem__ = _calls_update("__delitem__") clear = _calls_update("clear") popitem = _calls_update("popitem") update = _calls_update("update") from . import http def _calls_update(name): def oncall(self, *args, **kw): rv = getattr(super(UpdateDictMixin, self), name)(*args, **kw) if self.on_update is not None: self.on_update(self) return rv oncall.__name__ = name return oncall
null
172,406
import base64 import codecs import mimetypes import os import re from collections.abc import Collection from collections.abc import MutableSet from copy import deepcopy from io import BytesIO from itertools import repeat from os import fspath from . import exceptions from ._internal import _missing from . import http def _options_header_vkw(value, kw): return http.dump_options_header( value, {k.replace("_", "-"): v for k, v in kw.items()} )
null
172,407
import base64 import codecs import mimetypes import os import re from collections.abc import Collection from collections.abc import MutableSet from copy import deepcopy from io import BytesIO from itertools import repeat from os import fspath from . import exceptions from ._internal import _missing from . import http def _unicodify_header_value(value): if isinstance(value, bytes): value = value.decode("latin-1") if not isinstance(value, str): value = str(value) return value
null
172,408
import base64 import codecs import mimetypes import os import re from collections.abc import Collection from collections.abc import MutableSet from copy import deepcopy from io import BytesIO from itertools import repeat from os import fspath from . import exceptions from ._internal import _missing _mime_split_re = re.compile(r"/|(?:\s*;\s*)") from . import http def _normalize_mime(value): return _mime_split_re.split(value.lower())
null
172,409
import base64 import codecs import mimetypes import os import re from collections.abc import Collection from collections.abc import MutableSet from copy import deepcopy from io import BytesIO from itertools import repeat from os import fspath from . import exceptions from ._internal import _missing _locale_delim_re = re.compile(r"[_-]") from . import http The provided code snippet includes necessary dependencies for implementing the `_normalize_lang` function. Write a Python function `def _normalize_lang(value)` to solve the following problem: Process a language tag for matching. Here is the function: def _normalize_lang(value): """Process a language tag for matching.""" return _locale_delim_re.split(value.lower())
Process a language tag for matching.
172,410
import base64 import codecs import mimetypes import os import re from collections.abc import Collection from collections.abc import MutableSet from copy import deepcopy from io import BytesIO from itertools import repeat from os import fspath from . import exceptions from ._internal import _missing from . import http The provided code snippet includes necessary dependencies for implementing the `cache_control_property` function. Write a Python function `def cache_control_property(key, empty, type)` to solve the following problem: Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass. .. versionchanged:: 2.0 Renamed from ``cache_property``. Here is the function: def cache_control_property(key, empty, type): """Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass. .. versionchanged:: 2.0 Renamed from ``cache_property``. """ return property( lambda x: x._get_cache_value(key, empty, type), lambda x, v: x._set_cache_value(key, v, type), lambda x: x._del_cache_value(key), f"accessor for {key!r}", )
Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass. .. versionchanged:: 2.0 Renamed from ``cache_property``.
172,411
import base64 import codecs import mimetypes import os import re from collections.abc import Collection from collections.abc import MutableSet from copy import deepcopy from io import BytesIO from itertools import repeat from os import fspath from . import exceptions from ._internal import _missing from . import http The provided code snippet includes necessary dependencies for implementing the `csp_property` function. Write a Python function `def csp_property(key)` to solve the following problem: Return a new property object for a content security policy header. Useful if you want to add support for a csp extension in a subclass. Here is the function: def csp_property(key): """Return a new property object for a content security policy header. Useful if you want to add support for a csp extension in a subclass. """ return property( lambda x: x._get_value(key), lambda x, v: x._set_value(key, v), lambda x: x._del_value(key), f"accessor for {key!r}", )
Return a new property object for a content security policy header. Useful if you want to add support for a csp extension in a subclass.
172,412
import base64 import codecs import mimetypes import os import re from collections.abc import Collection from collections.abc import MutableSet from copy import deepcopy from io import BytesIO from itertools import repeat from os import fspath from . import exceptions from ._internal import _missing from . import http def _callback_property(name): def fget(self): return getattr(self, name) def fset(self, value): setattr(self, name, value) if self.on_update is not None: self.on_update(self) return property(fget, fset)
null
172,413
import base64 import codecs import mimetypes import os import re from collections.abc import Collection from collections.abc import MutableSet from copy import deepcopy from io import BytesIO from itertools import repeat from os import fspath from . import exceptions from ._internal import _missing from . import http The provided code snippet includes necessary dependencies for implementing the `auth_property` function. Write a Python function `def auth_property(name, doc=None)` to solve the following problem: A static helper function for Authentication subclasses to add extra authentication system properties onto a class:: class FooAuthenticate(WWWAuthenticate): special_realm = auth_property('special_realm') For more information have a look at the sourcecode to see how the regular properties (:attr:`realm` etc.) are implemented. Here is the function: def auth_property(name, doc=None): """A static helper function for Authentication subclasses to add extra authentication system properties onto a class:: class FooAuthenticate(WWWAuthenticate): special_realm = auth_property('special_realm') For more information have a look at the sourcecode to see how the regular properties (:attr:`realm` etc.) are implemented. """ def _set_value(self, value): if value is None: self.pop(name, None) else: self[name] = str(value) return property(lambda x: x.get(name), _set_value, doc=doc)
A static helper function for Authentication subclasses to add extra authentication system properties onto a class:: class FooAuthenticate(WWWAuthenticate): special_realm = auth_property('special_realm') For more information have a look at the sourcecode to see how the regular properties (:attr:`realm` etc.) are implemented.
172,414
import base64 import codecs import mimetypes import os import re from collections.abc import Collection from collections.abc import MutableSet from copy import deepcopy from io import BytesIO from itertools import repeat from os import fspath from . import exceptions from ._internal import _missing from . import http def _set_property(name, doc=None): def fget(self): def on_update(header_set): if not header_set and name in self: del self[name] elif header_set: self[name] = header_set.to_header() return http.parse_set_header(self.get(name), on_update) return property(fget, doc=doc)
null
172,415
import json import typing import typing as t import warnings from http import HTTPStatus from .._internal import _to_bytes from ..datastructures import Headers from ..http import remove_entity_headers from ..sansio.response import Response as _SansIOResponse from ..urls import iri_to_uri from ..urls import url_join from ..utils import cached_property from ..wsgi import ClosingIterator from ..wsgi import get_current_url from werkzeug._internal import _get_environ from werkzeug.http import generate_etag from werkzeug.http import http_date from werkzeug.http import is_resource_modified from werkzeug.http import parse_etags from werkzeug.http import parse_range_header from werkzeug.wsgi import _RangeWrapper if t.TYPE_CHECKING: import typing_extensions as te from _typeshed.wsgi import StartResponse from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment from .request import Request The provided code snippet includes necessary dependencies for implementing the `_warn_if_string` function. Write a Python function `def _warn_if_string(iterable: t.Iterable) -> None` to solve the following problem: Helper for the response objects to check if the iterable returned to the WSGI server is not a string. Here is the function: def _warn_if_string(iterable: t.Iterable) -> None: """Helper for the response objects to check if the iterable returned to the WSGI server is not a string. """ if isinstance(iterable, str): warnings.warn( "Response iterable was set to a string. This will appear to" " work but means that the server will send the data to the" " client one character at a time. This is almost never" " intended behavior, use 'response.data' to assign strings" " to the response object.", stacklevel=2, )
Helper for the response objects to check if the iterable returned to the WSGI server is not a string.
172,416
import json import typing import typing as t import warnings from http import HTTPStatus from .._internal import _to_bytes from ..datastructures import Headers from ..http import remove_entity_headers from ..sansio.response import Response as _SansIOResponse from ..urls import iri_to_uri from ..urls import url_join from ..utils import cached_property from ..wsgi import ClosingIterator from ..wsgi import get_current_url from werkzeug._internal import _get_environ from werkzeug.http import generate_etag from werkzeug.http import http_date from werkzeug.http import is_resource_modified from werkzeug.http import parse_etags from werkzeug.http import parse_range_header from werkzeug.wsgi import _RangeWrapper if t.TYPE_CHECKING: import typing_extensions as te from _typeshed.wsgi import StartResponse from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment from .request import Request def _iter_encoded( iterable: t.Iterable[t.Union[str, bytes]], charset: str ) -> t.Iterator[bytes]: for item in iterable: if isinstance(item, str): yield item.encode(charset) else: yield item
null
172,417
import json import typing import typing as t import warnings from http import HTTPStatus from .._internal import _to_bytes from ..datastructures import Headers from ..http import remove_entity_headers from ..sansio.response import Response as _SansIOResponse from ..urls import iri_to_uri from ..urls import url_join from ..utils import cached_property from ..wsgi import ClosingIterator from ..wsgi import get_current_url from werkzeug._internal import _get_environ from werkzeug.http import generate_etag from werkzeug.http import http_date from werkzeug.http import is_resource_modified from werkzeug.http import parse_etags from werkzeug.http import parse_range_header from werkzeug.wsgi import _RangeWrapper if t.TYPE_CHECKING: import typing_extensions as te from _typeshed.wsgi import StartResponse from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment from .request import Request def _clean_accept_ranges(accept_ranges: t.Union[bool, str]) -> str: if accept_ranges is True: return "bytes" elif accept_ranges is False: return "none" elif isinstance(accept_ranges, str): return accept_ranges raise ValueError("Invalid accept_ranges value")
null
172,418
import errno import io import os import socket import socketserver import sys import typing as t from datetime import datetime as dt from datetime import timedelta from datetime import timezone from http.server import BaseHTTPRequestHandler from http.server import HTTPServer from ._internal import _log from ._internal import _wsgi_encoding_dance from .exceptions import InternalServerError from .urls import uri_to_iri from .urls import url_parse from .urls import url_unquote if t.TYPE_CHECKING: import typing_extensions as te # noqa: F401 from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment from cryptography.hazmat.primitives.asymmetric.rsa import ( RSAPrivateKeyWithSerialization, ) from cryptography.x509 import Certificate def generate_adhoc_ssl_pair( cn: t.Optional[str] = None, ) -> t.Tuple["Certificate", "RSAPrivateKeyWithSerialization"]: try: from cryptography import x509 from cryptography.x509.oid import NameOID from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa except ImportError: raise TypeError( "Using ad-hoc certificates requires the cryptography library." ) from None backend = default_backend() pkey = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=backend ) # pretty damn sure that this is not actually accepted by anyone if cn is None: cn = "*" subject = x509.Name( [ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dummy Certificate"), x509.NameAttribute(NameOID.COMMON_NAME, cn), ] ) backend = default_backend() cert = ( x509.CertificateBuilder() .subject_name(subject) .issuer_name(subject) .public_key(pkey.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(dt.now(timezone.utc)) .not_valid_after(dt.now(timezone.utc) + timedelta(days=365)) .add_extension(x509.ExtendedKeyUsage([x509.OID_SERVER_AUTH]), critical=False) .add_extension(x509.SubjectAlternativeName([x509.DNSName(cn)]), critical=False) .sign(pkey, hashes.SHA256(), backend) ) return cert, pkey The provided code snippet includes necessary dependencies for implementing the `make_ssl_devcert` function. Write a Python function `def make_ssl_devcert( base_path: str, host: t.Optional[str] = None, cn: t.Optional[str] = None ) -> t.Tuple[str, str]` to solve the following problem: Creates an SSL key for development. This should be used instead of the ``'adhoc'`` key which generates a new cert on each server start. It accepts a path for where it should store the key and cert and either a host or CN. If a host is given it will use the CN ``*.host/CN=host``. For more information see :func:`run_simple`. .. versionadded:: 0.9 :param base_path: the path to the certificate and key. The extension ``.crt`` is added for the certificate, ``.key`` is added for the key. :param host: the name of the host. This can be used as an alternative for the `cn`. :param cn: the `CN` to use. Here is the function: def make_ssl_devcert( base_path: str, host: t.Optional[str] = None, cn: t.Optional[str] = None ) -> t.Tuple[str, str]: """Creates an SSL key for development. This should be used instead of the ``'adhoc'`` key which generates a new cert on each server start. It accepts a path for where it should store the key and cert and either a host or CN. If a host is given it will use the CN ``*.host/CN=host``. For more information see :func:`run_simple`. .. versionadded:: 0.9 :param base_path: the path to the certificate and key. The extension ``.crt`` is added for the certificate, ``.key`` is added for the key. :param host: the name of the host. This can be used as an alternative for the `cn`. :param cn: the `CN` to use. """ if host is not None: cn = f"*.{host}/CN={host}" cert, pkey = generate_adhoc_ssl_pair(cn=cn) from cryptography.hazmat.primitives import serialization cert_file = f"{base_path}.crt" pkey_file = f"{base_path}.key" with open(cert_file, "wb") as f: f.write(cert.public_bytes(serialization.Encoding.PEM)) with open(pkey_file, "wb") as f: f.write( pkey.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), ) ) return cert_file, pkey_file
Creates an SSL key for development. This should be used instead of the ``'adhoc'`` key which generates a new cert on each server start. It accepts a path for where it should store the key and cert and either a host or CN. If a host is given it will use the CN ``*.host/CN=host``. For more information see :func:`run_simple`. .. versionadded:: 0.9 :param base_path: the path to the certificate and key. The extension ``.crt`` is added for the certificate, ``.key`` is added for the key. :param host: the name of the host. This can be used as an alternative for the `cn`. :param cn: the `CN` to use.
172,419
import errno import io import os import socket import socketserver import sys import typing as t from datetime import datetime as dt from datetime import timedelta from datetime import timezone from http.server import BaseHTTPRequestHandler from http.server import HTTPServer from ._internal import _log from ._internal import _wsgi_encoding_dance from .exceptions import InternalServerError from .urls import uri_to_iri from .urls import url_parse from .urls import url_unquote if os.name == "nt": try: __import__("colorama") except ImportError: _log_add_style = False def generate_adhoc_ssl_pair( cn: t.Optional[str] = None, ) -> t.Tuple["Certificate", "RSAPrivateKeyWithSerialization"]: try: from cryptography import x509 from cryptography.x509.oid import NameOID from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa except ImportError: raise TypeError( "Using ad-hoc certificates requires the cryptography library." ) from None backend = default_backend() pkey = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=backend ) # pretty damn sure that this is not actually accepted by anyone if cn is None: cn = "*" subject = x509.Name( [ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dummy Certificate"), x509.NameAttribute(NameOID.COMMON_NAME, cn), ] ) backend = default_backend() cert = ( x509.CertificateBuilder() .subject_name(subject) .issuer_name(subject) .public_key(pkey.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(dt.now(timezone.utc)) .not_valid_after(dt.now(timezone.utc) + timedelta(days=365)) .add_extension(x509.ExtendedKeyUsage([x509.OID_SERVER_AUTH]), critical=False) .add_extension(x509.SubjectAlternativeName([x509.DNSName(cn)]), critical=False) .sign(pkey, hashes.SHA256(), backend) ) return cert, pkey def load_ssl_context( cert_file: str, pkey_file: t.Optional[str] = None, protocol: t.Optional[int] = None ) -> "ssl.SSLContext": """Loads SSL context from cert/private key files and optional protocol. Many parameters are directly taken from the API of :py:class:`ssl.SSLContext`. :param cert_file: Path of the certificate to use. :param pkey_file: Path of the private key to use. If not given, the key will be obtained from the certificate file. :param protocol: A ``PROTOCOL`` constant from the :mod:`ssl` module. Defaults to :data:`ssl.PROTOCOL_TLS_SERVER`. """ if protocol is None: protocol = ssl.PROTOCOL_TLS_SERVER ctx = ssl.SSLContext(protocol) ctx.load_cert_chain(cert_file, pkey_file) return ctx The provided code snippet includes necessary dependencies for implementing the `generate_adhoc_ssl_context` function. Write a Python function `def generate_adhoc_ssl_context() -> "ssl.SSLContext"` to solve the following problem: Generates an adhoc SSL context for the development server. Here is the function: def generate_adhoc_ssl_context() -> "ssl.SSLContext": """Generates an adhoc SSL context for the development server.""" import tempfile import atexit cert, pkey = generate_adhoc_ssl_pair() from cryptography.hazmat.primitives import serialization cert_handle, cert_file = tempfile.mkstemp() pkey_handle, pkey_file = tempfile.mkstemp() atexit.register(os.remove, pkey_file) atexit.register(os.remove, cert_file) os.write(cert_handle, cert.public_bytes(serialization.Encoding.PEM)) os.write( pkey_handle, pkey.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), ), ) os.close(cert_handle) os.close(pkey_handle) ctx = load_ssl_context(cert_file, pkey_file) return ctx
Generates an adhoc SSL context for the development server.
172,420
import errno import io import os import socket import socketserver import sys import typing as t from datetime import datetime as dt from datetime import timedelta from datetime import timezone from http.server import BaseHTTPRequestHandler from http.server import HTTPServer from ._internal import _log from ._internal import _wsgi_encoding_dance from .exceptions import InternalServerError from .urls import uri_to_iri from .urls import url_parse from .urls import url_unquote try: import ssl except ImportError: ssl = _SslDummy() # type: ignore if t.TYPE_CHECKING: import typing_extensions as te # noqa: F401 from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment from cryptography.hazmat.primitives.asymmetric.rsa import ( RSAPrivateKeyWithSerialization, ) from cryptography.x509 import Certificate The provided code snippet includes necessary dependencies for implementing the `is_ssl_error` function. Write a Python function `def is_ssl_error(error: t.Optional[Exception] = None) -> bool` to solve the following problem: Checks if the given error (or the current one) is an SSL error. Here is the function: def is_ssl_error(error: t.Optional[Exception] = None) -> bool: """Checks if the given error (or the current one) is an SSL error.""" if error is None: error = t.cast(Exception, sys.exc_info()[1]) return isinstance(error, ssl.SSLError)
Checks if the given error (or the current one) is an SSL error.
172,421
import errno import io import os import socket import socketserver import sys import typing as t from datetime import datetime as dt from datetime import timedelta from datetime import timezone from http.server import BaseHTTPRequestHandler from http.server import HTTPServer from ._internal import _log from ._internal import _wsgi_encoding_dance from .exceptions import InternalServerError from .urls import uri_to_iri from .urls import url_parse from .urls import url_unquote The provided code snippet includes necessary dependencies for implementing the `select_address_family` function. Write a Python function `def select_address_family(host: str, port: int) -> socket.AddressFamily` to solve the following problem: Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on the host and port. Here is the function: def select_address_family(host: str, port: int) -> socket.AddressFamily: """Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on the host and port.""" if host.startswith("unix://"): return socket.AF_UNIX elif ":" in host and hasattr(socket, "AF_INET6"): return socket.AF_INET6 return socket.AF_INET
Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on the host and port.
172,422
import errno import io import os import socket import socketserver import sys import typing as t from datetime import datetime as dt from datetime import timedelta from datetime import timezone from http.server import BaseHTTPRequestHandler from http.server import HTTPServer from ._internal import _log from ._internal import _wsgi_encoding_dance from .exceptions import InternalServerError from .urls import uri_to_iri from .urls import url_parse from .urls import url_unquote try: af_unix = socket.AF_UNIX except AttributeError: af_unix = None # type: ignore if t.TYPE_CHECKING: import typing_extensions as te # noqa: F401 from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment from cryptography.hazmat.primitives.asymmetric.rsa import ( RSAPrivateKeyWithSerialization, ) from cryptography.x509 import Certificate The provided code snippet includes necessary dependencies for implementing the `get_sockaddr` function. Write a Python function `def get_sockaddr( host: str, port: int, family: socket.AddressFamily ) -> t.Union[t.Tuple[str, int], str]` to solve the following problem: Return a fully qualified socket address that can be passed to :func:`socket.bind`. Here is the function: def get_sockaddr( host: str, port: int, family: socket.AddressFamily ) -> t.Union[t.Tuple[str, int], str]: """Return a fully qualified socket address that can be passed to :func:`socket.bind`.""" if family == af_unix: return host.split("://", 1)[1] try: res = socket.getaddrinfo( host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP ) except socket.gaierror: return host, port return res[0][4] # type: ignore
Return a fully qualified socket address that can be passed to :func:`socket.bind`.
172,423
import errno import io import os import socket import socketserver import sys import typing as t from datetime import datetime as dt from datetime import timedelta from datetime import timezone from http.server import BaseHTTPRequestHandler from http.server import HTTPServer from ._internal import _log from ._internal import _wsgi_encoding_dance from .exceptions import InternalServerError from .urls import uri_to_iri from .urls import url_parse from .urls import url_unquote The provided code snippet includes necessary dependencies for implementing the `get_interface_ip` function. Write a Python function `def get_interface_ip(family: socket.AddressFamily) -> str` to solve the following problem: Get the IP address of an external interface. Used when binding to 0.0.0.0 or ::1 to show a more useful URL. :meta private: Here is the function: def get_interface_ip(family: socket.AddressFamily) -> str: """Get the IP address of an external interface. Used when binding to 0.0.0.0 or ::1 to show a more useful URL. :meta private: """ # arbitrary private address host = "fd31:f903:5ab5:1::1" if family == socket.AF_INET6 else "10.253.155.219" with socket.socket(family, socket.SOCK_DGRAM) as s: try: s.connect((host, 58162)) except OSError: return "::1" if family == socket.AF_INET6 else "127.0.0.1" return s.getsockname()[0] # type: ignore
Get the IP address of an external interface. Used when binding to 0.0.0.0 or ::1 to show a more useful URL. :meta private:
172,424
import typing as t from datetime import datetime from markupsafe import escape from markupsafe import Markup from ._internal import _get_environ class HTTPException(Exception): """The base class for all HTTP exceptions. This exception can be called as a WSGI application to render a default error page or you can catch the subclasses of it independently and render nicer error messages. .. versionchanged:: 2.1 Removed the ``wrap`` class method. """ code: t.Optional[int] = None description: t.Optional[str] = None def __init__( self, description: t.Optional[str] = None, response: t.Optional["Response"] = None, ) -> None: super().__init__() if description is not None: self.description = description self.response = response def name(self) -> str: """The status name.""" from .http import HTTP_STATUS_CODES return HTTP_STATUS_CODES.get(self.code, "Unknown Error") # type: ignore def get_description( self, environ: t.Optional["WSGIEnvironment"] = None, scope: t.Optional[dict] = None, ) -> str: """Get the description.""" if self.description is None: description = "" elif not isinstance(self.description, str): description = str(self.description) else: description = self.description description = escape(description).replace("\n", Markup("<br>")) return f"<p>{description}</p>" def get_body( self, environ: t.Optional["WSGIEnvironment"] = None, scope: t.Optional[dict] = None, ) -> str: """Get the HTML body.""" return ( "<!doctype html>\n" "<html lang=en>\n" f"<title>{self.code} {escape(self.name)}</title>\n" f"<h1>{escape(self.name)}</h1>\n" f"{self.get_description(environ)}\n" ) def get_headers( self, environ: t.Optional["WSGIEnvironment"] = None, scope: t.Optional[dict] = None, ) -> t.List[t.Tuple[str, str]]: """Get a list of headers.""" return [("Content-Type", "text/html; charset=utf-8")] def get_response( self, environ: t.Optional[t.Union["WSGIEnvironment", "WSGIRequest"]] = None, scope: t.Optional[dict] = None, ) -> "Response": """Get a response object. If one was passed to the exception it's returned directly. :param environ: the optional environ for the request. This can be used to modify the response depending on how the request looked like. :return: a :class:`Response` object or a subclass thereof. """ from .wrappers.response import Response as WSGIResponse # noqa: F811 if self.response is not None: return self.response if environ is not None: environ = _get_environ(environ) headers = self.get_headers(environ, scope) return WSGIResponse(self.get_body(environ, scope), self.code, headers) def __call__( self, environ: "WSGIEnvironment", start_response: "StartResponse" ) -> t.Iterable[bytes]: """Call the exception as WSGI application. :param environ: the WSGI environment. :param start_response: the response callable provided by the WSGI server. """ response = t.cast("WSGIResponse", self.get_response(environ)) return response(environ, start_response) def __str__(self) -> str: code = self.code if self.code is not None else "???" return f"{code} {self.name}: {self.description}" def __repr__(self) -> str: code = self.code if self.code is not None else "???" return f"<{type(self).__name__} '{code}: {self.name}'>" default_exceptions: t.Dict[int, t.Type[HTTPException]] = {} def _find_exceptions() -> None: for obj in globals().values(): try: is_http_exception = issubclass(obj, HTTPException) except TypeError: is_http_exception = False if not is_http_exception or obj.code is None: continue old_obj = default_exceptions.get(obj.code, None) if old_obj is not None and issubclass(obj, old_obj): continue default_exceptions[obj.code] = obj
null
172,425
import typing as t from datetime import datetime from markupsafe import escape from markupsafe import Markup from ._internal import _get_environ if t.TYPE_CHECKING: import typing_extensions as te from _typeshed.wsgi import StartResponse from _typeshed.wsgi import WSGIEnvironment from .datastructures import WWWAuthenticate from .sansio.response import Response from .wrappers.request import Request as WSGIRequest # noqa: F401 from .wrappers.response import Response as WSGIResponse # noqa: F401 _aborter: Aborter = Aborter() The provided code snippet includes necessary dependencies for implementing the `abort` function. Write a Python function `def abort( status: t.Union[int, "Response"], *args: t.Any, **kwargs: t.Any ) -> "te.NoReturn"` to solve the following problem: Raises an :py:exc:`HTTPException` for the given status code or WSGI application. If a status code is given, it will be looked up in the list of exceptions and will raise that exception. If passed a WSGI application, it will wrap it in a proxy WSGI exception and raise that:: abort(404) # 404 Not Found abort(Response('Hello World')) Here is the function: def abort( status: t.Union[int, "Response"], *args: t.Any, **kwargs: t.Any ) -> "te.NoReturn": """Raises an :py:exc:`HTTPException` for the given status code or WSGI application. If a status code is given, it will be looked up in the list of exceptions and will raise that exception. If passed a WSGI application, it will wrap it in a proxy WSGI exception and raise that:: abort(404) # 404 Not Found abort(Response('Hello World')) """ _aborter(status, *args, **kwargs)
Raises an :py:exc:`HTTPException` for the given status code or WSGI application. If a status code is given, it will be looked up in the list of exceptions and will raise that exception. If passed a WSGI application, it will wrap it in a proxy WSGI exception and raise that:: abort(404) # 404 Not Found abort(Response('Hello World'))
172,426
import ast import re import typing as t from dataclasses import dataclass from string import Template from types import CodeType from .._internal import _to_bytes from ..urls import url_encode from ..urls import url_quote from .converters import ValidationError The provided code snippet includes necessary dependencies for implementing the `_find` function. Write a Python function `def _find(value: str, target: str, pos: int) -> int` to solve the following problem: Find the *target* in *value* after *pos*. Returns the *value* length if *target* isn't found. Here is the function: def _find(value: str, target: str, pos: int) -> int: """Find the *target* in *value* after *pos*. Returns the *value* length if *target* isn't found. """ try: return value.index(target, pos) except ValueError: return len(value)
Find the *target* in *value* after *pos*. Returns the *value* length if *target* isn't found.
172,427
import ast import re import typing as t from dataclasses import dataclass from string import Template from types import CodeType from .._internal import _to_bytes from ..urls import url_encode from ..urls import url_quote from .converters import ValidationError if t.TYPE_CHECKING: from .converters import BaseConverter from .map import Map _converter_args_re = re.compile( r""" ((?P<name>\w+)\s*=\s*)? (?P<value> True|False| \d+.\d+| \d+.| \d+| [\w\d_.]+| [urUR]?(?P<stringval>"[^"]*?"|'[^']*') )\s*, """, re.VERBOSE, ) def _pythonize(value: str) -> t.Union[None, bool, int, float, str]: def parse_converter_args(argstr: str) -> t.Tuple[t.Tuple, t.Dict[str, t.Any]]: argstr += "," args = [] kwargs = {} for item in _converter_args_re.finditer(argstr): value = item.group("stringval") if value is None: value = item.group("value") value = _pythonize(value) if not item.group("name"): args.append(value) else: name = item.group("name") kwargs[name] = value return tuple(args), kwargs
null
172,428
import ast import re import typing as t from dataclasses import dataclass from string import Template from types import CodeType from .._internal import _to_bytes from ..urls import url_encode from ..urls import url_quote from .converters import ValidationError The provided code snippet includes necessary dependencies for implementing the `_prefix_names` function. Write a Python function `def _prefix_names(src: str) -> ast.stmt` to solve the following problem: ast parse and prefix names with `.` to avoid collision with user vars Here is the function: def _prefix_names(src: str) -> ast.stmt: """ast parse and prefix names with `.` to avoid collision with user vars""" tree = ast.parse(src).body[0] if isinstance(tree, ast.Expr): tree = tree.value # type: ignore for node in ast.walk(tree): if isinstance(node, ast.Name): node.id = f".{node.id}" return tree
ast parse and prefix names with `.` to avoid collision with user vars
172,429
import hashlib import hmac import os import posixpath import secrets import typing as t def gen_salt(length: int) -> str: """Generate a random string of SALT_CHARS with specified ``length``.""" if length <= 0: raise ValueError("Salt length must be positive") return "".join(secrets.choice(SALT_CHARS) for _ in range(length)) def _hash_internal(method: str, salt: str, password: str) -> t.Tuple[str, str]: """Internal password hash helper. Supports plaintext without salt, unsalted and salted passwords. In case salted passwords are used hmac is used. """ if method == "plain": return password, method salt = salt.encode("utf-8") password = password.encode("utf-8") if method.startswith("pbkdf2:"): if not salt: raise ValueError("Salt is required for PBKDF2") args = method[7:].split(":") if len(args) not in (1, 2): raise ValueError("Invalid number of arguments for PBKDF2") method = args.pop(0) iterations = int(args[0] or 0) if args else DEFAULT_PBKDF2_ITERATIONS return ( hashlib.pbkdf2_hmac(method, password, salt, iterations).hex(), f"pbkdf2:{method}:{iterations}", ) if salt: return hmac.new(salt, password, method).hexdigest(), method return hashlib.new(method, password).hexdigest(), method The provided code snippet includes necessary dependencies for implementing the `generate_password_hash` function. Write a Python function `def generate_password_hash( password: str, method: str = "pbkdf2:sha256", salt_length: int = 16 ) -> str` to solve the following problem: Hash a password with the given method and salt with a string of the given length. The format of the string returned includes the method that was used so that :func:`check_password_hash` can check the hash. The format for the hashed string looks like this:: method$salt$hash This method can **not** generate unsalted passwords but it is possible to set param method='plain' in order to enforce plaintext passwords. If a salt is used, hmac is used internally to salt the password. If PBKDF2 is wanted it can be enabled by setting the method to ``pbkdf2:method:iterations`` where iterations is optional:: pbkdf2:sha256:80000$salt$hash pbkdf2:sha256$salt$hash :param password: the password to hash. :param method: the hash method to use (one that hashlib supports). Can optionally be in the format ``pbkdf2:method:iterations`` to enable PBKDF2. :param salt_length: the length of the salt in letters. Here is the function: def generate_password_hash( password: str, method: str = "pbkdf2:sha256", salt_length: int = 16 ) -> str: """Hash a password with the given method and salt with a string of the given length. The format of the string returned includes the method that was used so that :func:`check_password_hash` can check the hash. The format for the hashed string looks like this:: method$salt$hash This method can **not** generate unsalted passwords but it is possible to set param method='plain' in order to enforce plaintext passwords. If a salt is used, hmac is used internally to salt the password. If PBKDF2 is wanted it can be enabled by setting the method to ``pbkdf2:method:iterations`` where iterations is optional:: pbkdf2:sha256:80000$salt$hash pbkdf2:sha256$salt$hash :param password: the password to hash. :param method: the hash method to use (one that hashlib supports). Can optionally be in the format ``pbkdf2:method:iterations`` to enable PBKDF2. :param salt_length: the length of the salt in letters. """ salt = gen_salt(salt_length) if method != "plain" else "" h, actual_method = _hash_internal(method, salt, password) return f"{actual_method}${salt}${h}"
Hash a password with the given method and salt with a string of the given length. The format of the string returned includes the method that was used so that :func:`check_password_hash` can check the hash. The format for the hashed string looks like this:: method$salt$hash This method can **not** generate unsalted passwords but it is possible to set param method='plain' in order to enforce plaintext passwords. If a salt is used, hmac is used internally to salt the password. If PBKDF2 is wanted it can be enabled by setting the method to ``pbkdf2:method:iterations`` where iterations is optional:: pbkdf2:sha256:80000$salt$hash pbkdf2:sha256$salt$hash :param password: the password to hash. :param method: the hash method to use (one that hashlib supports). Can optionally be in the format ``pbkdf2:method:iterations`` to enable PBKDF2. :param salt_length: the length of the salt in letters.
172,430
import hashlib import hmac import os import posixpath import secrets import typing as t def _hash_internal(method: str, salt: str, password: str) -> t.Tuple[str, str]: """Internal password hash helper. Supports plaintext without salt, unsalted and salted passwords. In case salted passwords are used hmac is used. """ if method == "plain": return password, method salt = salt.encode("utf-8") password = password.encode("utf-8") if method.startswith("pbkdf2:"): if not salt: raise ValueError("Salt is required for PBKDF2") args = method[7:].split(":") if len(args) not in (1, 2): raise ValueError("Invalid number of arguments for PBKDF2") method = args.pop(0) iterations = int(args[0] or 0) if args else DEFAULT_PBKDF2_ITERATIONS return ( hashlib.pbkdf2_hmac(method, password, salt, iterations).hex(), f"pbkdf2:{method}:{iterations}", ) if salt: return hmac.new(salt, password, method).hexdigest(), method return hashlib.new(method, password).hexdigest(), method The provided code snippet includes necessary dependencies for implementing the `check_password_hash` function. Write a Python function `def check_password_hash(pwhash: str, password: str) -> bool` to solve the following problem: Check a password against a given salted and hashed password value. In order to support unsalted legacy passwords this method supports plain text passwords, md5 and sha1 hashes (both salted and unsalted). Returns `True` if the password matched, `False` otherwise. :param pwhash: a hashed string like returned by :func:`generate_password_hash`. :param password: the plaintext password to compare against the hash. Here is the function: def check_password_hash(pwhash: str, password: str) -> bool: """Check a password against a given salted and hashed password value. In order to support unsalted legacy passwords this method supports plain text passwords, md5 and sha1 hashes (both salted and unsalted). Returns `True` if the password matched, `False` otherwise. :param pwhash: a hashed string like returned by :func:`generate_password_hash`. :param password: the plaintext password to compare against the hash. """ if pwhash.count("$") < 2: return False method, salt, hashval = pwhash.split("$", 2) return hmac.compare_digest(_hash_internal(method, salt, password)[0], hashval)
Check a password against a given salted and hashed password value. In order to support unsalted legacy passwords this method supports plain text passwords, md5 and sha1 hashes (both salted and unsalted). Returns `True` if the password matched, `False` otherwise. :param pwhash: a hashed string like returned by :func:`generate_password_hash`. :param password: the plaintext password to compare against the hash.
172,431
import typing as t from datetime import datetime from datetime import timedelta from datetime import timezone from http import HTTPStatus from .._internal import _to_str from ..datastructures import Headers from ..datastructures import HeaderSet from ..http import dump_cookie from ..http import HTTP_STATUS_CODES from ..utils import get_content_type from werkzeug.datastructures import CallbackDict from werkzeug.datastructures import ContentRange from werkzeug.datastructures import ContentSecurityPolicy from werkzeug.datastructures import ResponseCacheControl from werkzeug.datastructures import WWWAuthenticate from werkzeug.http import COEP from werkzeug.http import COOP from werkzeug.http import dump_age from werkzeug.http import dump_header from werkzeug.http import dump_options_header from werkzeug.http import http_date from werkzeug.http import parse_age from werkzeug.http import parse_cache_control_header from werkzeug.http import parse_content_range_header from werkzeug.http import parse_csp_header from werkzeug.http import parse_date from werkzeug.http import parse_options_header from werkzeug.http import parse_set_header from werkzeug.http import parse_www_authenticate_header from werkzeug.http import quote_etag from werkzeug.http import unquote_etag from werkzeug.utils import header_property class HeaderSet(MutableSet): """Similar to the :class:`ETags` class this implements a set-like structure. Unlike :class:`ETags` this is case insensitive and used for vary, allow, and content-language headers. If not constructed using the :func:`parse_set_header` function the instantiation works like this: >>> hs = HeaderSet(['foo', 'bar', 'baz']) >>> hs HeaderSet(['foo', 'bar', 'baz']) """ def __init__(self, headers=None, on_update=None): self._headers = list(headers or ()) self._set = {x.lower() for x in self._headers} self.on_update = on_update def add(self, header): """Add a new header to the set.""" self.update((header,)) def remove(self, header): """Remove a header from the set. This raises an :exc:`KeyError` if the header is not in the set. .. versionchanged:: 0.5 In older versions a :exc:`IndexError` was raised instead of a :exc:`KeyError` if the object was missing. :param header: the header to be removed. """ key = header.lower() if key not in self._set: raise KeyError(header) self._set.remove(key) for idx, key in enumerate(self._headers): if key.lower() == header: del self._headers[idx] break if self.on_update is not None: self.on_update(self) def update(self, iterable): """Add all the headers from the iterable to the set. :param iterable: updates the set with the items from the iterable. """ inserted_any = False for header in iterable: key = header.lower() if key not in self._set: self._headers.append(header) self._set.add(key) inserted_any = True if inserted_any and self.on_update is not None: self.on_update(self) def discard(self, header): """Like :meth:`remove` but ignores errors. :param header: the header to be discarded. """ try: self.remove(header) except KeyError: pass def find(self, header): """Return the index of the header in the set or return -1 if not found. :param header: the header to be looked up. """ header = header.lower() for idx, item in enumerate(self._headers): if item.lower() == header: return idx return -1 def index(self, header): """Return the index of the header in the set or raise an :exc:`IndexError`. :param header: the header to be looked up. """ rv = self.find(header) if rv < 0: raise IndexError(header) return rv def clear(self): """Clear the set.""" self._set.clear() del self._headers[:] if self.on_update is not None: self.on_update(self) def as_set(self, preserve_casing=False): """Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost. :param preserve_casing: if set to `True` the items in the set returned will have the original case like in the :class:`HeaderSet`, otherwise they will be lowercase. """ if preserve_casing: return set(self._headers) return set(self._set) def to_header(self): """Convert the header set into an HTTP header string.""" return ", ".join(map(http.quote_header_value, self._headers)) def __getitem__(self, idx): return self._headers[idx] def __delitem__(self, idx): rv = self._headers.pop(idx) self._set.remove(rv.lower()) if self.on_update is not None: self.on_update(self) def __setitem__(self, idx, value): old = self._headers[idx] self._set.remove(old.lower()) self._headers[idx] = value self._set.add(value.lower()) if self.on_update is not None: self.on_update(self) def __contains__(self, header): return header.lower() in self._set def __len__(self): return len(self._set) def __iter__(self): return iter(self._headers) def __bool__(self): return bool(self._set) def __str__(self): return self.to_header() def __repr__(self): return f"{type(self).__name__}({self._headers!r})" def dump_header( iterable: t.Union[t.Dict[str, t.Union[str, int]], t.Iterable[str]], allow_token: bool = True, ) -> str: """Dump an HTTP header again. This is the reversal of :func:`parse_list_header`, :func:`parse_set_header` and :func:`parse_dict_header`. This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs. >>> dump_header({'foo': 'bar baz'}) 'foo="bar baz"' >>> dump_header(('foo', 'bar baz')) 'foo, "bar baz"' :param iterable: the iterable or dict of values to quote. :param allow_token: if set to `False` tokens as values are disallowed. See :func:`quote_header_value` for more details. """ if isinstance(iterable, dict): items = [] for key, value in iterable.items(): if value is None: items.append(key) elif _is_extended_parameter(key): items.append(f"{key}={value}") else: items.append( f"{key}={quote_header_value(value, allow_token=allow_token)}" ) else: items = [quote_header_value(x, allow_token=allow_token) for x in iterable] return ", ".join(items) def parse_set_header( value: t.Optional[str], on_update: t.Optional[t.Callable[["ds.HeaderSet"], None]] = None, ) -> "ds.HeaderSet": """Parse a set-like header and return a :class:`~werkzeug.datastructures.HeaderSet` object: >>> hs = parse_set_header('token, "quoted value"') The return value is an object that treats the items case-insensitively and keeps the order of the items: >>> 'TOKEN' in hs True >>> hs.index('quoted value') 1 >>> hs HeaderSet(['token', 'quoted value']) To create a header from the :class:`HeaderSet` again, use the :func:`dump_header` function. :param value: a set header to be parsed. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.HeaderSet` object is changed. :return: a :class:`~werkzeug.datastructures.HeaderSet` """ if not value: return ds.HeaderSet(None, on_update) return ds.HeaderSet(parse_list_header(value), on_update) def _set_property(name: str, doc: t.Optional[str] = None) -> property: def fget(self: "Response") -> HeaderSet: def on_update(header_set: HeaderSet) -> None: if not header_set and name in self.headers: del self.headers[name] elif header_set: self.headers[name] = header_set.to_header() return parse_set_header(self.headers.get(name), on_update) def fset( self: "Response", value: t.Optional[ t.Union[str, t.Dict[str, t.Union[str, int]], t.Iterable[str]] ], ) -> None: if not value: del self.headers[name] elif isinstance(value, str): self.headers[name] = value else: self.headers[name] = dump_header(value) return property(fget, fset, doc=doc)
null
172,432
import re import typing as t from datetime import datetime from .._internal import _cookie_parse_impl from .._internal import _dt_as_utc from .._internal import _to_str from ..http import generate_etag from ..http import parse_date from ..http import parse_etags from ..http import parse_if_range_header from ..http import unquote_etag from .. import datastructures as ds class datetime(date): min: ClassVar[datetime] max: ClassVar[datetime] resolution: ClassVar[timedelta] if sys.version_info >= (3, 6): def __new__( cls: Type[_S], year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ..., ) -> _S: ... else: def __new__( cls: Type[_S], year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> _S: ... def year(self) -> int: ... def month(self) -> int: ... def day(self) -> int: ... def hour(self) -> int: ... def minute(self) -> int: ... def second(self) -> int: ... def microsecond(self) -> int: ... def tzinfo(self) -> Optional[_tzinfo]: ... if sys.version_info >= (3, 6): def fold(self) -> int: ... def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S: ... def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ... def today(cls: Type[_S]) -> _S: ... def fromordinal(cls: Type[_S], n: int) -> _S: ... if sys.version_info >= (3, 8): def now(cls: Type[_S], tz: Optional[_tzinfo] = ...) -> _S: ... else: def now(cls: Type[_S], tz: None = ...) -> _S: ... def now(cls, tz: _tzinfo) -> datetime: ... def utcnow(cls: Type[_S]) -> _S: ... if sys.version_info >= (3, 6): def combine(cls, date: _date, time: _time, tzinfo: Optional[_tzinfo] = ...) -> datetime: ... else: def combine(cls, date: _date, time: _time) -> datetime: ... if sys.version_info >= (3, 7): def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... def strftime(self, fmt: _Text) -> str: ... if sys.version_info >= (3,): def __format__(self, fmt: str) -> str: ... else: def __format__(self, fmt: AnyStr) -> AnyStr: ... def toordinal(self) -> int: ... def timetuple(self) -> struct_time: ... if sys.version_info >= (3, 3): def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _date: ... def time(self) -> _time: ... def timetz(self) -> _time: ... if sys.version_info >= (3, 6): def replace( self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ..., ) -> datetime: ... else: def replace( self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> datetime: ... if sys.version_info >= (3, 8): def astimezone(self: _S, tz: Optional[_tzinfo] = ...) -> _S: ... elif sys.version_info >= (3, 3): def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ... else: def astimezone(self, tz: _tzinfo) -> datetime: ... def ctime(self) -> str: ... if sys.version_info >= (3, 6): def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... else: def isoformat(self, sep: str = ...) -> str: ... def strptime(cls, date_string: _Text, format: _Text) -> datetime: ... def utcoffset(self) -> Optional[timedelta]: ... def tzname(self) -> Optional[str]: ... def dst(self) -> Optional[timedelta]: ... def __le__(self, other: datetime) -> bool: ... # type: ignore def __lt__(self, other: datetime) -> bool: ... # type: ignore def __ge__(self, other: datetime) -> bool: ... # type: ignore def __gt__(self, other: datetime) -> bool: ... # type: ignore if sys.version_info >= (3, 8): def __add__(self: _S, other: timedelta) -> _S: ... def __radd__(self: _S, other: timedelta) -> _S: ... else: def __add__(self, other: timedelta) -> datetime: ... def __radd__(self, other: timedelta) -> datetime: ... def __sub__(self, other: datetime) -> timedelta: ... def __sub__(self, other: timedelta) -> datetime: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... def isocalendar(self) -> Tuple[int, int, int]: ... def _dt_as_utc(dt: None) -> None: ... def _dt_as_utc(dt: datetime) -> datetime: ... def _dt_as_utc(dt: t.Optional[datetime]) -> t.Optional[datetime]: if dt is None: return dt if dt.tzinfo is None: return dt.replace(tzinfo=timezone.utc) elif dt.tzinfo != timezone.utc: return dt.astimezone(timezone.utc) return dt def parse_if_range_header(value: t.Optional[str]) -> "ds.IfRange": """Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object. .. versionchanged:: 2.0 If the value represents a datetime, it is timezone-aware. .. versionadded:: 0.7 """ if not value: return ds.IfRange() date = parse_date(value) if date is not None: return ds.IfRange(date=date) # drop weakness information return ds.IfRange(unquote_etag(value)[0]) def unquote_etag( etag: t.Optional[str], ) -> t.Union[t.Tuple[str, bool], t.Tuple[None, None]]: """Unquote a single etag: >>> unquote_etag('W/"bar"') ('bar', True) >>> unquote_etag('"bar"') ('bar', False) :param etag: the etag identifier to unquote. :return: a ``(etag, weak)`` tuple. """ if not etag: return None, None etag = etag.strip() weak = False if etag.startswith(("W/", "w/")): weak = True etag = etag[2:] if etag[:1] == etag[-1:] == '"': etag = etag[1:-1] return etag, weak def parse_etags(value: t.Optional[str]) -> "ds.ETags": """Parse an etag header. :param value: the tag header to parse :return: an :class:`~werkzeug.datastructures.ETags` object. """ if not value: return ds.ETags() strong = [] weak = [] end = len(value) pos = 0 while pos < end: match = _etag_re.match(value, pos) if match is None: break is_weak, quoted, raw = match.groups() if raw == "*": return ds.ETags(star_tag=True) elif quoted: raw = quoted if is_weak: weak.append(raw) else: strong.append(raw) pos = match.end() return ds.ETags(strong, weak) def generate_etag(data: bytes) -> str: """Generate an etag for some data. .. versionchanged:: 2.0 Use SHA-1. MD5 may not be available in some environments. """ return sha1(data).hexdigest() def parse_date(value: t.Optional[str]) -> t.Optional[datetime]: """Parse an :rfc:`2822` date into a timezone-aware :class:`datetime.datetime` object, or ``None`` if parsing fails. This is a wrapper for :func:`email.utils.parsedate_to_datetime`. It returns ``None`` if parsing fails instead of raising an exception, and always returns a timezone-aware datetime object. If the string doesn't have timezone information, it is assumed to be UTC. :param value: A string with a supported date format. .. versionchanged:: 2.0 Return a timezone-aware datetime object. Use ``email.utils.parsedate_to_datetime``. """ if value is None: return None try: dt = email.utils.parsedate_to_datetime(value) except (TypeError, ValueError): return None if dt.tzinfo is None: return dt.replace(tzinfo=timezone.utc) return dt The provided code snippet includes necessary dependencies for implementing the `is_resource_modified` function. Write a Python function `def is_resource_modified( http_range: t.Optional[str] = None, http_if_range: t.Optional[str] = None, http_if_modified_since: t.Optional[str] = None, http_if_none_match: t.Optional[str] = None, http_if_match: t.Optional[str] = None, etag: t.Optional[str] = None, data: t.Optional[bytes] = None, last_modified: t.Optional[t.Union[datetime, str]] = None, ignore_if_range: bool = True, ) -> bool` to solve the following problem: Convenience method for conditional requests. :param http_range: Range HTTP header :param http_if_range: If-Range HTTP header :param http_if_modified_since: If-Modified-Since HTTP header :param http_if_none_match: If-None-Match HTTP header :param http_if_match: If-Match HTTP header :param etag: the etag for the response for comparison. :param data: or alternatively the data of the response to automatically generate an etag using :func:`generate_etag`. :param last_modified: an optional date of the last modification. :param ignore_if_range: If `False`, `If-Range` header will be taken into account. :return: `True` if the resource was modified, otherwise `False`. .. versionadded:: 2.2 Here is the function: def is_resource_modified( http_range: t.Optional[str] = None, http_if_range: t.Optional[str] = None, http_if_modified_since: t.Optional[str] = None, http_if_none_match: t.Optional[str] = None, http_if_match: t.Optional[str] = None, etag: t.Optional[str] = None, data: t.Optional[bytes] = None, last_modified: t.Optional[t.Union[datetime, str]] = None, ignore_if_range: bool = True, ) -> bool: """Convenience method for conditional requests. :param http_range: Range HTTP header :param http_if_range: If-Range HTTP header :param http_if_modified_since: If-Modified-Since HTTP header :param http_if_none_match: If-None-Match HTTP header :param http_if_match: If-Match HTTP header :param etag: the etag for the response for comparison. :param data: or alternatively the data of the response to automatically generate an etag using :func:`generate_etag`. :param last_modified: an optional date of the last modification. :param ignore_if_range: If `False`, `If-Range` header will be taken into account. :return: `True` if the resource was modified, otherwise `False`. .. versionadded:: 2.2 """ if etag is None and data is not None: etag = generate_etag(data) elif data is not None: raise TypeError("both data and etag given") unmodified = False if isinstance(last_modified, str): last_modified = parse_date(last_modified) # HTTP doesn't use microsecond, remove it to avoid false positive # comparisons. Mark naive datetimes as UTC. if last_modified is not None: last_modified = _dt_as_utc(last_modified.replace(microsecond=0)) if_range = None if not ignore_if_range and http_range is not None: # https://tools.ietf.org/html/rfc7233#section-3.2 # A server MUST ignore an If-Range header field received in a request # that does not contain a Range header field. if_range = parse_if_range_header(http_if_range) if if_range is not None and if_range.date is not None: modified_since: t.Optional[datetime] = if_range.date else: modified_since = parse_date(http_if_modified_since) if modified_since and last_modified and last_modified <= modified_since: unmodified = True if etag: etag, _ = unquote_etag(etag) etag = t.cast(str, etag) if if_range is not None and if_range.etag is not None: unmodified = parse_etags(if_range.etag).contains(etag) else: if_none_match = parse_etags(http_if_none_match) if if_none_match: # https://tools.ietf.org/html/rfc7232#section-3.2 # "A recipient MUST use the weak comparison function when comparing # entity-tags for If-None-Match" unmodified = if_none_match.contains_weak(etag) # https://tools.ietf.org/html/rfc7232#section-3.1 # "Origin server MUST use the strong comparison function when # comparing entity-tags for If-Match" if_match = parse_etags(http_if_match) if if_match: unmodified = not if_match.is_strong(etag) return not unmodified
Convenience method for conditional requests. :param http_range: Range HTTP header :param http_if_range: If-Range HTTP header :param http_if_modified_since: If-Modified-Since HTTP header :param http_if_none_match: If-None-Match HTTP header :param http_if_match: If-Match HTTP header :param etag: the etag for the response for comparison. :param data: or alternatively the data of the response to automatically generate an etag using :func:`generate_etag`. :param last_modified: an optional date of the last modification. :param ignore_if_range: If `False`, `If-Range` header will be taken into account. :return: `True` if the resource was modified, otherwise `False`. .. versionadded:: 2.2
172,433
import re import typing as t from datetime import datetime from .._internal import _cookie_parse_impl from .._internal import _dt_as_utc from .._internal import _to_str from ..http import generate_etag from ..http import parse_date from ..http import parse_etags from ..http import parse_if_range_header from ..http import unquote_etag from .. import datastructures as ds def _to_str( # type: ignore x: None, charset: t.Optional[str] = ..., errors: str = ..., allow_none_charset: bool = ..., ) -> None: ... def _to_str( x: t.Any, charset: t.Optional[str] = ..., errors: str = ..., allow_none_charset: bool = ..., ) -> str: ... def _to_str( x: t.Optional[t.Any], charset: t.Optional[str] = _default_encoding, errors: str = "strict", allow_none_charset: bool = False, ) -> t.Optional[t.Union[str, bytes]]: if x is None or isinstance(x, str): return x if not isinstance(x, (bytes, bytearray)): return str(x) if charset is None: if allow_none_charset: return x return x.decode(charset, errors) # type: ignore def _cookie_parse_impl(b: bytes) -> t.Iterator[t.Tuple[bytes, bytes]]: """Lowlevel cookie parsing facility that operates on bytes.""" i = 0 n = len(b) b += b";" while i < n: match = _cookie_re.match(b, i) if not match: break i = match.end(0) key = match.group("key").strip() if not key: continue value = match.group("val") or b"" yield key, _cookie_unquote(value) The provided code snippet includes necessary dependencies for implementing the `parse_cookie` function. Write a Python function `def parse_cookie( cookie: t.Union[bytes, str, None] = "", charset: str = "utf-8", errors: str = "replace", cls: t.Optional[t.Type["ds.MultiDict"]] = None, ) -> "ds.MultiDict[str, str]"` to solve the following problem: Parse a cookie from a string. The same key can be provided multiple times, the values are stored in-order. The default :class:`MultiDict` will have the first value first, and all values can be retrieved with :meth:`MultiDict.getlist`. :param cookie: The cookie header as a string. :param charset: The charset for the cookie values. :param errors: The error behavior for the charset decoding. :param cls: A dict-like class to store the parsed cookies in. Defaults to :class:`MultiDict`. .. versionadded:: 2.2 Here is the function: def parse_cookie( cookie: t.Union[bytes, str, None] = "", charset: str = "utf-8", errors: str = "replace", cls: t.Optional[t.Type["ds.MultiDict"]] = None, ) -> "ds.MultiDict[str, str]": """Parse a cookie from a string. The same key can be provided multiple times, the values are stored in-order. The default :class:`MultiDict` will have the first value first, and all values can be retrieved with :meth:`MultiDict.getlist`. :param cookie: The cookie header as a string. :param charset: The charset for the cookie values. :param errors: The error behavior for the charset decoding. :param cls: A dict-like class to store the parsed cookies in. Defaults to :class:`MultiDict`. .. versionadded:: 2.2 """ # PEP 3333 sends headers through the environ as latin1 decoded # strings. Encode strings back to bytes for parsing. if isinstance(cookie, str): cookie = cookie.encode("latin1", "replace") if cls is None: cls = ds.MultiDict def _parse_pairs() -> t.Iterator[t.Tuple[str, str]]: for key, val in _cookie_parse_impl(cookie): # type: ignore key_str = _to_str(key, charset, errors, allow_none_charset=True) val_str = _to_str(val, charset, errors, allow_none_charset=True) yield key_str, val_str return cls(_parse_pairs())
Parse a cookie from a string. The same key can be provided multiple times, the values are stored in-order. The default :class:`MultiDict` will have the first value first, and all values can be retrieved with :meth:`MultiDict.getlist`. :param cookie: The cookie header as a string. :param charset: The charset for the cookie values. :param errors: The error behavior for the charset decoding. :param cls: A dict-like class to store the parsed cookies in. Defaults to :class:`MultiDict`. .. versionadded:: 2.2
172,445
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance from . import datastructures as ds from .sansio import http as _sansio_http The provided code snippet includes necessary dependencies for implementing the `dump_csp_header` function. Write a Python function `def dump_csp_header(header: "ds.ContentSecurityPolicy") -> str` to solve the following problem: Dump a Content Security Policy header. These are structured into policies such as "default-src 'self'; script-src 'self'". .. versionadded:: 1.0.0 Support for Content Security Policy headers was added. Here is the function: def dump_csp_header(header: "ds.ContentSecurityPolicy") -> str: """Dump a Content Security Policy header. These are structured into policies such as "default-src 'self'; script-src 'self'". .. versionadded:: 1.0.0 Support for Content Security Policy headers was added. """ return "; ".join(f"{key} {value}" for key, value in header.items())
Dump a Content Security Policy header. These are structured into policies such as "default-src 'self'; script-src 'self'". .. versionadded:: 1.0.0 Support for Content Security Policy headers was added.
172,446
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment _option_header_piece_re = re.compile( r""" ;\s*,?\s* # newlines were replaced with commas (?P<key> "[^"\\]*(?:\\.[^"\\]*)*" # quoted string | [^\s;,=*]+ # token ) (?:\*(?P<count>\d+))? # *1, optional continuation index \s* (?: # optionally followed by =value (?: # equals sign, possibly with encoding \*\s*=\s* # * indicates extended notation (?: # optional encoding (?P<encoding>[^\s]+?) '(?P<language>[^\s]*?)' )? | =\s* # basic notation ) (?P<value> "[^"\\]*(?:\\.[^"\\]*)*" # quoted string | [^;,]+ # token )? )? \s* """, flags=re.VERBOSE, ) _option_header_start_mime_type = re.compile(r",\s*([^;,\s]+)([;,]\s*.+)?") def unquote_header_value(value: str, is_filename: bool = False) -> str: r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. .. versionadded:: 0.5 :param value: the header value to unquote. :param is_filename: The value represents a filename or path. """ if value and value[0] == value[-1] == '"': # this is not the real unquoting, but fixing this so that the # RFC is met will result in bugs with internet explorer and # probably some other browsers as well. IE for example is # uploading files with "C:\foo\bar.txt" as filename value = value[1:-1] # if this is a filename and the starting characters look like # a UNC path, then just return the value without quotes. Using the # replace sequence below on a UNC path has the effect of turning # the leading double slash into a single slash and then # _fix_ie_filename() doesn't work correctly. See #458. if not is_filename or value[:2] != "\\\\": return value.replace("\\\\", "\\").replace('\\"', '"') return value from . import datastructures as ds from .sansio import http as _sansio_http The provided code snippet includes necessary dependencies for implementing the `parse_options_header` function. Write a Python function `def parse_options_header(value: t.Optional[str]) -> t.Tuple[str, t.Dict[str, str]]` to solve the following problem: Parse a ``Content-Type``-like header into a tuple with the value and any options: >>> parse_options_header('text/html; charset=utf8') ('text/html', {'charset': 'utf8'}) This should is not for ``Cache-Control``-like headers, which use a different format. For those, use :func:`parse_dict_header`. :param value: The header value to parse. .. versionchanged:: 2.2 Option names are always converted to lowercase. .. versionchanged:: 2.1 The ``multiple`` parameter is deprecated and will be removed in Werkzeug 2.2. .. versionchanged:: 0.15 :rfc:`2231` parameter continuations are handled. .. versionadded:: 0.5 Here is the function: def parse_options_header(value: t.Optional[str]) -> t.Tuple[str, t.Dict[str, str]]: """Parse a ``Content-Type``-like header into a tuple with the value and any options: >>> parse_options_header('text/html; charset=utf8') ('text/html', {'charset': 'utf8'}) This should is not for ``Cache-Control``-like headers, which use a different format. For those, use :func:`parse_dict_header`. :param value: The header value to parse. .. versionchanged:: 2.2 Option names are always converted to lowercase. .. versionchanged:: 2.1 The ``multiple`` parameter is deprecated and will be removed in Werkzeug 2.2. .. versionchanged:: 0.15 :rfc:`2231` parameter continuations are handled. .. versionadded:: 0.5 """ if not value: return "", {} result: t.List[t.Any] = [] value = "," + value.replace("\n", ",") while value: match = _option_header_start_mime_type.match(value) if not match: break result.append(match.group(1)) # mimetype options: t.Dict[str, str] = {} # Parse options rest = match.group(2) encoding: t.Optional[str] continued_encoding: t.Optional[str] = None while rest: optmatch = _option_header_piece_re.match(rest) if not optmatch: break option, count, encoding, language, option_value = optmatch.groups() # Continuations don't have to supply the encoding after the # first line. If we're in a continuation, track the current # encoding to use for subsequent lines. Reset it when the # continuation ends. if not count: continued_encoding = None else: if not encoding: encoding = continued_encoding continued_encoding = encoding option = unquote_header_value(option).lower() if option_value is not None: option_value = unquote_header_value(option_value, option == "filename") if encoding is not None: option_value = _unquote(option_value).decode(encoding) if count: # Continuations append to the existing value. For # simplicity, this ignores the possibility of # out-of-order indices, which shouldn't happen anyway. if option_value is not None: options[option] = options.get(option, "") + option_value else: options[option] = option_value # type: ignore[assignment] rest = rest[optmatch.end() :] result.append(options) return tuple(result) # type: ignore[return-value] return tuple(result) if result else ("", {}) # type: ignore[return-value]
Parse a ``Content-Type``-like header into a tuple with the value and any options: >>> parse_options_header('text/html; charset=utf8') ('text/html', {'charset': 'utf8'}) This should is not for ``Cache-Control``-like headers, which use a different format. For those, use :func:`parse_dict_header`. :param value: The header value to parse. .. versionchanged:: 2.2 Option names are always converted to lowercase. .. versionchanged:: 2.1 The ``multiple`` parameter is deprecated and will be removed in Werkzeug 2.2. .. versionchanged:: 0.15 :rfc:`2231` parameter continuations are handled. .. versionadded:: 0.5
172,447
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment from . import datastructures as ds from .sansio import http as _sansio_http def parse_accept_header(value: t.Optional[str]) -> "ds.Accept": ...
null
172,448
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment _TAnyAccept = t.TypeVar("_TAnyAccept", bound="ds.Accept") from . import datastructures as ds from .sansio import http as _sansio_http def parse_accept_header( value: t.Optional[str], cls: t.Type[_TAnyAccept] ) -> _TAnyAccept: ...
null
172,449
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment _accept_re = re.compile( r""" ( # media-range capturing-parenthesis [^\s;,]+ # type/subtype (?:[ \t]*;[ \t]* # ";" (?: # parameter non-capturing-parenthesis [^\s;,q][^\s;,]* # token that doesn't start with "q" | # or q[^\s;,=][^\s;,]* # token that is more than just "q" ) )* # zero or more parameters ) # end of media-range (?:[ \t]*;[ \t]*q= # weight is a "q" parameter (\d*(?:\.\d+)?) # qvalue capturing-parentheses [^,]* # "extension" accept params: who cares? )? # accept params are optional """, re.VERBOSE, ) _TAnyAccept = t.TypeVar("_TAnyAccept", bound="ds.Accept") from . import datastructures as ds from .sansio import http as _sansio_http The provided code snippet includes necessary dependencies for implementing the `parse_accept_header` function. Write a Python function `def parse_accept_header( value: t.Optional[str], cls: t.Optional[t.Type[_TAnyAccept]] = None ) -> _TAnyAccept` to solve the following problem: Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction. Returns a new :class:`Accept` object (basically a list of ``(value, quality)`` tuples sorted by the quality with some additional accessor methods). The second parameter can be a subclass of :class:`Accept` that is created with the parsed values and returned. :param value: the accept header string to be parsed. :param cls: the wrapper class for the return value (can be :class:`Accept` or a subclass thereof) :return: an instance of `cls`. Here is the function: def parse_accept_header( value: t.Optional[str], cls: t.Optional[t.Type[_TAnyAccept]] = None ) -> _TAnyAccept: """Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction. Returns a new :class:`Accept` object (basically a list of ``(value, quality)`` tuples sorted by the quality with some additional accessor methods). The second parameter can be a subclass of :class:`Accept` that is created with the parsed values and returned. :param value: the accept header string to be parsed. :param cls: the wrapper class for the return value (can be :class:`Accept` or a subclass thereof) :return: an instance of `cls`. """ if cls is None: cls = t.cast(t.Type[_TAnyAccept], ds.Accept) if not value: return cls(None) result = [] for match in _accept_re.finditer(value): quality_match = match.group(2) if not quality_match: quality: float = 1 else: quality = max(min(float(quality_match), 1), 0) result.append((match.group(1), quality)) return cls(result)
Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction. Returns a new :class:`Accept` object (basically a list of ``(value, quality)`` tuples sorted by the quality with some additional accessor methods). The second parameter can be a subclass of :class:`Accept` that is created with the parsed values and returned. :param value: the accept header string to be parsed. :param cls: the wrapper class for the return value (can be :class:`Accept` or a subclass thereof) :return: an instance of `cls`.
172,450
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment _t_cc_update = t.Optional[t.Callable[[_TAnyCC], None]] from . import datastructures as ds from .sansio import http as _sansio_http def parse_cache_control_header( value: t.Optional[str], on_update: _t_cc_update, cls: None = None ) -> "ds.RequestCacheControl": ...
null
172,451
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment _TAnyCC = t.TypeVar("_TAnyCC", bound="ds._CacheControl") _t_cc_update = t.Optional[t.Callable[[_TAnyCC], None]] from . import datastructures as ds from .sansio import http as _sansio_http def parse_cache_control_header( value: t.Optional[str], on_update: _t_cc_update, cls: t.Type[_TAnyCC] ) -> _TAnyCC: ...
null
172,452
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment def parse_dict_header(value: str, cls: t.Type[dict] = dict) -> t.Dict[str, str]: """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the `cls` argument): >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. .. versionchanged:: 0.9 Added support for `cls` argument. :param value: a string with a dict header. :param cls: callable to use for storage of parsed results. :return: an instance of `cls` """ result = cls() if isinstance(value, bytes): value = value.decode("latin1") for item in _parse_list_header(value): if "=" not in item: result[item] = None continue name, value = item.split("=", 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result _TAnyCC = t.TypeVar("_TAnyCC", bound="ds._CacheControl") _t_cc_update = t.Optional[t.Callable[[_TAnyCC], None]] from . import datastructures as ds from .sansio import http as _sansio_http The provided code snippet includes necessary dependencies for implementing the `parse_cache_control_header` function. Write a Python function `def parse_cache_control_header( value: t.Optional[str], on_update: _t_cc_update = None, cls: t.Optional[t.Type[_TAnyCC]] = None, ) -> _TAnyCC` to solve the following problem: Parse a cache control header. The RFC differs between response and request cache control, this method does not. It's your responsibility to not use the wrong control statements. .. versionadded:: 0.5 The `cls` was added. If not specified an immutable :class:`~werkzeug.datastructures.RequestCacheControl` is returned. :param value: a cache control header to be parsed. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.CacheControl` object is changed. :param cls: the class for the returned object. By default :class:`~werkzeug.datastructures.RequestCacheControl` is used. :return: a `cls` object. Here is the function: def parse_cache_control_header( value: t.Optional[str], on_update: _t_cc_update = None, cls: t.Optional[t.Type[_TAnyCC]] = None, ) -> _TAnyCC: """Parse a cache control header. The RFC differs between response and request cache control, this method does not. It's your responsibility to not use the wrong control statements. .. versionadded:: 0.5 The `cls` was added. If not specified an immutable :class:`~werkzeug.datastructures.RequestCacheControl` is returned. :param value: a cache control header to be parsed. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.CacheControl` object is changed. :param cls: the class for the returned object. By default :class:`~werkzeug.datastructures.RequestCacheControl` is used. :return: a `cls` object. """ if cls is None: cls = t.cast(t.Type[_TAnyCC], ds.RequestCacheControl) if not value: return cls((), on_update) return cls(parse_dict_header(value), on_update)
Parse a cache control header. The RFC differs between response and request cache control, this method does not. It's your responsibility to not use the wrong control statements. .. versionadded:: 0.5 The `cls` was added. If not specified an immutable :class:`~werkzeug.datastructures.RequestCacheControl` is returned. :param value: a cache control header to be parsed. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.CacheControl` object is changed. :param cls: the class for the returned object. By default :class:`~werkzeug.datastructures.RequestCacheControl` is used. :return: a `cls` object.
172,453
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment _t_csp_update = t.Optional[t.Callable[[_TAnyCSP], None]] from . import datastructures as ds from .sansio import http as _sansio_http def parse_csp_header( value: t.Optional[str], on_update: _t_csp_update, cls: None = None ) -> "ds.ContentSecurityPolicy": ...
null
172,454
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment _TAnyCSP = t.TypeVar("_TAnyCSP", bound="ds.ContentSecurityPolicy") _t_csp_update = t.Optional[t.Callable[[_TAnyCSP], None]] from . import datastructures as ds from .sansio import http as _sansio_http def parse_csp_header( value: t.Optional[str], on_update: _t_csp_update, cls: t.Type[_TAnyCSP] ) -> _TAnyCSP: ...
null
172,455
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment _TAnyCSP = t.TypeVar("_TAnyCSP", bound="ds.ContentSecurityPolicy") _t_csp_update = t.Optional[t.Callable[[_TAnyCSP], None]] from . import datastructures as ds from .sansio import http as _sansio_http The provided code snippet includes necessary dependencies for implementing the `parse_csp_header` function. Write a Python function `def parse_csp_header( value: t.Optional[str], on_update: _t_csp_update = None, cls: t.Optional[t.Type[_TAnyCSP]] = None, ) -> _TAnyCSP` to solve the following problem: Parse a Content Security Policy header. .. versionadded:: 1.0.0 Support for Content Security Policy headers was added. :param value: a csp header to be parsed. :param on_update: an optional callable that is called every time a value on the object is changed. :param cls: the class for the returned object. By default :class:`~werkzeug.datastructures.ContentSecurityPolicy` is used. :return: a `cls` object. Here is the function: def parse_csp_header( value: t.Optional[str], on_update: _t_csp_update = None, cls: t.Optional[t.Type[_TAnyCSP]] = None, ) -> _TAnyCSP: """Parse a Content Security Policy header. .. versionadded:: 1.0.0 Support for Content Security Policy headers was added. :param value: a csp header to be parsed. :param on_update: an optional callable that is called every time a value on the object is changed. :param cls: the class for the returned object. By default :class:`~werkzeug.datastructures.ContentSecurityPolicy` is used. :return: a `cls` object. """ if cls is None: cls = t.cast(t.Type[_TAnyCSP], ds.ContentSecurityPolicy) if value is None: return cls((), on_update) items = [] for policy in value.split(";"): policy = policy.strip() # Ignore badly formatted policies (no space) if " " in policy: directive, value = policy.strip().split(" ", 1) items.append((directive.strip(), value.strip())) return cls(items, on_update)
Parse a Content Security Policy header. .. versionadded:: 1.0.0 Support for Content Security Policy headers was added. :param value: a csp header to be parsed. :param on_update: an optional callable that is called every time a value on the object is changed. :param cls: the class for the returned object. By default :class:`~werkzeug.datastructures.ContentSecurityPolicy` is used. :return: a `cls` object.
172,456
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment def parse_dict_header(value: str, cls: t.Type[dict] = dict) -> t.Dict[str, str]: """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the `cls` argument): >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. .. versionchanged:: 0.9 Added support for `cls` argument. :param value: a string with a dict header. :param cls: callable to use for storage of parsed results. :return: an instance of `cls` """ result = cls() if isinstance(value, bytes): value = value.decode("latin1") for item in _parse_list_header(value): if "=" not in item: result[item] = None continue name, value = item.split("=", 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result from . import datastructures as ds from .sansio import http as _sansio_http def _to_str( # type: ignore x: None, charset: t.Optional[str] = ..., errors: str = ..., allow_none_charset: bool = ..., ) -> None: ... def _to_str( x: t.Any, charset: t.Optional[str] = ..., errors: str = ..., allow_none_charset: bool = ..., ) -> str: ... def _to_str( x: t.Optional[t.Any], charset: t.Optional[str] = _default_encoding, errors: str = "strict", allow_none_charset: bool = False, ) -> t.Optional[t.Union[str, bytes]]: if x is None or isinstance(x, str): return x if not isinstance(x, (bytes, bytearray)): return str(x) if charset is None: if allow_none_charset: return x return x.decode(charset, errors) # type: ignore def _wsgi_decoding_dance( s: str, charset: str = "utf-8", errors: str = "replace" ) -> str: return s.encode("latin1").decode(charset, errors) The provided code snippet includes necessary dependencies for implementing the `parse_authorization_header` function. Write a Python function `def parse_authorization_header( value: t.Optional[str], ) -> t.Optional["ds.Authorization"]` to solve the following problem: Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either `None` if the header was invalid or not given, otherwise an :class:`~werkzeug.datastructures.Authorization` object. :param value: the authorization header to parse. :return: a :class:`~werkzeug.datastructures.Authorization` object or `None`. Here is the function: def parse_authorization_header( value: t.Optional[str], ) -> t.Optional["ds.Authorization"]: """Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either `None` if the header was invalid or not given, otherwise an :class:`~werkzeug.datastructures.Authorization` object. :param value: the authorization header to parse. :return: a :class:`~werkzeug.datastructures.Authorization` object or `None`. """ if not value: return None value = _wsgi_decoding_dance(value) try: auth_type, auth_info = value.split(None, 1) auth_type = auth_type.lower() except ValueError: return None if auth_type == "basic": try: username, password = base64.b64decode(auth_info).split(b":", 1) except Exception: return None try: return ds.Authorization( "basic", { "username": _to_str(username, "utf-8"), "password": _to_str(password, "utf-8"), }, ) except UnicodeDecodeError: return None elif auth_type == "digest": auth_map = parse_dict_header(auth_info) for key in "username", "realm", "nonce", "uri", "response": if key not in auth_map: return None if "qop" in auth_map: if not auth_map.get("nc") or not auth_map.get("cnonce"): return None return ds.Authorization("digest", auth_map) return None
Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either `None` if the header was invalid or not given, otherwise an :class:`~werkzeug.datastructures.Authorization` object. :param value: the authorization header to parse. :return: a :class:`~werkzeug.datastructures.Authorization` object or `None`.
172,457
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment def parse_dict_header(value: str, cls: t.Type[dict] = dict) -> t.Dict[str, str]: """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the `cls` argument): >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. .. versionchanged:: 0.9 Added support for `cls` argument. :param value: a string with a dict header. :param cls: callable to use for storage of parsed results. :return: an instance of `cls` """ result = cls() if isinstance(value, bytes): value = value.decode("latin1") for item in _parse_list_header(value): if "=" not in item: result[item] = None continue name, value = item.split("=", 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result from . import datastructures as ds from .sansio import http as _sansio_http The provided code snippet includes necessary dependencies for implementing the `parse_www_authenticate_header` function. Write a Python function `def parse_www_authenticate_header( value: t.Optional[str], on_update: t.Optional[t.Callable[["ds.WWWAuthenticate"], None]] = None, ) -> "ds.WWWAuthenticate"` to solve the following problem: Parse an HTTP WWW-Authenticate header into a :class:`~werkzeug.datastructures.WWWAuthenticate` object. :param value: a WWW-Authenticate header to parse. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.WWWAuthenticate` object is changed. :return: a :class:`~werkzeug.datastructures.WWWAuthenticate` object. Here is the function: def parse_www_authenticate_header( value: t.Optional[str], on_update: t.Optional[t.Callable[["ds.WWWAuthenticate"], None]] = None, ) -> "ds.WWWAuthenticate": """Parse an HTTP WWW-Authenticate header into a :class:`~werkzeug.datastructures.WWWAuthenticate` object. :param value: a WWW-Authenticate header to parse. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.WWWAuthenticate` object is changed. :return: a :class:`~werkzeug.datastructures.WWWAuthenticate` object. """ if not value: return ds.WWWAuthenticate(on_update=on_update) try: auth_type, auth_info = value.split(None, 1) auth_type = auth_type.lower() except (ValueError, AttributeError): return ds.WWWAuthenticate(value.strip().lower(), on_update=on_update) return ds.WWWAuthenticate(auth_type, parse_dict_header(auth_info), on_update)
Parse an HTTP WWW-Authenticate header into a :class:`~werkzeug.datastructures.WWWAuthenticate` object. :param value: a WWW-Authenticate header to parse. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.WWWAuthenticate` object is changed. :return: a :class:`~werkzeug.datastructures.WWWAuthenticate` object.
172,458
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment from . import datastructures as ds from .sansio import http as _sansio_http The provided code snippet includes necessary dependencies for implementing the `parse_range_header` function. Write a Python function `def parse_range_header( value: t.Optional[str], make_inclusive: bool = True ) -> t.Optional["ds.Range"]` to solve the following problem: Parses a range header into a :class:`~werkzeug.datastructures.Range` object. If the header is missing or malformed `None` is returned. `ranges` is a list of ``(start, stop)`` tuples where the ranges are non-inclusive. .. versionadded:: 0.7 Here is the function: def parse_range_header( value: t.Optional[str], make_inclusive: bool = True ) -> t.Optional["ds.Range"]: """Parses a range header into a :class:`~werkzeug.datastructures.Range` object. If the header is missing or malformed `None` is returned. `ranges` is a list of ``(start, stop)`` tuples where the ranges are non-inclusive. .. versionadded:: 0.7 """ if not value or "=" not in value: return None ranges = [] last_end = 0 units, rng = value.split("=", 1) units = units.strip().lower() for item in rng.split(","): item = item.strip() if "-" not in item: return None if item.startswith("-"): if last_end < 0: return None try: begin = int(item) except ValueError: return None end = None last_end = -1 elif "-" in item: begin_str, end_str = item.split("-", 1) begin_str = begin_str.strip() end_str = end_str.strip() try: begin = int(begin_str) except ValueError: return None if begin < last_end or last_end < 0: return None if end_str: try: end = int(end_str) + 1 except ValueError: return None if begin >= end: return None else: end = None last_end = end if end is not None else -1 ranges.append((begin, end)) return ds.Range(units, ranges)
Parses a range header into a :class:`~werkzeug.datastructures.Range` object. If the header is missing or malformed `None` is returned. `ranges` is a list of ``(start, stop)`` tuples where the ranges are non-inclusive. .. versionadded:: 0.7
172,459
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment def is_byte_range_valid( start: t.Optional[int], stop: t.Optional[int], length: t.Optional[int] ) -> bool: """Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7 """ if (start is None) != (stop is None): return False elif start is None: return length is None or length >= 0 elif length is None: return 0 <= start < stop # type: ignore elif start >= stop: # type: ignore return False return 0 <= start < length from . import datastructures as ds from .sansio import http as _sansio_http The provided code snippet includes necessary dependencies for implementing the `parse_content_range_header` function. Write a Python function `def parse_content_range_header( value: t.Optional[str], on_update: t.Optional[t.Callable[["ds.ContentRange"], None]] = None, ) -> t.Optional["ds.ContentRange"]` to solve the following problem: Parses a range header into a :class:`~werkzeug.datastructures.ContentRange` object or `None` if parsing is not possible. .. versionadded:: 0.7 :param value: a content range header to be parsed. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.ContentRange` object is changed. Here is the function: def parse_content_range_header( value: t.Optional[str], on_update: t.Optional[t.Callable[["ds.ContentRange"], None]] = None, ) -> t.Optional["ds.ContentRange"]: """Parses a range header into a :class:`~werkzeug.datastructures.ContentRange` object or `None` if parsing is not possible. .. versionadded:: 0.7 :param value: a content range header to be parsed. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.ContentRange` object is changed. """ if value is None: return None try: units, rangedef = (value or "").strip().split(None, 1) except ValueError: return None if "/" not in rangedef: return None rng, length_str = rangedef.split("/", 1) if length_str == "*": length = None else: try: length = int(length_str) except ValueError: return None if rng == "*": if not is_byte_range_valid(None, None, length): return None return ds.ContentRange(units, None, None, length, on_update=on_update) elif "-" not in rng: return None start_str, stop_str = rng.split("-", 1) try: start = int(start_str) stop = int(stop_str) + 1 except ValueError: return None if is_byte_range_valid(start, stop, length): return ds.ContentRange(units, start, stop, length, on_update=on_update) return None
Parses a range header into a :class:`~werkzeug.datastructures.ContentRange` object or `None` if parsing is not possible. .. versionadded:: 0.7 :param value: a content range header to be parsed. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.ContentRange` object is changed.
172,460
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance from . import datastructures as ds from .sansio import http as _sansio_http The provided code snippet includes necessary dependencies for implementing the `quote_etag` function. Write a Python function `def quote_etag(etag: str, weak: bool = False) -> str` to solve the following problem: Quote an etag. :param etag: the etag to quote. :param weak: set to `True` to tag it "weak". Here is the function: def quote_etag(etag: str, weak: bool = False) -> str: """Quote an etag. :param etag: the etag to quote. :param weak: set to `True` to tag it "weak". """ if '"' in etag: raise ValueError("invalid etag") etag = f'"{etag}"' if weak: etag = f"W/{etag}" return etag
Quote an etag. :param etag: the etag to quote. :param weak: set to `True` to tag it "weak".
172,461
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment from . import datastructures as ds from .sansio import http as _sansio_http class timedelta(SupportsAbs[timedelta]): min: ClassVar[timedelta] max: ClassVar[timedelta] resolution: ClassVar[timedelta] if sys.version_info >= (3, 6): def __init__( self, days: float = ..., seconds: float = ..., microseconds: float = ..., milliseconds: float = ..., minutes: float = ..., hours: float = ..., weeks: float = ..., *, fold: int = ..., ) -> None: ... else: def __init__( self, days: float = ..., seconds: float = ..., microseconds: float = ..., milliseconds: float = ..., minutes: float = ..., hours: float = ..., weeks: float = ..., ) -> None: ... def days(self) -> int: ... def seconds(self) -> int: ... def microseconds(self) -> int: ... def total_seconds(self) -> float: ... def __add__(self, other: timedelta) -> timedelta: ... def __radd__(self, other: timedelta) -> timedelta: ... def __sub__(self, other: timedelta) -> timedelta: ... def __rsub__(self, other: timedelta) -> timedelta: ... def __neg__(self) -> timedelta: ... def __pos__(self) -> timedelta: ... def __abs__(self) -> timedelta: ... def __mul__(self, other: float) -> timedelta: ... def __rmul__(self, other: float) -> timedelta: ... def __floordiv__(self, other: timedelta) -> int: ... def __floordiv__(self, other: int) -> timedelta: ... if sys.version_info >= (3,): def __truediv__(self, other: timedelta) -> float: ... def __truediv__(self, other: float) -> timedelta: ... def __mod__(self, other: timedelta) -> timedelta: ... def __divmod__(self, other: timedelta) -> Tuple[int, timedelta]: ... else: def __div__(self, other: timedelta) -> float: ... def __div__(self, other: float) -> timedelta: ... def __le__(self, other: timedelta) -> bool: ... def __lt__(self, other: timedelta) -> bool: ... def __ge__(self, other: timedelta) -> bool: ... def __gt__(self, other: timedelta) -> bool: ... def __hash__(self) -> int: ... The provided code snippet includes necessary dependencies for implementing the `parse_age` function. Write a Python function `def parse_age(value: t.Optional[str] = None) -> t.Optional[timedelta]` to solve the following problem: Parses a base-10 integer count of seconds into a timedelta. If parsing fails, the return value is `None`. :param value: a string consisting of an integer represented in base-10 :return: a :class:`datetime.timedelta` object or `None`. Here is the function: def parse_age(value: t.Optional[str] = None) -> t.Optional[timedelta]: """Parses a base-10 integer count of seconds into a timedelta. If parsing fails, the return value is `None`. :param value: a string consisting of an integer represented in base-10 :return: a :class:`datetime.timedelta` object or `None`. """ if not value: return None try: seconds = int(value) except ValueError: return None if seconds < 0: return None try: return timedelta(seconds=seconds) except OverflowError: return None
Parses a base-10 integer count of seconds into a timedelta. If parsing fails, the return value is `None`. :param value: a string consisting of an integer represented in base-10 :return: a :class:`datetime.timedelta` object or `None`.
172,462
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment from . import datastructures as ds from .sansio import http as _sansio_http class timedelta(SupportsAbs[timedelta]): min: ClassVar[timedelta] max: ClassVar[timedelta] resolution: ClassVar[timedelta] if sys.version_info >= (3, 6): def __init__( self, days: float = ..., seconds: float = ..., microseconds: float = ..., milliseconds: float = ..., minutes: float = ..., hours: float = ..., weeks: float = ..., *, fold: int = ..., ) -> None: ... else: def __init__( self, days: float = ..., seconds: float = ..., microseconds: float = ..., milliseconds: float = ..., minutes: float = ..., hours: float = ..., weeks: float = ..., ) -> None: ... def days(self) -> int: ... def seconds(self) -> int: ... def microseconds(self) -> int: ... def total_seconds(self) -> float: ... def __add__(self, other: timedelta) -> timedelta: ... def __radd__(self, other: timedelta) -> timedelta: ... def __sub__(self, other: timedelta) -> timedelta: ... def __rsub__(self, other: timedelta) -> timedelta: ... def __neg__(self) -> timedelta: ... def __pos__(self) -> timedelta: ... def __abs__(self) -> timedelta: ... def __mul__(self, other: float) -> timedelta: ... def __rmul__(self, other: float) -> timedelta: ... def __floordiv__(self, other: timedelta) -> int: ... def __floordiv__(self, other: int) -> timedelta: ... if sys.version_info >= (3,): def __truediv__(self, other: timedelta) -> float: ... def __truediv__(self, other: float) -> timedelta: ... def __mod__(self, other: timedelta) -> timedelta: ... def __divmod__(self, other: timedelta) -> Tuple[int, timedelta]: ... else: def __div__(self, other: timedelta) -> float: ... def __div__(self, other: float) -> timedelta: ... def __le__(self, other: timedelta) -> bool: ... def __lt__(self, other: timedelta) -> bool: ... def __ge__(self, other: timedelta) -> bool: ... def __gt__(self, other: timedelta) -> bool: ... def __hash__(self) -> int: ... The provided code snippet includes necessary dependencies for implementing the `dump_age` function. Write a Python function `def dump_age(age: t.Optional[t.Union[timedelta, int]] = None) -> t.Optional[str]` to solve the following problem: Formats the duration as a base-10 integer. :param age: should be an integer number of seconds, a :class:`datetime.timedelta` object, or, if the age is unknown, `None` (default). Here is the function: def dump_age(age: t.Optional[t.Union[timedelta, int]] = None) -> t.Optional[str]: """Formats the duration as a base-10 integer. :param age: should be an integer number of seconds, a :class:`datetime.timedelta` object, or, if the age is unknown, `None` (default). """ if age is None: return None if isinstance(age, timedelta): age = int(age.total_seconds()) else: age = int(age) if age < 0: raise ValueError("age cannot be negative") return str(age)
Formats the duration as a base-10 integer. :param age: should be an integer number of seconds, a :class:`datetime.timedelta` object, or, if the age is unknown, `None` (default).
172,463
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment from . import datastructures as ds from .sansio import http as _sansio_http class datetime(date): min: ClassVar[datetime] max: ClassVar[datetime] resolution: ClassVar[timedelta] if sys.version_info >= (3, 6): def __new__( cls: Type[_S], year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ..., ) -> _S: ... else: def __new__( cls: Type[_S], year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> _S: ... def year(self) -> int: ... def month(self) -> int: ... def day(self) -> int: ... def hour(self) -> int: ... def minute(self) -> int: ... def second(self) -> int: ... def microsecond(self) -> int: ... def tzinfo(self) -> Optional[_tzinfo]: ... if sys.version_info >= (3, 6): def fold(self) -> int: ... def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S: ... def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ... def today(cls: Type[_S]) -> _S: ... def fromordinal(cls: Type[_S], n: int) -> _S: ... if sys.version_info >= (3, 8): def now(cls: Type[_S], tz: Optional[_tzinfo] = ...) -> _S: ... else: def now(cls: Type[_S], tz: None = ...) -> _S: ... def now(cls, tz: _tzinfo) -> datetime: ... def utcnow(cls: Type[_S]) -> _S: ... if sys.version_info >= (3, 6): def combine(cls, date: _date, time: _time, tzinfo: Optional[_tzinfo] = ...) -> datetime: ... else: def combine(cls, date: _date, time: _time) -> datetime: ... if sys.version_info >= (3, 7): def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... def strftime(self, fmt: _Text) -> str: ... if sys.version_info >= (3,): def __format__(self, fmt: str) -> str: ... else: def __format__(self, fmt: AnyStr) -> AnyStr: ... def toordinal(self) -> int: ... def timetuple(self) -> struct_time: ... if sys.version_info >= (3, 3): def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _date: ... def time(self) -> _time: ... def timetz(self) -> _time: ... if sys.version_info >= (3, 6): def replace( self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ..., ) -> datetime: ... else: def replace( self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> datetime: ... if sys.version_info >= (3, 8): def astimezone(self: _S, tz: Optional[_tzinfo] = ...) -> _S: ... elif sys.version_info >= (3, 3): def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ... else: def astimezone(self, tz: _tzinfo) -> datetime: ... def ctime(self) -> str: ... if sys.version_info >= (3, 6): def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... else: def isoformat(self, sep: str = ...) -> str: ... def strptime(cls, date_string: _Text, format: _Text) -> datetime: ... def utcoffset(self) -> Optional[timedelta]: ... def tzname(self) -> Optional[str]: ... def dst(self) -> Optional[timedelta]: ... def __le__(self, other: datetime) -> bool: ... # type: ignore def __lt__(self, other: datetime) -> bool: ... # type: ignore def __ge__(self, other: datetime) -> bool: ... # type: ignore def __gt__(self, other: datetime) -> bool: ... # type: ignore if sys.version_info >= (3, 8): def __add__(self: _S, other: timedelta) -> _S: ... def __radd__(self: _S, other: timedelta) -> _S: ... else: def __add__(self, other: timedelta) -> datetime: ... def __radd__(self, other: timedelta) -> datetime: ... def __sub__(self, other: datetime) -> timedelta: ... def __sub__(self, other: timedelta) -> datetime: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... def isocalendar(self) -> Tuple[int, int, int]: ... The provided code snippet includes necessary dependencies for implementing the `is_resource_modified` function. Write a Python function `def is_resource_modified( environ: "WSGIEnvironment", etag: t.Optional[str] = None, data: t.Optional[bytes] = None, last_modified: t.Optional[t.Union[datetime, str]] = None, ignore_if_range: bool = True, ) -> bool` to solve the following problem: Convenience method for conditional requests. :param environ: the WSGI environment of the request to be checked. :param etag: the etag for the response for comparison. :param data: or alternatively the data of the response to automatically generate an etag using :func:`generate_etag`. :param last_modified: an optional date of the last modification. :param ignore_if_range: If `False`, `If-Range` header will be taken into account. :return: `True` if the resource was modified, otherwise `False`. .. versionchanged:: 2.0 SHA-1 is used to generate an etag value for the data. MD5 may not be available in some environments. .. versionchanged:: 1.0.0 The check is run for methods other than ``GET`` and ``HEAD``. Here is the function: def is_resource_modified( environ: "WSGIEnvironment", etag: t.Optional[str] = None, data: t.Optional[bytes] = None, last_modified: t.Optional[t.Union[datetime, str]] = None, ignore_if_range: bool = True, ) -> bool: """Convenience method for conditional requests. :param environ: the WSGI environment of the request to be checked. :param etag: the etag for the response for comparison. :param data: or alternatively the data of the response to automatically generate an etag using :func:`generate_etag`. :param last_modified: an optional date of the last modification. :param ignore_if_range: If `False`, `If-Range` header will be taken into account. :return: `True` if the resource was modified, otherwise `False`. .. versionchanged:: 2.0 SHA-1 is used to generate an etag value for the data. MD5 may not be available in some environments. .. versionchanged:: 1.0.0 The check is run for methods other than ``GET`` and ``HEAD``. """ return _sansio_http.is_resource_modified( http_range=environ.get("HTTP_RANGE"), http_if_range=environ.get("HTTP_IF_RANGE"), http_if_modified_since=environ.get("HTTP_IF_MODIFIED_SINCE"), http_if_none_match=environ.get("HTTP_IF_NONE_MATCH"), http_if_match=environ.get("HTTP_IF_MATCH"), etag=etag, data=data, last_modified=last_modified, ignore_if_range=ignore_if_range, )
Convenience method for conditional requests. :param environ: the WSGI environment of the request to be checked. :param etag: the etag for the response for comparison. :param data: or alternatively the data of the response to automatically generate an etag using :func:`generate_etag`. :param last_modified: an optional date of the last modification. :param ignore_if_range: If `False`, `If-Range` header will be taken into account. :return: `True` if the resource was modified, otherwise `False`. .. versionchanged:: 2.0 SHA-1 is used to generate an etag value for the data. MD5 may not be available in some environments. .. versionchanged:: 1.0.0 The check is run for methods other than ``GET`` and ``HEAD``.
172,464
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment def is_entity_header(header: str) -> bool: """Check if a header is an entity header. .. versionadded:: 0.5 :param header: the header to test. :return: `True` if it's an entity header, `False` otherwise. """ return header.lower() in _entity_headers from . import datastructures as ds from .sansio import http as _sansio_http The provided code snippet includes necessary dependencies for implementing the `remove_entity_headers` function. Write a Python function `def remove_entity_headers( headers: t.Union["ds.Headers", t.List[t.Tuple[str, str]]], allowed: t.Iterable[str] = ("expires", "content-location"), ) -> None` to solve the following problem: Remove all entity headers from a list or :class:`Headers` object. This operation works in-place. `Expires` and `Content-Location` headers are by default not removed. The reason for this is :rfc:`2616` section 10.3.5 which specifies some entity headers that should be sent. .. versionchanged:: 0.5 added `allowed` parameter. :param headers: a list or :class:`Headers` object. :param allowed: a list of headers that should still be allowed even though they are entity headers. Here is the function: def remove_entity_headers( headers: t.Union["ds.Headers", t.List[t.Tuple[str, str]]], allowed: t.Iterable[str] = ("expires", "content-location"), ) -> None: """Remove all entity headers from a list or :class:`Headers` object. This operation works in-place. `Expires` and `Content-Location` headers are by default not removed. The reason for this is :rfc:`2616` section 10.3.5 which specifies some entity headers that should be sent. .. versionchanged:: 0.5 added `allowed` parameter. :param headers: a list or :class:`Headers` object. :param allowed: a list of headers that should still be allowed even though they are entity headers. """ allowed = {x.lower() for x in allowed} headers[:] = [ (key, value) for key, value in headers if not is_entity_header(key) or key.lower() in allowed ]
Remove all entity headers from a list or :class:`Headers` object. This operation works in-place. `Expires` and `Content-Location` headers are by default not removed. The reason for this is :rfc:`2616` section 10.3.5 which specifies some entity headers that should be sent. .. versionchanged:: 0.5 added `allowed` parameter. :param headers: a list or :class:`Headers` object. :param allowed: a list of headers that should still be allowed even though they are entity headers.
172,465
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment def is_hop_by_hop_header(header: str) -> bool: """Check if a header is an HTTP/1.1 "Hop-by-Hop" header. .. versionadded:: 0.5 :param header: the header to test. :return: `True` if it's an HTTP/1.1 "Hop-by-Hop" header, `False` otherwise. """ return header.lower() in _hop_by_hop_headers from . import datastructures as ds from .sansio import http as _sansio_http The provided code snippet includes necessary dependencies for implementing the `remove_hop_by_hop_headers` function. Write a Python function `def remove_hop_by_hop_headers( headers: t.Union["ds.Headers", t.List[t.Tuple[str, str]]] ) -> None` to solve the following problem: Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or :class:`Headers` object. This operation works in-place. .. versionadded:: 0.5 :param headers: a list or :class:`Headers` object. Here is the function: def remove_hop_by_hop_headers( headers: t.Union["ds.Headers", t.List[t.Tuple[str, str]]] ) -> None: """Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or :class:`Headers` object. This operation works in-place. .. versionadded:: 0.5 :param headers: a list or :class:`Headers` object. """ headers[:] = [ (key, value) for key, value in headers if not is_hop_by_hop_header(key) ]
Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or :class:`Headers` object. This operation works in-place. .. versionadded:: 0.5 :param headers: a list or :class:`Headers` object.
172,466
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment from . import datastructures as ds from .sansio import http as _sansio_http The provided code snippet includes necessary dependencies for implementing the `parse_cookie` function. Write a Python function `def parse_cookie( header: t.Union["WSGIEnvironment", str, bytes, None], charset: str = "utf-8", errors: str = "replace", cls: t.Optional[t.Type["ds.MultiDict"]] = None, ) -> "ds.MultiDict[str, str]"` to solve the following problem: Parse a cookie from a string or WSGI environ. The same key can be provided multiple times, the values are stored in-order. The default :class:`MultiDict` will have the first value first, and all values can be retrieved with :meth:`MultiDict.getlist`. :param header: The cookie header as a string, or a WSGI environ dict with a ``HTTP_COOKIE`` key. :param charset: The charset for the cookie values. :param errors: The error behavior for the charset decoding. :param cls: A dict-like class to store the parsed cookies in. Defaults to :class:`MultiDict`. .. versionchanged:: 1.0.0 Returns a :class:`MultiDict` instead of a ``TypeConversionDict``. .. versionchanged:: 0.5 Returns a :class:`TypeConversionDict` instead of a regular dict. The ``cls`` parameter was added. Here is the function: def parse_cookie( header: t.Union["WSGIEnvironment", str, bytes, None], charset: str = "utf-8", errors: str = "replace", cls: t.Optional[t.Type["ds.MultiDict"]] = None, ) -> "ds.MultiDict[str, str]": """Parse a cookie from a string or WSGI environ. The same key can be provided multiple times, the values are stored in-order. The default :class:`MultiDict` will have the first value first, and all values can be retrieved with :meth:`MultiDict.getlist`. :param header: The cookie header as a string, or a WSGI environ dict with a ``HTTP_COOKIE`` key. :param charset: The charset for the cookie values. :param errors: The error behavior for the charset decoding. :param cls: A dict-like class to store the parsed cookies in. Defaults to :class:`MultiDict`. .. versionchanged:: 1.0.0 Returns a :class:`MultiDict` instead of a ``TypeConversionDict``. .. versionchanged:: 0.5 Returns a :class:`TypeConversionDict` instead of a regular dict. The ``cls`` parameter was added. """ if isinstance(header, dict): cookie = header.get("HTTP_COOKIE", "") elif header is None: cookie = "" else: cookie = header return _sansio_http.parse_cookie( cookie=cookie, charset=charset, errors=errors, cls=cls )
Parse a cookie from a string or WSGI environ. The same key can be provided multiple times, the values are stored in-order. The default :class:`MultiDict` will have the first value first, and all values can be retrieved with :meth:`MultiDict.getlist`. :param header: The cookie header as a string, or a WSGI environ dict with a ``HTTP_COOKIE`` key. :param charset: The charset for the cookie values. :param errors: The error behavior for the charset decoding. :param cls: A dict-like class to store the parsed cookies in. Defaults to :class:`MultiDict`. .. versionchanged:: 1.0.0 Returns a :class:`MultiDict` instead of a ``TypeConversionDict``. .. versionchanged:: 0.5 Returns a :class:`TypeConversionDict` instead of a regular dict. The ``cls`` parameter was added.
172,467
import base64 import email.utils import re import typing import typing as t import warnings from datetime import date from datetime import datetime from datetime import time from datetime import timedelta from datetime import timezone from enum import Enum from hashlib import sha1 from time import mktime from time import struct_time from urllib.parse import unquote_to_bytes as _unquote from urllib.request import parse_http_list as _parse_list_header from ._internal import _cookie_quote from ._internal import _dt_as_utc from ._internal import _make_cookie_domain from ._internal import _to_bytes from ._internal import _to_str from ._internal import _wsgi_decoding_dance if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment def http_date( timestamp: t.Optional[t.Union[datetime, date, int, float, struct_time]] = None ) -> str: """Format a datetime object or timestamp into an :rfc:`2822` date string. This is a wrapper for :func:`email.utils.format_datetime`. It assumes naive datetime objects are in UTC instead of raising an exception. :param timestamp: The datetime or timestamp to format. Defaults to the current time. .. versionchanged:: 2.0 Use ``email.utils.format_datetime``. Accept ``date`` objects. """ if isinstance(timestamp, date): if not isinstance(timestamp, datetime): # Assume plain date is midnight UTC. timestamp = datetime.combine(timestamp, time(), tzinfo=timezone.utc) else: # Ensure datetime is timezone-aware. timestamp = _dt_as_utc(timestamp) return email.utils.format_datetime(timestamp, usegmt=True) if isinstance(timestamp, struct_time): timestamp = mktime(timestamp) return email.utils.formatdate(timestamp, usegmt=True) from . import datastructures as ds from .sansio import http as _sansio_http class timedelta(SupportsAbs[timedelta]): min: ClassVar[timedelta] max: ClassVar[timedelta] resolution: ClassVar[timedelta] if sys.version_info >= (3, 6): def __init__( self, days: float = ..., seconds: float = ..., microseconds: float = ..., milliseconds: float = ..., minutes: float = ..., hours: float = ..., weeks: float = ..., *, fold: int = ..., ) -> None: ... else: def __init__( self, days: float = ..., seconds: float = ..., microseconds: float = ..., milliseconds: float = ..., minutes: float = ..., hours: float = ..., weeks: float = ..., ) -> None: ... def days(self) -> int: ... def seconds(self) -> int: ... def microseconds(self) -> int: ... def total_seconds(self) -> float: ... def __add__(self, other: timedelta) -> timedelta: ... def __radd__(self, other: timedelta) -> timedelta: ... def __sub__(self, other: timedelta) -> timedelta: ... def __rsub__(self, other: timedelta) -> timedelta: ... def __neg__(self) -> timedelta: ... def __pos__(self) -> timedelta: ... def __abs__(self) -> timedelta: ... def __mul__(self, other: float) -> timedelta: ... def __rmul__(self, other: float) -> timedelta: ... def __floordiv__(self, other: timedelta) -> int: ... def __floordiv__(self, other: int) -> timedelta: ... if sys.version_info >= (3,): def __truediv__(self, other: timedelta) -> float: ... def __truediv__(self, other: float) -> timedelta: ... def __mod__(self, other: timedelta) -> timedelta: ... def __divmod__(self, other: timedelta) -> Tuple[int, timedelta]: ... else: def __div__(self, other: timedelta) -> float: ... def __div__(self, other: float) -> timedelta: ... def __le__(self, other: timedelta) -> bool: ... def __lt__(self, other: timedelta) -> bool: ... def __ge__(self, other: timedelta) -> bool: ... def __gt__(self, other: timedelta) -> bool: ... def __hash__(self) -> int: ... class datetime(date): min: ClassVar[datetime] max: ClassVar[datetime] resolution: ClassVar[timedelta] if sys.version_info >= (3, 6): def __new__( cls: Type[_S], year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ..., ) -> _S: ... else: def __new__( cls: Type[_S], year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> _S: ... def year(self) -> int: ... def month(self) -> int: ... def day(self) -> int: ... def hour(self) -> int: ... def minute(self) -> int: ... def second(self) -> int: ... def microsecond(self) -> int: ... def tzinfo(self) -> Optional[_tzinfo]: ... if sys.version_info >= (3, 6): def fold(self) -> int: ... def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S: ... def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ... def today(cls: Type[_S]) -> _S: ... def fromordinal(cls: Type[_S], n: int) -> _S: ... if sys.version_info >= (3, 8): def now(cls: Type[_S], tz: Optional[_tzinfo] = ...) -> _S: ... else: def now(cls: Type[_S], tz: None = ...) -> _S: ... def now(cls, tz: _tzinfo) -> datetime: ... def utcnow(cls: Type[_S]) -> _S: ... if sys.version_info >= (3, 6): def combine(cls, date: _date, time: _time, tzinfo: Optional[_tzinfo] = ...) -> datetime: ... else: def combine(cls, date: _date, time: _time) -> datetime: ... if sys.version_info >= (3, 7): def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... def strftime(self, fmt: _Text) -> str: ... if sys.version_info >= (3,): def __format__(self, fmt: str) -> str: ... else: def __format__(self, fmt: AnyStr) -> AnyStr: ... def toordinal(self) -> int: ... def timetuple(self) -> struct_time: ... if sys.version_info >= (3, 3): def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _date: ... def time(self) -> _time: ... def timetz(self) -> _time: ... if sys.version_info >= (3, 6): def replace( self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ..., ) -> datetime: ... else: def replace( self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> datetime: ... if sys.version_info >= (3, 8): def astimezone(self: _S, tz: Optional[_tzinfo] = ...) -> _S: ... elif sys.version_info >= (3, 3): def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ... else: def astimezone(self, tz: _tzinfo) -> datetime: ... def ctime(self) -> str: ... if sys.version_info >= (3, 6): def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... else: def isoformat(self, sep: str = ...) -> str: ... def strptime(cls, date_string: _Text, format: _Text) -> datetime: ... def utcoffset(self) -> Optional[timedelta]: ... def tzname(self) -> Optional[str]: ... def dst(self) -> Optional[timedelta]: ... def __le__(self, other: datetime) -> bool: ... # type: ignore def __lt__(self, other: datetime) -> bool: ... # type: ignore def __ge__(self, other: datetime) -> bool: ... # type: ignore def __gt__(self, other: datetime) -> bool: ... # type: ignore if sys.version_info >= (3, 8): def __add__(self: _S, other: timedelta) -> _S: ... def __radd__(self: _S, other: timedelta) -> _S: ... else: def __add__(self, other: timedelta) -> datetime: ... def __radd__(self, other: timedelta) -> datetime: ... def __sub__(self, other: datetime) -> timedelta: ... def __sub__(self, other: timedelta) -> datetime: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... def isocalendar(self) -> Tuple[int, int, int]: ... def _to_bytes( x: t.Union[str, bytes], charset: str = _default_encoding, errors: str = "strict" ) -> bytes: if x is None or isinstance(x, bytes): return x if isinstance(x, (bytearray, memoryview)): return bytes(x) if isinstance(x, str): return x.encode(charset, errors) raise TypeError("Expected bytes") def _cookie_quote(b: bytes) -> bytes: buf = bytearray() all_legal = True _lookup = _cookie_quoting_map.get _push = buf.extend for char_int in b: char = char_int.to_bytes(1, sys.byteorder) if char not in _legal_cookie_chars: all_legal = False char = _lookup(char, char) _push(char) if all_legal: return bytes(buf) return bytes(b'"' + buf + b'"') def _make_cookie_domain(domain: None) -> None: ... def _make_cookie_domain(domain: str) -> bytes: ... def _make_cookie_domain(domain: t.Optional[str]) -> t.Optional[bytes]: if domain is None: return None domain = _encode_idna(domain) if b":" in domain: domain = domain.split(b":", 1)[0] if b"." in domain: return domain raise ValueError( "Setting 'domain' for a cookie on a server running locally (ex: " "localhost) is not supported by complying browsers. You should " "have something like: '127.0.0.1 localhost dev.localhost' on " "your hosts file and then point your server to run on " "'dev.localhost' and also set 'domain' for 'dev.localhost'" ) def iri_to_uri( iri: t.Union[str, t.Tuple[str, str, str, str, str]], charset: str = "utf-8", errors: str = "strict", safe_conversion: bool = False, ) -> str: """Convert an IRI to a URI. All non-ASCII and unsafe characters are quoted. If the URL has a domain, it is encoded to Punycode. >>> iri_to_uri('http://\\u2603.net/p\\xe5th?q=\\xe8ry%DF') 'http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF' :param iri: The IRI to convert. :param charset: The encoding of the IRI. :param errors: Error handler to use during ``bytes.encode``. :param safe_conversion: Return the URL unchanged if it only contains ASCII characters and no whitespace. See the explanation below. There is a general problem with IRI conversion with some protocols that are in violation of the URI specification. Consider the following two IRIs:: magnet:?xt=uri:whatever itms-services://?action=download-manifest After parsing, we don't know if the scheme requires the ``//``, which is dropped if empty, but conveys different meanings in the final URL if it's present or not. In this case, you can use ``safe_conversion``, which will return the URL unchanged if it only contains ASCII characters and no whitespace. This can result in a URI with unquoted characters if it was not already quoted correctly, but preserves the URL's semantics. Werkzeug uses this for the ``Location`` header for redirects. .. versionchanged:: 0.15 All reserved characters remain unquoted. Previously, only some reserved characters were left unquoted. .. versionchanged:: 0.9.6 The ``safe_conversion`` parameter was added. .. versionadded:: 0.6 """ if isinstance(iri, tuple): iri = url_unparse(iri) if safe_conversion: # If we're not sure if it's safe to convert the URL, and it only # contains ASCII characters, return it unconverted. try: native_iri = _to_str(iri) ascii_iri = native_iri.encode("ascii") # Only return if it doesn't have whitespace. (Why?) if len(ascii_iri.split()) == 1: return native_iri except UnicodeError: pass iri = url_parse(_to_str(iri, charset, errors)) path = url_quote(iri.path, charset, errors, _to_uri_safe) query = url_quote(iri.query, charset, errors, _to_uri_safe) fragment = url_quote(iri.fragment, charset, errors, _to_uri_safe) return url_unparse((iri.scheme, iri.encode_netloc(), path, query, fragment)) The provided code snippet includes necessary dependencies for implementing the `dump_cookie` function. Write a Python function `def dump_cookie( key: str, value: t.Union[bytes, str] = "", max_age: t.Optional[t.Union[timedelta, int]] = None, expires: t.Optional[t.Union[str, datetime, int, float]] = None, path: t.Optional[str] = "/", domain: t.Optional[str] = None, secure: bool = False, httponly: bool = False, charset: str = "utf-8", sync_expires: bool = True, max_size: int = 4093, samesite: t.Optional[str] = None, ) -> str` to solve the following problem: Create a Set-Cookie header without the ``Set-Cookie`` prefix. The return value is usually restricted to ascii as the vast majority of values are properly escaped, but that is no guarantee. It's tunneled through latin1 as required by :pep:`3333`. The return value is not ASCII safe if the key contains unicode characters. This is technically against the specification but happens in the wild. It's strongly recommended to not use non-ASCII values for the keys. :param max_age: should be a number of seconds, or `None` (default) if the cookie should last only as long as the client's browser session. Additionally `timedelta` objects are accepted, too. :param expires: should be a `datetime` object or unix timestamp. :param path: limits the cookie to a given path, per default it will span the whole domain. :param domain: Use this if you want to set a cross-domain cookie. For example, ``domain=".example.com"`` will set a cookie that is readable by the domain ``www.example.com``, ``foo.example.com`` etc. Otherwise, a cookie will only be readable by the domain that set it. :param secure: The cookie will only be available via HTTPS :param httponly: disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers. :param charset: the encoding for string values. :param sync_expires: automatically set expires if max_age is defined but expires not. :param max_size: Warn if the final header value exceeds this size. The default, 4093, should be safely `supported by most browsers <cookie_>`_. Set to 0 to disable this check. :param samesite: Limits the scope of the cookie such that it will only be attached to requests if those requests are same-site. .. _`cookie`: http://browsercookielimits.squawky.net/ .. versionchanged:: 1.0.0 The string ``'None'`` is accepted for ``samesite``. Here is the function: def dump_cookie( key: str, value: t.Union[bytes, str] = "", max_age: t.Optional[t.Union[timedelta, int]] = None, expires: t.Optional[t.Union[str, datetime, int, float]] = None, path: t.Optional[str] = "/", domain: t.Optional[str] = None, secure: bool = False, httponly: bool = False, charset: str = "utf-8", sync_expires: bool = True, max_size: int = 4093, samesite: t.Optional[str] = None, ) -> str: """Create a Set-Cookie header without the ``Set-Cookie`` prefix. The return value is usually restricted to ascii as the vast majority of values are properly escaped, but that is no guarantee. It's tunneled through latin1 as required by :pep:`3333`. The return value is not ASCII safe if the key contains unicode characters. This is technically against the specification but happens in the wild. It's strongly recommended to not use non-ASCII values for the keys. :param max_age: should be a number of seconds, or `None` (default) if the cookie should last only as long as the client's browser session. Additionally `timedelta` objects are accepted, too. :param expires: should be a `datetime` object or unix timestamp. :param path: limits the cookie to a given path, per default it will span the whole domain. :param domain: Use this if you want to set a cross-domain cookie. For example, ``domain=".example.com"`` will set a cookie that is readable by the domain ``www.example.com``, ``foo.example.com`` etc. Otherwise, a cookie will only be readable by the domain that set it. :param secure: The cookie will only be available via HTTPS :param httponly: disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers. :param charset: the encoding for string values. :param sync_expires: automatically set expires if max_age is defined but expires not. :param max_size: Warn if the final header value exceeds this size. The default, 4093, should be safely `supported by most browsers <cookie_>`_. Set to 0 to disable this check. :param samesite: Limits the scope of the cookie such that it will only be attached to requests if those requests are same-site. .. _`cookie`: http://browsercookielimits.squawky.net/ .. versionchanged:: 1.0.0 The string ``'None'`` is accepted for ``samesite``. """ key = _to_bytes(key, charset) value = _to_bytes(value, charset) if path is not None: from .urls import iri_to_uri path = iri_to_uri(path, charset) domain = _make_cookie_domain(domain) if isinstance(max_age, timedelta): max_age = int(max_age.total_seconds()) if expires is not None: if not isinstance(expires, str): expires = http_date(expires) elif max_age is not None and sync_expires: expires = http_date(datetime.now(tz=timezone.utc).timestamp() + max_age) if samesite is not None: samesite = samesite.title() if samesite not in {"Strict", "Lax", "None"}: raise ValueError("SameSite must be 'Strict', 'Lax', or 'None'.") buf = [key + b"=" + _cookie_quote(value)] # XXX: In theory all of these parameters that are not marked with `None` # should be quoted. Because stdlib did not quote it before I did not # want to introduce quoting there now. for k, v, q in ( (b"Domain", domain, True), (b"Expires", expires, False), (b"Max-Age", max_age, False), (b"Secure", secure, None), (b"HttpOnly", httponly, None), (b"Path", path, False), (b"SameSite", samesite, False), ): if q is None: if v: buf.append(k) continue if v is None: continue tmp = bytearray(k) if not isinstance(v, (bytes, bytearray)): v = _to_bytes(str(v), charset) if q: v = _cookie_quote(v) tmp += b"=" + v buf.append(bytes(tmp)) # The return value will be an incorrectly encoded latin1 header for # consistency with the headers object. rv = b"; ".join(buf) rv = rv.decode("latin1") # Warn if the final value of the cookie is larger than the limit. If the # cookie is too large, then it may be silently ignored by the browser, # which can be quite hard to debug. cookie_size = len(rv) if max_size and cookie_size > max_size: value_size = len(value) warnings.warn( f"The {key.decode(charset)!r} cookie is too large: the value was" f" {value_size} bytes but the" f" header required {cookie_size - value_size} extra bytes. The final size" f" was {cookie_size} bytes but the limit is {max_size} bytes. Browsers may" f" silently ignore cookies larger than this.", stacklevel=2, ) return rv
Create a Set-Cookie header without the ``Set-Cookie`` prefix. The return value is usually restricted to ascii as the vast majority of values are properly escaped, but that is no guarantee. It's tunneled through latin1 as required by :pep:`3333`. The return value is not ASCII safe if the key contains unicode characters. This is technically against the specification but happens in the wild. It's strongly recommended to not use non-ASCII values for the keys. :param max_age: should be a number of seconds, or `None` (default) if the cookie should last only as long as the client's browser session. Additionally `timedelta` objects are accepted, too. :param expires: should be a `datetime` object or unix timestamp. :param path: limits the cookie to a given path, per default it will span the whole domain. :param domain: Use this if you want to set a cross-domain cookie. For example, ``domain=".example.com"`` will set a cookie that is readable by the domain ``www.example.com``, ``foo.example.com`` etc. Otherwise, a cookie will only be readable by the domain that set it. :param secure: The cookie will only be available via HTTPS :param httponly: disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers. :param charset: the encoding for string values. :param sync_expires: automatically set expires if max_age is defined but expires not. :param max_size: Warn if the final header value exceeds this size. The default, 4093, should be safely `supported by most browsers <cookie_>`_. Set to 0 to disable this check. :param samesite: Limits the scope of the cookie such that it will only be attached to requests if those requests are same-site. .. _`cookie`: http://browsercookielimits.squawky.net/ .. versionchanged:: 1.0.0 The string ``'None'`` is accepted for ``samesite``.
172,468
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary def _wsgi_encoding_dance( s: str, charset: str = "utf-8", errors: str = "replace" ) -> str: if isinstance(s, bytes): return s.decode("latin1", errors) return s.encode(charset).decode("latin1", errors)
null
172,469
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment from .wrappers.request import Request # noqa: F401 def _get_environ(obj: t.Union["WSGIEnvironment", "Request"]) -> "WSGIEnvironment": env = getattr(obj, "environ", obj) assert isinstance( env, dict ), f"{type(obj).__name__!r} is not a WSGI environment (has to be a dict)" return env
null
172,470
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment from .wrappers.request import Request # noqa: F401 def _decode_idna(domain: t.Union[str, bytes]) -> str: # If the input is a string try to encode it to ascii to do the idna # decoding. If that fails because of a unicode error, then we # already have a decoded idna domain. if isinstance(domain, str): try: domain = domain.encode("ascii") except UnicodeError: return domain # type: ignore # Decode each part separately. If a part fails, try to decode it # with ascii and silently ignore errors. This makes sense because # the idna codec does not have error handling. def decode_part(part: bytes) -> str: try: return part.decode("idna") except UnicodeError: return part.decode("ascii", "ignore") return ".".join(decode_part(p) for p in domain.split(b"."))
null
172,471
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment from .wrappers.request import Request # noqa: F401 The provided code snippet includes necessary dependencies for implementing the `_easteregg` function. Write a Python function `def _easteregg(app: t.Optional["WSGIApplication"] = None) -> "WSGIApplication"` to solve the following problem: Like the name says. But who knows how it works? Here is the function: def _easteregg(app: t.Optional["WSGIApplication"] = None) -> "WSGIApplication": """Like the name says. But who knows how it works?""" def bzzzzzzz(gyver: bytes) -> str: import base64 import zlib return zlib.decompress(base64.b64decode(gyver)).decode("ascii") gyver = "\n".join( [ x + (77 - len(x)) * " " for x in bzzzzzzz( b""" eJyFlzuOJDkMRP06xRjymKgDJCDQStBYT8BCgK4gTwfQ2fcFs2a2FzvZk+hvlcRvRJD148efHt9m 9Xz94dRY5hGt1nrYcXx7us9qlcP9HHNh28rz8dZj+q4rynVFFPdlY4zH873NKCexrDM6zxxRymzz 4QIxzK4bth1PV7+uHn6WXZ5C4ka/+prFzx3zWLMHAVZb8RRUxtFXI5DTQ2n3Hi2sNI+HK43AOWSY jmEzE4naFp58PdzhPMdslLVWHTGUVpSxImw+pS/D+JhzLfdS1j7PzUMxij+mc2U0I9zcbZ/HcZxc q1QjvvcThMYFnp93agEx392ZdLJWXbi/Ca4Oivl4h/Y1ErEqP+lrg7Xa4qnUKu5UE9UUA4xeqLJ5 jWlPKJvR2yhRI7xFPdzPuc6adXu6ovwXwRPXXnZHxlPtkSkqWHilsOrGrvcVWXgGP3daXomCj317 8P2UOw/NnA0OOikZyFf3zZ76eN9QXNwYdD8f8/LdBRFg0BO3bB+Pe/+G8er8tDJv83XTkj7WeMBJ v/rnAfdO51d6sFglfi8U7zbnr0u9tyJHhFZNXYfH8Iafv2Oa+DT6l8u9UYlajV/hcEgk1x8E8L/r XJXl2SK+GJCxtnyhVKv6GFCEB1OO3f9YWAIEbwcRWv/6RPpsEzOkXURMN37J0PoCSYeBnJQd9Giu LxYQJNlYPSo/iTQwgaihbART7Fcyem2tTSCcwNCs85MOOpJtXhXDe0E7zgZJkcxWTar/zEjdIVCk iXy87FW6j5aGZhttDBoAZ3vnmlkx4q4mMmCdLtnHkBXFMCReqthSGkQ+MDXLLCpXwBs0t+sIhsDI tjBB8MwqYQpLygZ56rRHHpw+OAVyGgaGRHWy2QfXez+ZQQTTBkmRXdV/A9LwH6XGZpEAZU8rs4pE 1R4FQ3Uwt8RKEtRc0/CrANUoes3EzM6WYcFyskGZ6UTHJWenBDS7h163Eo2bpzqxNE9aVgEM2CqI GAJe9Yra4P5qKmta27VjzYdR04Vc7KHeY4vs61C0nbywFmcSXYjzBHdiEjraS7PGG2jHHTpJUMxN Jlxr3pUuFvlBWLJGE3GcA1/1xxLcHmlO+LAXbhrXah1tD6Ze+uqFGdZa5FM+3eHcKNaEarutAQ0A QMAZHV+ve6LxAwWnXbbSXEG2DmCX5ijeLCKj5lhVFBrMm+ryOttCAeFpUdZyQLAQkA06RLs56rzG 8MID55vqr/g64Qr/wqwlE0TVxgoiZhHrbY2h1iuuyUVg1nlkpDrQ7Vm1xIkI5XRKLedN9EjzVchu jQhXcVkjVdgP2O99QShpdvXWoSwkp5uMwyjt3jiWCqWGSiaaPAzohjPanXVLbM3x0dNskJsaCEyz DTKIs+7WKJD4ZcJGfMhLFBf6hlbnNkLEePF8Cx2o2kwmYF4+MzAxa6i+6xIQkswOqGO+3x9NaZX8 MrZRaFZpLeVTYI9F/djY6DDVVs340nZGmwrDqTCiiqD5luj3OzwpmQCiQhdRYowUYEA3i1WWGwL4 GCtSoO4XbIPFeKGU13XPkDf5IdimLpAvi2kVDVQbzOOa4KAXMFlpi/hV8F6IDe0Y2reg3PuNKT3i RYhZqtkQZqSB2Qm0SGtjAw7RDwaM1roESC8HWiPxkoOy0lLTRFG39kvbLZbU9gFKFRvixDZBJmpi Xyq3RE5lW00EJjaqwp/v3EByMSpVZYsEIJ4APaHmVtpGSieV5CALOtNUAzTBiw81GLgC0quyzf6c NlWknzJeCsJ5fup2R4d8CYGN77mu5vnO1UqbfElZ9E6cR6zbHjgsr9ly18fXjZoPeDjPuzlWbFwS pdvPkhntFvkc13qb9094LL5NrA3NIq3r9eNnop9DizWOqCEbyRBFJTHn6Tt3CG1o8a4HevYh0XiJ sR0AVVHuGuMOIfbuQ/OKBkGRC6NJ4u7sbPX8bG/n5sNIOQ6/Y/BX3IwRlTSabtZpYLB85lYtkkgm p1qXK3Du2mnr5INXmT/78KI12n11EFBkJHHp0wJyLe9MvPNUGYsf+170maayRoy2lURGHAIapSpQ krEDuNoJCHNlZYhKpvw4mspVWxqo415n8cD62N9+EfHrAvqQnINStetek7RY2Urv8nxsnGaZfRr/ nhXbJ6m/yl1LzYqscDZA9QHLNbdaSTTr+kFg3bC0iYbX/eQy0Bv3h4B50/SGYzKAXkCeOLI3bcAt mj2Z/FM1vQWgDynsRwNvrWnJHlespkrp8+vO1jNaibm+PhqXPPv30YwDZ6jApe3wUjFQobghvW9p 7f2zLkGNv8b191cD/3vs9Q833z8t""" ).splitlines() ] ) def easteregged( environ: "WSGIEnvironment", start_response: "StartResponse" ) -> t.Iterable[bytes]: def injecting_start_response( status: str, headers: t.List[t.Tuple[str, str]], exc_info: t.Any = None ) -> t.Callable[[bytes], t.Any]: headers.append(("X-Powered-By", "Werkzeug")) return start_response(status, headers, exc_info) if app is not None and environ.get("QUERY_STRING") != "macgybarchakku": return app(environ, injecting_start_response) injecting_start_response("200 OK", [("Content-Type", "text/html")]) return [ f"""\ <!doctype html> <html lang=en> <head> <title>About Werkzeug</title> <style type="text/css"> body {{ font: 15px Georgia, serif; text-align: center; }} a {{ color: #333; text-decoration: none; }} h1 {{ font-size: 30px; margin: 20px 0 10px 0; }} p {{ margin: 0 0 30px 0; }} pre {{ font: 11px 'Consolas', 'Monaco', monospace; line-height: 0.95; }} </style> </head> <body> <h1><a href="http://werkzeug.pocoo.org/">Werkzeug</a></h1> <p>the Swiss Army knife of Python web development.</p> <pre>{gyver}\n\n\n</pre> </body> </html>""".encode( "latin1" ) ] return easteregged
Like the name says. But who knows how it works?
172,472
import fnmatch import os import subprocess import sys import threading import time import typing as t from itertools import chain from pathlib import PurePath from ._internal import _log _stat_ignore_scan = tuple(prefix) _ignore_common_dirs = { "__pycache__", ".git", ".hg", ".tox", ".nox", ".pytest_cache", ".mypy_cache", } def _iter_module_paths() -> t.Iterator[str]: """Find the filesystem paths associated with imported modules.""" # List is in case the value is modified by the app while updating. for module in list(sys.modules.values()): name = getattr(module, "__file__", None) if name is None or name.startswith(_ignore_always): continue while not os.path.isfile(name): # Zip file, find the base file without the module path. old = name name = os.path.dirname(name) if name == old: # skip if it was all directories somehow break else: yield name def _remove_by_pattern(paths: t.Set[str], exclude_patterns: t.Set[str]) -> None: for pattern in exclude_patterns: paths.difference_update(fnmatch.filter(paths, pattern)) class chain(Iterator[_T], Generic[_T]): def __init__(self, *iterables: Iterable[_T]) -> None: ... def __next__(self) -> _T: ... def __iter__(self) -> Iterator[_T]: ... def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... The provided code snippet includes necessary dependencies for implementing the `_find_stat_paths` function. Write a Python function `def _find_stat_paths( extra_files: t.Set[str], exclude_patterns: t.Set[str] ) -> t.Iterable[str]` to solve the following problem: Find paths for the stat reloader to watch. Returns imported module files, Python files under non-system paths. Extra files and Python files under extra directories can also be scanned. System paths have to be excluded for efficiency. Non-system paths, such as a project root or ``sys.path.insert``, should be the paths of interest to the user anyway. Here is the function: def _find_stat_paths( extra_files: t.Set[str], exclude_patterns: t.Set[str] ) -> t.Iterable[str]: """Find paths for the stat reloader to watch. Returns imported module files, Python files under non-system paths. Extra files and Python files under extra directories can also be scanned. System paths have to be excluded for efficiency. Non-system paths, such as a project root or ``sys.path.insert``, should be the paths of interest to the user anyway. """ paths = set() for path in chain(list(sys.path), extra_files): path = os.path.abspath(path) if os.path.isfile(path): # zip file on sys.path, or extra file paths.add(path) continue parent_has_py = {os.path.dirname(path): True} for root, dirs, files in os.walk(path): # Optimizations: ignore system prefixes, __pycache__ will # have a py or pyc module at the import path, ignore some # common known dirs such as version control and tool caches. if ( root.startswith(_stat_ignore_scan) or os.path.basename(root) in _ignore_common_dirs ): dirs.clear() continue has_py = False for name in files: if name.endswith((".py", ".pyc")): has_py = True paths.add(os.path.join(root, name)) # Optimization: stop scanning a directory if neither it nor # its parent contained Python files. if not (has_py or parent_has_py[os.path.dirname(root)]): dirs.clear() continue parent_has_py[root] = has_py paths.update(_iter_module_paths()) _remove_by_pattern(paths, exclude_patterns) return paths
Find paths for the stat reloader to watch. Returns imported module files, Python files under non-system paths. Extra files and Python files under extra directories can also be scanned. System paths have to be excluded for efficiency. Non-system paths, such as a project root or ``sys.path.insert``, should be the paths of interest to the user anyway.
172,473
import fnmatch import os import subprocess import sys import threading import time import typing as t from itertools import chain from pathlib import PurePath from ._internal import _log def _iter_module_paths() -> t.Iterator[str]: """Find the filesystem paths associated with imported modules.""" # List is in case the value is modified by the app while updating. for module in list(sys.modules.values()): name = getattr(module, "__file__", None) if name is None or name.startswith(_ignore_always): continue while not os.path.isfile(name): # Zip file, find the base file without the module path. old = name name = os.path.dirname(name) if name == old: # skip if it was all directories somehow break else: yield name def _remove_by_pattern(paths: t.Set[str], exclude_patterns: t.Set[str]) -> None: for pattern in exclude_patterns: paths.difference_update(fnmatch.filter(paths, pattern)) def _find_common_roots(paths: t.Iterable[str]) -> t.Iterable[str]: root: t.Dict[str, dict] = {} for chunks in sorted((PurePath(x).parts for x in paths), key=len, reverse=True): node = root for chunk in chunks: node = node.setdefault(chunk, {}) node.clear() rv = set() def _walk(node: t.Mapping[str, dict], path: t.Tuple[str, ...]) -> None: for prefix, child in node.items(): _walk(child, path + (prefix,)) if not node: rv.add(os.path.join(*path)) _walk(root, ()) return rv class chain(Iterator[_T], Generic[_T]): def __init__(self, *iterables: Iterable[_T]) -> None: ... def __next__(self) -> _T: ... def __iter__(self) -> Iterator[_T]: ... def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... The provided code snippet includes necessary dependencies for implementing the `_find_watchdog_paths` function. Write a Python function `def _find_watchdog_paths( extra_files: t.Set[str], exclude_patterns: t.Set[str] ) -> t.Iterable[str]` to solve the following problem: Find paths for the stat reloader to watch. Looks at the same sources as the stat reloader, but watches everything under directories instead of individual files. Here is the function: def _find_watchdog_paths( extra_files: t.Set[str], exclude_patterns: t.Set[str] ) -> t.Iterable[str]: """Find paths for the stat reloader to watch. Looks at the same sources as the stat reloader, but watches everything under directories instead of individual files. """ dirs = set() for name in chain(list(sys.path), extra_files): name = os.path.abspath(name) if os.path.isfile(name): name = os.path.dirname(name) dirs.add(name) for name in _iter_module_paths(): dirs.add(os.path.dirname(name)) _remove_by_pattern(dirs, exclude_patterns) return _find_common_roots(dirs)
Find paths for the stat reloader to watch. Looks at the same sources as the stat reloader, but watches everything under directories instead of individual files.
172,474
import fnmatch import os import subprocess import sys import threading import time import typing as t from itertools import chain from pathlib import PurePath from ._internal import _log The provided code snippet includes necessary dependencies for implementing the `_get_args_for_reloading` function. Write a Python function `def _get_args_for_reloading() -> t.List[str]` to solve the following problem: Determine how the script was executed, and return the args needed to execute it again in a new process. Here is the function: def _get_args_for_reloading() -> t.List[str]: """Determine how the script was executed, and return the args needed to execute it again in a new process. """ rv = [sys.executable] py_script = sys.argv[0] args = sys.argv[1:] # Need to look at main module to determine how it was executed. __main__ = sys.modules["__main__"] # The value of __package__ indicates how Python was called. It may # not exist if a setuptools script is installed as an egg. It may be # set incorrectly for entry points created with pip on Windows. if getattr(__main__, "__package__", None) is None or ( os.name == "nt" and __main__.__package__ == "" and not os.path.exists(py_script) and os.path.exists(f"{py_script}.exe") ): # Executed a file, like "python app.py". py_script = os.path.abspath(py_script) if os.name == "nt": # Windows entry points have ".exe" extension and should be # called directly. if not os.path.exists(py_script) and os.path.exists(f"{py_script}.exe"): py_script += ".exe" if ( os.path.splitext(sys.executable)[1] == ".exe" and os.path.splitext(py_script)[1] == ".exe" ): rv.pop(0) rv.append(py_script) else: # Executed a module, like "python -m werkzeug.serving". if os.path.isfile(py_script): # Rewritten by Python from "-m script" to "/path/to/script.py". py_module = t.cast(str, __main__.__package__) name = os.path.splitext(os.path.basename(py_script))[0] if name != "__main__": py_module += f".{name}" else: # Incorrectly rewritten by pydevd debugger from "-m script" to "script". py_module = py_script rv.extend(("-m", py_module.lstrip("."))) rv.extend(args) return rv
Determine how the script was executed, and return the args needed to execute it again in a new process.
172,475
import io import re import typing as t import warnings from functools import partial from functools import update_wrapper from itertools import chain from ._internal import _make_encode_wrapper from ._internal import _to_bytes from ._internal import _to_str from .sansio import utils as _sansio_utils from .sansio.utils import host_is_trusted from .urls import _URLTuple from .urls import uri_to_iri from .urls import url_join from .urls import url_parse from .urls import url_quote if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment def update_wrapper(wrapper: _T, wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> _T: ... The provided code snippet includes necessary dependencies for implementing the `responder` function. Write a Python function `def responder(f: t.Callable[..., "WSGIApplication"]) -> "WSGIApplication"` to solve the following problem: Marks a function as responder. Decorate a function with it and it will automatically call the return value as WSGI application. Example:: @responder def application(environ, start_response): return Response('Hello World!') Here is the function: def responder(f: t.Callable[..., "WSGIApplication"]) -> "WSGIApplication": """Marks a function as responder. Decorate a function with it and it will automatically call the return value as WSGI application. Example:: @responder def application(environ, start_response): return Response('Hello World!') """ return update_wrapper(lambda *a: f(*a)(*a[-2:]), f)
Marks a function as responder. Decorate a function with it and it will automatically call the return value as WSGI application. Example:: @responder def application(environ, start_response): return Response('Hello World!')
172,476
import io import re import typing as t import warnings from functools import partial from functools import update_wrapper from itertools import chain from ._internal import _make_encode_wrapper from ._internal import _to_bytes from ._internal import _to_str from .sansio import utils as _sansio_utils from .sansio.utils import host_is_trusted from .urls import _URLTuple from .urls import uri_to_iri from .urls import url_join from .urls import url_parse from .urls import url_quote if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIApplication from _typeshed.wsgi import WSGIEnvironment def get_content_length(environ: "WSGIEnvironment") -> t.Optional[int]: """Returns the content length from the WSGI environment as integer. If it's not available or chunked transfer encoding is used, ``None`` is returned. .. versionadded:: 0.9 :param environ: the WSGI environ to fetch the content length from. """ return _sansio_utils.get_content_length( http_content_length=environ.get("CONTENT_LENGTH"), http_transfer_encoding=environ.get("HTTP_TRANSFER_ENCODING", ""), ) class LimitedStream(io.IOBase): """Wraps a stream so that it doesn't read more than n bytes. If the stream is exhausted and the caller tries to get more bytes from it :func:`on_exhausted` is called which by default returns an empty string. The return value of that function is forwarded to the reader function. So if it returns an empty string :meth:`read` will return an empty string as well. The limit however must never be higher than what the stream can output. Otherwise :meth:`readlines` will try to read past the limit. .. admonition:: Note on WSGI compliance calls to :meth:`readline` and :meth:`readlines` are not WSGI compliant because it passes a size argument to the readline methods. Unfortunately the WSGI PEP is not safely implementable without a size argument to :meth:`readline` because there is no EOF marker in the stream. As a result of that the use of :meth:`readline` is discouraged. For the same reason iterating over the :class:`LimitedStream` is not portable. It internally calls :meth:`readline`. We strongly suggest using :meth:`read` only or using the :func:`make_line_iter` which safely iterates line-based over a WSGI input stream. :param stream: the stream to wrap. :param limit: the limit for the stream, must not be longer than what the string can provide if the stream does not end with `EOF` (like `wsgi.input`) """ def __init__(self, stream: t.IO[bytes], limit: int) -> None: self._read = stream.read self._readline = stream.readline self._pos = 0 self.limit = limit def __iter__(self) -> "LimitedStream": return self def is_exhausted(self) -> bool: """If the stream is exhausted this attribute is `True`.""" return self._pos >= self.limit def on_exhausted(self) -> bytes: """This is called when the stream tries to read past the limit. The return value of this function is returned from the reading function. """ # Read null bytes from the stream so that we get the # correct end of stream marker. return self._read(0) def on_disconnect(self) -> bytes: """What should happen if a disconnect is detected? The return value of this function is returned from read functions in case the client went away. By default a :exc:`~werkzeug.exceptions.ClientDisconnected` exception is raised. """ from .exceptions import ClientDisconnected raise ClientDisconnected() def _exhaust_chunks(self, chunk_size: int = 1024 * 64) -> t.Iterator[bytes]: """Exhaust the stream by reading until the limit is reached or the client disconnects, yielding each chunk. :param chunk_size: How many bytes to read at a time. :meta private: .. versionadded:: 2.2.3 """ to_read = self.limit - self._pos while to_read > 0: chunk = self.read(min(to_read, chunk_size)) yield chunk to_read -= len(chunk) def exhaust(self, chunk_size: int = 1024 * 64) -> None: """Exhaust the stream by reading until the limit is reached or the client disconnects, discarding the data. :param chunk_size: How many bytes to read at a time. .. versionchanged:: 2.2.3 Handle case where wrapped stream returns fewer bytes than requested. """ for _ in self._exhaust_chunks(chunk_size): pass def read(self, size: t.Optional[int] = None) -> bytes: """Read up to ``size`` bytes from the underlying stream. If size is not provided, read until the limit. If the limit is reached, :meth:`on_exhausted` is called, which returns empty bytes. If no bytes are read and the limit is not reached, or if an error occurs during the read, :meth:`on_disconnect` is called, which raises :exc:`.ClientDisconnected`. :param size: The number of bytes to read. ``None``, default, reads until the limit is reached. .. versionchanged:: 2.2.3 Handle case where wrapped stream returns fewer bytes than requested. """ if self._pos >= self.limit: return self.on_exhausted() if size is None or size == -1: # -1 is for consistency with file # Keep reading from the wrapped stream until the limit is reached. Can't # rely on stream.read(size) because it's not guaranteed to return size. buf = bytearray() for chunk in self._exhaust_chunks(): buf.extend(chunk) return bytes(buf) to_read = min(self.limit - self._pos, size) try: read = self._read(to_read) except (OSError, ValueError): return self.on_disconnect() if to_read and not len(read): # If no data was read, treat it as a disconnect. As long as some data was # read, a subsequent call can still return more before reaching the limit. return self.on_disconnect() self._pos += len(read) return read def readline(self, size: t.Optional[int] = None) -> bytes: """Reads one line from the stream.""" if self._pos >= self.limit: return self.on_exhausted() if size is None: size = self.limit - self._pos else: size = min(size, self.limit - self._pos) try: line = self._readline(size) except (ValueError, OSError): return self.on_disconnect() if size and not line: return self.on_disconnect() self._pos += len(line) return line def readlines(self, size: t.Optional[int] = None) -> t.List[bytes]: """Reads a file into a list of strings. It calls :meth:`readline` until the file is read to the end. It does support the optional `size` argument if the underlying stream supports it for `readline`. """ last_pos = self._pos result = [] if size is not None: end = min(self.limit, last_pos + size) else: end = self.limit while True: if size is not None: size -= last_pos - self._pos if self._pos >= end: break result.append(self.readline(size)) if size is not None: last_pos = self._pos return result def tell(self) -> int: """Returns the position of the stream. .. versionadded:: 0.9 """ return self._pos def __next__(self) -> bytes: line = self.readline() if not line: raise StopIteration() return line def readable(self) -> bool: return True The provided code snippet includes necessary dependencies for implementing the `get_input_stream` function. Write a Python function `def get_input_stream( environ: "WSGIEnvironment", safe_fallback: bool = True ) -> t.IO[bytes]` to solve the following problem: Returns the input stream from the WSGI environment and wraps it in the most sensible way possible. The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length. If content length is not set, the stream will be empty for safety reasons. If the WSGI server supports chunked or infinite streams, it should set the ``wsgi.input_terminated`` value in the WSGI environ to indicate that. .. versionadded:: 0.9 :param environ: the WSGI environ to fetch the stream from. :param safe_fallback: use an empty stream as a safe fallback when the content length is not set. Disabling this allows infinite streams, which can be a denial-of-service risk. Here is the function: def get_input_stream( environ: "WSGIEnvironment", safe_fallback: bool = True ) -> t.IO[bytes]: """Returns the input stream from the WSGI environment and wraps it in the most sensible way possible. The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length. If content length is not set, the stream will be empty for safety reasons. If the WSGI server supports chunked or infinite streams, it should set the ``wsgi.input_terminated`` value in the WSGI environ to indicate that. .. versionadded:: 0.9 :param environ: the WSGI environ to fetch the stream from. :param safe_fallback: use an empty stream as a safe fallback when the content length is not set. Disabling this allows infinite streams, which can be a denial-of-service risk. """ stream = t.cast(t.IO[bytes], environ["wsgi.input"]) content_length = get_content_length(environ) # A wsgi extension that tells us if the input is terminated. In # that case we return the stream unchanged as we know we can safely # read it until the end. if environ.get("wsgi.input_terminated"): return stream # If the request doesn't specify a content length, returning the stream is # potentially dangerous because it could be infinite, malicious or not. If # safe_fallback is true, return an empty stream instead for safety. if content_length is None: return io.BytesIO() if safe_fallback else stream # Otherwise limit the stream to the content length return t.cast(t.IO[bytes], LimitedStream(stream, content_length))
Returns the input stream from the WSGI environment and wraps it in the most sensible way possible. The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length. If content length is not set, the stream will be empty for safety reasons. If the WSGI server supports chunked or infinite streams, it should set the ``wsgi.input_terminated`` value in the WSGI environ to indicate that. .. versionadded:: 0.9 :param environ: the WSGI environ to fetch the stream from. :param safe_fallback: use an empty stream as a safe fallback when the content length is not set. Disabling this allows infinite streams, which can be a denial-of-service risk.
172,477
import io import re import typing as t import warnings from functools import partial from functools import update_wrapper from itertools import chain from ._internal import _make_encode_wrapper from ._internal import _to_bytes from ._internal import _to_str from .sansio import utils as _sansio_utils from .sansio.utils import host_is_trusted from .urls import _URLTuple from .urls import uri_to_iri from .urls import url_join from .urls import url_parse from .urls import url_quote def url_quote( string: t.Union[str, bytes], charset: str = "utf-8", errors: str = "strict", safe: t.Union[str, bytes] = "/:", unsafe: t.Union[str, bytes] = "", ) -> str: """URL encode a single string with a given encoding. :param s: the string to quote. :param charset: the charset to be used. :param safe: an optional sequence of safe characters. :param unsafe: an optional sequence of unsafe characters. .. versionadded:: 0.9.2 The `unsafe` parameter was added. """ if not isinstance(string, (str, bytes, bytearray)): string = str(string) if isinstance(string, str): string = string.encode(charset, errors) if isinstance(safe, str): safe = safe.encode(charset, errors) if isinstance(unsafe, str): unsafe = unsafe.encode(charset, errors) safe = (frozenset(bytearray(safe)) | _always_safe) - frozenset(bytearray(unsafe)) rv = bytearray() for char in bytearray(string): if char in safe: rv.append(char) else: rv.extend(_bytetohex[char]) return bytes(rv).decode(charset) The provided code snippet includes necessary dependencies for implementing the `get_query_string` function. Write a Python function `def get_query_string(environ: "WSGIEnvironment") -> str` to solve the following problem: Returns the ``QUERY_STRING`` from the WSGI environment. This also takes care of the WSGI decoding dance. The string returned will be restricted to ASCII characters. :param environ: WSGI environment to get the query string from. .. deprecated:: 2.2 Will be removed in Werkzeug 2.3. .. versionadded:: 0.9 Here is the function: def get_query_string(environ: "WSGIEnvironment") -> str: """Returns the ``QUERY_STRING`` from the WSGI environment. This also takes care of the WSGI decoding dance. The string returned will be restricted to ASCII characters. :param environ: WSGI environment to get the query string from. .. deprecated:: 2.2 Will be removed in Werkzeug 2.3. .. versionadded:: 0.9 """ warnings.warn( "'get_query_string' is deprecated and will be removed in Werkzeug 2.3.", DeprecationWarning, stacklevel=2, ) qs = environ.get("QUERY_STRING", "").encode("latin1") # QUERY_STRING really should be ascii safe but some browsers # will send us some unicode stuff (I am looking at you IE). # In that case we want to urllib quote it badly. return url_quote(qs, safe=":&%=+$!*'(),")
Returns the ``QUERY_STRING`` from the WSGI environment. This also takes care of the WSGI decoding dance. The string returned will be restricted to ASCII characters. :param environ: WSGI environment to get the query string from. .. deprecated:: 2.2 Will be removed in Werkzeug 2.3. .. versionadded:: 0.9