idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
20,800
def get_verified_jwt ( providers , audiences , check_authorization_header = True , check_query_arg = True , request = None , cache = memcache ) : if not ( check_authorization_header or check_query_arg ) : raise ValueError ( 'Either check_authorization_header or check_query_arg must be True.' ) if check_query_arg and re...
This function will extract verify and parse a JWT token from the Authorization header or access_token query argument .
20,801
def __item_descriptor ( self , config ) : descriptor = { 'kind' : 'discovery#directoryItem' , 'icons' : { 'x16' : 'https://www.gstatic.com/images/branding/product/1x/' 'googleg_16dp.png' , 'x32' : 'https://www.gstatic.com/images/branding/product/1x/' 'googleg_32dp.png' , } , 'preferred' : True , } description = config ...
Builds an item descriptor for a service configuration .
20,802
def __directory_list_descriptor ( self , configs ) : descriptor = { 'kind' : 'discovery#directoryList' , 'discoveryVersion' : 'v1' , } items = [ ] for config in configs : item_descriptor = self . __item_descriptor ( config ) if item_descriptor : items . append ( item_descriptor ) if items : descriptor [ 'items' ] = ite...
Builds a directory list for an API .
20,803
def get_directory_list_doc ( self , configs ) : if not isinstance ( configs , ( tuple , list ) ) : configs = [ configs ] util . check_list_type ( configs , dict , 'configs' , allow_none = False ) return self . __directory_list_descriptor ( configs )
JSON dict description of a protorpc . remote . Service in list format .
20,804
def pretty_print_config_to_json ( self , configs ) : descriptor = self . get_directory_list_doc ( configs ) return json . dumps ( descriptor , sort_keys = True , indent = 2 , separators = ( ',' , ': ' ) )
JSON string description of a protorpc . remote . Service in a discovery doc .
20,805
def __format_error ( self , error_list_tag ) : error = { 'domain' : self . domain ( ) , 'reason' : self . reason ( ) , 'message' : self . message ( ) } error . update ( self . extra_fields ( ) or { } ) return { 'error' : { error_list_tag : [ error ] , 'code' : self . status_code ( ) , 'message' : self . message ( ) } }
Format this error into a JSON response .
20,806
def rest_error ( self ) : error_json = self . __format_error ( 'errors' ) return json . dumps ( error_json , indent = 1 , sort_keys = True )
Format this error into a response to a REST request .
20,807
def _get_status_code ( self , http_status ) : try : return int ( http_status . split ( ' ' , 1 ) [ 0 ] ) except TypeError : _logger . warning ( 'Unable to find status code in HTTP status %r.' , http_status ) return 500
Get the HTTP status code from an HTTP status string .
20,808
def process_api_config_response ( self , config_json ) : with self . _config_lock : self . _add_discovery_config ( ) for config in config_json . get ( 'items' , [ ] ) : lookup_key = config . get ( 'name' , '' ) , config . get ( 'version' , '' ) self . _configs [ lookup_key ] = config for config in self . _configs . ite...
Parses a JSON API config and registers methods for dispatch .
20,809
def _get_sorted_methods ( self , methods ) : if not methods : return methods def _sorted_methods_comparison ( method_info1 , method_info2 ) : def _score_path ( path ) : score = 0 parts = path . split ( '/' ) for part in parts : score <<= 1 if not part or part [ 0 ] != '{' : score += 1 score <<= 31 - len ( parts ) retur...
Get a copy of methods sorted the way they would be on the live server .
20,810
def _get_path_params ( match ) : result = { } for var_name , value in match . groupdict ( ) . iteritems ( ) : actual_var_name = ApiConfigManager . _from_safe_path_param_name ( var_name ) result [ actual_var_name ] = urllib . unquote_plus ( value ) return result
Gets path parameters from a regular expression match .
20,811
def lookup_rest_method ( self , path , request_uri , http_method ) : method_key = http_method . lower ( ) with self . _config_lock : for compiled_path_pattern , unused_path , methods in self . _rest_methods : if method_key not in methods : continue candidate_method_info = methods [ method_key ] match_against = request_...
Look up the rest method at call time .
20,812
def _add_discovery_config ( self ) : lookup_key = ( discovery_service . DiscoveryService . API_CONFIG [ 'name' ] , discovery_service . DiscoveryService . API_CONFIG [ 'version' ] ) self . _configs [ lookup_key ] = discovery_service . DiscoveryService . API_CONFIG
Add the Discovery configuration to our list of configs .
20,813
def save_config ( self , lookup_key , config ) : with self . _config_lock : self . _configs [ lookup_key ] = config
Save a configuration to the cache of configs .
20,814
def _from_safe_path_param_name ( safe_parameter ) : assert safe_parameter . startswith ( '_' ) safe_parameter_as_base32 = safe_parameter [ 1 : ] padding_length = - len ( safe_parameter_as_base32 ) % 8 padding = '=' * padding_length return base64 . b32decode ( safe_parameter_as_base32 + padding )
Takes a safe regex group name and converts it back to the original value .
20,815
def _compile_path_pattern ( pattern ) : r def replace_variable ( match ) : if match . lastindex > 1 : var_name = ApiConfigManager . _to_safe_path_param_name ( match . group ( 2 ) ) return '%s(?P<%s>%s)' % ( match . group ( 1 ) , var_name , _PATH_VALUE_PATTERN ) return match . group ( 0 ) pattern = re . sub ( '(/|^){(%s...
r Generates a compiled regex pattern for a path pattern .
20,816
def _save_rest_method ( self , method_name , api_name , version , method ) : path_pattern = '/' . join ( ( api_name , version , method . get ( 'path' , '' ) ) ) http_method = method . get ( 'httpMethod' , '' ) . lower ( ) for _ , path , methods in self . _rest_methods : if path == path_pattern : methods [ http_method ]...
Store Rest api methods in a list for lookup at call time .
20,817
def api_server ( api_services , ** kwargs ) : if 'protocols' in kwargs : raise TypeError ( "__init__() got an unexpected keyword argument 'protocols'" ) from . import _logger as endpoints_logger from . import __version__ as endpoints_version endpoints_logger . info ( 'Initializing Endpoints Framework version %s' , endp...
Create an api_server .
20,818
def register_backend ( self , config_contents ) : if config_contents is None : return self . __register_class ( config_contents ) self . __api_configs . append ( config_contents ) self . __register_methods ( config_contents )
Register a single API and its config contents .
20,819
def __register_class ( self , parsed_config ) : methods = parsed_config . get ( 'methods' ) if not methods : return service_classes = set ( ) for method in methods . itervalues ( ) : rosy_method = method . get ( 'rosyMethod' ) if rosy_method and '.' in rosy_method : method_class = rosy_method . split ( '.' , 1 ) [ 0 ] ...
Register the class implementing this config so we only add it once .
20,820
def __register_methods ( self , parsed_config ) : methods = parsed_config . get ( 'methods' ) if not methods : return for method_name , method in methods . iteritems ( ) : self . __api_methods [ method_name ] = method . get ( 'rosyMethod' )
Register all methods from the given api config file .
20,821
def __register_services ( api_name_version_map , api_config_registry ) : generator = api_config . ApiConfigGenerator ( ) protorpc_services = [ ] for service_factories in api_name_version_map . itervalues ( ) : service_classes = [ service_factory . service_class for service_factory in service_factories ] config_dict = g...
Register & return a list of each URL and class that handles that URL .
20,822
def __is_json_error ( self , status , headers ) : content_header = headers . get ( 'content-type' , '' ) content_type , unused_params = cgi . parse_header ( content_header ) return ( status . startswith ( '400' ) and content_type . lower ( ) in _ALL_JSON_CONTENT_TYPES )
Determine if response is an error .
20,823
def __write_error ( self , status_code , error_message = None ) : if error_message is None : error_message = httplib . responses [ status_code ] status = '%d %s' % ( status_code , httplib . responses [ status_code ] ) message = EndpointsErrorMessage ( state = EndpointsErrorMessage . State . APPLICATION_ERROR , error_me...
Return the HTTP status line and body for a given error code and message .
20,824
def protorpc_to_endpoints_error ( self , status , body ) : try : rpc_error = self . __PROTOJSON . decode_message ( remote . RpcStatus , body ) except ( ValueError , messages . ValidationError ) : rpc_error = remote . RpcStatus ( ) if rpc_error . state == remote . RpcStatus . State . APPLICATION_ERROR : error_class = _E...
Convert a ProtoRPC error to the format expected by Google Endpoints .
20,825
def _add_dispatcher ( self , path_regex , dispatch_function ) : self . _dispatchers . append ( ( re . compile ( path_regex ) , dispatch_function ) )
Add a request path and dispatch handler .
20,826
def dispatch ( self , request , start_response ) : dispatched_response = self . dispatch_non_api_requests ( request , start_response ) if dispatched_response is not None : return dispatched_response try : return self . call_backend ( request , start_response ) except errors . RequestError as error : return self . _hand...
Handles dispatch to apiserver handlers .
20,827
def dispatch_non_api_requests ( self , request , start_response ) : for path_regex , dispatch_function in self . _dispatchers : if path_regex . match ( request . relative_url ) : return dispatch_function ( request , start_response ) if request . http_method == 'OPTIONS' : cors_handler = self . _create_cors_handler ( re...
Dispatch this request if this is a request to a reserved URL .
20,828
def verify_response ( response , status_code , content_type = None ) : status = int ( response . status . split ( ' ' , 1 ) [ 0 ] ) if status != status_code : return False if content_type is None : return True for header , value in response . headers : if header . lower ( ) == 'content-type' : return value == content_t...
Verifies that a response has the expected status and content type .
20,829
def prepare_backend_environ ( self , host , method , relative_url , headers , body , source_ip , port ) : if isinstance ( body , unicode ) : body = body . encode ( 'ascii' ) url = urlparse . urlsplit ( relative_url ) if port != 80 : host = '%s:%s' % ( host , port ) else : host = host environ = { 'CONTENT_LENGTH' : str ...
Build an environ object for the backend to consume .
20,830
def handle_backend_response ( self , orig_request , backend_request , response_status , response_headers , response_body , method_config , start_response ) : for header , value in response_headers : if ( header . lower ( ) == 'content-type' and not value . lower ( ) . startswith ( 'application/json' ) ) : return self ....
Handle backend response transforming output as needed .
20,831
def fail_request ( self , orig_request , message , start_response ) : cors_handler = self . _create_cors_handler ( orig_request ) return util . send_wsgi_error_response ( message , start_response , cors_handler = cors_handler )
Write an immediate failure response to outfile no redirect .
20,832
def lookup_rest_method ( self , orig_request ) : method_name , method , params = self . config_manager . lookup_rest_method ( orig_request . path , orig_request . request_uri , orig_request . http_method ) orig_request . method_name = method_name return method , params
Looks up and returns rest method for the currently - pending request .
20,833
def transform_request ( self , orig_request , params , method_config ) : method_params = method_config . get ( 'request' , { } ) . get ( 'parameters' , { } ) request = self . transform_rest_request ( orig_request , params , method_params ) request . path = method_config . get ( 'rosyMethod' , '' ) return request
Transforms orig_request to apiserving request .
20,834
def _add_message_field ( self , field_name , value , params ) : if '.' not in field_name : params [ field_name ] = value return root , remaining = field_name . split ( '.' , 1 ) sub_params = params . setdefault ( root , { } ) self . _add_message_field ( remaining , value , sub_params )
Converts a . delimitied field name to a message field in parameters .
20,835
def _update_from_body ( self , destination , source ) : for key , value in source . iteritems ( ) : destination_value = destination . get ( key ) if isinstance ( value , dict ) and isinstance ( destination_value , dict ) : self . _update_from_body ( destination_value , value ) else : destination [ key ] = value
Updates the dictionary for an API payload with the request body .
20,836
def transform_rest_request ( self , orig_request , params , method_parameters ) : request = orig_request . copy ( ) body_json = { } for key , value in params . iteritems ( ) : body_json [ key ] = [ value ] if request . parameters : for key , value in request . parameters . iteritems ( ) : if key in body_json : body_jso...
Translates a Rest request into an apiserving request .
20,837
def check_error_response ( self , body , status ) : status_code = int ( status . split ( ' ' , 1 ) [ 0 ] ) if status_code >= 300 : raise errors . BackendError ( body , status )
Raise an exception if the response from the backend was an error .
20,838
def check_empty_response ( self , orig_request , method_config , start_response ) : response_config = method_config . get ( 'response' , { } ) . get ( 'body' ) if response_config == 'empty' : cors_handler = self . _create_cors_handler ( orig_request ) return util . send_wsgi_no_content_response ( start_response , cors_...
If the response from the backend is empty return a HTTP 204 No Content .
20,839
def transform_rest_response ( self , response_body ) : body_json = json . loads ( response_body ) return json . dumps ( body_json , indent = 1 , sort_keys = True )
Translates an apiserving REST response so it s ready to return .
20,840
def _handle_request_error ( self , orig_request , error , start_response ) : headers = [ ( 'Content-Type' , 'application/json' ) ] status_code = error . status_code ( ) body = error . rest_error ( ) response_status = '%d %s' % ( status_code , httplib . responses . get ( status_code , 'Unknown Error' ) ) cors_handler = ...
Handle a request error converting it to a WSGI response .
20,841
def _WriteFile ( output_path , name , content ) : path = os . path . join ( output_path , name ) with open ( path , 'wb' ) as f : f . write ( content ) return path
Write given content to a file in a given directory .
20,842
def GenApiConfig ( service_class_names , config_string_generator = None , hostname = None , application_path = None , ** additional_kwargs ) : api_service_map = collections . OrderedDict ( ) resolved_services = [ ] for service_class_name in service_class_names : module_name , base_service_class_name = service_class_nam...
Write an API configuration for endpoints annotated ProtoRPC services .
20,843
def _GetAppYamlHostname ( application_path , open_func = open ) : try : app_yaml_file = open_func ( os . path . join ( application_path or '.' , 'app.yaml' ) ) config = yaml . safe_load ( app_yaml_file . read ( ) ) except IOError : return None application = config . get ( 'application' ) if not application : return Non...
Build the hostname for this app based on the name in app . yaml .
20,844
def _GenDiscoveryDoc ( service_class_names , output_path , hostname = None , application_path = None ) : output_files = [ ] service_configs = GenApiConfig ( service_class_names , hostname = hostname , config_string_generator = discovery_generator . DiscoveryGenerator ( ) , application_path = application_path ) for api_...
Write discovery documents generated from the service classes to file .
20,845
def _GenOpenApiSpec ( service_class_names , output_path , hostname = None , application_path = None , x_google_api_name = False ) : output_files = [ ] service_configs = GenApiConfig ( service_class_names , hostname = hostname , config_string_generator = openapi_generator . OpenApiGenerator ( ) , application_path = appl...
Write openapi documents generated from the service classes to file .
20,846
def _GetClientLib ( service_class_names , language , output_path , build_system , hostname = None , application_path = None ) : client_libs = [ ] service_configs = GenApiConfig ( service_class_names , hostname = hostname , config_string_generator = discovery_generator . DiscoveryGenerator ( ) , application_path = appli...
Fetch client libraries from a cloud service .
20,847
def _GenApiConfigCallback ( args , api_func = GenApiConfig ) : service_configs = api_func ( args . service , hostname = args . hostname , application_path = args . application ) for api_name_version , config in service_configs . iteritems ( ) : _WriteFile ( args . output , api_name_version + '.api' , config )
Generate an api file .
20,848
def _GetClientLibCallback ( args , client_func = _GetClientLib ) : client_paths = client_func ( args . service , args . language , args . output , args . build_system , hostname = args . hostname , application_path = args . application ) for client_path in client_paths : print 'API client library written to %s' % clien...
Generate discovery docs and client libraries to files .
20,849
def _GenDiscoveryDocCallback ( args , discovery_func = _GenDiscoveryDoc ) : discovery_paths = discovery_func ( args . service , args . output , hostname = args . hostname , application_path = args . application ) for discovery_path in discovery_paths : print 'API discovery document written to %s' % discovery_path
Generate discovery docs to files .
20,850
def _GenClientLibCallback ( args , client_func = _GenClientLib ) : client_path = client_func ( args . discovery_doc [ 0 ] , args . language , args . output , args . build_system ) print 'API client library written to %s' % client_path
Generate a client library to file .
20,851
def error ( self , message ) : subcommands_quoted = ', ' . join ( [ repr ( command ) for command in _VISIBLE_COMMANDS ] ) subcommands = ', ' . join ( _VISIBLE_COMMANDS ) message = re . sub ( r'(argument {%s}: invalid choice: .*) \(choose from (.*)\)$' % subcommands , r'\1 (choose from %s)' % subcommands_quoted , messag...
Override superclass to support customized error message .
20,852
def _SetupPaths ( ) : sdk_path = _FindSdkPath ( ) if sdk_path : sys . path . append ( sdk_path ) try : import dev_appserver if hasattr ( dev_appserver , 'fix_sys_path' ) : dev_appserver . fix_sys_path ( ) else : logging . warning ( _NO_FIX_SYS_PATH_WARNING ) except ImportError : logging . warning ( _IMPORT_ERROR_WARNIN...
Sets up the sys . path with special directories for endpointscfg . py .
20,853
def _Enum ( docstring , * names ) : enums = dict ( zip ( names , range ( len ( names ) ) ) ) reverse = dict ( ( value , key ) for key , value in enums . iteritems ( ) ) enums [ 'reverse_mapping' ] = reverse enums [ '__doc__' ] = docstring return type ( 'Enum' , ( object , ) , enums )
Utility to generate enum classes used by annotations .
20,854
def _CheckType ( value , check_type , name , allow_none = True ) : if value is None and allow_none : return if not isinstance ( value , check_type ) : raise TypeError ( '%s type doesn\'t match %s.' % ( name , check_type ) )
Check that the type of an object is acceptable .
20,855
def api ( name , version , description = None , hostname = None , audiences = None , scopes = None , allowed_client_ids = None , canonical_name = None , auth = None , owner_domain = None , owner_name = None , package_path = None , frontend_limits = None , title = None , documentation = None , auth_level = None , issuer...
Decorate a ProtoRPC Service class for use by the framework above .
20,856
def method ( request_message = message_types . VoidMessage , response_message = message_types . VoidMessage , name = None , path = None , http_method = 'POST' , scopes = None , audiences = None , allowed_client_ids = None , auth_level = None , api_key_required = None , metric_costs = None , use_request_uri = None ) : i...
Decorate a ProtoRPC Method for use by the framework above .
20,857
def is_same_api ( self , other ) : if not isinstance ( other , _ApiInfo ) : return False return self . __common_info is other . __common_info
Check if this implements the same API as another _ApiInfo instance .
20,858
def api_class ( self , resource_name = None , path = None , audiences = None , scopes = None , allowed_client_ids = None , auth_level = None , api_key_required = None ) : if auth_level is not None : _logger . warn ( _AUTH_LEVEL_WARNING ) def apiserving_api_decorator ( api_class ) : self . __classes . append ( api_class...
Get a decorator for a class that implements an API .
20,859
def __safe_name ( self , method_name ) : safe_name = re . sub ( r'[^\.a-zA-Z0-9_]' , '' , method_name ) safe_name = safe_name . lstrip ( '_' ) return safe_name [ 0 : 1 ] . lower ( ) + safe_name [ 1 : ]
Restrict method name to a - zA - Z0 - 9_ first char lowercase .
20,860
def method_id ( self , api_info ) : if api_info . resource_name : resource_part = '.%s' % self . __safe_name ( api_info . resource_name ) else : resource_part = '' return '%s%s.%s' % ( self . __safe_name ( api_info . name ) , resource_part , self . __safe_name ( self . name ) )
Computed method name .
20,861
def __field_to_subfields ( self , field ) : if not isinstance ( field , messages . MessageField ) : return [ [ field ] ] result = [ ] for subfield in sorted ( field . message_type . all_fields ( ) , key = lambda f : f . number ) : subfield_results = self . __field_to_subfields ( subfield ) for subfields_list in subfiel...
Fully describes data represented by field including the nested case .
20,862
def __field_to_parameter_type ( self , field ) : variant = field . variant if variant == messages . Variant . MESSAGE : raise TypeError ( 'A message variant can\'t be used in a parameter.' ) custom_variant_map = { messages . Variant . SINT32 : 'int32' , messages . Variant . SINT64 : 'int64' , messages . Variant . BOOL ...
Converts the field variant type into a string describing the parameter .
20,863
def __get_path_parameters ( self , path ) : path_parameters_by_segment = { } for format_var_name in re . findall ( _PATH_VARIABLE_PATTERN , path ) : first_segment = format_var_name . split ( '.' , 1 ) [ 0 ] matches = path_parameters_by_segment . setdefault ( first_segment , [ ] ) matches . append ( format_var_name ) re...
Parses path paremeters from a URI path and organizes them by parameter .
20,864
def __validate_simple_subfield ( self , parameter , field , segment_list , _segment_index = 0 ) : if _segment_index >= len ( segment_list ) : if isinstance ( field , messages . MessageField ) : field_class = field . __class__ . __name__ raise TypeError ( 'Can\'t use messages in path. Subfield %r was ' 'included but is ...
Verifies that a proposed subfield actually exists and is a simple field .
20,865
def __validate_path_parameters ( self , field , path_parameters ) : for param in path_parameters : segment_list = param . split ( '.' ) if segment_list [ 0 ] != field . name : raise TypeError ( 'Subfield %r can\'t come from field %r.' % ( param , field . name ) ) self . __validate_simple_subfield ( field . name , field...
Verifies that all path parameters correspond to an existing subfield .
20,866
def __parameter_default ( self , final_subfield ) : if final_subfield . default : if isinstance ( final_subfield , messages . EnumField ) : return final_subfield . default . name else : return final_subfield . default
Returns default value of final subfield if it has one .
20,867
def __parameter_enum ( self , final_subfield ) : if isinstance ( final_subfield , messages . EnumField ) : enum_descriptor = { } for enum_value in final_subfield . type . to_dict ( ) . keys ( ) : enum_descriptor [ enum_value ] = { 'backendValue' : enum_value } return enum_descriptor
Returns enum descriptor of final subfield if it is an enum .
20,868
def __parameter_descriptor ( self , subfield_list ) : descriptor = { } final_subfield = subfield_list [ - 1 ] if all ( subfield . required for subfield in subfield_list ) : descriptor [ 'required' ] = True descriptor [ 'type' ] = self . __field_to_parameter_type ( final_subfield ) default = self . __parameter_default (...
Creates descriptor for a parameter using the subfields that define it .
20,869
def __schema_descriptor ( self , services ) : methods_desc = { } for service in services : protorpc_methods = service . all_remote_methods ( ) for protorpc_method_name in protorpc_methods . iterkeys ( ) : rosy_method = '%s.%s' % ( service . __name__ , protorpc_method_name ) method_id = self . __id_from_name [ rosy_meth...
Descriptor for the all the JSON Schema used .
20,870
def __auth_descriptor ( self , api_info ) : if api_info . auth is None : return None auth_descriptor = { } if api_info . auth . allow_cookie_auth is not None : auth_descriptor [ 'allowCookieAuth' ] = api_info . auth . allow_cookie_auth if api_info . auth . blocked_regions : auth_descriptor [ 'blockedRegions' ] = api_in...
Builds an auth descriptor from API info .
20,871
def __frontend_limit_descriptor ( self , api_info ) : if api_info . frontend_limits is None : return None descriptor = { } for propname , descname in ( ( 'unregistered_user_qps' , 'unregisteredUserQps' ) , ( 'unregistered_qps' , 'unregisteredQps' ) , ( 'unregistered_daily' , 'unregisteredDaily' ) ) : if getattr ( api_i...
Builds a frontend limit descriptor from API info .
20,872
def __frontend_limit_rules_descriptor ( self , api_info ) : if not api_info . frontend_limits . rules : return None rules = [ ] for rule in api_info . frontend_limits . rules : descriptor = { } for propname , descname in ( ( 'match' , 'match' ) , ( 'qps' , 'qps' ) , ( 'user_qps' , 'userQps' ) , ( 'daily' , 'daily' ) , ...
Builds a frontend limit rules descriptor from API info .
20,873
def get_config_dict ( self , services , hostname = None ) : if not isinstance ( services , ( tuple , list ) ) : services = [ services ] endpoints_util . check_list_type ( services , remote . _ServiceClass , 'services' , allow_none = False ) return self . __api_descriptor ( services , hostname = hostname )
JSON dict description of a protorpc . remote . Service in API format .
20,874
def pretty_print_config_to_json ( self , services , hostname = None ) : descriptor = self . get_config_dict ( services , hostname ) return json . dumps ( descriptor , sort_keys = True , indent = 2 , separators = ( ',' , ': ' ) )
JSON string description of a protorpc . remote . Service in API format .
20,875
def __parameter_enum ( self , param ) : if isinstance ( param , messages . EnumField ) : return [ enum_entry [ 0 ] for enum_entry in sorted ( param . type . to_dict ( ) . items ( ) , key = lambda v : v [ 1 ] ) ]
Returns enum descriptor of a parameter if it is an enum .
20,876
def __params_order_descriptor ( self , message_type , path , is_params_class = False ) : path_params = [ ] query_params = [ ] path_parameter_dict = self . __get_path_parameters ( path ) for field in sorted ( message_type . all_fields ( ) , key = lambda f : f . number ) : matched_path_parameters = path_parameter_dict . ...
Describe the order of path parameters .
20,877
def __schemas_descriptor ( self ) : result = { } for schema_key , schema_value in self . __parser . schemas ( ) . iteritems ( ) : field_keys = schema_value . keys ( ) key_result = { } if 'properties' in field_keys : key_result [ 'properties' ] = schema_value [ 'properties' ] . copy ( ) for prop_key , prop_value in sche...
Describes the schemas section of the discovery document .
20,878
def __resource_descriptor ( self , resource_path , methods ) : descriptor = { } method_map = { } sub_resource_index = collections . defaultdict ( list ) sub_resource_map = { } resource_path_tokens = resource_path . split ( '.' ) for service , protorpc_meth_info in methods : method_info = getattr ( protorpc_meth_info , ...
Describes a resource .
20,879
def __discovery_doc_descriptor ( self , services , hostname = None ) : merged_api_info = self . __get_merged_api_info ( services ) descriptor = self . get_descriptor_defaults ( merged_api_info , hostname = hostname ) description = merged_api_info . description if not description and len ( services ) == 1 : description ...
Builds a discovery doc for an API .
20,880
def get_discovery_doc ( self , services , hostname = None ) : if not isinstance ( services , ( tuple , list ) ) : services = [ services ] util . check_list_type ( services , remote . _ServiceClass , 'services' , allow_none = False ) return self . __discovery_doc_descriptor ( services , hostname = hostname )
JSON dict description of a protorpc . remote . Service in discovery format .
20,881
def send_wsgi_response ( status , headers , content , start_response , cors_handler = None ) : if cors_handler : cors_handler . update_headers ( headers ) content_len = len ( content ) if content else 0 headers = [ ( header , value ) for header , value in headers if header . lower ( ) != 'content-length' ] headers . ap...
Dump reformatted response to CGI start_response .
20,882
def get_headers_from_environ ( environ ) : headers = wsgiref . headers . Headers ( [ ] ) for header , value in environ . iteritems ( ) : if header . startswith ( 'HTTP_' ) : headers [ header [ 5 : ] . replace ( '_' , '-' ) ] = value if 'CONTENT_TYPE' in environ : headers [ 'CONTENT-TYPE' ] = environ [ 'CONTENT_TYPE' ] ...
Get a wsgiref . headers . Headers object with headers from the environment .
20,883
def put_headers_in_environ ( headers , environ ) : for key , value in headers : environ [ 'HTTP_%s' % key . upper ( ) . replace ( '-' , '_' ) ] = value
Given a list of headers put them into environ based on PEP - 333 .
20,884
def get_hostname_prefix ( ) : parts = [ ] version = modules . get_current_version_name ( ) default_version = modules . get_default_version ( ) if version != default_version : parts . append ( version ) module = modules . get_current_module_name ( ) if module != 'default' : parts . append ( module ) if parts : parts . a...
Returns the hostname prefix of a running Endpoints service .
20,885
def get_app_hostname ( ) : if not is_running_on_app_engine ( ) or is_running_on_localhost ( ) : return None app_id = app_identity . get_application_id ( ) prefix = get_hostname_prefix ( ) suffix = 'appspot.com' if ':' in app_id : tokens = app_id . split ( ':' ) api_name = tokens [ 1 ] if tokens [ 0 ] == 'google.com' : ...
Return hostname of a running Endpoints service .
20,886
def check_list_type ( objects , allowed_type , name , allow_none = True ) : if objects is None : if not allow_none : raise TypeError ( '%s is None, which is not allowed.' % name ) return objects if not isinstance ( objects , ( tuple , list ) ) : raise TypeError ( '%s is not a list.' % name ) if not all ( isinstance ( i...
Verify that objects in list are of the allowed type or raise TypeError .
20,887
def snake_case_to_headless_camel_case ( snake_string ) : return '' . join ( [ snake_string . split ( '_' ) [ 0 ] ] + list ( sub_string . capitalize ( ) for sub_string in snake_string . split ( '_' ) [ 1 : ] ) )
Convert snake_case to headlessCamelCase .
20,888
def Proxy ( self , status , headers , exc_info = None ) : self . call_context [ 'status' ] = status self . call_context [ 'headers' ] = headers self . call_context [ 'exc_info' ] = exc_info return self . body_buffer . write
Save args defer start_response until response body is parsed .
20,889
def _send_success_response ( self , response , start_response ) : headers = [ ( 'Content-Type' , 'application/json; charset=UTF-8' ) ] return util . send_wsgi_response ( '200 OK' , headers , response , start_response )
Sends an HTTP 200 json success response .
20,890
def _get_rest_doc ( self , request , start_response ) : api = request . body_json [ 'api' ] version = request . body_json [ 'version' ] generator = discovery_generator . DiscoveryGenerator ( request = request ) services = [ s for s in self . _backend . api_services if s . api_info . name == api and s . api_info . api_v...
Sends back HTTP response with API directory .
20,891
def _generate_api_config_with_root ( self , request ) : actual_root = self . _get_actual_root ( request ) generator = api_config . ApiConfigGenerator ( ) api = request . body_json [ 'api' ] version = request . body_json [ 'version' ] lookup_key = ( api , version ) service_factories = self . _backend . api_name_version_...
Generate an API config with a specific root hostname .
20,892
def _list ( self , request , start_response ) : configs = [ ] generator = directory_list_generator . DirectoryListGenerator ( request ) for config in self . _config_manager . configs . itervalues ( ) : if config != self . API_CONFIG : configs . append ( config ) directory = generator . pretty_print_config_to_json ( con...
Sends HTTP response containing the API directory .
20,893
def handle_discovery_request ( self , path , request , start_response ) : if path == self . _GET_REST_API : return self . _get_rest_doc ( request , start_response ) elif path == self . _GET_RPC_API : error_msg = ( 'RPC format documents are no longer supported with the ' 'Endpoints Framework for Python. Please use the R...
Returns the result of a discovery service request .
20,894
def _process_req_body ( self , body ) : try : return json . loads ( body ) except ValueError : return urlparse . parse_qs ( body , keep_blank_values = True )
Process the body of the HTTP request .
20,895
def _reconstruct_relative_url ( self , environ ) : url = urllib . quote ( environ . get ( 'SCRIPT_NAME' , '' ) ) url += urllib . quote ( environ . get ( 'PATH_INFO' , '' ) ) if environ . get ( 'QUERY_STRING' ) : url += '?' + environ [ 'QUERY_STRING' ] return url
Reconstruct the relative URL of this request .
20,896
def reconstruct_hostname ( self , port_override = None ) : url = self . server port = port_override or self . port if port and ( ( self . url_scheme == 'https' and str ( port ) != '443' ) or ( self . url_scheme != 'https' and str ( port ) != '80' ) ) : url += ':{0}' . format ( port ) return url
Reconstruct the hostname of a request .
20,897
def reconstruct_full_url ( self , port_override = None ) : return '{0}://{1}{2}' . format ( self . url_scheme , self . reconstruct_hostname ( port_override ) , self . relative_url )
Reconstruct the full URL of a request .
20,898
def _construct_operation_id ( self , service_name , protorpc_method_name ) : method_name_camel = util . snake_case_to_headless_camel_case ( protorpc_method_name ) return '{0}_{1}' . format ( service_name , method_name_camel )
Return an operation id for a service method .
20,899
def __definitions_descriptor ( self ) : result = { } for def_key , def_value in self . __parser . schemas ( ) . iteritems ( ) : if 'properties' in def_value or 'type' in def_value : key_result = { } required_keys = set ( ) if 'type' in def_value : key_result [ 'type' ] = def_value [ 'type' ] if 'properties' in def_valu...
Describes the definitions section of the OpenAPI spec .