idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
37,700 | def app_context_processor ( self , func : Callable ) -> Callable : self . record_once ( lambda state : state . app . context_processor ( func ) ) return func | Add a context processor function to the app . |
37,701 | def record_once ( self , func : DeferedSetupFunction ) -> None : def wrapper ( state : 'BlueprintSetupState' ) -> None : if state . first_registration : func ( state ) self . record ( update_wrapper ( wrapper , func ) ) | Used to register a deferred action that happens only once . |
37,702 | def register ( self , app : 'Quart' , first_registration : bool , * , url_prefix : Optional [ str ] = None , ) -> None : state = self . make_setup_state ( app , first_registration , url_prefix = url_prefix ) if self . has_static_folder : state . add_url_rule ( self . static_url_path + '/<path:filename>' , view_func = s... | Register this blueprint on the app given . |
37,703 | def make_setup_state ( self , app : 'Quart' , first_registration : bool , * , url_prefix : Optional [ str ] = None , ) -> 'BlueprintSetupState' : return BlueprintSetupState ( self , app , first_registration , url_prefix = url_prefix ) | Return a blueprint setup state instance . |
37,704 | def to_dict ( self , flat : bool = True ) -> Dict [ Any , Any ] : if flat : return { key : value for key , value in self . items ( ) } else : return { key : self . getall ( key ) for key in self } | Convert the multidict to a plain dictionary . |
37,705 | def save ( self , destination : BinaryIO , buffer_size : int = 16384 ) -> None : close_destination = False if isinstance ( destination , str ) : destination = open ( destination , 'wb' ) close_destination = True try : copyfileobj ( self . stream , destination , buffer_size ) finally : if close_destination : destination... | Save the file to the destination . |
37,706 | async def get_data ( self , raw : bool = True ) -> AnyStr : try : body_future = asyncio . ensure_future ( self . body ) raw_data = await asyncio . wait_for ( body_future , timeout = self . body_timeout ) except asyncio . TimeoutError : body_future . cancel ( ) from . . exceptions import RequestTimeout raise RequestTime... | The request body data . |
37,707 | async def accept ( self , headers : Optional [ Union [ dict , CIMultiDict , Headers ] ] = None , subprotocol : Optional [ str ] = None , ) -> None : if headers is None : headers_ = Headers ( ) else : headers_ = Headers ( headers ) await self . _accept ( headers_ , subprotocol ) | Manually chose to accept the websocket connection . |
37,708 | def create_logger ( app : 'Quart' ) -> Logger : logger = getLogger ( 'quart.app' ) if app . debug and logger . level == NOTSET : logger . setLevel ( DEBUG ) logger . addHandler ( default_handler ) return logger | Create a logger for the app based on the app settings . |
37,709 | def create_serving_logger ( ) -> Logger : logger = getLogger ( 'quart.serving' ) if logger . level == NOTSET : logger . setLevel ( INFO ) logger . addHandler ( serving_handler ) return logger | Create a logger for serving . |
37,710 | def create_cookie ( key : str , value : str = '' , max_age : Optional [ Union [ int , timedelta ] ] = None , expires : Optional [ Union [ int , float , datetime ] ] = None , path : str = '/' , domain : Optional [ str ] = None , secure : bool = False , httponly : bool = False , ) -> SimpleCookie : cookie = SimpleCookie ... | Create a Cookie given the options set |
37,711 | def name ( self ) -> str : if self . import_name == '__main__' : path = Path ( getattr ( sys . modules [ '__main__' ] , '__file__' , '__main__.py' ) ) return path . stem return self . import_name | The name of this application . |
37,712 | def jinja_env ( self ) -> Environment : if self . _jinja_env is None : self . _jinja_env = self . create_jinja_environment ( ) return self . _jinja_env | The jinja environment used to load templates . |
37,713 | def auto_find_instance_path ( self ) -> Path : prefix , package_path = find_package ( self . import_name ) if prefix is None : return package_path / "instance" return prefix / "var" / f"{self.name}-instance" | Locates the instace_path if it was not provided |
37,714 | def make_config ( self , instance_relative : bool = False ) -> Config : config = self . config_class ( self . instance_path if instance_relative else self . root_path , DEFAULT_CONFIG , ) config [ 'ENV' ] = get_env ( ) config [ 'DEBUG' ] = get_debug_flag ( ) return config | Create and return the configuration with appropriate defaults . |
37,715 | def create_url_adapter ( self , request : Optional [ BaseRequestWebsocket ] ) -> Optional [ MapAdapter ] : if request is not None : host = request . host return self . url_map . bind_to_request ( request . scheme , host , request . method , request . path , request . query_string , ) if self . config [ 'SERVER_NAME' ] ... | Create and return a URL adapter . |
37,716 | def create_jinja_environment ( self ) -> Environment : options = dict ( self . jinja_options ) if 'autoescape' not in options : options [ 'autoescape' ] = self . select_jinja_autoescape if 'auto_reload' not in options : options [ 'auto_reload' ] = self . config [ 'TEMPLATES_AUTO_RELOAD' ] or self . debug jinja_env = se... | Create and return the jinja environment . |
37,717 | def select_jinja_autoescape ( self , filename : str ) -> bool : if filename is None : return True return Path ( filename ) . suffix in { '.htm' , '.html' , '.xhtml' , '.xml' } | Returns True if the filename indicates that it should be escaped . |
37,718 | async def update_template_context ( self , context : dict ) -> None : processors = self . template_context_processors [ None ] if has_request_context ( ) : blueprint = _request_ctx_stack . top . request . blueprint if blueprint is not None and blueprint in self . template_context_processors : processors = chain ( proce... | Update the provided template context . |
37,719 | def make_shell_context ( self ) -> dict : context = { 'app' : self , 'g' : g } for processor in self . shell_context_processors : context . update ( processor ( ) ) return context | Create a context for interactive shell usage . |
37,720 | def endpoint ( self , endpoint : str ) -> Callable : def decorator ( func : Callable ) -> Callable : handler = ensure_coroutine ( func ) self . view_functions [ endpoint ] = handler return func return decorator | Register a function as an endpoint . |
37,721 | def register_error_handler ( self , error : Union [ Type [ Exception ] , int ] , func : Callable , name : AppOrBlueprintKey = None , ) -> None : handler = ensure_coroutine ( func ) if isinstance ( error , int ) : error = all_http_exceptions [ error ] self . error_handler_spec [ name ] [ error ] = handler | Register a function as an error handler . |
37,722 | def context_processor ( self , func : Callable , name : AppOrBlueprintKey = None ) -> Callable : self . template_context_processors [ name ] . append ( ensure_coroutine ( func ) ) return func | Add a template context processor . |
37,723 | def shell_context_processor ( self , func : Callable ) -> Callable : self . shell_context_processors . append ( func ) return func | Add a shell context processor . |
37,724 | def inject_url_defaults ( self , endpoint : str , values : dict ) -> None : functions = self . url_value_preprocessors [ None ] if '.' in endpoint : blueprint = endpoint . rsplit ( '.' , 1 ) [ 0 ] functions = chain ( functions , self . url_value_preprocessors [ blueprint ] ) for function in functions : function ( endpo... | Injects default URL values into the passed values dict . |
37,725 | def handle_url_build_error ( self , error : Exception , endpoint : str , values : dict ) -> str : for handler in self . url_build_error_handlers : result = handler ( error , endpoint , values ) if result is not None : return result raise error | Handle a build error . |
37,726 | async def handle_http_exception ( self , error : Exception ) -> Response : handler = self . _find_exception_handler ( error ) if handler is None : return error . get_response ( ) else : return await handler ( error ) | Handle a HTTPException subclass error . |
37,727 | async def handle_user_exception ( self , error : Exception ) -> Response : if isinstance ( error , HTTPException ) and not self . trap_http_exception ( error ) : return await self . handle_http_exception ( error ) handler = self . _find_exception_handler ( error ) if handler is None : raise error return await handler (... | Handle an exception that has been raised . |
37,728 | def before_request ( self , func : Callable , name : AppOrBlueprintKey = None ) -> Callable : handler = ensure_coroutine ( func ) self . before_request_funcs [ name ] . append ( handler ) return func | Add a before request function . |
37,729 | def before_websocket ( self , func : Callable , name : AppOrBlueprintKey = None ) -> Callable : handler = ensure_coroutine ( func ) self . before_websocket_funcs [ name ] . append ( handler ) return func | Add a before websocket function . |
37,730 | def before_serving ( self , func : Callable ) -> Callable : handler = ensure_coroutine ( func ) self . before_serving_funcs . append ( handler ) return func | Add a before serving function . |
37,731 | def after_request ( self , func : Callable , name : AppOrBlueprintKey = None ) -> Callable : handler = ensure_coroutine ( func ) self . after_request_funcs [ name ] . append ( handler ) return func | Add an after request function . |
37,732 | def after_websocket ( self , func : Callable , name : AppOrBlueprintKey = None ) -> Callable : handler = ensure_coroutine ( func ) self . after_websocket_funcs [ name ] . append ( handler ) return func | Add an after websocket function . |
37,733 | def after_serving ( self , func : Callable ) -> Callable : handler = ensure_coroutine ( func ) self . after_serving_funcs . append ( handler ) return func | Add a after serving function . |
37,734 | def teardown_request ( self , func : Callable , name : AppOrBlueprintKey = None ) -> Callable : handler = ensure_coroutine ( func ) self . teardown_request_funcs [ name ] . append ( handler ) return func | Add a teardown request function . |
37,735 | def teardown_websocket ( self , func : Callable , name : AppOrBlueprintKey = None ) -> Callable : handler = ensure_coroutine ( func ) self . teardown_websocket_funcs [ name ] . append ( handler ) return func | Add a teardown websocket function . |
37,736 | def register_blueprint ( self , blueprint : Blueprint , url_prefix : Optional [ str ] = None ) -> None : first_registration = False if blueprint . name in self . blueprints and self . blueprints [ blueprint . name ] is not blueprint : raise RuntimeError ( f"Blueprint name '{blueprint.name}' " f"is already registered by... | Register a blueprint on the app . |
37,737 | async def open_session ( self , request : BaseRequestWebsocket ) -> Session : return await ensure_coroutine ( self . session_interface . open_session ) ( self , request ) | Open and return a Session using the request . |
37,738 | async def save_session ( self , session : Session , response : Response ) -> None : await ensure_coroutine ( self . session_interface . save_session ) ( self , session , response ) | Saves the session to the response . |
37,739 | async def do_teardown_request ( self , exc : Optional [ BaseException ] , request_context : Optional [ RequestContext ] = None , ) -> None : request_ = ( request_context or _request_ctx_stack . top ) . request functions = self . teardown_request_funcs [ None ] blueprint = request_ . blueprint if blueprint is not None :... | Teardown the request calling the teardown functions . |
37,740 | async def do_teardown_websocket ( self , exc : Optional [ BaseException ] , websocket_context : Optional [ WebsocketContext ] = None , ) -> None : websocket_ = ( websocket_context or _websocket_ctx_stack . top ) . websocket functions = self . teardown_websocket_funcs [ None ] blueprint = websocket_ . blueprint if bluep... | Teardown the websocket calling the teardown functions . |
37,741 | def run ( self , host : str = '127.0.0.1' , port : int = 5000 , debug : Optional [ bool ] = None , use_reloader : bool = True , loop : Optional [ asyncio . AbstractEventLoop ] = None , ca_certs : Optional [ str ] = None , certfile : Optional [ str ] = None , keyfile : Optional [ str ] = None , ** kwargs : Any , ) -> No... | Run this application . |
37,742 | async def try_trigger_before_first_request_functions ( self ) -> None : if self . _got_first_request : return self . teardown_appcontext_funcs = list ( reversed ( self . teardown_appcontext_funcs ) ) for key , value in self . teardown_request_funcs . items ( ) : self . teardown_request_funcs [ key ] = list ( reversed (... | Trigger the before first request methods . |
37,743 | async def make_default_options_response ( self ) -> Response : methods = _request_ctx_stack . top . url_adapter . allowed_methods ( ) return self . response_class ( '' , headers = { 'Allow' : ', ' . join ( methods ) } ) | This is the default route function for OPTIONS requests . |
37,744 | async def make_response ( self , result : ResponseReturnValue ) -> Response : status_or_headers = None headers = None status = None if isinstance ( result , tuple ) : value , status_or_headers , headers = result + ( None , ) * ( 3 - len ( result ) ) else : value = result if value is None : raise TypeError ( 'The respon... | Make a Response from the result of the route handler . |
37,745 | async def full_dispatch_request ( self , request_context : Optional [ RequestContext ] = None , ) -> Response : await self . try_trigger_before_first_request_functions ( ) await request_started . send ( self ) try : result = await self . preprocess_request ( request_context ) if result is None : result = await self . d... | Adds pre and post processing to the request dispatching . |
37,746 | async def preprocess_request ( self , request_context : Optional [ RequestContext ] = None , ) -> Optional [ ResponseReturnValue ] : request_ = ( request_context or _request_ctx_stack . top ) . request blueprint = request_ . blueprint processors = self . url_value_preprocessors [ None ] if blueprint is not None : proce... | Preprocess the request i . e . call before_request functions . |
37,747 | async def dispatch_request ( self , request_context : Optional [ RequestContext ] = None , ) -> ResponseReturnValue : request_ = ( request_context or _request_ctx_stack . top ) . request if request_ . routing_exception is not None : raise request_ . routing_exception if request_ . method == 'OPTIONS' and request_ . url... | Dispatch the request to the view function . |
37,748 | async def process_response ( self , response : Response , request_context : Optional [ RequestContext ] = None , ) -> Response : request_ = ( request_context or _request_ctx_stack . top ) . request functions = ( request_context or _request_ctx_stack . top ) . _after_request_functions blueprint = request_ . blueprint if... | Postprocess the request acting on the response . |
37,749 | async def full_dispatch_websocket ( self , websocket_context : Optional [ WebsocketContext ] = None , ) -> Optional [ Response ] : await self . try_trigger_before_first_request_functions ( ) await websocket_started . send ( self ) try : result = await self . preprocess_websocket ( websocket_context ) if result is None ... | Adds pre and post processing to the websocket dispatching . |
37,750 | async def preprocess_websocket ( self , websocket_context : Optional [ WebsocketContext ] = None , ) -> Optional [ ResponseReturnValue ] : websocket_ = ( websocket_context or _websocket_ctx_stack . top ) . websocket blueprint = websocket_ . blueprint processors = self . url_value_preprocessors [ None ] if blueprint is ... | Preprocess the websocket i . e . call before_websocket functions . |
37,751 | async def dispatch_websocket ( self , websocket_context : Optional [ WebsocketContext ] = None , ) -> None : websocket_ = ( websocket_context or _websocket_ctx_stack . top ) . websocket if websocket_ . routing_exception is not None : raise websocket_ . routing_exception handler = self . view_functions [ websocket_ . ur... | Dispatch the websocket to the view function . |
37,752 | async def postprocess_websocket ( self , response : Optional [ Response ] , websocket_context : Optional [ WebsocketContext ] = None , ) -> Response : websocket_ = ( websocket_context or _websocket_ctx_stack . top ) . websocket functions = ( websocket_context or _websocket_ctx_stack . top ) . _after_websocket_functions... | Postprocess the websocket acting on the response . |
37,753 | def after_this_request ( func : Callable ) -> Callable : _request_ctx_stack . top . _after_request_functions . append ( func ) return func | Schedule the func to be called after the current request . |
37,754 | def after_this_websocket ( func : Callable ) -> Callable : _websocket_ctx_stack . top . _after_websocket_functions . append ( func ) return func | Schedule the func to be called after the current websocket . |
37,755 | def copy_current_app_context ( func : Callable ) -> Callable : if not has_app_context ( ) : raise RuntimeError ( 'Attempt to copy app context outside of a app context' ) app_context = _app_ctx_stack . top . copy ( ) @ wraps ( func ) async def wrapper ( * args : Any , ** kwargs : Any ) -> Any : async with app_context : ... | Share the current app context with the function decorated . |
37,756 | def copy_current_request_context ( func : Callable ) -> Callable : if not has_request_context ( ) : raise RuntimeError ( 'Attempt to copy request context outside of a request context' ) request_context = _request_ctx_stack . top . copy ( ) @ wraps ( func ) async def wrapper ( * args : Any , ** kwargs : Any ) -> Any : a... | Share the current request context with the function decorated . |
37,757 | def copy_current_websocket_context ( func : Callable ) -> Callable : if not has_websocket_context ( ) : raise RuntimeError ( 'Attempt to copy websocket context outside of a websocket context' ) websocket_context = _websocket_ctx_stack . top . copy ( ) @ wraps ( func ) async def wrapper ( * args : Any , ** kwargs : Any ... | Share the current websocket context with the function decorated . |
37,758 | def match_request ( self ) -> None : try : self . request_websocket . url_rule , self . request_websocket . view_args = self . url_adapter . match ( ) except ( NotFound , MethodNotAllowed , RedirectRequired ) as error : self . request_websocket . routing_exception = error | Match the request against the adapter . |
37,759 | def get ( self , name : str , default : Optional [ Any ] = None ) -> Any : return self . __dict__ . get ( name , default ) | Get a named attribute of this instance or return the default . |
37,760 | def pop ( self , name : str , default : Any = _sentinel ) -> Any : if default is _sentinel : return self . __dict__ . pop ( name ) else : return self . __dict__ . pop ( name , default ) | Pop get and remove the named attribute of this instance . |
37,761 | def setdefault ( self , name : str , default : Any = None ) -> Any : return self . __dict__ . setdefault ( name , default ) | Set an attribute with a default value . |
37,762 | def get_cookie_domain ( self , app : 'Quart' ) -> Optional [ str ] : if app . config [ 'SESSION_COOKIE_DOMAIN' ] is not None : return app . config [ 'SESSION_COOKIE_DOMAIN' ] elif app . config [ 'SERVER_NAME' ] is not None : return '.' + app . config [ 'SERVER_NAME' ] . rsplit ( ':' , 1 ) [ 0 ] else : return None | Helper method to return the Cookie Domain for the App . |
37,763 | def get_expiration_time ( self , app : 'Quart' , session : SessionMixin ) -> Optional [ datetime ] : if session . permanent : return datetime . utcnow ( ) + app . permanent_session_lifetime else : return None | Helper method to return the Session expiration time . |
37,764 | def should_set_cookie ( self , app : 'Quart' , session : SessionMixin ) -> bool : if session . modified : return True save_each = app . config [ 'SESSION_REFRESH_EACH_REQUEST' ] return save_each and session . permanent | Helper method to return if the Set Cookie header should be present . |
37,765 | def get_signing_serializer ( self , app : 'Quart' ) -> Optional [ URLSafeTimedSerializer ] : if not app . secret_key : return None options = { 'key_derivation' : self . key_derivation , 'digest_method' : self . digest_method , } return URLSafeTimedSerializer ( app . secret_key , salt = self . salt , serializer = self .... | Return a serializer for the session that also signs data . |
37,766 | async def open_session ( self , app : 'Quart' , request : BaseRequestWebsocket , ) -> Optional [ SecureCookieSession ] : signer = self . get_signing_serializer ( app ) if signer is None : return None cookie = request . cookies . get ( app . session_cookie_name ) if cookie is None : return self . session_class ( ) try :... | Open a secure cookie based session . |
37,767 | async def save_session ( self , app : 'Quart' , session : SecureCookieSession , response : Response , ) -> None : domain = self . get_cookie_domain ( app ) path = self . get_cookie_path ( app ) if not session : if session . modified : response . delete_cookie ( app . session_cookie_name , domain = domain , path = path ... | Saves the session to the response in a secure cookie . |
37,768 | async def get_data ( self , raw : bool = True ) -> AnyStr : if self . implicit_sequence_conversion : self . response = self . data_body_class ( await self . response . convert_to_sequence ( ) ) result = b'' if raw else '' async with self . response as body : async for data in body : if raw : result += data else : resul... | Return the body data . |
37,769 | def set_data ( self , data : AnyStr ) -> None : if isinstance ( data , str ) : bytes_data = data . encode ( self . charset ) else : bytes_data = data self . response = self . data_body_class ( bytes_data ) if self . automatically_set_content_length : self . content_length = len ( bytes_data ) | Set the response data . |
37,770 | async def make_conditional ( self , request_range : Range , max_partial_size : Optional [ int ] = None , ) -> None : self . accept_ranges = "bytes" if len ( request_range . ranges ) == 0 : return if request_range . units != "bytes" or len ( request_range . ranges ) > 1 : from . . exceptions import RequestRangeNotSatisf... | Make the response conditional to the |
37,771 | def set_cookie ( self , key : str , value : AnyStr = '' , max_age : Optional [ Union [ int , timedelta ] ] = None , expires : Optional [ datetime ] = None , path : str = '/' , domain : Optional [ str ] = None , secure : bool = False , httponly : bool = False , ) -> None : if isinstance ( value , bytes ) : value = value... | Set a cookie in the response headers . |
37,772 | def match ( self , path : str ) -> Tuple [ Optional [ Dict [ str , Any ] ] , bool ] : match = self . _pattern . match ( path ) if match is not None : needs_slash = ( self . strict_slashes and not self . is_leaf and match . groupdict ( ) [ '__slash__' ] != '/' ) try : converted_varaibles = { name : self . _converters [ ... | Check if the path matches this Rule . |
37,773 | def provides_defaults_for ( self , rule : 'Rule' , ** values : Any ) -> bool : defaults_match = all ( values [ key ] == self . defaults [ key ] for key in self . defaults if key in values ) return self != rule and bool ( self . defaults ) and defaults_match | Returns true if this rule provides defaults for the argument and values . |
37,774 | def build ( self , ** values : Any ) -> str : converted_values = { key : self . _converters [ key ] . to_url ( value ) for key , value in values . items ( ) if key in self . _converters } result = self . _builder . format ( ** converted_values ) . split ( '|' , 1 ) [ 1 ] query_string = urlencode ( { key : value for key... | Build this rule into a path using the values given . |
37,775 | def buildable ( self , values : Optional [ dict ] = None , method : Optional [ str ] = None ) -> bool : if method is not None and method not in self . methods : return False defaults_match = all ( values [ key ] == self . defaults [ key ] for key in self . defaults if key in values ) return defaults_match and set ( val... | Return True if this rule can build with the values and method . |
37,776 | def bind ( self , map : Map ) -> None : if self . map is not None : raise RuntimeError ( f"{self!r} is already bound to {self.map!r}" ) self . map = map pattern = '' builder = '' full_rule = "{}\\|{}" . format ( self . host or '' , self . rule ) for part in _parse_rule ( full_rule ) : if isinstance ( part , VariablePar... | Bind the Rule to a Map and compile it . |
37,777 | def match_key ( self ) -> Tuple [ bool , bool , int , List [ WeightedPart ] ] : if self . map is None : raise RuntimeError ( f"{self!r} is not bound to a Map" ) complex_rule = any ( weight . converter for weight in self . _weights ) return ( not bool ( self . defaults ) , complex_rule , - len ( self . _weights ) , self... | A Key to sort the rules by weight for matching . |
37,778 | def build_key ( self ) -> Tuple [ bool , int ] : if self . map is None : raise RuntimeError ( f"{self!r} is not bound to a Map" ) return ( not bool ( self . defaults ) , - sum ( 1 for weight in self . _weights if weight . converter ) ) | A Key to sort the rules by weight for building . |
37,779 | def get_tile ( tile_number ) : tile_number = int ( tile_number ) max_tiles = app . max_tiles if tile_number > max_tiles * max_tiles : raise TileOutOfBoundsError ( 'Requested an out of bounds tile' ) tile_size = Point ( app . img . size [ 0 ] // max_tiles , app . img . size [ 1 ] // max_tiles ) tile_coords = Point ( til... | Returns a crop of img based on a sequence number tile_number . |
37,780 | async def tile ( tile_number ) : try : tile = get_tile ( tile_number ) except TileOutOfBoundsError : abort ( 404 ) buf = BytesIO ( tile . tobytes ( ) ) tile . save ( buf , 'JPEG' ) content = buf . getvalue ( ) response = await make_response ( content ) response . headers [ 'Content-Type' ] = 'image/jpg' response . head... | Handles GET requests for a tile number . |
37,781 | def is_json ( self ) -> bool : content_type = self . mimetype if content_type == 'application/json' or ( content_type . startswith ( 'application/' ) and content_type . endswith ( '+json' ) ) : return True else : return False | Returns True if the content_type is json like . |
37,782 | async def get_json ( self , force : bool = False , silent : bool = False , cache : bool = True , ) -> Any : if cache and self . _cached_json is not sentinel : return self . _cached_json if not ( force or self . is_json ) : return None data = await self . _load_json_data ( ) try : result = loads ( data ) except ValueErr... | Parses the body data as JSON and returns it . |
37,783 | def mimetype ( self , value : str ) -> None : if ( value . startswith ( 'text/' ) or value == 'application/xml' or ( value . startswith ( 'application/' ) and value . endswith ( '+xml' ) ) ) : mimetype = f"{value}; charset={self.charset}" else : mimetype = value self . headers [ 'Content-Type' ] = mimetype | Set the mimetype to the value . |
37,784 | def blueprint ( self ) -> Optional [ str ] : if self . endpoint is not None and '.' in self . endpoint : return self . endpoint . rsplit ( '.' , 1 ) [ 0 ] else : return None | Returns the blueprint the matched endpoint belongs to . |
37,785 | def base_url ( self ) -> str : return urlunparse ( ParseResult ( self . scheme , self . host , self . path , '' , '' , '' ) ) | Returns the base url without query string or fragments . |
37,786 | def url ( self ) -> str : return urlunparse ( ParseResult ( self . scheme , self . host , self . path , '' , self . query_string . decode ( 'ascii' ) , '' , ) , ) | Returns the full url requested . |
37,787 | def cookies ( self ) -> Dict [ str , str ] : cookies = SimpleCookie ( ) cookies . load ( self . headers . get ( 'Cookie' , '' ) ) return { key : cookie . value for key , cookie in cookies . items ( ) } | The parsed cookies attached to this request . |
37,788 | def from_envvar ( self , variable_name : str , silent : bool = False ) -> None : value = os . environ . get ( variable_name ) if value is None and not silent : raise RuntimeError ( f"Environment variable {variable_name} is not present, cannot load config" , ) return self . from_pyfile ( value ) | Load the configuration from a location specified in the environment . |
37,789 | def from_pyfile ( self , filename : str , silent : bool = False ) -> None : file_path = self . root_path / filename try : spec = importlib . util . spec_from_file_location ( "module.name" , file_path ) if spec is None : parser = ConfigParser ( ) parser . optionxform = str with open ( file_path ) as file_ : config_str =... | Load the configuration from a Python cfg or py file . |
37,790 | def from_object ( self , instance : Union [ object , str ] ) -> None : if isinstance ( instance , str ) : try : path , config = instance . rsplit ( '.' , 1 ) except ValueError : path = instance instance = importlib . import_module ( path ) else : module = importlib . import_module ( path ) instance = getattr ( module ,... | Load the configuration from a Python object . |
37,791 | def from_json ( self , filename : str , silent : bool = False ) -> None : file_path = self . root_path / filename try : with open ( file_path ) as file_ : data = json . loads ( file_ . read ( ) ) except ( FileNotFoundError , IsADirectoryError ) : if not silent : raise else : self . from_mapping ( data ) | Load the configuration values from a JSON formatted file . |
37,792 | def from_mapping ( self , mapping : Optional [ Mapping [ str , Any ] ] = None , ** kwargs : Any ) -> None : mappings : Dict [ str , Any ] = { } if mapping is not None : mappings . update ( mapping ) mappings . update ( kwargs ) for key , value in mappings . items ( ) : if key . isupper ( ) : self [ key ] = value | Load the configuration values from a mapping . |
37,793 | def get_namespace ( self , namespace : str , lowercase : bool = True , trim_namespace : bool = True , ) -> Dict [ str , Any ] : config = { } for key , value in self . items ( ) : if key . startswith ( namespace ) : if trim_namespace : new_key = key [ len ( namespace ) : ] else : new_key = key if lowercase : new_key = n... | Return a dictionary of keys within a namespace . |
37,794 | async def make_response ( * args : Any ) -> Response : if not args : return current_app . response_class ( ) if len ( args ) == 1 : args = args [ 0 ] return await current_app . make_response ( args ) | Create a response a simple wrapper function . |
37,795 | def get_flashed_messages ( with_categories : bool = False , category_filter : List [ str ] = [ ] , ) -> Union [ List [ str ] , List [ Tuple [ str , str ] ] ] : flashes = session . pop ( '_flashes' ) if '_flashes' in session else [ ] if category_filter : flashes = [ flash for flash in flashes if flash [ 0 ] in category_... | Retrieve the flashed messages stored in the session . |
37,796 | def url_for ( endpoint : str , * , _anchor : Optional [ str ] = None , _external : Optional [ bool ] = None , _method : Optional [ str ] = None , _scheme : Optional [ str ] = None , ** values : Any , ) -> str : app_context = _app_ctx_stack . top request_context = _request_ctx_stack . top if request_context is not None ... | Return the url for a specific endpoint . |
37,797 | def stream_with_context ( func : Callable ) -> Callable : request_context = _request_ctx_stack . top . copy ( ) @ wraps ( func ) async def generator ( * args : Any , ** kwargs : Any ) -> Any : async with request_context : async for data in func ( * args , ** kwargs ) : yield data return generator | Share the current request context with a generator . |
37,798 | def safe_join ( directory : FilePath , * paths : FilePath ) -> Path : try : safe_path = file_path_to_path ( directory ) . resolve ( strict = True ) full_path = file_path_to_path ( directory , * paths ) . resolve ( strict = True ) except FileNotFoundError : raise NotFound ( ) try : full_path . relative_to ( safe_path ) ... | Safely join the paths to the known directory to return a full path . |
37,799 | async def send_from_directory ( directory : FilePath , file_name : str , * , mimetype : Optional [ str ] = None , as_attachment : bool = False , attachment_filename : Optional [ str ] = None , add_etags : bool = True , cache_timeout : Optional [ int ] = None , conditional : bool = True , last_modified : Optional [ date... | Send a file from a given directory . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.