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 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 . |
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 . 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 . |
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' ] = items return descriptor | 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 . 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 . |
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 ) return score 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 path_result = cmp ( method_info1 [ 1 ] . get ( 'path' , '' ) , method_info2 [ 1 ] . get ( 'path' , '' ) ) if path_result != 0 : return path_result 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 . |
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_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 . |
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)}(?=/|$|:)' % _PATH_VARIABLE_PATTERN , replace_variable , pattern ) return re . compile ( pattern + '/?$' ) | 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 ] = 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 . |
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' , endpoints_version ) apis_app = _ApiServer ( api_services , ** kwargs ) dispatcher = endpoints_dispatcher . EndpointsDispatcherMiddleware ( apis_app ) 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 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 ) controller = control_client . Loaders . DEFAULT . load ( service_name ) control_client . use_gae_thread ( ) controller . start ( ) return control_wsgi . add_all ( dispatcher , app_identity . get_application_id ( ) , controller ) | 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 ] 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 . |
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 = 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 . |
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_message = error_message ) return status , self . __PROTOJSON . encode_message ( message ) | 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 = _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 . |
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 . _handle_request_error ( request , error , start_response ) | 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 ( request ) if cors_handler . allow_cors_request : return util . send_wsgi_response ( '200' , [ ] , '' , start_response , cors_handler ) return None | 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_type return False | 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 ( 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 . |
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 . fail_request ( orig_request , 'Non-JSON reply: %s' % response_body , start_response ) self . check_error_response ( response_body , response_status ) 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 . |
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_json [ key ] = value + body_json [ key ] else : body_json [ key ] = value 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 ] body_json [ key ] = parameter_converter . transform_parameter_value ( key , body_json [ key ] , current_parameter ) message_value = body_json . pop ( key ) self . _add_message_field ( key , message_value , body_json ) 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 . |
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_handler ) | 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 = 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 . |
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_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 ) 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' hostname = services [ 0 ] . api_info . hostname or hostname or app_yaml_hostname 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 . |
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 None if ':' in application : return None 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 . |
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_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 . |
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 = 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 . |
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 = 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 . |
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' % client_path | 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 , message ) super ( _EndpointsParser , self ) . error ( message ) | 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_WARNING ) else : logging . warning ( _NOT_FOUND_WARNING ) 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 . |
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 , 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 . |
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 ) : if auth_level is not None : _logger . warn ( _AUTH_LEVEL_WARNING ) DEFAULT_HTTP_METHOD = 'POST' def apiserving_method_decorator ( api_method ) : 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 ) : users_id_token . _maybe_set_current_user_vars ( invoke_remote , api_info = getattr ( service_instance , 'api_info' , None ) , request = request ) 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 . |
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 ) 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 . |
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 subfield_results : subfields_list . insert ( 0 , field ) result . append ( subfields_list ) return result | 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 : '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 . |
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 ) return path_parameters_by_segment | 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 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 . |
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 , segment_list [ 1 : ] ) | 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 ( final_subfield ) if default is not None : descriptor [ 'default' ] = default if any ( subfield . repeated for subfield in subfield_list ) : descriptor [ 'repeated' ] = True 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 . |
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_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 . |
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_info . auth . blocked_regions return auth_descriptor | 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_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 . |
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' ) , ( '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 . |
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 . 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 . |
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 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 : 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 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 . |
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 , '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 ) 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 ) ) effective_resource_path = current_resource_path [ len ( resource_path_tokens ) : ] 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 ) 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 . |
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 = services [ 0 ] . __doc__ if description : descriptor [ 'description' ] = description descriptor [ 'parameters' ] = self . __standard_parameters_descriptor ( ) descriptor [ 'auth' ] = self . __standard_auth_descriptor ( services ) if merged_api_info . namespace : descriptor [ 'ownerDomain' ] = merged_api_info . namespace . owner_domain descriptor [ 'ownerName' ] = merged_api_info . namespace . owner_name descriptor [ 'packagePath' ] = merged_api_info . namespace . package_path or '' else : if merged_api_info . owner_domain is not None : descriptor [ 'ownerDomain' ] = merged_api_info . owner_domain if merged_api_info . owner_name is not None : descriptor [ 'ownerName' ] = merged_api_info . owner_name if merged_api_info . package_path is not None : descriptor [ 'packagePath' ] = merged_api_info . package_path method_map = { } method_collision_tracker = { } rest_collision_tracker = { } resource_index = collections . defaultdict ( list ) resource_map = { } for service in services : remote_methods = service . all_remote_methods ( ) for protorpc_meth_name , protorpc_meth_info in remote_methods . iteritems ( ) : method_info = getattr ( protorpc_meth_info , 'method_info' , None ) if method_info is None : continue 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 ) resource_path = self . _get_resource_path ( method_id ) if method_id in method_collision_tracker : raise api_exceptions . ApiConfigurationError ( 'Method %s used multiple times, in classes %s and %s' % ( method_id , method_collision_tracker [ method_id ] , service . __name__ ) ) else : method_collision_tracker [ method_id ] = service . __name__ rest_identifier = ( method_info . http_method , path ) if rest_identifier in rest_collision_tracker : raise api_exceptions . ApiConfigurationError ( '%s path "%s" used multiple times, in classes %s and %s' % ( method_info . http_method , path , rest_collision_tracker [ rest_identifier ] , service . __name__ ) ) else : rest_collision_tracker [ rest_identifier ] = service . __name__ if resource_path : resource_index [ resource_path [ 0 ] ] . append ( ( service , protorpc_meth_info ) ) else : method_map [ canonical_method_id ] = self . __method_descriptor ( service , method_info , protorpc_meth_info ) for resource , resource_methods in resource_index . items ( ) : resource_map [ resource ] = self . __resource_descriptor ( resource , resource_methods ) if method_map : descriptor [ 'methods' ] = method_map if resource_map : descriptor [ 'resources' ] = resource_map schemas = self . __schemas_descriptor ( ) if schemas : descriptor [ 'schemas' ] = schemas return descriptor | 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 . append ( ( 'Content-Length' , '%s' % content_len ) ) start_response ( status , headers ) return content | 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' ] return headers | 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 . append ( '' ) return '-dot-' . join ( parts ) | 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' : suffix = 'googleplex.com' else : api_name = app_id return '{0}{1}.{2}' . format ( prefix , api_name , suffix ) | 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 , 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 . |
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_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 . |
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_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 ) 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 . |
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 ( configs ) if not directory : _logger . error ( 'Failed to get API directory' ) return util . send_wsgi_not_found_response ( start_response ) return self . _send_success_response ( directory , start_response ) | 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 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 . |
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_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' ] if required_keys : key_result [ 'required' ] = sorted ( required_keys ) result [ def_key ] = key_result 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.