idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
20,700
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 request is None : raise ValueError ( 'Cannot check query arg without request object.' ) schemes = ( 'Bearer' , ) if check_authorization_header else ( ) keys = ( 'access_token' , ) if check_query_arg else ( ) token = _get_token ( request = request , allowed_auth_schemes = schemes , allowed_query_keys = keys ) if token is None : return None time_now = long ( time . time ( ) ) for provider in providers : parsed_token = _parse_and_verify_jwt ( token , time_now , ( provider [ 'issuer' ] , ) , audiences , provider [ 'cert_uri' ] , cache ) if parsed_token is not None : return parsed_token return None
This function will extract verify and parse a JWT token from the Authorization header or access_token query argument .
255
22
20,701
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 . get ( 'description' ) root_url = config . get ( 'root' ) name = config . get ( 'name' ) version = config . get ( 'api_version' ) relative_path = '/apis/{0}/{1}/rest' . format ( name , version ) if description : descriptor [ 'description' ] = description descriptor [ 'name' ] = name descriptor [ 'version' ] = version descriptor [ 'discoveryLink' ] = '.{0}' . format ( relative_path ) root_url_port = urlparse . urlparse ( root_url ) . port original_path = self . __request . reconstruct_full_url ( port_override = root_url_port ) descriptor [ 'discoveryRestUrl' ] = '{0}/{1}/{2}/rest' . format ( original_path , name , version ) if name and version : descriptor [ 'id' ] = '{0}:{1}' . format ( name , version ) return descriptor
Builds an item descriptor for a service configuration .
343
10
20,702
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' ] = items return descriptor
Builds a directory list for an API .
100
9
20,703
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 .
76
16
20,704
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 .
61
17
20,705
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 .
103
8
20,706
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 .
42
11
20,707
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 .
65
11
20,708
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 . itervalues ( ) : name = config . get ( 'name' , '' ) api_version = config . get ( 'api_version' , '' ) path_version = config . get ( 'path_version' , '' ) sorted_methods = self . _get_sorted_methods ( config . get ( 'methods' , { } ) ) for method_name , method in sorted_methods : self . _save_rest_method ( method_name , name , path_version , method )
Parses a JSON API config and registers methods for dispatch .
211
13
20,709
def _get_sorted_methods ( self , methods ) : if not methods : return methods # Comparison function we'll use to sort the methods: def _sorted_methods_comparison ( method_info1 , method_info2 ) : """Sort method info by path and http_method. Args: method_info1: Method name and info for the first method to compare. method_info2: Method name and info for the method to compare to. Returns: Negative if the first method should come first, positive if the first method should come after the second. Zero if they're equivalent. """ def _score_path ( path ) : """Calculate the score for this path, used for comparisons. Higher scores have priority, and if scores are equal, the path text is sorted alphabetically. Scores are based on the number and location of the constant parts of the path. The server has some special handling for variables with regexes, which we don't handle here. Args: path: The request path that we're calculating a score for. Returns: The score for the given path. """ score = 0 parts = path . split ( '/' ) for part in parts : score <<= 1 if not part or part [ 0 ] != '{' : # Found a constant. score += 1 # Shift by 31 instead of 32 because some (!) versions of Python like # to convert the int to a long if we shift by 32, and the sorted() # function that uses this blows up if it receives anything but an int. score <<= 31 - len ( parts ) return score # Higher path scores come first. path_score1 = _score_path ( method_info1 [ 1 ] . get ( 'path' , '' ) ) path_score2 = _score_path ( method_info2 [ 1 ] . get ( 'path' , '' ) ) if path_score1 != path_score2 : return path_score2 - path_score1 # Compare by path text next, sorted alphabetically. path_result = cmp ( method_info1 [ 1 ] . get ( 'path' , '' ) , method_info2 [ 1 ] . get ( 'path' , '' ) ) if path_result != 0 : return path_result # All else being equal, sort by HTTP method. method_result = cmp ( method_info1 [ 1 ] . get ( 'httpMethod' , '' ) , method_info2 [ 1 ] . get ( 'httpMethod' , '' ) ) return method_result return sorted ( methods . items ( ) , _sorted_methods_comparison )
Get a copy of methods sorted the way they would be on the live server .
557
16
20,710
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 .
82
10
20,711
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_uri if candidate_method_info [ 1 ] . get ( 'useRequestUri' ) else path match = compiled_path_pattern . match ( match_against ) if match : params = self . _get_path_params ( match ) method_name , method = candidate_method_info break else : _logger . warn ( 'No endpoint found for path: %r, method: %r' , path , http_method ) method_name = None method = None params = None return method_name , method , params
Look up the rest method at call time .
200
9
20,712
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 .
73
11
20,713
def save_config ( self , lookup_key , config ) : with self . _config_lock : self . _configs [ lookup_key ] = config
Save a configuration to the cache of configs .
34
10
20,714
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 .
98
16
20,715
def _compile_path_pattern ( pattern ) : def replace_variable ( match ) : """Replaces a {variable} with a regex to match it by name. Changes the string corresponding to the variable name to the base32 representation of the string, prepended by an underscore. This is necessary because we can have message variable names in URL patterns (e.g. via {x.y}) but the character '.' can't be in a regex group name. Args: match: A regex match object, the matching regex group as sent by re.sub(). Returns: A string regex to match the variable by name, if the full pattern was matched. """ 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)}(?=/|$|:)' % _PATH_VARIABLE_PATTERN , replace_variable , pattern ) return re . compile ( pattern + '/?$' )
r Generates a compiled regex pattern for a path pattern .
270
12
20,716
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 ] = method_name , method break else : self . _rest_methods . append ( ( self . _compile_path_pattern ( path_pattern ) , path_pattern , { http_method : ( method_name , method ) } ) )
Store Rest api methods in a list for lookup at call time .
152
13
20,717
def api_server ( api_services , * * kwargs ) : # Disallow protocol configuration for now, Lily is json-only. 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' , endpoints_version ) # Construct the api serving app apis_app = _ApiServer ( api_services , * * kwargs ) dispatcher = endpoints_dispatcher . EndpointsDispatcherMiddleware ( apis_app ) # Determine the service name service_name = os . environ . get ( 'ENDPOINTS_SERVICE_NAME' ) if not service_name : _logger . warn ( 'Did not specify the ENDPOINTS_SERVICE_NAME environment' ' variable so service control is disabled. Please specify' ' the name of service in ENDPOINTS_SERVICE_NAME to enable' ' it.' ) return dispatcher # If we're using a local server, just return the dispatcher now to bypass # control client. if control_wsgi . running_on_devserver ( ) : _logger . warn ( 'Running on local devserver, so service control is disabled.' ) return dispatcher from endpoints_management import _logger as management_logger from endpoints_management import __version__ as management_version management_logger . info ( 'Initializing Endpoints Management Framework version %s' , management_version ) # The DEFAULT 'config' should be tuned so that it's always OK for python # App Engine workloads. The config can be adjusted, but that's probably # unnecessary on App Engine. controller = control_client . Loaders . DEFAULT . load ( service_name ) # Start the GAE background thread that powers the control client's cache. control_client . use_gae_thread ( ) controller . start ( ) return control_wsgi . add_all ( dispatcher , app_identity . get_application_id ( ) , controller )
Create an api_server .
474
6
20,718
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 .
63
9
20,719
def __register_class ( self , parsed_config ) : methods = parsed_config . get ( 'methods' ) if not methods : return # Determine the name of the class that implements this configuration. 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 ] service_classes . add ( method_class ) for service_class in service_classes : if service_class in self . __registered_classes : raise api_exceptions . ApiConfigurationError ( 'API class %s has already been registered.' % service_class ) self . __registered_classes . add ( service_class )
Register the class implementing this config so we only add it once .
181
13
20,720
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 .
69
10
20,721
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 = generator . get_config_dict ( service_classes ) api_config_registry . register_backend ( config_dict ) for service_factory in service_factories : protorpc_class_name = service_factory . service_class . __name__ root = '%s%s' % ( service_factory . service_class . api_info . base_path , protorpc_class_name ) if any ( service_map [ 0 ] == root or service_map [ 1 ] == service_factory for service_map in protorpc_services ) : raise api_config . ApiConfigurationError ( 'Can\'t reuse the same class in multiple APIs: %s' % protorpc_class_name ) protorpc_services . append ( ( root , service_factory ) ) return protorpc_services
Register & return a list of each URL and class that handles that URL .
278
15
20,722
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 .
83
9
20,723
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_message = error_message ) return status , self . __PROTOJSON . encode_message ( message )
Return the HTTP status line and body for a given error code and message .
110
15
20,724
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 : # Try to map to HTTP error code. error_class = _ERROR_NAME_MAP . get ( rpc_error . error_name ) if error_class : status , body = self . __write_error ( error_class . http_status , rpc_error . error_message ) return status , body
Convert a ProtoRPC error to the format expected by Google Endpoints .
158
16
20,725
def _add_dispatcher ( self , path_regex , dispatch_function ) : self . _dispatchers . append ( ( re . compile ( path_regex ) , dispatch_function ) )
Add a request path and dispatch handler .
45
8
20,726
def dispatch ( self , request , start_response ) : # Check if this matches any of our special handlers. dispatched_response = self . dispatch_non_api_requests ( request , start_response ) if dispatched_response is not None : return dispatched_response # Call the service. try : return self . call_backend ( request , start_response ) except errors . RequestError as error : return self . _handle_request_error ( request , error , start_response )
Handles dispatch to apiserver handlers .
103
9
20,727
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 ( request ) if cors_handler . allow_cors_request : # The server returns 200 rather than 204, for some reason. return util . send_wsgi_response ( '200' , [ ] , '' , start_response , cors_handler ) return None
Dispatch this request if this is a request to a reserved URL .
148
13
20,728
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_type # If we fall through to here, the verification has failed, so return False. return False
Verifies that a response has the expected status and content type .
102
13
20,729
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 ( len ( body ) ) , 'PATH_INFO' : url . path , 'QUERY_STRING' : url . query , 'REQUEST_METHOD' : method , 'REMOTE_ADDR' : source_ip , 'SERVER_NAME' : host , 'SERVER_PORT' : str ( port ) , 'SERVER_PROTOCOL' : 'HTTP/1.1' , 'wsgi.version' : ( 1 , 0 ) , 'wsgi.url_scheme' : 'http' , 'wsgi.errors' : cStringIO . StringIO ( ) , 'wsgi.multithread' : True , 'wsgi.multiprocess' : True , 'wsgi.input' : cStringIO . StringIO ( body ) } util . put_headers_in_environ ( headers , environ ) environ [ 'HTTP_HOST' ] = host return environ
Build an environ object for the backend to consume .
307
11
20,730
def handle_backend_response ( self , orig_request , backend_request , response_status , response_headers , response_body , method_config , start_response ) : # Verify that the response is json. If it isn't treat, the body as an # error message and wrap it in a json error response. for header , value in response_headers : if ( header . lower ( ) == 'content-type' and not value . lower ( ) . startswith ( 'application/json' ) ) : return self . fail_request ( orig_request , 'Non-JSON reply: %s' % response_body , start_response ) self . check_error_response ( response_body , response_status ) # Check if the response from the API was empty. Empty REST responses # generate a HTTP 204. empty_response = self . check_empty_response ( orig_request , method_config , start_response ) if empty_response is not None : return empty_response body = self . transform_rest_response ( response_body ) cors_handler = self . _create_cors_handler ( orig_request ) return util . send_wsgi_response ( response_status , response_headers , body , start_response , cors_handler = cors_handler )
Handle backend response transforming output as needed .
279
8
20,731
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 .
65
11
20,732
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 .
71
13
20,733
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 .
86
11
20,734
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 .
83
16
20,735
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 .
79
13
20,736
def transform_rest_request ( self , orig_request , params , method_parameters ) : request = orig_request . copy ( ) body_json = { } # Handle parameters from the URL path. for key , value in params . iteritems ( ) : # Values need to be in a list to interact with query parameter values # and to account for case of repeated parameters body_json [ key ] = [ value ] # Add in parameters from the query string. if request . parameters : # For repeated elements, query and path work together for key , value in request . parameters . iteritems ( ) : if key in body_json : body_json [ key ] = value + body_json [ key ] else : body_json [ key ] = value # Validate all parameters we've merged so far and convert any '.' delimited # parameters to nested parameters. We don't use iteritems since we may # modify body_json within the loop. For instance, 'a.b' is not a valid key # and would be replaced with 'a'. for key , value in body_json . items ( ) : current_parameter = method_parameters . get ( key , { } ) repeated = current_parameter . get ( 'repeated' , False ) if not repeated : body_json [ key ] = body_json [ key ] [ 0 ] # Order is important here. Parameter names are dot-delimited in # parameters instead of nested in dictionaries as a message field is, so # we need to call transform_parameter_value on them before calling # _add_message_field. body_json [ key ] = parameter_converter . transform_parameter_value ( key , body_json [ key ] , current_parameter ) # Remove the old key and try to convert to nested message value message_value = body_json . pop ( key ) self . _add_message_field ( key , message_value , body_json ) # Add in values from the body of the request. if request . body_json : self . _update_from_body ( body_json , request . body_json ) request . body_json = body_json request . body = json . dumps ( request . body_json ) return request
Translates a Rest request into an apiserving request .
482
13
20,737
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 .
51
14
20,738
def check_empty_response ( self , orig_request , method_config , start_response ) : response_config = method_config . get ( 'response' , { } ) . get ( 'body' ) if response_config == 'empty' : # The response to this function should be empty. We should return a 204. # Note that it's possible that the backend returned something, but we'll # ignore it. This matches the behavior in the Endpoints server. cors_handler = self . _create_cors_handler ( orig_request ) return util . send_wsgi_no_content_response ( start_response , cors_handler )
If the response from the backend is empty return a HTTP 204 No Content .
142
15
20,739
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 .
45
16
20,740
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 = self . _create_cors_handler ( orig_request ) return util . send_wsgi_response ( response_status , headers , body , start_response , cors_handler = cors_handler )
Handle a request error converting it to a WSGI response .
143
12
20,741
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 .
48
11
20,742
def GenApiConfig ( service_class_names , config_string_generator = None , hostname = None , application_path = None , * * additional_kwargs ) : # First, gather together all the different APIs implemented by these # classes. There may be fewer APIs than service classes. Each API is # uniquely identified by (name, version). Order needs to be preserved here, # so APIs that were listed first are returned first. api_service_map = collections . OrderedDict ( ) resolved_services = [ ] for service_class_name in service_class_names : module_name , base_service_class_name = service_class_name . rsplit ( '.' , 1 ) module = __import__ ( module_name , fromlist = base_service_class_name ) service = getattr ( module , base_service_class_name ) if hasattr ( service , 'get_api_classes' ) : resolved_services . extend ( service . get_api_classes ( ) ) elif ( not isinstance ( service , type ) or not issubclass ( service , remote . Service ) ) : raise TypeError ( '%s is not a ProtoRPC service' % service_class_name ) else : resolved_services . append ( service ) for resolved_service in resolved_services : services = api_service_map . setdefault ( ( resolved_service . api_info . name , resolved_service . api_info . api_version ) , [ ] ) services . append ( resolved_service ) # If hostname isn't specified in the API or on the command line, we'll # try to build it from information in app.yaml. app_yaml_hostname = _GetAppYamlHostname ( application_path ) service_map = collections . OrderedDict ( ) config_string_generator = ( config_string_generator or api_config . ApiConfigGenerator ( ) ) for api_info , services in api_service_map . iteritems ( ) : assert services , 'An API must have at least one ProtoRPC service' # Only override hostname if None. Hostname will be the same for all # services within an API, since it's stored in common info. hostname = services [ 0 ] . api_info . hostname or hostname or app_yaml_hostname # Map each API by name-version. service_map [ '%s-%s' % api_info ] = ( config_string_generator . pretty_print_config_to_json ( services , hostname = hostname , * * additional_kwargs ) ) return service_map
Write an API configuration for endpoints annotated ProtoRPC services .
575
14
20,743
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 : # Couldn't open/read app.yaml. return None application = config . get ( 'application' ) if not application : return None if ':' in application : # Don't try to deal with alternate domains. return None # If there's a prefix ending in a '~', strip it. tilde_index = application . rfind ( '~' ) if tilde_index >= 0 : application = application [ tilde_index + 1 : ] if not application : return None return '%s.appspot.com' % application
Build the hostname for this app based on the name in app . yaml .
193
17
20,744
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_name_version , config in service_configs . iteritems ( ) : discovery_name = api_name_version + '.discovery' output_files . append ( _WriteFile ( output_path , discovery_name , config ) ) return output_files
Write discovery documents generated from the service classes to file .
141
11
20,745
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 = application_path , x_google_api_name = x_google_api_name ) for api_name_version , config in service_configs . iteritems ( ) : openapi_name = api_name_version . replace ( '-' , '' ) + 'openapi.json' output_files . append ( _WriteFile ( output_path , openapi_name , config ) ) return output_files
Write openapi documents generated from the service classes to file .
183
12
20,746
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 = application_path ) for api_name_version , config in service_configs . iteritems ( ) : client_name = api_name_version + '.zip' client_libs . append ( _GenClientLibFromContents ( config , language , output_path , build_system , client_name ) ) return client_libs
Fetch client libraries from a cloud service .
157
9
20,747
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 .
88
6
20,748
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' % client_path
Generate discovery docs and client libraries to files .
86
10
20,749
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 .
78
7
20,750
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 .
64
8
20,751
def error ( self , message ) : # subcommands_quoted is the same as subcommands, except each value is # surrounded with double quotes. This is done to match the standard # output of the ArgumentParser, while hiding commands we don't want users # to use, as they are no longer documented and only here for legacy use. 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 , message ) super ( _EndpointsParser , self ) . error ( message )
Override superclass to support customized error message .
187
9
20,752
def _SetupPaths ( ) : sdk_path = _FindSdkPath ( ) if sdk_path : sys . path . append ( sdk_path ) try : import dev_appserver # pylint: disable=g-import-not-at-top 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_WARNING ) else : logging . warning ( _NOT_FOUND_WARNING ) # Add the path above this directory, so we can import the endpoints package # from the user's app code (rather than from another, possibly outdated SDK). # pylint: disable=g-import-not-at-top from google . appengine . ext import vendor vendor . add ( os . path . dirname ( os . path . dirname ( __file__ ) ) )
Sets up the sys . path with special directories for endpointscfg . py .
220
17
20,753
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 .
92
10
20,754
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 .
66
10
20,755
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 , issuers = None , namespace = None , api_key_required = None , base_path = None , limit_definitions = None , use_request_uri = None ) : if auth_level is not None : _logger . warn ( _AUTH_LEVEL_WARNING ) return _ApiDecorator ( name , version , description = description , hostname = hostname , audiences = audiences , scopes = scopes , allowed_client_ids = allowed_client_ids , canonical_name = canonical_name , auth = auth , owner_domain = owner_domain , owner_name = owner_name , package_path = package_path , frontend_limits = frontend_limits , title = title , documentation = documentation , auth_level = auth_level , issuers = issuers , namespace = namespace , api_key_required = api_key_required , base_path = base_path , limit_definitions = limit_definitions , use_request_uri = use_request_uri )
Decorate a ProtoRPC Service class for use by the framework above .
302
15
20,756
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 ) : if auth_level is not None : _logger . warn ( _AUTH_LEVEL_WARNING ) # Default HTTP method if one is not specified. DEFAULT_HTTP_METHOD = 'POST' def apiserving_method_decorator ( api_method ) : """Decorator for ProtoRPC method that configures Google's API server. Args: api_method: Original method being wrapped. Returns: Function responsible for actual invocation. Assigns the following attributes to invocation function: remote: Instance of RemoteInfo, contains remote method information. remote.request_type: Expected request type for remote method. remote.response_type: Response type returned from remote method. method_info: Instance of _MethodInfo, api method configuration. It is also assigned attributes corresponding to the aforementioned kwargs. Raises: TypeError: if the request_type or response_type parameters are not proper subclasses of messages.Message. KeyError: if the request_message is a ResourceContainer and the newly created remote method has been reference by the container before. This should never occur because a remote method is created once. """ request_body_class = None request_params_class = None if isinstance ( request_message , resource_container . ResourceContainer ) : remote_decorator = remote . method ( request_message . combined_message_class , response_message ) request_body_class = request_message . body_message_class ( ) request_params_class = request_message . parameters_message_class ( ) else : remote_decorator = remote . method ( request_message , response_message ) remote_method = remote_decorator ( api_method ) def invoke_remote ( service_instance , request ) : # If the server didn't specify any auth information, build it now. # pylint: disable=protected-access users_id_token . _maybe_set_current_user_vars ( invoke_remote , api_info = getattr ( service_instance , 'api_info' , None ) , request = request ) # pylint: enable=protected-access return remote_method ( service_instance , request ) invoke_remote . remote = remote_method . remote if isinstance ( request_message , resource_container . ResourceContainer ) : resource_container . ResourceContainer . add_to_cache ( invoke_remote . remote , request_message ) invoke_remote . method_info = _MethodInfo ( name = name or api_method . __name__ , path = path or api_method . __name__ , http_method = http_method or DEFAULT_HTTP_METHOD , scopes = scopes , audiences = audiences , allowed_client_ids = allowed_client_ids , auth_level = auth_level , api_key_required = api_key_required , metric_costs = metric_costs , use_request_uri = use_request_uri , request_body_class = request_body_class , request_params_class = request_params_class ) invoke_remote . __name__ = invoke_remote . method_info . name return invoke_remote endpoints_util . check_list_type ( scopes , ( basestring , endpoints_types . OAuth2Scope ) , 'scopes' ) endpoints_util . check_list_type ( allowed_client_ids , basestring , 'allowed_client_ids' ) _CheckEnum ( auth_level , AUTH_LEVEL , 'auth_level' ) _CheckAudiences ( audiences ) _CheckType ( metric_costs , dict , 'metric_costs' ) return apiserving_method_decorator
Decorate a ProtoRPC Method for use by the framework above .
883
14
20,757
def is_same_api ( self , other ) : if not isinstance ( other , _ApiInfo ) : return False # pylint: disable=protected-access return self . __common_info is other . __common_info
Check if this implements the same API as another _ApiInfo instance .
51
15
20,758
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 ) : """Decorator for ProtoRPC class that configures Google's API server. Args: api_class: remote.Service class, ProtoRPC service class being wrapped. Returns: Same class with API attributes assigned in api_info. """ self . __classes . append ( api_class ) api_class . api_info = _ApiInfo ( self . __common_info , resource_name = resource_name , path = path , audiences = audiences , scopes = scopes , allowed_client_ids = allowed_client_ids , auth_level = auth_level , api_key_required = api_key_required ) return api_class return apiserving_api_decorator
Get a decorator for a class that implements an API .
238
12
20,759
def __safe_name ( self , method_name ) : # Endpoints backend restricts what chars are allowed in a method name. safe_name = re . sub ( r'[^\.a-zA-Z0-9_]' , '' , method_name ) # Strip any number of leading underscores. safe_name = safe_name . lstrip ( '_' ) # Ensure the first character is lowercase. # Slice from 0:1 rather than indexing [0] in case safe_name is length 0. return safe_name [ 0 : 1 ] . lower ( ) + safe_name [ 1 : ]
Restrict method name to a - zA - Z0 - 9_ first char lowercase .
134
20
20,760
def method_id ( self , api_info ) : # This is done here for now because at __init__ time, the method is known # but not the api, and thus not the api name. Later, in # ApiConfigGenerator.__method_descriptor, the api name is known. 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 .
148
5
20,761
def __field_to_subfields ( self , field ) : # Termination condition 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 subfield_results : subfields_list . insert ( 0 , field ) result . append ( subfields_list ) return result
Fully describes data represented by field including the nested case .
120
12
20,762
def __field_to_parameter_type ( self , field ) : # We use lowercase values for types (e.g. 'string' instead of 'STRING'). 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 : 'boolean' , messages . Variant . ENUM : 'string' , } return custom_variant_map . get ( variant ) or variant . name . lower ( )
Converts the field variant type into a string describing the parameter .
151
13
20,763
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 ) return path_parameters_by_segment
Parses path paremeters from a URI path and organizes them by parameter .
117
19
20,764
def __validate_simple_subfield ( self , parameter , field , segment_list , _segment_index = 0 ) : if _segment_index >= len ( segment_list ) : # In this case, the field is the final one, so should be simple type if isinstance ( field , messages . MessageField ) : field_class = field . __class__ . __name__ raise TypeError ( 'Can\'t use messages in path. Subfield %r was ' 'included but is a %s.' % ( parameter , field_class ) ) return segment = segment_list [ _segment_index ] parameter += '.' + segment try : field = field . type . field_by_name ( segment ) except ( AttributeError , KeyError ) : raise TypeError ( 'Subfield %r from path does not exist.' % ( parameter , ) ) self . __validate_simple_subfield ( parameter , field , segment_list , _segment_index = _segment_index + 1 )
Verifies that a proposed subfield actually exists and is a simple field .
221
15
20,765
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 , segment_list [ 1 : ] )
Verifies that all path parameters correspond to an existing subfield .
103
13
20,766
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 .
57
12
20,767
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 .
89
13
20,768
def __parameter_descriptor ( self , subfield_list ) : descriptor = { } final_subfield = subfield_list [ - 1 ] # Required if all ( subfield . required for subfield in subfield_list ) : descriptor [ 'required' ] = True # Type descriptor [ 'type' ] = self . __field_to_parameter_type ( final_subfield ) # Default default = self . __parameter_default ( final_subfield ) if default is not None : descriptor [ 'default' ] = default # Repeated if any ( subfield . repeated for subfield in subfield_list ) : descriptor [ 'repeated' ] = True # Enum enum_descriptor = self . __parameter_enum ( final_subfield ) if enum_descriptor is not None : descriptor [ 'enum' ] = enum_descriptor return descriptor
Creates descriptor for a parameter using the subfields that define it .
193
14
20,769
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_method ] request_response = { } request_schema_id = self . __request_schema . get ( method_id ) if request_schema_id : request_response [ 'request' ] = { '$ref' : request_schema_id } response_schema_id = self . __response_schema . get ( method_id ) if response_schema_id : request_response [ 'response' ] = { '$ref' : response_schema_id } methods_desc [ rosy_method ] = request_response descriptor = { 'methods' : methods_desc , 'schemas' : self . __parser . schemas ( ) , } return descriptor
Descriptor for the all the JSON Schema used .
261
12
20,770
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_info . auth . blocked_regions return auth_descriptor
Builds an auth descriptor from API info .
117
9
20,771
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_info . frontend_limits , propname ) is not None : descriptor [ descname ] = getattr ( api_info . frontend_limits , propname ) rules = self . __frontend_limit_rules_descriptor ( api_info ) if rules : descriptor [ 'rules' ] = rules return descriptor
Builds a frontend limit descriptor from API info .
171
11
20,772
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' ) , ( 'analytics_id' , 'analyticsId' ) ) : if getattr ( rule , propname ) is not None : descriptor [ descname ] = getattr ( rule , propname ) if descriptor : rules . append ( descriptor ) return rules
Builds a frontend limit rules descriptor from API info .
166
12
20,773
def get_config_dict ( self , services , hostname = None ) : if not isinstance ( services , ( tuple , list ) ) : services = [ services ] # The type of a class that inherits from remote.Service is actually # remote._ServiceClass, thanks to metaclass strangeness. # pylint: disable=protected-access 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 .
122
16
20,774
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 .
65
16
20,775
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 .
65
12
20,776
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 . get ( field . name , [ ] ) if not isinstance ( field , messages . MessageField ) : name = field . name if name in matched_path_parameters : path_params . append ( name ) elif is_params_class and field . required : query_params . append ( name ) else : for subfield_list in self . __field_to_subfields ( field ) : name = '.' . join ( subfield . name for subfield in subfield_list ) if name in matched_path_parameters : path_params . append ( name ) elif is_params_class and field . required : query_params . append ( name ) return path_params + sorted ( query_params )
Describe the order of path parameters .
252
8
20,777
def __schemas_descriptor ( self ) : # Filter out any keys that aren't 'properties', 'type', or 'id' result = { } for schema_key , schema_value in self . __parser . schemas ( ) . iteritems ( ) : field_keys = schema_value . keys ( ) key_result = { } # Some special processing for the properties value if 'properties' in field_keys : key_result [ 'properties' ] = schema_value [ 'properties' ] . copy ( ) # Add in enumDescriptions for any enum properties and strip out # the required tag for consistency with Java framework for prop_key , prop_value in schema_value [ 'properties' ] . iteritems ( ) : if 'enum' in prop_value : num_enums = len ( prop_value [ 'enum' ] ) key_result [ 'properties' ] [ prop_key ] [ 'enumDescriptions' ] = ( [ '' ] * num_enums ) elif 'default' in prop_value : # stringify default values if prop_value . get ( 'type' ) == 'boolean' : prop_value [ 'default' ] = 'true' if prop_value [ 'default' ] else 'false' else : prop_value [ 'default' ] = str ( prop_value [ 'default' ] ) key_result [ 'properties' ] [ prop_key ] . pop ( 'required' , None ) for key in ( 'type' , 'id' , 'description' ) : if key in field_keys : key_result [ key ] = schema_value [ key ] if key_result : result [ schema_key ] = key_result # Add 'type': 'object' to all object properties for schema_value in result . itervalues ( ) : for field_value in schema_value . itervalues ( ) : if isinstance ( field_value , dict ) : if '$ref' in field_value : field_value [ 'type' ] = 'object' return result
Describes the schemas section of the discovery document .
447
11
20,778
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 , 'method_info' , None ) path = method_info . get_path ( service . api_info ) method_id = method_info . method_id ( service . api_info ) canonical_method_id = self . _get_canonical_method_id ( method_id ) current_resource_path = self . _get_resource_path ( method_id ) # Sanity-check that this method belongs to the resource path if ( current_resource_path [ : len ( resource_path_tokens ) ] != resource_path_tokens ) : raise api_exceptions . ToolError ( 'Internal consistency error in resource path {0}' . format ( current_resource_path ) ) # Remove the portion of the current method's resource path that's already # part of the resource path at this level. effective_resource_path = current_resource_path [ len ( resource_path_tokens ) : ] # If this method is part of a sub-resource, note it and skip it for now if effective_resource_path : sub_resource_name = effective_resource_path [ 0 ] new_resource_path = '.' . join ( [ resource_path , sub_resource_name ] ) sub_resource_index [ new_resource_path ] . append ( ( service , protorpc_meth_info ) ) else : method_map [ canonical_method_id ] = self . __method_descriptor ( service , method_info , protorpc_meth_info ) # Process any sub-resources for sub_resource , sub_resource_methods in sub_resource_index . items ( ) : sub_resource_name = sub_resource . split ( '.' ) [ - 1 ] sub_resource_map [ sub_resource_name ] = self . __resource_descriptor ( sub_resource , sub_resource_methods ) if method_map : descriptor [ 'methods' ] = method_map if sub_resource_map : descriptor [ 'resources' ] = sub_resource_map return descriptor
Describes a resource .
544
5
20,779
def get_discovery_doc ( self , services , hostname = None ) : if not isinstance ( services , ( tuple , list ) ) : services = [ services ] # The type of a class that inherits from remote.Service is actually # remote._ServiceClass, thanks to metaclass strangeness. # pylint: disable=protected-access 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 .
123
16
20,780
def send_wsgi_response ( status , headers , content , start_response , cors_handler = None ) : if cors_handler : cors_handler . update_headers ( headers ) # Update content length. content_len = len ( content ) if content else 0 headers = [ ( header , value ) for header , value in headers if header . lower ( ) != 'content-length' ] headers . append ( ( 'Content-Length' , '%s' % content_len ) ) start_response ( status , headers ) return content
Dump reformatted response to CGI start_response .
118
11
20,781
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 # Content-Type is special; it does not start with 'HTTP_'. if 'CONTENT_TYPE' in environ : headers [ 'CONTENT-TYPE' ] = environ [ 'CONTENT_TYPE' ] return headers
Get a wsgiref . headers . Headers object with headers from the environment .
124
18
20,782
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 .
51
17
20,783
def get_hostname_prefix ( ) : parts = [ ] # Check if this is the default version version = modules . get_current_version_name ( ) default_version = modules . get_default_version ( ) if version != default_version : parts . append ( version ) # Check if this is the default module module = modules . get_current_module_name ( ) if module != 'default' : parts . append ( module ) # If there is anything to prepend, add an extra blank entry for the trailing # -dot- if parts : parts . append ( '' ) return '-dot-' . join ( parts )
Returns the hostname prefix of a running Endpoints service .
135
12
20,784
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' : suffix = 'googleplex.com' else : api_name = app_id return '{0}{1}.{2}' . format ( prefix , api_name , suffix )
Return hostname of a running Endpoints service .
148
10
20,785
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 , allowed_type ) for i in objects ) : type_list = sorted ( list ( set ( type ( obj ) for obj in objects ) ) ) raise TypeError ( '%s contains types that don\'t match %s: %s' % ( name , allowed_type . __name__ , type_list ) ) return objects
Verify that objects in list are of the allowed type or raise TypeError .
161
16
20,786
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 .
71
12
20,787
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 .
64
12
20,788
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 .
64
9
20,789
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_version == version ] doc = generator . pretty_print_config_to_json ( services ) if not doc : error_msg = ( 'Failed to convert .api to discovery doc for ' 'version %s of api %s' ) % ( version , api ) _logger . error ( '%s' , error_msg ) return util . send_wsgi_error_response ( error_msg , start_response ) return self . _send_success_response ( doc , start_response )
Sends back HTTP response with API directory .
199
9
20,790
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_map . get ( lookup_key ) if not service_factories : return None service_classes = [ service_factory . service_class for service_factory in service_factories ] config_dict = generator . get_config_dict ( service_classes , hostname = actual_root ) # Save to cache for config in config_dict . get ( 'items' , [ ] ) : lookup_key_with_root = ( config . get ( 'name' , '' ) , config . get ( 'version' , '' ) , actual_root ) self . _config_manager . save_config ( lookup_key_with_root , config ) return config_dict
Generate an API config with a specific root hostname .
241
12
20,791
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 ( configs ) if not directory : _logger . error ( 'Failed to get API directory' ) # By returning a 404, code explorer still works if you select the # API in the URL return util . send_wsgi_not_found_response ( start_response ) return self . _send_success_response ( directory , start_response )
Sends HTTP response containing the API directory .
160
9
20,792
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 REST ' 'format.' ) _logger . error ( '%s' , error_msg ) return util . send_wsgi_error_response ( error_msg , start_response ) elif path == self . _LIST_API : return self . _list ( request , start_response ) return False
Returns the result of a discovery service request .
155
9
20,793
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 .
44
8
20,794
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 .
93
10
20,795
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 .
94
10
20,796
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 .
58
10
20,797
def _construct_operation_id ( self , service_name , protorpc_method_name ) : # camelCase the 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 .
86
9
20,798
def __definitions_descriptor ( self ) : # Filter out any keys that aren't 'properties' or 'type' 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_value : for prop_key , prop_value in def_value [ 'properties' ] . items ( ) : if isinstance ( prop_value , dict ) and 'required' in prop_value : required_keys . add ( prop_key ) del prop_value [ 'required' ] key_result [ 'properties' ] = def_value [ 'properties' ] # Add in the required fields, if any if required_keys : key_result [ 'required' ] = sorted ( required_keys ) result [ def_key ] = key_result # Add 'type': 'object' to all object properties # Also, recursively add relative path to all $ref values for def_value in result . itervalues ( ) : for prop_value in def_value . itervalues ( ) : if isinstance ( prop_value , dict ) : if '$ref' in prop_value : prop_value [ 'type' ] = 'object' self . _add_def_paths ( prop_value ) return result
Describes the definitions section of the OpenAPI spec .
341
11
20,799
def __response_message_descriptor ( self , message_type , method_id ) : # Skeleton response descriptor, common to all response objects descriptor = { '200' : { 'description' : 'A successful response' } } if message_type != message_types . VoidMessage ( ) : self . __parser . add_message ( message_type . __class__ ) self . __response_schema [ method_id ] = self . __parser . ref_for_message_type ( message_type . __class__ ) descriptor [ '200' ] [ 'schema' ] = { '$ref' : '#/definitions/{0}' . format ( self . __response_schema [ method_id ] ) } return dict ( descriptor )
Describes the response .
167
5