repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
cloudendpoints/endpoints-python
endpoints/users_id_token.py
get_verified_jwt
def get_verified_jwt( providers, audiences, check_authorization_header=True, check_query_arg=True, request=None, cache=memcache): """ This function will extract, verify, and parse a JWT token from the Authorization header or access_token query argument. The JWT is assumed to contain an issuer and audience claim, as well as issued-at and expiration timestamps. The signature will be cryptographically verified, the claims and timestamps will be checked, and the resulting parsed JWT body is returned. If at any point the JWT is missing or found to be invalid, the return result will be None. Arguments: providers - An iterable of dicts each containing 'issuer' and 'cert_uri' keys audiences - An iterable of valid audiences check_authorization_header - Boolean; check 'Authorization: Bearer' header check_query_arg - Boolean; check 'access_token' query arg request - Must be the request object if check_query_arg is true; otherwise ignored. cache - In testing, override the certificate cache """ 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
python
def get_verified_jwt( providers, audiences, check_authorization_header=True, check_query_arg=True, request=None, cache=memcache): """ This function will extract, verify, and parse a JWT token from the Authorization header or access_token query argument. The JWT is assumed to contain an issuer and audience claim, as well as issued-at and expiration timestamps. The signature will be cryptographically verified, the claims and timestamps will be checked, and the resulting parsed JWT body is returned. If at any point the JWT is missing or found to be invalid, the return result will be None. Arguments: providers - An iterable of dicts each containing 'issuer' and 'cert_uri' keys audiences - An iterable of valid audiences check_authorization_header - Boolean; check 'Authorization: Bearer' header check_query_arg - Boolean; check 'access_token' query arg request - Must be the request object if check_query_arg is true; otherwise ignored. cache - In testing, override the certificate cache """ 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
[ "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. The JWT is assumed to contain an issuer and audience claim, as well as issued-at and expiration timestamps. The signature will be cryptographically verified, the claims and timestamps will be checked, and the resulting parsed JWT body is returned. If at any point the JWT is missing or found to be invalid, the return result will be None. Arguments: providers - An iterable of dicts each containing 'issuer' and 'cert_uri' keys audiences - An iterable of valid audiences check_authorization_header - Boolean; check 'Authorization: Bearer' header check_query_arg - Boolean; check 'access_token' query arg request - Must be the request object if check_query_arg is true; otherwise ignored. cache - In testing, override the certificate cache
[ "This", "function", "will", "extract", "verify", "and", "parse", "a", "JWT", "token", "from", "the", "Authorization", "header", "or", "access_token", "query", "argument", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L750-L794
train
cloudendpoints/endpoints-python
endpoints/directory_list_generator.py
DirectoryListGenerator.__item_descriptor
def __item_descriptor(self, config): """Builds an item descriptor for a service configuration. Args: config: A dictionary containing the service configuration to describe. Returns: A dictionary that describes the service configuration. """ 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
python
def __item_descriptor(self, config): """Builds an item descriptor for a service configuration. Args: config: A dictionary containing the service configuration to describe. Returns: A dictionary that describes the service configuration. """ 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
[ "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. Args: config: A dictionary containing the service configuration to describe. Returns: A dictionary that describes the service configuration.
[ "Builds", "an", "item", "descriptor", "for", "a", "service", "configuration", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/directory_list_generator.py#L56-L99
train
cloudendpoints/endpoints-python
endpoints/directory_list_generator.py
DirectoryListGenerator.__directory_list_descriptor
def __directory_list_descriptor(self, configs): """Builds a directory list for an API. Args: configs: List of dicts containing the service configurations to list. Returns: A dictionary that can be deserialized into JSON in discovery list format. Raises: ApiConfigurationError: If there's something wrong with the API configuration, such as a multiclass API decorated with different API descriptors (see the docstring for api()), or a repeated method signature. """ 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
python
def __directory_list_descriptor(self, configs): """Builds a directory list for an API. Args: configs: List of dicts containing the service configurations to list. Returns: A dictionary that can be deserialized into JSON in discovery list format. Raises: ApiConfigurationError: If there's something wrong with the API configuration, such as a multiclass API decorated with different API descriptors (see the docstring for api()), or a repeated method signature. """ 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
[ "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. Args: configs: List of dicts containing the service configurations to list. Returns: A dictionary that can be deserialized into JSON in discovery list format. Raises: ApiConfigurationError: If there's something wrong with the API configuration, such as a multiclass API decorated with different API descriptors (see the docstring for api()), or a repeated method signature.
[ "Builds", "a", "directory", "list", "for", "an", "API", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/directory_list_generator.py#L101-L130
train
cloudendpoints/endpoints-python
endpoints/directory_list_generator.py
DirectoryListGenerator.get_directory_list_doc
def get_directory_list_doc(self, configs): """JSON dict description of a protorpc.remote.Service in list format. Args: configs: Either a single dict or a list of dicts containing the service configurations to list. Returns: dict, The directory list document as a JSON dict. """ if not isinstance(configs, (tuple, list)): configs = [configs] util.check_list_type(configs, dict, 'configs', allow_none=False) return self.__directory_list_descriptor(configs)
python
def get_directory_list_doc(self, configs): """JSON dict description of a protorpc.remote.Service in list format. Args: configs: Either a single dict or a list of dicts containing the service configurations to list. Returns: dict, The directory list document as a JSON dict. """ if not isinstance(configs, (tuple, list)): configs = [configs] util.check_list_type(configs, dict, 'configs', allow_none=False) return self.__directory_list_descriptor(configs)
[ "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. Args: configs: Either a single dict or a list of dicts containing the service configurations to list. Returns: dict, The directory list document as a JSON dict.
[ "JSON", "dict", "description", "of", "a", "protorpc", ".", "remote", ".", "Service", "in", "list", "format", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/directory_list_generator.py#L132-L148
train
cloudendpoints/endpoints-python
endpoints/directory_list_generator.py
DirectoryListGenerator.pretty_print_config_to_json
def pretty_print_config_to_json(self, configs): """JSON string description of a protorpc.remote.Service in a discovery doc. Args: configs: Either a single dict or a list of dicts containing the service configurations to list. Returns: string, The directory list document as a JSON string. """ descriptor = self.get_directory_list_doc(configs) return json.dumps(descriptor, sort_keys=True, indent=2, separators=(',', ': '))
python
def pretty_print_config_to_json(self, configs): """JSON string description of a protorpc.remote.Service in a discovery doc. Args: configs: Either a single dict or a list of dicts containing the service configurations to list. Returns: string, The directory list document as a JSON string. """ descriptor = self.get_directory_list_doc(configs) return json.dumps(descriptor, sort_keys=True, indent=2, separators=(',', ': '))
[ "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. Args: configs: Either a single dict or a list of dicts containing the service configurations to list. Returns: string, The directory list document as a JSON string.
[ "JSON", "string", "description", "of", "a", "protorpc", ".", "remote", ".", "Service", "in", "a", "discovery", "doc", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/directory_list_generator.py#L150-L162
train
cloudendpoints/endpoints-python
endpoints/errors.py
RequestError.__format_error
def __format_error(self, error_list_tag): """Format this error into a JSON response. Args: error_list_tag: A string specifying the name of the tag to use for the error list. Returns: A dict containing the reformatted JSON error response. """ 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()}}
python
def __format_error(self, error_list_tag): """Format this error into a JSON response. Args: error_list_tag: A string specifying the name of the tag to use for the error list. Returns: A dict containing the reformatted JSON error response. """ 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()}}
[ "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. Args: error_list_tag: A string specifying the name of the tag to use for the error list. Returns: A dict containing the reformatted JSON error response.
[ "Format", "this", "error", "into", "a", "JSON", "response", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/errors.py#L100-L116
train
cloudendpoints/endpoints-python
endpoints/errors.py
RequestError.rest_error
def rest_error(self): """Format this error into a response to a REST request. Returns: A string containing the reformatted error response. """ error_json = self.__format_error('errors') return json.dumps(error_json, indent=1, sort_keys=True)
python
def rest_error(self): """Format this error into a response to a REST request. Returns: A string containing the reformatted error response. """ error_json = self.__format_error('errors') return json.dumps(error_json, indent=1, sort_keys=True)
[ "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. Returns: A string containing the reformatted error response.
[ "Format", "this", "error", "into", "a", "response", "to", "a", "REST", "request", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/errors.py#L118-L125
train
cloudendpoints/endpoints-python
endpoints/errors.py
BackendError._get_status_code
def _get_status_code(self, http_status): """Get the HTTP status code from an HTTP status string. Args: http_status: A string containing a HTTP status code and reason. Returns: An integer with the status code number from 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
python
def _get_status_code(self, http_status): """Get the HTTP status code from an HTTP status string. Args: http_status: A string containing a HTTP status code and reason. Returns: An integer with the status code number from 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
[ "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. Args: http_status: A string containing a HTTP status code and reason. Returns: An integer with the status code number from http_status.
[ "Get", "the", "HTTP", "status", "code", "from", "an", "HTTP", "status", "string", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/errors.py#L239-L253
train
cloudendpoints/endpoints-python
endpoints/api_config_manager.py
ApiConfigManager.process_api_config_response
def process_api_config_response(self, config_json): """Parses a JSON API config and registers methods for dispatch. Side effects: Parses method name, etc. for all methods and updates the indexing data structures with the information. Args: config_json: A dict, the JSON body of the getApiConfigs response. """ 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)
python
def process_api_config_response(self, config_json): """Parses a JSON API config and registers methods for dispatch. Side effects: Parses method name, etc. for all methods and updates the indexing data structures with the information. Args: config_json: A dict, the JSON body of the getApiConfigs response. """ 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)
[ "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. Side effects: Parses method name, etc. for all methods and updates the indexing data structures with the information. Args: config_json: A dict, the JSON body of the getApiConfigs response.
[ "Parses", "a", "JSON", "API", "config", "and", "registers", "methods", "for", "dispatch", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L53-L77
train
cloudendpoints/endpoints-python
endpoints/api_config_manager.py
ApiConfigManager._get_sorted_methods
def _get_sorted_methods(self, methods): """Get a copy of 'methods' sorted the way they would be on the live server. Args: methods: JSON configuration of an API's methods. Returns: The same configuration with the methods sorted based on what order they'll be checked by the server. """ 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)
python
def _get_sorted_methods(self, methods): """Get a copy of 'methods' sorted the way they would be on the live server. Args: methods: JSON configuration of an API's methods. Returns: The same configuration with the methods sorted based on what order they'll be checked by the server. """ 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)
[ "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.\n\n Args:\n method_info1: Method name and info for the first method to compare.\n method_info2: Method name and info for the method to compare to.\n\n Returns:\n Negative if the first method should come first, positive if the\n first method should come after the second. Zero if they're\n equivalent.\n \"\"\"", "def", "_score_path", "(", "path", ")", ":", "\"\"\"Calculate the score for this path, used for comparisons.\n\n Higher scores have priority, and if scores are equal, the path text\n is sorted alphabetically. Scores are based on the number and location\n of the constant parts of the path. The server has some special handling\n for variables with regexes, which we don't handle here.\n\n Args:\n path: The request path that we're calculating a score for.\n\n Returns:\n The score for the given path.\n \"\"\"", "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. Args: methods: JSON configuration of an API's methods. Returns: The same configuration with the methods sorted based on what order they'll be checked by the server.
[ "Get", "a", "copy", "of", "methods", "sorted", "the", "way", "they", "would", "be", "on", "the", "live", "server", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L79-L150
train
cloudendpoints/endpoints-python
endpoints/api_config_manager.py
ApiConfigManager._get_path_params
def _get_path_params(match): """Gets path parameters from a regular expression match. Args: match: A regular expression Match object for a path. Returns: A dictionary containing the variable names converted from base64. """ 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
python
def _get_path_params(match): """Gets path parameters from a regular expression match. Args: match: A regular expression Match object for a path. Returns: A dictionary containing the variable names converted from base64. """ 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
[ "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. Args: match: A regular expression Match object for a path. Returns: A dictionary containing the variable names converted from base64.
[ "Gets", "path", "parameters", "from", "a", "regular", "expression", "match", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L153-L166
train
cloudendpoints/endpoints-python
endpoints/api_config_manager.py
ApiConfigManager.lookup_rest_method
def lookup_rest_method(self, path, request_uri, http_method): """Look up the rest method at call time. The method is looked up in self._rest_methods, the list it is saved in for SaveRestMethod. Args: path: A string containing the path from the URL of the request. http_method: A string containing HTTP method of the request. Returns: Tuple of (<method name>, <method>, <params>) Where: <method name> is the string name of the method that was matched. <method> is the descriptor as specified in the API configuration. -and- <params> is a dict of path parameters matched in the rest request. """ 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
python
def lookup_rest_method(self, path, request_uri, http_method): """Look up the rest method at call time. The method is looked up in self._rest_methods, the list it is saved in for SaveRestMethod. Args: path: A string containing the path from the URL of the request. http_method: A string containing HTTP method of the request. Returns: Tuple of (<method name>, <method>, <params>) Where: <method name> is the string name of the method that was matched. <method> is the descriptor as specified in the API configuration. -and- <params> is a dict of path parameters matched in the rest request. """ 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
[ "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. The method is looked up in self._rest_methods, the list it is saved in for SaveRestMethod. Args: path: A string containing the path from the URL of the request. http_method: A string containing HTTP method of the request. Returns: Tuple of (<method name>, <method>, <params>) Where: <method name> is the string name of the method that was matched. <method> is the descriptor as specified in the API configuration. -and- <params> is a dict of path parameters matched in the rest request.
[ "Look", "up", "the", "rest", "method", "at", "call", "time", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L168-L202
train
cloudendpoints/endpoints-python
endpoints/api_config_manager.py
ApiConfigManager._add_discovery_config
def _add_discovery_config(self): """Add the Discovery configuration to our list of configs. This should only be called with self._config_lock. The code here assumes the lock is held. """ lookup_key = (discovery_service.DiscoveryService.API_CONFIG['name'], discovery_service.DiscoveryService.API_CONFIG['version']) self._configs[lookup_key] = discovery_service.DiscoveryService.API_CONFIG
python
def _add_discovery_config(self): """Add the Discovery configuration to our list of configs. This should only be called with self._config_lock. The code here assumes the lock is held. """ lookup_key = (discovery_service.DiscoveryService.API_CONFIG['name'], discovery_service.DiscoveryService.API_CONFIG['version']) self._configs[lookup_key] = discovery_service.DiscoveryService.API_CONFIG
[ "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. This should only be called with self._config_lock. The code here assumes the lock is held.
[ "Add", "the", "Discovery", "configuration", "to", "our", "list", "of", "configs", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L204-L212
train
cloudendpoints/endpoints-python
endpoints/api_config_manager.py
ApiConfigManager.save_config
def save_config(self, lookup_key, config): """Save a configuration to the cache of configs. Args: lookup_key: A string containing the cache lookup key. config: The dict containing the configuration to save to the cache. """ with self._config_lock: self._configs[lookup_key] = config
python
def save_config(self, lookup_key, config): """Save a configuration to the cache of configs. Args: lookup_key: A string containing the cache lookup key. config: The dict containing the configuration to save to the cache. """ with self._config_lock: self._configs[lookup_key] = config
[ "def", "save_config", "(", "self", ",", "lookup_key", ",", "config", ")", ":", "with", "self", ".", "_config_lock", ":", "self", ".", "_configs", "[", "lookup_key", "]", "=", "config" ]
Save a configuration to the cache of configs. Args: lookup_key: A string containing the cache lookup key. config: The dict containing the configuration to save to the cache.
[ "Save", "a", "configuration", "to", "the", "cache", "of", "configs", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L214-L222
train
cloudendpoints/endpoints-python
endpoints/api_config_manager.py
ApiConfigManager._from_safe_path_param_name
def _from_safe_path_param_name(safe_parameter): """Takes a safe regex group name and converts it back to the original value. Only alphanumeric characters and underscore are allowed in variable name tokens, and numeric are not allowed as the first character. The safe_parameter is a base32 representation of the actual value. Args: safe_parameter: A string that was generated by _to_safe_path_param_name. Returns: A string, the parameter matched from the URL template. """ 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)
python
def _from_safe_path_param_name(safe_parameter): """Takes a safe regex group name and converts it back to the original value. Only alphanumeric characters and underscore are allowed in variable name tokens, and numeric are not allowed as the first character. The safe_parameter is a base32 representation of the actual value. Args: safe_parameter: A string that was generated by _to_safe_path_param_name. Returns: A string, the parameter matched from the URL template. """ 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)
[ "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. Only alphanumeric characters and underscore are allowed in variable name tokens, and numeric are not allowed as the first character. The safe_parameter is a base32 representation of the actual value. Args: safe_parameter: A string that was generated by _to_safe_path_param_name. Returns: A string, the parameter matched from the URL template.
[ "Takes", "a", "safe", "regex", "group", "name", "and", "converts", "it", "back", "to", "the", "original", "value", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L245-L264
train
cloudendpoints/endpoints-python
endpoints/api_config_manager.py
ApiConfigManager._compile_path_pattern
def _compile_path_pattern(pattern): r"""Generates a compiled regex pattern for a path pattern. e.g. '/MyApi/v1/notes/{id}' returns re.compile(r'/MyApi/v1/notes/(?P<id>[^/?#\[\]{}]*)') Args: pattern: A string, the parameterized path pattern to be checked. Returns: A compiled regex object to match this path 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 + '/?$')
python
def _compile_path_pattern(pattern): r"""Generates a compiled regex pattern for a path pattern. e.g. '/MyApi/v1/notes/{id}' returns re.compile(r'/MyApi/v1/notes/(?P<id>[^/?#\[\]{}]*)') Args: pattern: A string, the parameterized path pattern to be checked. Returns: A compiled regex object to match this path 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 + '/?$')
[ "def", "_compile_path_pattern", "(", "pattern", ")", ":", "def", "replace_variable", "(", "match", ")", ":", "\"\"\"Replaces a {variable} with a regex to match it by name.\n\n Changes the string corresponding to the variable name to the base32\n representation of the string, prepended by an underscore. This is\n necessary because we can have message variable names in URL patterns\n (e.g. via {x.y}) but the character '.' can't be in a regex group name.\n\n Args:\n match: A regex match object, the matching regex group as sent by\n re.sub().\n\n Returns:\n A string regex to match the variable by name, if the full pattern was\n matched.\n \"\"\"", "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. e.g. '/MyApi/v1/notes/{id}' returns re.compile(r'/MyApi/v1/notes/(?P<id>[^/?#\[\]{}]*)') Args: pattern: A string, the parameterized path pattern to be checked. Returns: A compiled regex object to match this path pattern.
[ "r", "Generates", "a", "compiled", "regex", "pattern", "for", "a", "path", "pattern", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L267-L304
train
cloudendpoints/endpoints-python
endpoints/api_config_manager.py
ApiConfigManager._save_rest_method
def _save_rest_method(self, method_name, api_name, version, method): """Store Rest api methods in a list for lookup at call time. The list is self._rest_methods, a list of tuples: [(<compiled_path>, <path_pattern>, <method_dict>), ...] where: <compiled_path> is a compiled regex to match against the incoming URL <path_pattern> is a string representing the original path pattern, checked on insertion to prevent duplicates. -and- <method_dict> is a dict of httpMethod => (method_name, method) This structure is a bit complex, it supports use in two contexts: Creation time: - SaveRestMethod is called repeatedly, each method will have a path, which we want to be compiled for fast lookup at call time - We want to prevent duplicate incoming path patterns, so store the un-compiled path, not counting on a compiled regex being a stable comparison as it is not documented as being stable for this use. - Need to store the method that will be mapped at calltime. - Different methods may have the same path but different http method. Call time: - Quickly scan through the list attempting .match(path) on each compiled regex to find the path that matches. - When a path is matched, look up the API method from the request and get the method name and method config for the matching API method and method name. Args: method_name: A string containing the name of the API method. api_name: A string containing the name of the API. version: A string containing the version of the API. method: A dict containing the method descriptor (as in the api config file). """ 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)}))
python
def _save_rest_method(self, method_name, api_name, version, method): """Store Rest api methods in a list for lookup at call time. The list is self._rest_methods, a list of tuples: [(<compiled_path>, <path_pattern>, <method_dict>), ...] where: <compiled_path> is a compiled regex to match against the incoming URL <path_pattern> is a string representing the original path pattern, checked on insertion to prevent duplicates. -and- <method_dict> is a dict of httpMethod => (method_name, method) This structure is a bit complex, it supports use in two contexts: Creation time: - SaveRestMethod is called repeatedly, each method will have a path, which we want to be compiled for fast lookup at call time - We want to prevent duplicate incoming path patterns, so store the un-compiled path, not counting on a compiled regex being a stable comparison as it is not documented as being stable for this use. - Need to store the method that will be mapped at calltime. - Different methods may have the same path but different http method. Call time: - Quickly scan through the list attempting .match(path) on each compiled regex to find the path that matches. - When a path is matched, look up the API method from the request and get the method name and method config for the matching API method and method name. Args: method_name: A string containing the name of the API method. api_name: A string containing the name of the API. version: A string containing the version of the API. method: A dict containing the method descriptor (as in the api config file). """ 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)}))
[ "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. The list is self._rest_methods, a list of tuples: [(<compiled_path>, <path_pattern>, <method_dict>), ...] where: <compiled_path> is a compiled regex to match against the incoming URL <path_pattern> is a string representing the original path pattern, checked on insertion to prevent duplicates. -and- <method_dict> is a dict of httpMethod => (method_name, method) This structure is a bit complex, it supports use in two contexts: Creation time: - SaveRestMethod is called repeatedly, each method will have a path, which we want to be compiled for fast lookup at call time - We want to prevent duplicate incoming path patterns, so store the un-compiled path, not counting on a compiled regex being a stable comparison as it is not documented as being stable for this use. - Need to store the method that will be mapped at calltime. - Different methods may have the same path but different http method. Call time: - Quickly scan through the list attempting .match(path) on each compiled regex to find the path that matches. - When a path is matched, look up the API method from the request and get the method name and method config for the matching API method and method name. Args: method_name: A string containing the name of the API method. api_name: A string containing the name of the API. version: A string containing the version of the API. method: A dict containing the method descriptor (as in the api config file).
[ "Store", "Rest", "api", "methods", "in", "a", "list", "for", "lookup", "at", "call", "time", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L306-L350
train
cloudendpoints/endpoints-python
endpoints/apiserving.py
api_server
def api_server(api_services, **kwargs): """Create an api_server. The primary function of this method is to set up the WSGIApplication instance for the service handlers described by the services passed in. Additionally, it registers each API in ApiConfigRegistry for later use in the BackendService.getApiConfigs() (API config enumeration service). It also configures service control. Args: api_services: List of protorpc.remote.Service classes implementing the API or a list of _ApiDecorator instances that decorate the service classes for an API. **kwargs: Passed through to protorpc.wsgi.service.service_handlers except: protocols - ProtoRPC protocols are not supported, and are disallowed. Returns: A new WSGIApplication that serves the API backend and config registry. Raises: TypeError: if protocols are configured (this feature is not supported). """ # 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)
python
def api_server(api_services, **kwargs): """Create an api_server. The primary function of this method is to set up the WSGIApplication instance for the service handlers described by the services passed in. Additionally, it registers each API in ApiConfigRegistry for later use in the BackendService.getApiConfigs() (API config enumeration service). It also configures service control. Args: api_services: List of protorpc.remote.Service classes implementing the API or a list of _ApiDecorator instances that decorate the service classes for an API. **kwargs: Passed through to protorpc.wsgi.service.service_handlers except: protocols - ProtoRPC protocols are not supported, and are disallowed. Returns: A new WSGIApplication that serves the API backend and config registry. Raises: TypeError: if protocols are configured (this feature is not supported). """ # 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)
[ "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. The primary function of this method is to set up the WSGIApplication instance for the service handlers described by the services passed in. Additionally, it registers each API in ApiConfigRegistry for later use in the BackendService.getApiConfigs() (API config enumeration service). It also configures service control. Args: api_services: List of protorpc.remote.Service classes implementing the API or a list of _ApiDecorator instances that decorate the service classes for an API. **kwargs: Passed through to protorpc.wsgi.service.service_handlers except: protocols - ProtoRPC protocols are not supported, and are disallowed. Returns: A new WSGIApplication that serves the API backend and config registry. Raises: TypeError: if protocols are configured (this feature is not supported).
[ "Create", "an", "api_server", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/apiserving.py#L541-L606
train
cloudendpoints/endpoints-python
endpoints/apiserving.py
ApiConfigRegistry.register_backend
def register_backend(self, config_contents): """Register a single API and its config contents. Args: config_contents: Dict containing API configuration. """ if config_contents is None: return self.__register_class(config_contents) self.__api_configs.append(config_contents) self.__register_methods(config_contents)
python
def register_backend(self, config_contents): """Register a single API and its config contents. Args: config_contents: Dict containing API configuration. """ if config_contents is None: return self.__register_class(config_contents) self.__api_configs.append(config_contents) self.__register_methods(config_contents)
[ "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. Args: config_contents: Dict containing API configuration.
[ "Register", "a", "single", "API", "and", "its", "config", "contents", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/apiserving.py#L197-L207
train
cloudendpoints/endpoints-python
endpoints/apiserving.py
ApiConfigRegistry.__register_class
def __register_class(self, parsed_config): """Register the class implementing this config, so we only add it once. Args: parsed_config: The JSON object with the API configuration being added. Raises: ApiConfigurationError: If the class has already been registered. """ 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)
python
def __register_class(self, parsed_config): """Register the class implementing this config, so we only add it once. Args: parsed_config: The JSON object with the API configuration being added. Raises: ApiConfigurationError: If the class has already been registered. """ 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)
[ "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. Args: parsed_config: The JSON object with the API configuration being added. Raises: ApiConfigurationError: If the class has already been registered.
[ "Register", "the", "class", "implementing", "this", "config", "so", "we", "only", "add", "it", "once", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/apiserving.py#L209-L234
train
cloudendpoints/endpoints-python
endpoints/apiserving.py
ApiConfigRegistry.__register_methods
def __register_methods(self, parsed_config): """Register all methods from the given api config file. Methods are stored in a map from method_name to rosyMethod, the name of the ProtoRPC method to be called on the backend. If no rosyMethod was specified the value will be None. Args: parsed_config: The JSON object with the API configuration being added. """ methods = parsed_config.get('methods') if not methods: return for method_name, method in methods.iteritems(): self.__api_methods[method_name] = method.get('rosyMethod')
python
def __register_methods(self, parsed_config): """Register all methods from the given api config file. Methods are stored in a map from method_name to rosyMethod, the name of the ProtoRPC method to be called on the backend. If no rosyMethod was specified the value will be None. Args: parsed_config: The JSON object with the API configuration being added. """ methods = parsed_config.get('methods') if not methods: return for method_name, method in methods.iteritems(): self.__api_methods[method_name] = method.get('rosyMethod')
[ "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. Methods are stored in a map from method_name to rosyMethod, the name of the ProtoRPC method to be called on the backend. If no rosyMethod was specified the value will be None. Args: parsed_config: The JSON object with the API configuration being added.
[ "Register", "all", "methods", "from", "the", "given", "api", "config", "file", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/apiserving.py#L236-L251
train
cloudendpoints/endpoints-python
endpoints/apiserving.py
_ApiServer.__register_services
def __register_services(api_name_version_map, api_config_registry): """Register & return a list of each URL and class that handles that URL. This finds every service class in api_name_version_map, registers it with the given ApiConfigRegistry, builds the URL for that class, and adds the URL and its factory to a list that's returned. Args: api_name_version_map: A mapping from (api name, api version) to a list of service factories, as returned by __create_name_version_map. api_config_registry: The ApiConfigRegistry where service classes will be registered. Returns: A list of (URL, service_factory) for each service class in api_name_version_map. Raises: ApiConfigurationError: If a Service class appears more than once in api_name_version_map. This could happen if one class is used to implement multiple APIs. """ 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
python
def __register_services(api_name_version_map, api_config_registry): """Register & return a list of each URL and class that handles that URL. This finds every service class in api_name_version_map, registers it with the given ApiConfigRegistry, builds the URL for that class, and adds the URL and its factory to a list that's returned. Args: api_name_version_map: A mapping from (api name, api version) to a list of service factories, as returned by __create_name_version_map. api_config_registry: The ApiConfigRegistry where service classes will be registered. Returns: A list of (URL, service_factory) for each service class in api_name_version_map. Raises: ApiConfigurationError: If a Service class appears more than once in api_name_version_map. This could happen if one class is used to implement multiple APIs. """ 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
[ "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. This finds every service class in api_name_version_map, registers it with the given ApiConfigRegistry, builds the URL for that class, and adds the URL and its factory to a list that's returned. Args: api_name_version_map: A mapping from (api name, api version) to a list of service factories, as returned by __create_name_version_map. api_config_registry: The ApiConfigRegistry where service classes will be registered. Returns: A list of (URL, service_factory) for each service class in api_name_version_map. Raises: ApiConfigurationError: If a Service class appears more than once in api_name_version_map. This could happen if one class is used to implement multiple APIs.
[ "Register", "&", "return", "a", "list", "of", "each", "URL", "and", "class", "that", "handles", "that", "URL", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/apiserving.py#L392-L432
train
cloudendpoints/endpoints-python
endpoints/apiserving.py
_ApiServer.__is_json_error
def __is_json_error(self, status, headers): """Determine if response is an error. Args: status: HTTP status code. headers: Dictionary of (lowercase) header name to value. Returns: True if the response was an error, else False. """ 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)
python
def __is_json_error(self, status, headers): """Determine if response is an error. Args: status: HTTP status code. headers: Dictionary of (lowercase) header name to value. Returns: True if the response was an error, else False. """ 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)
[ "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. Args: status: HTTP status code. headers: Dictionary of (lowercase) header name to value. Returns: True if the response was an error, else False.
[ "Determine", "if", "response", "is", "an", "error", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/apiserving.py#L434-L447
train
cloudendpoints/endpoints-python
endpoints/apiserving.py
_ApiServer.__write_error
def __write_error(self, status_code, error_message=None): """Return the HTTP status line and body for a given error code and message. Args: status_code: HTTP status code to be returned. error_message: Error message to be returned. Returns: Tuple (http_status, body): http_status: HTTP status line, e.g. 200 OK. body: Body of the HTTP request. """ 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)
python
def __write_error(self, status_code, error_message=None): """Return the HTTP status line and body for a given error code and message. Args: status_code: HTTP status code to be returned. error_message: Error message to be returned. Returns: Tuple (http_status, body): http_status: HTTP status line, e.g. 200 OK. body: Body of the HTTP request. """ 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)
[ "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. Args: status_code: HTTP status code to be returned. error_message: Error message to be returned. Returns: Tuple (http_status, body): http_status: HTTP status line, e.g. 200 OK. body: Body of the HTTP request.
[ "Return", "the", "HTTP", "status", "line", "and", "body", "for", "a", "given", "error", "code", "and", "message", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/apiserving.py#L449-L467
train
cloudendpoints/endpoints-python
endpoints/apiserving.py
_ApiServer.protorpc_to_endpoints_error
def protorpc_to_endpoints_error(self, status, body): """Convert a ProtoRPC error to the format expected by Google Endpoints. If the body does not contain an ProtoRPC message in state APPLICATION_ERROR the status and body will be returned unchanged. Args: status: HTTP status of the response from the backend body: JSON-encoded error in format expected by Endpoints frontend. Returns: Tuple of (http 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
python
def protorpc_to_endpoints_error(self, status, body): """Convert a ProtoRPC error to the format expected by Google Endpoints. If the body does not contain an ProtoRPC message in state APPLICATION_ERROR the status and body will be returned unchanged. Args: status: HTTP status of the response from the backend body: JSON-encoded error in format expected by Endpoints frontend. Returns: Tuple of (http 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
[ "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. If the body does not contain an ProtoRPC message in state APPLICATION_ERROR the status and body will be returned unchanged. Args: status: HTTP status of the response from the backend body: JSON-encoded error in format expected by Endpoints frontend. Returns: Tuple of (http status, body)
[ "Convert", "a", "ProtoRPC", "error", "to", "the", "format", "expected", "by", "Google", "Endpoints", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/apiserving.py#L469-L494
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware._add_dispatcher
def _add_dispatcher(self, path_regex, dispatch_function): """Add a request path and dispatch handler. Args: path_regex: A string regex, the path to match against incoming requests. dispatch_function: The function to call for these requests. The function should take (request, start_response) as arguments and return the contents of the response body. """ self._dispatchers.append((re.compile(path_regex), dispatch_function))
python
def _add_dispatcher(self, path_regex, dispatch_function): """Add a request path and dispatch handler. Args: path_regex: A string regex, the path to match against incoming requests. dispatch_function: The function to call for these requests. The function should take (request, start_response) as arguments and return the contents of the response body. """ self._dispatchers.append((re.compile(path_regex), dispatch_function))
[ "def", "_add_dispatcher", "(", "self", ",", "path_regex", ",", "dispatch_function", ")", ":", "self", ".", "_dispatchers", ".", "append", "(", "(", "re", ".", "compile", "(", "path_regex", ")", ",", "dispatch_function", ")", ")" ]
Add a request path and dispatch handler. Args: path_regex: A string regex, the path to match against incoming requests. dispatch_function: The function to call for these requests. The function should take (request, start_response) as arguments and return the contents of the response body.
[ "Add", "a", "request", "path", "and", "dispatch", "handler", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L103-L112
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware.dispatch
def dispatch(self, request, start_response): """Handles dispatch to apiserver handlers. This typically ends up calling start_response and returning the entire body of the response. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: A string, the body of the 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)
python
def dispatch(self, request, start_response): """Handles dispatch to apiserver handlers. This typically ends up calling start_response and returning the entire body of the response. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: A string, the body of the 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)
[ "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. This typically ends up calling start_response and returning the entire body of the response. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: A string, the body of the response.
[ "Handles", "dispatch", "to", "apiserver", "handlers", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L149-L172
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware.dispatch_non_api_requests
def dispatch_non_api_requests(self, request, start_response): """Dispatch this request if this is a request to a reserved URL. If the request matches one of our reserved URLs, this calls start_response and returns the response body. This also handles OPTIONS CORS requests. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: None if the request doesn't match one of the reserved URLs this handles. Otherwise, returns the response body. """ 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
python
def dispatch_non_api_requests(self, request, start_response): """Dispatch this request if this is a request to a reserved URL. If the request matches one of our reserved URLs, this calls start_response and returns the response body. This also handles OPTIONS CORS requests. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: None if the request doesn't match one of the reserved URLs this handles. Otherwise, returns the response body. """ 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
[ "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. If the request matches one of our reserved URLs, this calls start_response and returns the response body. This also handles OPTIONS CORS requests. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: None if the request doesn't match one of the reserved URLs this handles. Otherwise, returns the response body.
[ "Dispatch", "this", "request", "if", "this", "is", "a", "request", "to", "a", "reserved", "URL", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L174-L200
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware.verify_response
def verify_response(response, status_code, content_type=None): """Verifies that a response has the expected status and content type. Args: response: The ResponseTuple to be checked. status_code: An int, the HTTP status code to be compared with response status. content_type: A string with the acceptable Content-Type header value. None allows any content type. Returns: True if both status_code and content_type match, else False. """ 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
python
def verify_response(response, status_code, content_type=None): """Verifies that a response has the expected status and content type. Args: response: The ResponseTuple to be checked. status_code: An int, the HTTP status code to be compared with response status. content_type: A string with the acceptable Content-Type header value. None allows any content type. Returns: True if both status_code and content_type match, else False. """ 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
[ "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. Args: response: The ResponseTuple to be checked. status_code: An int, the HTTP status code to be compared with response status. content_type: A string with the acceptable Content-Type header value. None allows any content type. Returns: True if both status_code and content_type match, else False.
[ "Verifies", "that", "a", "response", "has", "the", "expected", "status", "and", "content", "type", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L246-L271
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware.prepare_backend_environ
def prepare_backend_environ(self, host, method, relative_url, headers, body, source_ip, port): """Build an environ object for the backend to consume. Args: host: A string containing the host serving the request. method: A string containing the HTTP method of the request. relative_url: A string containing path and query string of the request. headers: A list of (key, value) tuples where key and value are both strings. body: A string containing the request body. source_ip: The source IP address for the request. port: The port to which to direct the request. Returns: An environ object with all the information necessary for the backend to process the request. """ 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
python
def prepare_backend_environ(self, host, method, relative_url, headers, body, source_ip, port): """Build an environ object for the backend to consume. Args: host: A string containing the host serving the request. method: A string containing the HTTP method of the request. relative_url: A string containing path and query string of the request. headers: A list of (key, value) tuples where key and value are both strings. body: A string containing the request body. source_ip: The source IP address for the request. port: The port to which to direct the request. Returns: An environ object with all the information necessary for the backend to process the request. """ 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
[ "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. Args: host: A string containing the host serving the request. method: A string containing the HTTP method of the request. relative_url: A string containing path and query string of the request. headers: A list of (key, value) tuples where key and value are both strings. body: A string containing the request body. source_ip: The source IP address for the request. port: The port to which to direct the request. Returns: An environ object with all the information necessary for the backend to process the request.
[ "Build", "an", "environ", "object", "for", "the", "backend", "to", "consume", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L273-L315
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware.handle_backend_response
def handle_backend_response(self, orig_request, backend_request, response_status, response_headers, response_body, method_config, start_response): """Handle backend response, transforming output as needed. This calls start_response and returns the response body. Args: orig_request: An ApiRequest, the original request from the user. backend_request: An ApiRequest, the transformed request that was sent to the backend handler. response_status: A string, the status from the response. response_headers: A dict, the headers from the response. response_body: A string, the body of the response. method_config: A dict, the API config of the method to be called. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body. """ # 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)
python
def handle_backend_response(self, orig_request, backend_request, response_status, response_headers, response_body, method_config, start_response): """Handle backend response, transforming output as needed. This calls start_response and returns the response body. Args: orig_request: An ApiRequest, the original request from the user. backend_request: An ApiRequest, the transformed request that was sent to the backend handler. response_status: A string, the status from the response. response_headers: A dict, the headers from the response. response_body: A string, the body of the response. method_config: A dict, the API config of the method to be called. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body. """ # 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)
[ "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. This calls start_response and returns the response body. Args: orig_request: An ApiRequest, the original request from the user. backend_request: An ApiRequest, the transformed request that was sent to the backend handler. response_status: A string, the status from the response. response_headers: A dict, the headers from the response. response_body: A string, the body of the response. method_config: A dict, the API config of the method to be called. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body.
[ "Handle", "backend", "response", "transforming", "output", "as", "needed", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L415-L457
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware.fail_request
def fail_request(self, orig_request, message, start_response): """Write an immediate failure response to outfile, no redirect. This calls start_response and returns the error body. Args: orig_request: An ApiRequest, the original request from the user. message: A string containing the error message to be displayed to user. start_response: A function with semantics defined in PEP-333. Returns: A string containing the body of the error response. """ cors_handler = self._create_cors_handler(orig_request) return util.send_wsgi_error_response( message, start_response, cors_handler=cors_handler)
python
def fail_request(self, orig_request, message, start_response): """Write an immediate failure response to outfile, no redirect. This calls start_response and returns the error body. Args: orig_request: An ApiRequest, the original request from the user. message: A string containing the error message to be displayed to user. start_response: A function with semantics defined in PEP-333. Returns: A string containing the body of the error response. """ cors_handler = self._create_cors_handler(orig_request) return util.send_wsgi_error_response( message, start_response, cors_handler=cors_handler)
[ "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. This calls start_response and returns the error body. Args: orig_request: An ApiRequest, the original request from the user. message: A string containing the error message to be displayed to user. start_response: A function with semantics defined in PEP-333. Returns: A string containing the body of the error response.
[ "Write", "an", "immediate", "failure", "response", "to", "outfile", "no", "redirect", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L459-L474
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware.lookup_rest_method
def lookup_rest_method(self, orig_request): """Looks up and returns rest method for the currently-pending request. Args: orig_request: An ApiRequest, the original request from the user. Returns: A tuple of (method descriptor, parameters), or (None, None) if no method was found for the current 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
python
def lookup_rest_method(self, orig_request): """Looks up and returns rest method for the currently-pending request. Args: orig_request: An ApiRequest, the original request from the user. Returns: A tuple of (method descriptor, parameters), or (None, None) if no method was found for the current 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
[ "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. Args: orig_request: An ApiRequest, the original request from the user. Returns: A tuple of (method descriptor, parameters), or (None, None) if no method was found for the current request.
[ "Looks", "up", "and", "returns", "rest", "method", "for", "the", "currently", "-", "pending", "request", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L476-L489
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware.transform_request
def transform_request(self, orig_request, params, method_config): """Transforms orig_request to apiserving request. This method uses orig_request to determine the currently-pending request and returns a new transformed request ready to send to the backend. This method accepts a rest-style or RPC-style request. Args: orig_request: An ApiRequest, the original request from the user. params: A dictionary containing path parameters for rest requests, or None for an RPC request. method_config: A dict, the API config of the method to be called. Returns: An ApiRequest that's a copy of the current request, modified so it can be sent to the backend. The path is updated and parts of the body or other properties may also be changed. """ 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
python
def transform_request(self, orig_request, params, method_config): """Transforms orig_request to apiserving request. This method uses orig_request to determine the currently-pending request and returns a new transformed request ready to send to the backend. This method accepts a rest-style or RPC-style request. Args: orig_request: An ApiRequest, the original request from the user. params: A dictionary containing path parameters for rest requests, or None for an RPC request. method_config: A dict, the API config of the method to be called. Returns: An ApiRequest that's a copy of the current request, modified so it can be sent to the backend. The path is updated and parts of the body or other properties may also be changed. """ 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
[ "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. This method uses orig_request to determine the currently-pending request and returns a new transformed request ready to send to the backend. This method accepts a rest-style or RPC-style request. Args: orig_request: An ApiRequest, the original request from the user. params: A dictionary containing path parameters for rest requests, or None for an RPC request. method_config: A dict, the API config of the method to be called. Returns: An ApiRequest that's a copy of the current request, modified so it can be sent to the backend. The path is updated and parts of the body or other properties may also be changed.
[ "Transforms", "orig_request", "to", "apiserving", "request", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L491-L512
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware._add_message_field
def _add_message_field(self, field_name, value, params): """Converts a . delimitied field name to a message field in parameters. This adds the field to the params dict, broken out so that message parameters appear as sub-dicts within the outer param. For example: {'a.b.c': ['foo']} becomes: {'a': {'b': {'c': ['foo']}}} Args: field_name: A string containing the '.' delimitied name to be converted into a dictionary. value: The value to be set. params: The dictionary holding all the parameters, where the value is eventually set. """ 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)
python
def _add_message_field(self, field_name, value, params): """Converts a . delimitied field name to a message field in parameters. This adds the field to the params dict, broken out so that message parameters appear as sub-dicts within the outer param. For example: {'a.b.c': ['foo']} becomes: {'a': {'b': {'c': ['foo']}}} Args: field_name: A string containing the '.' delimitied name to be converted into a dictionary. value: The value to be set. params: The dictionary holding all the parameters, where the value is eventually set. """ 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)
[ "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. This adds the field to the params dict, broken out so that message parameters appear as sub-dicts within the outer param. For example: {'a.b.c': ['foo']} becomes: {'a': {'b': {'c': ['foo']}}} Args: field_name: A string containing the '.' delimitied name to be converted into a dictionary. value: The value to be set. params: The dictionary holding all the parameters, where the value is eventually set.
[ "Converts", "a", ".", "delimitied", "field", "name", "to", "a", "message", "field", "in", "parameters", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L514-L538
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware._update_from_body
def _update_from_body(self, destination, source): """Updates the dictionary for an API payload with the request body. The values from the body should override those already in the payload, but for nested fields (message objects) the values can be combined recursively. Args: destination: A dictionary containing an API payload parsed from the path and query parameters in a request. source: A dictionary parsed from the body of the request. """ 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
python
def _update_from_body(self, destination, source): """Updates the dictionary for an API payload with the request body. The values from the body should override those already in the payload, but for nested fields (message objects) the values can be combined recursively. Args: destination: A dictionary containing an API payload parsed from the path and query parameters in a request. source: A dictionary parsed from the body of the request. """ 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
[ "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. The values from the body should override those already in the payload, but for nested fields (message objects) the values can be combined recursively. Args: destination: A dictionary containing an API payload parsed from the path and query parameters in a request. source: A dictionary parsed from the body of the request.
[ "Updates", "the", "dictionary", "for", "an", "API", "payload", "with", "the", "request", "body", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L540-L557
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware.transform_rest_request
def transform_rest_request(self, orig_request, params, method_parameters): """Translates a Rest request into an apiserving request. This makes a copy of orig_request and transforms it to apiserving format (moving request parameters to the body). The request can receive values from the path, query and body and combine them before sending them along to the backend. In cases of collision, objects from the body take precedence over those from the query, which in turn take precedence over those from the path. In the case that a repeated value occurs in both the query and the path, those values can be combined, but if that value also occurred in the body, it would override any other values. In the case of nested values from message fields, non-colliding values from subfields can be combined. For example, if '?a.c=10' occurs in the query string and "{'a': {'b': 11}}" occurs in the body, then they will be combined as { 'a': { 'b': 11, 'c': 10, } } before being sent to the backend. Args: orig_request: An ApiRequest, the original request from the user. params: A dict with URL path parameters extracted by the config_manager lookup. method_parameters: A dictionary containing the API configuration for the parameters for the request. Returns: A copy of the current request that's been modified so it can be sent to the backend. The body is updated to include parameters from the URL. """ 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
python
def transform_rest_request(self, orig_request, params, method_parameters): """Translates a Rest request into an apiserving request. This makes a copy of orig_request and transforms it to apiserving format (moving request parameters to the body). The request can receive values from the path, query and body and combine them before sending them along to the backend. In cases of collision, objects from the body take precedence over those from the query, which in turn take precedence over those from the path. In the case that a repeated value occurs in both the query and the path, those values can be combined, but if that value also occurred in the body, it would override any other values. In the case of nested values from message fields, non-colliding values from subfields can be combined. For example, if '?a.c=10' occurs in the query string and "{'a': {'b': 11}}" occurs in the body, then they will be combined as { 'a': { 'b': 11, 'c': 10, } } before being sent to the backend. Args: orig_request: An ApiRequest, the original request from the user. params: A dict with URL path parameters extracted by the config_manager lookup. method_parameters: A dictionary containing the API configuration for the parameters for the request. Returns: A copy of the current request that's been modified so it can be sent to the backend. The body is updated to include parameters from the URL. """ 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
[ "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. This makes a copy of orig_request and transforms it to apiserving format (moving request parameters to the body). The request can receive values from the path, query and body and combine them before sending them along to the backend. In cases of collision, objects from the body take precedence over those from the query, which in turn take precedence over those from the path. In the case that a repeated value occurs in both the query and the path, those values can be combined, but if that value also occurred in the body, it would override any other values. In the case of nested values from message fields, non-colliding values from subfields can be combined. For example, if '?a.c=10' occurs in the query string and "{'a': {'b': 11}}" occurs in the body, then they will be combined as { 'a': { 'b': 11, 'c': 10, } } before being sent to the backend. Args: orig_request: An ApiRequest, the original request from the user. params: A dict with URL path parameters extracted by the config_manager lookup. method_parameters: A dictionary containing the API configuration for the parameters for the request. Returns: A copy of the current request that's been modified so it can be sent to the backend. The body is updated to include parameters from the URL.
[ "Translates", "a", "Rest", "request", "into", "an", "apiserving", "request", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L559-L645
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware.check_error_response
def check_error_response(self, body, status): """Raise an exception if the response from the backend was an error. Args: body: A string containing the backend response body. status: A string containing the backend response status. Raises: BackendError if the response is an error. """ status_code = int(status.split(' ', 1)[0]) if status_code >= 300: raise errors.BackendError(body, status)
python
def check_error_response(self, body, status): """Raise an exception if the response from the backend was an error. Args: body: A string containing the backend response body. status: A string containing the backend response status. Raises: BackendError if the response is an error. """ status_code = int(status.split(' ', 1)[0]) if status_code >= 300: raise errors.BackendError(body, status)
[ "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. Args: body: A string containing the backend response body. status: A string containing the backend response status. Raises: BackendError if the response is an error.
[ "Raise", "an", "exception", "if", "the", "response", "from", "the", "backend", "was", "an", "error", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L647-L659
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware.check_empty_response
def check_empty_response(self, orig_request, method_config, start_response): """If the response from the backend is empty, return a HTTP 204 No Content. Args: orig_request: An ApiRequest, the original request from the user. method_config: A dict, the API config of the method to be called. start_response: A function with semantics defined in PEP-333. Returns: If the backend response was empty, this returns a string containing the response body that should be returned to the user. If the backend response wasn't empty, this returns None, indicating that we should not exit early with a 204. """ 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)
python
def check_empty_response(self, orig_request, method_config, start_response): """If the response from the backend is empty, return a HTTP 204 No Content. Args: orig_request: An ApiRequest, the original request from the user. method_config: A dict, the API config of the method to be called. start_response: A function with semantics defined in PEP-333. Returns: If the backend response was empty, this returns a string containing the response body that should be returned to the user. If the backend response wasn't empty, this returns None, indicating that we should not exit early with a 204. """ 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)
[ "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. Args: orig_request: An ApiRequest, the original request from the user. method_config: A dict, the API config of the method to be called. start_response: A function with semantics defined in PEP-333. Returns: If the backend response was empty, this returns a string containing the response body that should be returned to the user. If the backend response wasn't empty, this returns None, indicating that we should not exit early with a 204.
[ "If", "the", "response", "from", "the", "backend", "is", "empty", "return", "a", "HTTP", "204", "No", "Content", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L661-L681
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware.transform_rest_response
def transform_rest_response(self, response_body): """Translates an apiserving REST response so it's ready to return. Currently, the only thing that needs to be fixed here is indentation, so it's consistent with what the live app will return. Args: response_body: A string containing the backend response. Returns: A reformatted version of the response JSON. """ body_json = json.loads(response_body) return json.dumps(body_json, indent=1, sort_keys=True)
python
def transform_rest_response(self, response_body): """Translates an apiserving REST response so it's ready to return. Currently, the only thing that needs to be fixed here is indentation, so it's consistent with what the live app will return. Args: response_body: A string containing the backend response. Returns: A reformatted version of the response JSON. """ body_json = json.loads(response_body) return json.dumps(body_json, indent=1, sort_keys=True)
[ "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. Currently, the only thing that needs to be fixed here is indentation, so it's consistent with what the live app will return. Args: response_body: A string containing the backend response. Returns: A reformatted version of the response JSON.
[ "Translates", "an", "apiserving", "REST", "response", "so", "it", "s", "ready", "to", "return", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L683-L696
train
cloudendpoints/endpoints-python
endpoints/endpoints_dispatcher.py
EndpointsDispatcherMiddleware._handle_request_error
def _handle_request_error(self, orig_request, error, start_response): """Handle a request error, converting it to a WSGI response. Args: orig_request: An ApiRequest, the original request from the user. error: A RequestError containing information about the error. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body. """ 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)
python
def _handle_request_error(self, orig_request, error, start_response): """Handle a request error, converting it to a WSGI response. Args: orig_request: An ApiRequest, the original request from the user. error: A RequestError containing information about the error. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body. """ 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)
[ "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. Args: orig_request: An ApiRequest, the original request from the user. error: A RequestError containing information about the error. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body.
[ "Handle", "a", "request", "error", "converting", "it", "to", "a", "WSGI", "response", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L698-L718
train
cloudendpoints/endpoints-python
endpoints/_endpointscfg_impl.py
_WriteFile
def _WriteFile(output_path, name, content): """Write given content to a file in a given directory. Args: output_path: The directory to store the file in. name: The name of the file to store the content in. content: The content to write to the file.close Returns: The full path to the written file. """ path = os.path.join(output_path, name) with open(path, 'wb') as f: f.write(content) return path
python
def _WriteFile(output_path, name, content): """Write given content to a file in a given directory. Args: output_path: The directory to store the file in. name: The name of the file to store the content in. content: The content to write to the file.close Returns: The full path to the written file. """ path = os.path.join(output_path, name) with open(path, 'wb') as f: f.write(content) return path
[ "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. Args: output_path: The directory to store the file in. name: The name of the file to store the content in. content: The content to write to the file.close Returns: The full path to the written file.
[ "Write", "given", "content", "to", "a", "file", "in", "a", "given", "directory", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L138-L152
train
cloudendpoints/endpoints-python
endpoints/_endpointscfg_impl.py
GenApiConfig
def GenApiConfig(service_class_names, config_string_generator=None, hostname=None, application_path=None, **additional_kwargs): """Write an API configuration for endpoints annotated ProtoRPC services. Args: service_class_names: A list of fully qualified ProtoRPC service classes. config_string_generator: A generator object that produces API config strings using its pretty_print_config_to_json method. hostname: A string hostname which will be used as the default version hostname. If no hostname is specificied in the @endpoints.api decorator, this value is the fallback. application_path: A string with the path to the AppEngine application. Raises: TypeError: If any service classes don't inherit from remote.Service. messages.DefinitionNotFoundError: If a service can't be found. Returns: A map from service names to a string containing the API configuration of the service in JSON format. """ # 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
python
def GenApiConfig(service_class_names, config_string_generator=None, hostname=None, application_path=None, **additional_kwargs): """Write an API configuration for endpoints annotated ProtoRPC services. Args: service_class_names: A list of fully qualified ProtoRPC service classes. config_string_generator: A generator object that produces API config strings using its pretty_print_config_to_json method. hostname: A string hostname which will be used as the default version hostname. If no hostname is specificied in the @endpoints.api decorator, this value is the fallback. application_path: A string with the path to the AppEngine application. Raises: TypeError: If any service classes don't inherit from remote.Service. messages.DefinitionNotFoundError: If a service can't be found. Returns: A map from service names to a string containing the API configuration of the service in JSON format. """ # 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
[ "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. Args: service_class_names: A list of fully qualified ProtoRPC service classes. config_string_generator: A generator object that produces API config strings using its pretty_print_config_to_json method. hostname: A string hostname which will be used as the default version hostname. If no hostname is specificied in the @endpoints.api decorator, this value is the fallback. application_path: A string with the path to the AppEngine application. Raises: TypeError: If any service classes don't inherit from remote.Service. messages.DefinitionNotFoundError: If a service can't be found. Returns: A map from service names to a string containing the API configuration of the service in JSON format.
[ "Write", "an", "API", "configuration", "for", "endpoints", "annotated", "ProtoRPC", "services", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L155-L218
train
cloudendpoints/endpoints-python
endpoints/_endpointscfg_impl.py
_GetAppYamlHostname
def _GetAppYamlHostname(application_path, open_func=open): """Build the hostname for this app based on the name in app.yaml. Args: application_path: A string with the path to the AppEngine application. This should be the directory containing the app.yaml file. open_func: Function to call to open a file. Used to override the default open function in unit tests. Returns: A hostname, usually in the form of "myapp.appspot.com", based on the application name in the app.yaml file. If the file can't be found or there's a problem building the name, this will return None. """ 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
python
def _GetAppYamlHostname(application_path, open_func=open): """Build the hostname for this app based on the name in app.yaml. Args: application_path: A string with the path to the AppEngine application. This should be the directory containing the app.yaml file. open_func: Function to call to open a file. Used to override the default open function in unit tests. Returns: A hostname, usually in the form of "myapp.appspot.com", based on the application name in the app.yaml file. If the file can't be found or there's a problem building the name, this will return None. """ 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
[ "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. Args: application_path: A string with the path to the AppEngine application. This should be the directory containing the app.yaml file. open_func: Function to call to open a file. Used to override the default open function in unit tests. Returns: A hostname, usually in the form of "myapp.appspot.com", based on the application name in the app.yaml file. If the file can't be found or there's a problem building the name, this will return None.
[ "Build", "the", "hostname", "for", "this", "app", "based", "on", "the", "name", "in", "app", ".", "yaml", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L221-L257
train
cloudendpoints/endpoints-python
endpoints/_endpointscfg_impl.py
_GenDiscoveryDoc
def _GenDiscoveryDoc(service_class_names, output_path, hostname=None, application_path=None): """Write discovery documents generated from the service classes to file. Args: service_class_names: A list of fully qualified ProtoRPC service names. output_path: The directory to output the discovery docs to. hostname: A string hostname which will be used as the default version hostname. If no hostname is specificied in the @endpoints.api decorator, this value is the fallback. Defaults to None. application_path: A string containing the path to the AppEngine app. Returns: A list of discovery doc filenames. """ 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
python
def _GenDiscoveryDoc(service_class_names, output_path, hostname=None, application_path=None): """Write discovery documents generated from the service classes to file. Args: service_class_names: A list of fully qualified ProtoRPC service names. output_path: The directory to output the discovery docs to. hostname: A string hostname which will be used as the default version hostname. If no hostname is specificied in the @endpoints.api decorator, this value is the fallback. Defaults to None. application_path: A string containing the path to the AppEngine app. Returns: A list of discovery doc filenames. """ 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
[ "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. Args: service_class_names: A list of fully qualified ProtoRPC service names. output_path: The directory to output the discovery docs to. hostname: A string hostname which will be used as the default version hostname. If no hostname is specificied in the @endpoints.api decorator, this value is the fallback. Defaults to None. application_path: A string containing the path to the AppEngine app. Returns: A list of discovery doc filenames.
[ "Write", "discovery", "documents", "generated", "from", "the", "service", "classes", "to", "file", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L260-L285
train
cloudendpoints/endpoints-python
endpoints/_endpointscfg_impl.py
_GenOpenApiSpec
def _GenOpenApiSpec(service_class_names, output_path, hostname=None, application_path=None, x_google_api_name=False): """Write openapi documents generated from the service classes to file. Args: service_class_names: A list of fully qualified ProtoRPC service names. output_path: The directory to which to output the OpenAPI specs. hostname: A string hostname which will be used as the default version hostname. If no hostname is specified in the @endpoints.api decorator, this value is the fallback. Defaults to None. application_path: A string containing the path to the AppEngine app. Returns: A list of OpenAPI spec filenames. """ 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
python
def _GenOpenApiSpec(service_class_names, output_path, hostname=None, application_path=None, x_google_api_name=False): """Write openapi documents generated from the service classes to file. Args: service_class_names: A list of fully qualified ProtoRPC service names. output_path: The directory to which to output the OpenAPI specs. hostname: A string hostname which will be used as the default version hostname. If no hostname is specified in the @endpoints.api decorator, this value is the fallback. Defaults to None. application_path: A string containing the path to the AppEngine app. Returns: A list of OpenAPI spec filenames. """ 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
[ "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. Args: service_class_names: A list of fully qualified ProtoRPC service names. output_path: The directory to which to output the OpenAPI specs. hostname: A string hostname which will be used as the default version hostname. If no hostname is specified in the @endpoints.api decorator, this value is the fallback. Defaults to None. application_path: A string containing the path to the AppEngine app. Returns: A list of OpenAPI spec filenames.
[ "Write", "openapi", "documents", "generated", "from", "the", "service", "classes", "to", "file", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L288-L313
train
cloudendpoints/endpoints-python
endpoints/_endpointscfg_impl.py
_GetClientLib
def _GetClientLib(service_class_names, language, output_path, build_system, hostname=None, application_path=None): """Fetch client libraries from a cloud service. Args: service_class_names: A list of fully qualified ProtoRPC service names. language: The client library language to generate. (java) output_path: The directory to output the discovery docs to. build_system: The target build system for the client library language. hostname: A string hostname which will be used as the default version hostname. If no hostname is specificied in the @endpoints.api decorator, this value is the fallback. Defaults to None. application_path: A string containing the path to the AppEngine app. Returns: A list of paths to client libraries. """ 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
python
def _GetClientLib(service_class_names, language, output_path, build_system, hostname=None, application_path=None): """Fetch client libraries from a cloud service. Args: service_class_names: A list of fully qualified ProtoRPC service names. language: The client library language to generate. (java) output_path: The directory to output the discovery docs to. build_system: The target build system for the client library language. hostname: A string hostname which will be used as the default version hostname. If no hostname is specificied in the @endpoints.api decorator, this value is the fallback. Defaults to None. application_path: A string containing the path to the AppEngine app. Returns: A list of paths to client libraries. """ 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
[ "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. Args: service_class_names: A list of fully qualified ProtoRPC service names. language: The client library language to generate. (java) output_path: The directory to output the discovery docs to. build_system: The target build system for the client library language. hostname: A string hostname which will be used as the default version hostname. If no hostname is specificied in the @endpoints.api decorator, this value is the fallback. Defaults to None. application_path: A string containing the path to the AppEngine app. Returns: A list of paths to client libraries.
[ "Fetch", "client", "libraries", "from", "a", "cloud", "service", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L374-L401
train
cloudendpoints/endpoints-python
endpoints/_endpointscfg_impl.py
_GenApiConfigCallback
def _GenApiConfigCallback(args, api_func=GenApiConfig): """Generate an api file. Args: args: An argparse.Namespace object to extract parameters from. api_func: A function that generates and returns an API configuration for a list of services. """ 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)
python
def _GenApiConfigCallback(args, api_func=GenApiConfig): """Generate an api file. Args: args: An argparse.Namespace object to extract parameters from. api_func: A function that generates and returns an API configuration for a list of services. """ 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)
[ "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. Args: args: An argparse.Namespace object to extract parameters from. api_func: A function that generates and returns an API configuration for a list of services.
[ "Generate", "an", "api", "file", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L404-L417
train
cloudendpoints/endpoints-python
endpoints/_endpointscfg_impl.py
_GetClientLibCallback
def _GetClientLibCallback(args, client_func=_GetClientLib): """Generate discovery docs and client libraries to files. Args: args: An argparse.Namespace object to extract parameters from. client_func: A function that generates client libraries and stores them to files, accepting a list of service names, a client library language, an output directory, a build system for the client library language, and a hostname. """ 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
python
def _GetClientLibCallback(args, client_func=_GetClientLib): """Generate discovery docs and client libraries to files. Args: args: An argparse.Namespace object to extract parameters from. client_func: A function that generates client libraries and stores them to files, accepting a list of service names, a client library language, an output directory, a build system for the client library language, and a hostname. """ 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
[ "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. Args: args: An argparse.Namespace object to extract parameters from. client_func: A function that generates client libraries and stores them to files, accepting a list of service names, a client library language, an output directory, a build system for the client library language, and a hostname.
[ "Generate", "discovery", "docs", "and", "client", "libraries", "to", "files", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L420-L435
train
cloudendpoints/endpoints-python
endpoints/_endpointscfg_impl.py
_GenDiscoveryDocCallback
def _GenDiscoveryDocCallback(args, discovery_func=_GenDiscoveryDoc): """Generate discovery docs to files. Args: args: An argparse.Namespace object to extract parameters from discovery_func: A function that generates discovery docs and stores them to files, accepting a list of service names, a discovery doc format, and an output directory. """ 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
python
def _GenDiscoveryDocCallback(args, discovery_func=_GenDiscoveryDoc): """Generate discovery docs to files. Args: args: An argparse.Namespace object to extract parameters from discovery_func: A function that generates discovery docs and stores them to files, accepting a list of service names, a discovery doc format, and an output directory. """ 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
[ "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. Args: args: An argparse.Namespace object to extract parameters from discovery_func: A function that generates discovery docs and stores them to files, accepting a list of service names, a discovery doc format, and an output directory.
[ "Generate", "discovery", "docs", "to", "files", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L438-L451
train
cloudendpoints/endpoints-python
endpoints/_endpointscfg_impl.py
_GenClientLibCallback
def _GenClientLibCallback(args, client_func=_GenClientLib): """Generate a client library to file. Args: args: An argparse.Namespace object to extract parameters from client_func: A function that generates client libraries and stores them to files, accepting a path to a discovery doc, a client library language, an output directory, and a build system for the client library language. """ client_path = client_func(args.discovery_doc[0], args.language, args.output, args.build_system) print 'API client library written to %s' % client_path
python
def _GenClientLibCallback(args, client_func=_GenClientLib): """Generate a client library to file. Args: args: An argparse.Namespace object to extract parameters from client_func: A function that generates client libraries and stores them to files, accepting a path to a discovery doc, a client library language, an output directory, and a build system for the client library language. """ client_path = client_func(args.discovery_doc[0], args.language, args.output, args.build_system) print 'API client library written to %s' % client_path
[ "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. Args: args: An argparse.Namespace object to extract parameters from client_func: A function that generates client libraries and stores them to files, accepting a path to a discovery doc, a client library language, an output directory, and a build system for the client library language.
[ "Generate", "a", "client", "library", "to", "file", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L470-L481
train
cloudendpoints/endpoints-python
endpoints/_endpointscfg_impl.py
_EndpointsParser.error
def error(self, message): """Override superclass to support customized error message. Error message needs to be rewritten in order to display visible commands only, when invalid command is called by user. Otherwise, hidden commands will be displayed in stderr, which is not expected. Refer the following argparse python documentation for detailed method information: http://docs.python.org/2/library/argparse.html#exiting-methods Args: message: original error message that will be printed to stderr """ # 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)
python
def error(self, message): """Override superclass to support customized error message. Error message needs to be rewritten in order to display visible commands only, when invalid command is called by user. Otherwise, hidden commands will be displayed in stderr, which is not expected. Refer the following argparse python documentation for detailed method information: http://docs.python.org/2/library/argparse.html#exiting-methods Args: message: original error message that will be printed to stderr """ # 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)
[ "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. Error message needs to be rewritten in order to display visible commands only, when invalid command is called by user. Otherwise, hidden commands will be displayed in stderr, which is not expected. Refer the following argparse python documentation for detailed method information: http://docs.python.org/2/library/argparse.html#exiting-methods Args: message: original error message that will be printed to stderr
[ "Override", "superclass", "to", "support", "customized", "error", "message", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L111-L135
train
cloudendpoints/endpoints-python
endpoints/_endpointscfg_setup.py
_SetupPaths
def _SetupPaths(): """Sets up the sys.path with special directories for endpointscfg.py.""" 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__)))
python
def _SetupPaths(): """Sets up the sys.path with special directories for endpointscfg.py.""" 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__)))
[ "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.
[ "Sets", "up", "the", "sys", ".", "path", "with", "special", "directories", "for", "endpointscfg", ".", "py", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_setup.py#L84-L104
train
cloudendpoints/endpoints-python
endpoints/api_config.py
_Enum
def _Enum(docstring, *names): """Utility to generate enum classes used by annotations. Args: docstring: Docstring for the generated enum class. *names: Enum names. Returns: A class that contains enum names as attributes. """ 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)
python
def _Enum(docstring, *names): """Utility to generate enum classes used by annotations. Args: docstring: Docstring for the generated enum class. *names: Enum names. Returns: A class that contains enum names as attributes. """ 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)
[ "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. Args: docstring: Docstring for the generated enum class. *names: Enum names. Returns: A class that contains enum names as attributes.
[ "Utility", "to", "generate", "enum", "classes", "used", "by", "annotations", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L102-L116
train
cloudendpoints/endpoints-python
endpoints/api_config.py
_CheckType
def _CheckType(value, check_type, name, allow_none=True): """Check that the type of an object is acceptable. Args: value: The object whose type is to be checked. check_type: The type that the object must be an instance of. name: Name of the object, to be placed in any error messages. allow_none: True if value can be None, false if not. Raises: TypeError: If value is not an acceptable type. """ 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))
python
def _CheckType(value, check_type, name, allow_none=True): """Check that the type of an object is acceptable. Args: value: The object whose type is to be checked. check_type: The type that the object must be an instance of. name: Name of the object, to be placed in any error messages. allow_none: True if value can be None, false if not. Raises: TypeError: If value is not an acceptable type. """ 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))
[ "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. Args: value: The object whose type is to be checked. check_type: The type that the object must be an instance of. name: Name of the object, to be placed in any error messages. allow_none: True if value can be None, false if not. Raises: TypeError: If value is not an acceptable type.
[ "Check", "that", "the", "type", "of", "an", "object", "is", "acceptable", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L190-L205
train
cloudendpoints/endpoints-python
endpoints/api_config.py
api
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): """Decorate a ProtoRPC Service class for use by the framework above. This decorator can be used to specify an API name, version, description, and hostname for your API. Sample usage (python 2.7): @endpoints.api(name='guestbook', version='v0.2', description='Guestbook API') class PostService(remote.Service): ... Sample usage (python 2.5): class PostService(remote.Service): ... endpoints.api(name='guestbook', version='v0.2', description='Guestbook API')(PostService) Sample usage if multiple classes implement one API: api_root = endpoints.api(name='library', version='v1.0') @api_root.api_class(resource_name='shelves') class Shelves(remote.Service): ... @api_root.api_class(resource_name='books', path='books') class Books(remote.Service): ... Args: name: string, Name of the API. version: string, Version of the API. description: string, Short description of the API (Default: None) hostname: string, Hostname of the API (Default: app engine default host) audiences: list of strings, Acceptable audiences for authentication. scopes: list of strings, Acceptable scopes for authentication. allowed_client_ids: list of strings, Acceptable client IDs for auth. canonical_name: string, the canonical name for the API, a more human readable version of the name. auth: ApiAuth instance, the authentication configuration information for this API. owner_domain: string, the domain of the person or company that owns this API. Along with owner_name, this provides hints to properly name client libraries for this API. owner_name: string, the name of the owner of this API. Along with owner_domain, this provides hints to properly name client libraries for this API. package_path: string, the "package" this API belongs to. This '/' delimited value specifies logical groupings of APIs. This is used by client libraries of this API. frontend_limits: ApiFrontEndLimits, optional query limits for unregistered developers. title: string, the human readable title of your API. It is exposed in the discovery service. documentation: string, a URL where users can find documentation about this version of the API. This will be surfaced in the API Explorer and GPE plugin to allow users to learn about your service. auth_level: enum from AUTH_LEVEL, frontend authentication level. issuers: dict, mapping auth issuer names to endpoints.Issuer objects. namespace: endpoints.Namespace, the namespace for the API. api_key_required: bool, whether a key is required to call into this API. base_path: string, the base path for all endpoints in this API. limit_definitions: list of endpoints.LimitDefinition objects, quota metric definitions for this API. use_request_uri: if true, match requests against REQUEST_URI instead of PATH_INFO Returns: Class decorated with api_info attribute, an instance of ApiInfo. """ 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)
python
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): """Decorate a ProtoRPC Service class for use by the framework above. This decorator can be used to specify an API name, version, description, and hostname for your API. Sample usage (python 2.7): @endpoints.api(name='guestbook', version='v0.2', description='Guestbook API') class PostService(remote.Service): ... Sample usage (python 2.5): class PostService(remote.Service): ... endpoints.api(name='guestbook', version='v0.2', description='Guestbook API')(PostService) Sample usage if multiple classes implement one API: api_root = endpoints.api(name='library', version='v1.0') @api_root.api_class(resource_name='shelves') class Shelves(remote.Service): ... @api_root.api_class(resource_name='books', path='books') class Books(remote.Service): ... Args: name: string, Name of the API. version: string, Version of the API. description: string, Short description of the API (Default: None) hostname: string, Hostname of the API (Default: app engine default host) audiences: list of strings, Acceptable audiences for authentication. scopes: list of strings, Acceptable scopes for authentication. allowed_client_ids: list of strings, Acceptable client IDs for auth. canonical_name: string, the canonical name for the API, a more human readable version of the name. auth: ApiAuth instance, the authentication configuration information for this API. owner_domain: string, the domain of the person or company that owns this API. Along with owner_name, this provides hints to properly name client libraries for this API. owner_name: string, the name of the owner of this API. Along with owner_domain, this provides hints to properly name client libraries for this API. package_path: string, the "package" this API belongs to. This '/' delimited value specifies logical groupings of APIs. This is used by client libraries of this API. frontend_limits: ApiFrontEndLimits, optional query limits for unregistered developers. title: string, the human readable title of your API. It is exposed in the discovery service. documentation: string, a URL where users can find documentation about this version of the API. This will be surfaced in the API Explorer and GPE plugin to allow users to learn about your service. auth_level: enum from AUTH_LEVEL, frontend authentication level. issuers: dict, mapping auth issuer names to endpoints.Issuer objects. namespace: endpoints.Namespace, the namespace for the API. api_key_required: bool, whether a key is required to call into this API. base_path: string, the base path for all endpoints in this API. limit_definitions: list of endpoints.LimitDefinition objects, quota metric definitions for this API. use_request_uri: if true, match requests against REQUEST_URI instead of PATH_INFO Returns: Class decorated with api_info attribute, an instance of ApiInfo. """ 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)
[ "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. This decorator can be used to specify an API name, version, description, and hostname for your API. Sample usage (python 2.7): @endpoints.api(name='guestbook', version='v0.2', description='Guestbook API') class PostService(remote.Service): ... Sample usage (python 2.5): class PostService(remote.Service): ... endpoints.api(name='guestbook', version='v0.2', description='Guestbook API')(PostService) Sample usage if multiple classes implement one API: api_root = endpoints.api(name='library', version='v1.0') @api_root.api_class(resource_name='shelves') class Shelves(remote.Service): ... @api_root.api_class(resource_name='books', path='books') class Books(remote.Service): ... Args: name: string, Name of the API. version: string, Version of the API. description: string, Short description of the API (Default: None) hostname: string, Hostname of the API (Default: app engine default host) audiences: list of strings, Acceptable audiences for authentication. scopes: list of strings, Acceptable scopes for authentication. allowed_client_ids: list of strings, Acceptable client IDs for auth. canonical_name: string, the canonical name for the API, a more human readable version of the name. auth: ApiAuth instance, the authentication configuration information for this API. owner_domain: string, the domain of the person or company that owns this API. Along with owner_name, this provides hints to properly name client libraries for this API. owner_name: string, the name of the owner of this API. Along with owner_domain, this provides hints to properly name client libraries for this API. package_path: string, the "package" this API belongs to. This '/' delimited value specifies logical groupings of APIs. This is used by client libraries of this API. frontend_limits: ApiFrontEndLimits, optional query limits for unregistered developers. title: string, the human readable title of your API. It is exposed in the discovery service. documentation: string, a URL where users can find documentation about this version of the API. This will be surfaced in the API Explorer and GPE plugin to allow users to learn about your service. auth_level: enum from AUTH_LEVEL, frontend authentication level. issuers: dict, mapping auth issuer names to endpoints.Issuer objects. namespace: endpoints.Namespace, the namespace for the API. api_key_required: bool, whether a key is required to call into this API. base_path: string, the base path for all endpoints in this API. limit_definitions: list of endpoints.LimitDefinition objects, quota metric definitions for this API. use_request_uri: if true, match requests against REQUEST_URI instead of PATH_INFO Returns: Class decorated with api_info attribute, an instance of ApiInfo.
[ "Decorate", "a", "ProtoRPC", "Service", "class", "for", "use", "by", "the", "framework", "above", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L988-L1077
train
cloudendpoints/endpoints-python
endpoints/api_config.py
method
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): """Decorate a ProtoRPC Method for use by the framework above. This decorator can be used to specify a method name, path, http method, scopes, audiences, client ids and auth_level. Sample usage: @api_config.method(RequestMessage, ResponseMessage, name='insert', http_method='PUT') def greeting_insert(request): ... return response Args: request_message: Message type of expected request. response_message: Message type of expected response. name: string, Name of the method, prepended with <apiname>. to make it unique. (Default: python method name) path: string, Path portion of the URL to the method, for RESTful methods. http_method: string, HTTP method supported by the method. (Default: POST) scopes: list of string, OAuth2 token must contain one of these scopes. audiences: list of string, IdToken must contain one of these audiences. allowed_client_ids: list of string, Client IDs allowed to call the method. If None and auth_level is REQUIRED, no calls will be allowed. auth_level: enum from AUTH_LEVEL, Frontend auth level for the method. api_key_required: bool, whether a key is required to call the method metric_costs: dict with keys matching an API limit metric and values representing the cost for each successful call against that metric. use_request_uri: if true, match requests against REQUEST_URI instead of PATH_INFO Returns: 'apiserving_method_wrapper' function. Raises: TypeError: if the request_type or response_type parameters are not proper subclasses of messages.Message. """ 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
python
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): """Decorate a ProtoRPC Method for use by the framework above. This decorator can be used to specify a method name, path, http method, scopes, audiences, client ids and auth_level. Sample usage: @api_config.method(RequestMessage, ResponseMessage, name='insert', http_method='PUT') def greeting_insert(request): ... return response Args: request_message: Message type of expected request. response_message: Message type of expected response. name: string, Name of the method, prepended with <apiname>. to make it unique. (Default: python method name) path: string, Path portion of the URL to the method, for RESTful methods. http_method: string, HTTP method supported by the method. (Default: POST) scopes: list of string, OAuth2 token must contain one of these scopes. audiences: list of string, IdToken must contain one of these audiences. allowed_client_ids: list of string, Client IDs allowed to call the method. If None and auth_level is REQUIRED, no calls will be allowed. auth_level: enum from AUTH_LEVEL, Frontend auth level for the method. api_key_required: bool, whether a key is required to call the method metric_costs: dict with keys matching an API limit metric and values representing the cost for each successful call against that metric. use_request_uri: if true, match requests against REQUEST_URI instead of PATH_INFO Returns: 'apiserving_method_wrapper' function. Raises: TypeError: if the request_type or response_type parameters are not proper subclasses of messages.Message. """ 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
[ "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.\n\n Args:\n api_method: Original method being wrapped.\n\n Returns:\n Function responsible for actual invocation.\n Assigns the following attributes to invocation function:\n remote: Instance of RemoteInfo, contains remote method information.\n remote.request_type: Expected request type for remote method.\n remote.response_type: Response type returned from remote method.\n method_info: Instance of _MethodInfo, api method configuration.\n It is also assigned attributes corresponding to the aforementioned kwargs.\n\n Raises:\n TypeError: if the request_type or response_type parameters are not\n proper subclasses of messages.Message.\n KeyError: if the request_message is a ResourceContainer and the newly\n created remote method has been reference by the container before. This\n should never occur because a remote method is created once.\n \"\"\"", "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. This decorator can be used to specify a method name, path, http method, scopes, audiences, client ids and auth_level. Sample usage: @api_config.method(RequestMessage, ResponseMessage, name='insert', http_method='PUT') def greeting_insert(request): ... return response Args: request_message: Message type of expected request. response_message: Message type of expected response. name: string, Name of the method, prepended with <apiname>. to make it unique. (Default: python method name) path: string, Path portion of the URL to the method, for RESTful methods. http_method: string, HTTP method supported by the method. (Default: POST) scopes: list of string, OAuth2 token must contain one of these scopes. audiences: list of string, IdToken must contain one of these audiences. allowed_client_ids: list of string, Client IDs allowed to call the method. If None and auth_level is REQUIRED, no calls will be allowed. auth_level: enum from AUTH_LEVEL, Frontend auth level for the method. api_key_required: bool, whether a key is required to call the method metric_costs: dict with keys matching an API limit metric and values representing the cost for each successful call against that metric. use_request_uri: if true, match requests against REQUEST_URI instead of PATH_INFO Returns: 'apiserving_method_wrapper' function. Raises: TypeError: if the request_type or response_type parameters are not proper subclasses of messages.Message.
[ "Decorate", "a", "ProtoRPC", "Method", "for", "use", "by", "the", "framework", "above", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1257-L1379
train
cloudendpoints/endpoints-python
endpoints/api_config.py
_ApiInfo.is_same_api
def is_same_api(self, other): """Check if this implements the same API as another _ApiInfo instance.""" if not isinstance(other, _ApiInfo): return False # pylint: disable=protected-access return self.__common_info is other.__common_info
python
def is_same_api(self, other): """Check if this implements the same API as another _ApiInfo instance.""" if not isinstance(other, _ApiInfo): return False # pylint: disable=protected-access return self.__common_info is other.__common_info
[ "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.
[ "Check", "if", "this", "implements", "the", "same", "API", "as", "another", "_ApiInfo", "instance", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L307-L312
train
cloudendpoints/endpoints-python
endpoints/api_config.py
_ApiDecorator.api_class
def api_class(self, resource_name=None, path=None, audiences=None, scopes=None, allowed_client_ids=None, auth_level=None, api_key_required=None): """Get a decorator for a class that implements an API. This can be used for single-class or multi-class implementations. It's used implicitly in simple single-class APIs that only use @api directly. Args: resource_name: string, Resource name for the class this decorates. (Default: None) path: string, Base path prepended to any method paths in the class this decorates. (Default: None) audiences: list of strings, Acceptable audiences for authentication. (Default: None) scopes: list of strings, Acceptable scopes for authentication. (Default: None) allowed_client_ids: list of strings, Acceptable client IDs for auth. (Default: None) auth_level: enum from AUTH_LEVEL, Frontend authentication level. (Default: None) api_key_required: bool, Whether a key is required to call into this API. (Default: None) Returns: A decorator function to decorate a class that implements an API. """ 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
python
def api_class(self, resource_name=None, path=None, audiences=None, scopes=None, allowed_client_ids=None, auth_level=None, api_key_required=None): """Get a decorator for a class that implements an API. This can be used for single-class or multi-class implementations. It's used implicitly in simple single-class APIs that only use @api directly. Args: resource_name: string, Resource name for the class this decorates. (Default: None) path: string, Base path prepended to any method paths in the class this decorates. (Default: None) audiences: list of strings, Acceptable audiences for authentication. (Default: None) scopes: list of strings, Acceptable scopes for authentication. (Default: None) allowed_client_ids: list of strings, Acceptable client IDs for auth. (Default: None) auth_level: enum from AUTH_LEVEL, Frontend authentication level. (Default: None) api_key_required: bool, Whether a key is required to call into this API. (Default: None) Returns: A decorator function to decorate a class that implements an API. """ 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
[ "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.\n\n Args:\n api_class: remote.Service class, ProtoRPC service class being wrapped.\n\n Returns:\n Same class with API attributes assigned in api_info.\n \"\"\"", "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. This can be used for single-class or multi-class implementations. It's used implicitly in simple single-class APIs that only use @api directly. Args: resource_name: string, Resource name for the class this decorates. (Default: None) path: string, Base path prepended to any method paths in the class this decorates. (Default: None) audiences: list of strings, Acceptable audiences for authentication. (Default: None) scopes: list of strings, Acceptable scopes for authentication. (Default: None) allowed_client_ids: list of strings, Acceptable client IDs for auth. (Default: None) auth_level: enum from AUTH_LEVEL, Frontend authentication level. (Default: None) api_key_required: bool, Whether a key is required to call into this API. (Default: None) Returns: A decorator function to decorate a class that implements an API.
[ "Get", "a", "decorator", "for", "a", "class", "that", "implements", "an", "API", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L795-L842
train
cloudendpoints/endpoints-python
endpoints/api_config.py
_MethodInfo.__safe_name
def __safe_name(self, method_name): """Restrict method name to a-zA-Z0-9_, first char lowercase.""" # 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:]
python
def __safe_name(self, method_name): """Restrict method name to a-zA-Z0-9_, first char lowercase.""" # 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:]
[ "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.
[ "Restrict", "method", "name", "to", "a", "-", "zA", "-", "Z0", "-", "9_", "first", "char", "lowercase", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1126-L1136
train
cloudendpoints/endpoints-python
endpoints/api_config.py
_MethodInfo.method_id
def method_id(self, api_info): """Computed method name.""" # 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))
python
def method_id(self, api_info): """Computed method name.""" # 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))
[ "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.
[ "Computed", "method", "name", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1243-L1253
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.__field_to_subfields
def __field_to_subfields(self, field): """Fully describes data represented by field, including the nested case. In the case that the field is not a message field, we have no fields nested within a message definition, so we can simply return that field. However, in the nested case, we can't simply describe the data with one field or even with one chain of fields. For example, if we have a message field m_field = messages.MessageField(RefClass, 1) which references a class with two fields: class RefClass(messages.Message): one = messages.StringField(1) two = messages.IntegerField(2) then we would need to include both one and two to represent all the data contained. Calling __field_to_subfields(m_field) would return: [ [<MessageField "m_field">, <StringField "one">], [<MessageField "m_field">, <StringField "two">], ] If the second field was instead a message field class RefClass(messages.Message): one = messages.StringField(1) two = messages.MessageField(OtherRefClass, 2) referencing another class with two fields class OtherRefClass(messages.Message): three = messages.BooleanField(1) four = messages.FloatField(2) then we would need to recurse one level deeper for two. With this change, calling __field_to_subfields(m_field) would return: [ [<MessageField "m_field">, <StringField "one">], [<MessageField "m_field">, <StringField "two">, <StringField "three">], [<MessageField "m_field">, <StringField "two">, <StringField "four">], ] Args: field: An instance of a subclass of messages.Field. Returns: A list of lists, where each sublist is a list of fields. """ # 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
python
def __field_to_subfields(self, field): """Fully describes data represented by field, including the nested case. In the case that the field is not a message field, we have no fields nested within a message definition, so we can simply return that field. However, in the nested case, we can't simply describe the data with one field or even with one chain of fields. For example, if we have a message field m_field = messages.MessageField(RefClass, 1) which references a class with two fields: class RefClass(messages.Message): one = messages.StringField(1) two = messages.IntegerField(2) then we would need to include both one and two to represent all the data contained. Calling __field_to_subfields(m_field) would return: [ [<MessageField "m_field">, <StringField "one">], [<MessageField "m_field">, <StringField "two">], ] If the second field was instead a message field class RefClass(messages.Message): one = messages.StringField(1) two = messages.MessageField(OtherRefClass, 2) referencing another class with two fields class OtherRefClass(messages.Message): three = messages.BooleanField(1) four = messages.FloatField(2) then we would need to recurse one level deeper for two. With this change, calling __field_to_subfields(m_field) would return: [ [<MessageField "m_field">, <StringField "one">], [<MessageField "m_field">, <StringField "two">, <StringField "three">], [<MessageField "m_field">, <StringField "two">, <StringField "four">], ] Args: field: An instance of a subclass of messages.Field. Returns: A list of lists, where each sublist is a list of fields. """ # 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
[ "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. In the case that the field is not a message field, we have no fields nested within a message definition, so we can simply return that field. However, in the nested case, we can't simply describe the data with one field or even with one chain of fields. For example, if we have a message field m_field = messages.MessageField(RefClass, 1) which references a class with two fields: class RefClass(messages.Message): one = messages.StringField(1) two = messages.IntegerField(2) then we would need to include both one and two to represent all the data contained. Calling __field_to_subfields(m_field) would return: [ [<MessageField "m_field">, <StringField "one">], [<MessageField "m_field">, <StringField "two">], ] If the second field was instead a message field class RefClass(messages.Message): one = messages.StringField(1) two = messages.MessageField(OtherRefClass, 2) referencing another class with two fields class OtherRefClass(messages.Message): three = messages.BooleanField(1) four = messages.FloatField(2) then we would need to recurse one level deeper for two. With this change, calling __field_to_subfields(m_field) would return: [ [<MessageField "m_field">, <StringField "one">], [<MessageField "m_field">, <StringField "two">, <StringField "three">], [<MessageField "m_field">, <StringField "two">, <StringField "four">], ] Args: field: An instance of a subclass of messages.Field. Returns: A list of lists, where each sublist is a list of fields.
[ "Fully", "describes", "data", "represented", "by", "field", "including", "the", "nested", "case", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1438-L1503
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.__field_to_parameter_type
def __field_to_parameter_type(self, field): """Converts the field variant type into a string describing the parameter. Args: field: An instance of a subclass of messages.Field. Returns: A string corresponding to the variant enum of the field, with a few exceptions. In the case of signed ints, the 's' is dropped; for the BOOL variant, 'boolean' is used; and for the ENUM variant, 'string' is used. Raises: TypeError: if the field variant is a message variant. """ # 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()
python
def __field_to_parameter_type(self, field): """Converts the field variant type into a string describing the parameter. Args: field: An instance of a subclass of messages.Field. Returns: A string corresponding to the variant enum of the field, with a few exceptions. In the case of signed ints, the 's' is dropped; for the BOOL variant, 'boolean' is used; and for the ENUM variant, 'string' is used. Raises: TypeError: if the field variant is a message variant. """ # 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()
[ "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. Args: field: An instance of a subclass of messages.Field. Returns: A string corresponding to the variant enum of the field, with a few exceptions. In the case of signed ints, the 's' is dropped; for the BOOL variant, 'boolean' is used; and for the ENUM variant, 'string' is used. Raises: TypeError: if the field variant is a message variant.
[ "Converts", "the", "field", "variant", "type", "into", "a", "string", "describing", "the", "parameter", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1507-L1532
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.__get_path_parameters
def __get_path_parameters(self, path): """Parses path paremeters from a URI path and organizes them by parameter. Some of the parameters may correspond to message fields, and so will be represented as segments corresponding to each subfield; e.g. first.second if the field "second" in the message field "first" is pulled from the path. The resulting dictionary uses the first segments as keys and each key has as value the list of full parameter values with first segment equal to the key. If the match path parameter is null, that part of the path template is ignored; this occurs if '{}' is used in a template. Args: path: String; a URI path, potentially with some parameters. Returns: A dictionary with strings as keys and list of strings as values. """ 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
python
def __get_path_parameters(self, path): """Parses path paremeters from a URI path and organizes them by parameter. Some of the parameters may correspond to message fields, and so will be represented as segments corresponding to each subfield; e.g. first.second if the field "second" in the message field "first" is pulled from the path. The resulting dictionary uses the first segments as keys and each key has as value the list of full parameter values with first segment equal to the key. If the match path parameter is null, that part of the path template is ignored; this occurs if '{}' is used in a template. Args: path: String; a URI path, potentially with some parameters. Returns: A dictionary with strings as keys and list of strings as values. """ 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
[ "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. Some of the parameters may correspond to message fields, and so will be represented as segments corresponding to each subfield; e.g. first.second if the field "second" in the message field "first" is pulled from the path. The resulting dictionary uses the first segments as keys and each key has as value the list of full parameter values with first segment equal to the key. If the match path parameter is null, that part of the path template is ignored; this occurs if '{}' is used in a template. Args: path: String; a URI path, potentially with some parameters. Returns: A dictionary with strings as keys and list of strings as values.
[ "Parses", "path", "paremeters", "from", "a", "URI", "path", "and", "organizes", "them", "by", "parameter", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1534-L1559
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.__validate_simple_subfield
def __validate_simple_subfield(self, parameter, field, segment_list, _segment_index=0): """Verifies that a proposed subfield actually exists and is a simple field. Here, simple means it is not a MessageField (nested). Args: parameter: String; the '.' delimited name of the current field being considered. This is relative to some root. field: An instance of a subclass of messages.Field. Corresponds to the previous segment in the path (previous relative to _segment_index), since this field should be a message field with the current segment as a field in the message class. segment_list: The full list of segments from the '.' delimited subfield being validated. _segment_index: Integer; used to hold the position of current segment so that segment_list can be passed as a reference instead of having to copy using segment_list[1:] at each step. Raises: TypeError: If the final subfield (indicated by _segment_index relative to the length of segment_list) is a MessageField. TypeError: If at any stage the lookup at a segment fails, e.g if a.b exists but a.b.c does not exist. This can happen either if a.b is not a message field or if a.b.c is not a property on the message class from a.b. """ 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)
python
def __validate_simple_subfield(self, parameter, field, segment_list, _segment_index=0): """Verifies that a proposed subfield actually exists and is a simple field. Here, simple means it is not a MessageField (nested). Args: parameter: String; the '.' delimited name of the current field being considered. This is relative to some root. field: An instance of a subclass of messages.Field. Corresponds to the previous segment in the path (previous relative to _segment_index), since this field should be a message field with the current segment as a field in the message class. segment_list: The full list of segments from the '.' delimited subfield being validated. _segment_index: Integer; used to hold the position of current segment so that segment_list can be passed as a reference instead of having to copy using segment_list[1:] at each step. Raises: TypeError: If the final subfield (indicated by _segment_index relative to the length of segment_list) is a MessageField. TypeError: If at any stage the lookup at a segment fails, e.g if a.b exists but a.b.c does not exist. This can happen either if a.b is not a message field or if a.b.c is not a property on the message class from a.b. """ 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)
[ "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. Here, simple means it is not a MessageField (nested). Args: parameter: String; the '.' delimited name of the current field being considered. This is relative to some root. field: An instance of a subclass of messages.Field. Corresponds to the previous segment in the path (previous relative to _segment_index), since this field should be a message field with the current segment as a field in the message class. segment_list: The full list of segments from the '.' delimited subfield being validated. _segment_index: Integer; used to hold the position of current segment so that segment_list can be passed as a reference instead of having to copy using segment_list[1:] at each step. Raises: TypeError: If the final subfield (indicated by _segment_index relative to the length of segment_list) is a MessageField. TypeError: If at any stage the lookup at a segment fails, e.g if a.b exists but a.b.c does not exist. This can happen either if a.b is not a message field or if a.b.c is not a property on the message class from a.b.
[ "Verifies", "that", "a", "proposed", "subfield", "actually", "exists", "and", "is", "a", "simple", "field", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1561-L1604
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.__validate_path_parameters
def __validate_path_parameters(self, field, path_parameters): """Verifies that all path parameters correspond to an existing subfield. Args: field: An instance of a subclass of messages.Field. Should be the root level property name in each path parameter in path_parameters. For example, if the field is called 'foo', then each path parameter should begin with 'foo.'. path_parameters: A list of Strings representing URI parameter variables. Raises: TypeError: If one of the path parameters does not start with field.name. """ 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:])
python
def __validate_path_parameters(self, field, path_parameters): """Verifies that all path parameters correspond to an existing subfield. Args: field: An instance of a subclass of messages.Field. Should be the root level property name in each path parameter in path_parameters. For example, if the field is called 'foo', then each path parameter should begin with 'foo.'. path_parameters: A list of Strings representing URI parameter variables. Raises: TypeError: If one of the path parameters does not start with field.name. """ 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:])
[ "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. Args: field: An instance of a subclass of messages.Field. Should be the root level property name in each path parameter in path_parameters. For example, if the field is called 'foo', then each path parameter should begin with 'foo.'. path_parameters: A list of Strings representing URI parameter variables. Raises: TypeError: If one of the path parameters does not start with field.name.
[ "Verifies", "that", "all", "path", "parameters", "correspond", "to", "an", "existing", "subfield", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1606-L1624
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.__parameter_default
def __parameter_default(self, final_subfield): """Returns default value of final subfield if it has one. If this subfield comes from a field list returned from __field_to_subfields, none of the fields in the subfield list can have a default except the final one since they all must be message fields. Args: final_subfield: A simple field from the end of a subfield list. Returns: The default value of the subfield, if any exists, with the exception of an enum field, which will have its value cast to a string. """ if final_subfield.default: if isinstance(final_subfield, messages.EnumField): return final_subfield.default.name else: return final_subfield.default
python
def __parameter_default(self, final_subfield): """Returns default value of final subfield if it has one. If this subfield comes from a field list returned from __field_to_subfields, none of the fields in the subfield list can have a default except the final one since they all must be message fields. Args: final_subfield: A simple field from the end of a subfield list. Returns: The default value of the subfield, if any exists, with the exception of an enum field, which will have its value cast to a string. """ if final_subfield.default: if isinstance(final_subfield, messages.EnumField): return final_subfield.default.name else: return final_subfield.default
[ "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. If this subfield comes from a field list returned from __field_to_subfields, none of the fields in the subfield list can have a default except the final one since they all must be message fields. Args: final_subfield: A simple field from the end of a subfield list. Returns: The default value of the subfield, if any exists, with the exception of an enum field, which will have its value cast to a string.
[ "Returns", "default", "value", "of", "final", "subfield", "if", "it", "has", "one", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1626-L1644
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.__parameter_enum
def __parameter_enum(self, final_subfield): """Returns enum descriptor of final subfield if it is an enum. An enum descriptor is a dictionary with keys as the names from the enum and each value is a dictionary with a single key "backendValue" and value equal to the same enum name used to stored it in the descriptor. The key "description" can also be used next to "backendValue", but protorpc Enum classes have no way of supporting a description for each value. Args: final_subfield: A simple field from the end of a subfield list. Returns: The enum descriptor for the field, if it's an enum descriptor, else returns None. """ 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
python
def __parameter_enum(self, final_subfield): """Returns enum descriptor of final subfield if it is an enum. An enum descriptor is a dictionary with keys as the names from the enum and each value is a dictionary with a single key "backendValue" and value equal to the same enum name used to stored it in the descriptor. The key "description" can also be used next to "backendValue", but protorpc Enum classes have no way of supporting a description for each value. Args: final_subfield: A simple field from the end of a subfield list. Returns: The enum descriptor for the field, if it's an enum descriptor, else returns None. """ 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
[ "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. An enum descriptor is a dictionary with keys as the names from the enum and each value is a dictionary with a single key "backendValue" and value equal to the same enum name used to stored it in the descriptor. The key "description" can also be used next to "backendValue", but protorpc Enum classes have no way of supporting a description for each value. Args: final_subfield: A simple field from the end of a subfield list. Returns: The enum descriptor for the field, if it's an enum descriptor, else returns None.
[ "Returns", "enum", "descriptor", "of", "final", "subfield", "if", "it", "is", "an", "enum", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1646-L1667
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.__parameter_descriptor
def __parameter_descriptor(self, subfield_list): """Creates descriptor for a parameter using the subfields that define it. Each parameter is defined by a list of fields, with all but the last being a message field and the final being a simple (non-message) field. Many of the fields in the descriptor are determined solely by the simple field at the end, though some (such as repeated and required) take the whole chain of fields into consideration. Args: subfield_list: List of fields describing the parameter. Returns: Dictionary containing a descriptor for the parameter described by the list of fields. """ 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
python
def __parameter_descriptor(self, subfield_list): """Creates descriptor for a parameter using the subfields that define it. Each parameter is defined by a list of fields, with all but the last being a message field and the final being a simple (non-message) field. Many of the fields in the descriptor are determined solely by the simple field at the end, though some (such as repeated and required) take the whole chain of fields into consideration. Args: subfield_list: List of fields describing the parameter. Returns: Dictionary containing a descriptor for the parameter described by the list of fields. """ 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
[ "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. Each parameter is defined by a list of fields, with all but the last being a message field and the final being a simple (non-message) field. Many of the fields in the descriptor are determined solely by the simple field at the end, though some (such as repeated and required) take the whole chain of fields into consideration. Args: subfield_list: List of fields describing the parameter. Returns: Dictionary containing a descriptor for the parameter described by the list of fields.
[ "Creates", "descriptor", "for", "a", "parameter", "using", "the", "subfields", "that", "define", "it", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1669-L1710
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.__schema_descriptor
def __schema_descriptor(self, services): """Descriptor for the all the JSON Schema used. Args: services: List of protorpc.remote.Service instances implementing an api/version. Returns: Dictionary containing all the JSON Schema used in the service. """ 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
python
def __schema_descriptor(self, services): """Descriptor for the all the JSON Schema used. Args: services: List of protorpc.remote.Service instances implementing an api/version. Returns: Dictionary containing all the JSON Schema used in the service. """ 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
[ "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. Args: services: List of protorpc.remote.Service instances implementing an api/version. Returns: Dictionary containing all the JSON Schema used in the service.
[ "Descriptor", "for", "the", "all", "the", "JSON", "Schema", "used", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1960-L1999
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.__auth_descriptor
def __auth_descriptor(self, api_info): """Builds an auth descriptor from API info. Args: api_info: An _ApiInfo object. Returns: A dictionary with 'allowCookieAuth' and/or 'blockedRegions' keys. """ 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
python
def __auth_descriptor(self, api_info): """Builds an auth descriptor from API info. Args: api_info: An _ApiInfo object. Returns: A dictionary with 'allowCookieAuth' and/or 'blockedRegions' keys. """ 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
[ "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. Args: api_info: An _ApiInfo object. Returns: A dictionary with 'allowCookieAuth' and/or 'blockedRegions' keys.
[ "Builds", "an", "auth", "descriptor", "from", "API", "info", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L2028-L2046
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.__frontend_limit_descriptor
def __frontend_limit_descriptor(self, api_info): """Builds a frontend limit descriptor from API info. Args: api_info: An _ApiInfo object. Returns: A dictionary with frontend limit information. """ 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
python
def __frontend_limit_descriptor(self, api_info): """Builds a frontend limit descriptor from API info. Args: api_info: An _ApiInfo object. Returns: A dictionary with frontend limit information. """ 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
[ "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. Args: api_info: An _ApiInfo object. Returns: A dictionary with frontend limit information.
[ "Builds", "a", "frontend", "limit", "descriptor", "from", "API", "info", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L2048-L2071
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.__frontend_limit_rules_descriptor
def __frontend_limit_rules_descriptor(self, api_info): """Builds a frontend limit rules descriptor from API info. Args: api_info: An _ApiInfo object. Returns: A list of dictionaries with frontend limit rules information. """ 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
python
def __frontend_limit_rules_descriptor(self, api_info): """Builds a frontend limit rules descriptor from API info. Args: api_info: An _ApiInfo object. Returns: A list of dictionaries with frontend limit rules information. """ 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
[ "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. Args: api_info: An _ApiInfo object. Returns: A list of dictionaries with frontend limit rules information.
[ "Builds", "a", "frontend", "limit", "rules", "descriptor", "from", "API", "info", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L2073-L2098
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.get_config_dict
def get_config_dict(self, services, hostname=None): """JSON dict description of a protorpc.remote.Service in API format. Args: services: Either a single protorpc.remote.Service or a list of them that implements an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: dict, The API descriptor document as a JSON dict. """ 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)
python
def get_config_dict(self, services, hostname=None): """JSON dict description of a protorpc.remote.Service in API format. Args: services: Either a single protorpc.remote.Service or a list of them that implements an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: dict, The API descriptor document as a JSON dict. """ 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)
[ "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. Args: services: Either a single protorpc.remote.Service or a list of them that implements an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: dict, The API descriptor document as a JSON dict.
[ "JSON", "dict", "description", "of", "a", "protorpc", ".", "remote", ".", "Service", "in", "API", "format", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L2226-L2246
train
cloudendpoints/endpoints-python
endpoints/api_config.py
ApiConfigGenerator.pretty_print_config_to_json
def pretty_print_config_to_json(self, services, hostname=None): """JSON string description of a protorpc.remote.Service in API format. Args: services: Either a single protorpc.remote.Service or a list of them that implements an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: string, The API descriptor document as a JSON string. """ descriptor = self.get_config_dict(services, hostname) return json.dumps(descriptor, sort_keys=True, indent=2, separators=(',', ': '))
python
def pretty_print_config_to_json(self, services, hostname=None): """JSON string description of a protorpc.remote.Service in API format. Args: services: Either a single protorpc.remote.Service or a list of them that implements an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: string, The API descriptor document as a JSON string. """ descriptor = self.get_config_dict(services, hostname) return json.dumps(descriptor, sort_keys=True, indent=2, separators=(',', ': '))
[ "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. Args: services: Either a single protorpc.remote.Service or a list of them that implements an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: string, The API descriptor document as a JSON string.
[ "JSON", "string", "description", "of", "a", "protorpc", ".", "remote", ".", "Service", "in", "API", "format", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L2248-L2262
train
cloudendpoints/endpoints-python
endpoints/discovery_generator.py
DiscoveryGenerator.__parameter_enum
def __parameter_enum(self, param): """Returns enum descriptor of a parameter if it is an enum. An enum descriptor is a list of keys. Args: param: A simple field. Returns: The enum descriptor for the field, if it's an enum descriptor, else returns None. """ if isinstance(param, messages.EnumField): return [enum_entry[0] for enum_entry in sorted( param.type.to_dict().items(), key=lambda v: v[1])]
python
def __parameter_enum(self, param): """Returns enum descriptor of a parameter if it is an enum. An enum descriptor is a list of keys. Args: param: A simple field. Returns: The enum descriptor for the field, if it's an enum descriptor, else returns None. """ if isinstance(param, messages.EnumField): return [enum_entry[0] for enum_entry in sorted( param.type.to_dict().items(), key=lambda v: v[1])]
[ "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. An enum descriptor is a list of keys. Args: param: A simple field. Returns: The enum descriptor for the field, if it's an enum descriptor, else returns None.
[ "Returns", "enum", "descriptor", "of", "a", "parameter", "if", "it", "is", "an", "enum", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_generator.py#L332-L346
train
cloudendpoints/endpoints-python
endpoints/discovery_generator.py
DiscoveryGenerator.__params_order_descriptor
def __params_order_descriptor(self, message_type, path, is_params_class=False): """Describe the order of path parameters. Args: message_type: messages.Message class, Message with parameters to describe. path: string, HTTP path to method. is_params_class: boolean, Whether the message represents URL parameters. Returns: Descriptor list for the parameter order. """ 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)
python
def __params_order_descriptor(self, message_type, path, is_params_class=False): """Describe the order of path parameters. Args: message_type: messages.Message class, Message with parameters to describe. path: string, HTTP path to method. is_params_class: boolean, Whether the message represents URL parameters. Returns: Descriptor list for the parameter order. """ 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)
[ "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. Args: message_type: messages.Message class, Message with parameters to describe. path: string, HTTP path to method. is_params_class: boolean, Whether the message represents URL parameters. Returns: Descriptor list for the parameter order.
[ "Describe", "the", "order", "of", "path", "parameters", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_generator.py#L514-L545
train
cloudendpoints/endpoints-python
endpoints/discovery_generator.py
DiscoveryGenerator.__schemas_descriptor
def __schemas_descriptor(self): """Describes the schemas section of the discovery document. Returns: Dictionary describing the schemas of the document. """ # 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
python
def __schemas_descriptor(self): """Describes the schemas section of the discovery document. Returns: Dictionary describing the schemas of the document. """ # 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
[ "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. Returns: Dictionary describing the schemas of the document.
[ "Describes", "the", "schemas", "section", "of", "the", "discovery", "document", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_generator.py#L547-L591
train
cloudendpoints/endpoints-python
endpoints/discovery_generator.py
DiscoveryGenerator.__resource_descriptor
def __resource_descriptor(self, resource_path, methods): """Describes a resource. Args: resource_path: string, the path of the resource (e.g., 'entries.items') methods: list of tuples of type (endpoints.Service, protorpc.remote._RemoteMethodInfo), the methods that serve this resource. Returns: Dictionary describing the resource. """ 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
python
def __resource_descriptor(self, resource_path, methods): """Describes a resource. Args: resource_path: string, the path of the resource (e.g., 'entries.items') methods: list of tuples of type (endpoints.Service, protorpc.remote._RemoteMethodInfo), the methods that serve this resource. Returns: Dictionary describing the resource. """ 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
[ "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. Args: resource_path: string, the path of the resource (e.g., 'entries.items') methods: list of tuples of type (endpoints.Service, protorpc.remote._RemoteMethodInfo), the methods that serve this resource. Returns: Dictionary describing the resource.
[ "Describes", "a", "resource", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_generator.py#L706-L766
train
cloudendpoints/endpoints-python
endpoints/discovery_generator.py
DiscoveryGenerator.__discovery_doc_descriptor
def __discovery_doc_descriptor(self, services, hostname=None): """Builds a discovery doc for an API. Args: services: List of protorpc.remote.Service instances implementing an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: A dictionary that can be deserialized into JSON in discovery doc format. Raises: ApiConfigurationError: If there's something wrong with the API configuration, such as a multiclass API decorated with different API descriptors (see the docstring for api()), or a repeated method signature. """ 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) # Add namespace information, if provided 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 the first pass, only process top-level methods (that is, those methods # that are unattached to a resource). 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) # Skip methods that are not decorated with @method 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) # Make sure the same method name isn't repeated. 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__ # Make sure the same HTTP method & path aren't repeated. 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 this method is part of a resource, note it and skip it for now 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) # Do another pass for methods attached to resources 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 # Add schemas, if any schemas = self.__schemas_descriptor() if schemas: descriptor['schemas'] = schemas return descriptor
python
def __discovery_doc_descriptor(self, services, hostname=None): """Builds a discovery doc for an API. Args: services: List of protorpc.remote.Service instances implementing an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: A dictionary that can be deserialized into JSON in discovery doc format. Raises: ApiConfigurationError: If there's something wrong with the API configuration, such as a multiclass API decorated with different API descriptors (see the docstring for api()), or a repeated method signature. """ 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) # Add namespace information, if provided 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 the first pass, only process top-level methods (that is, those methods # that are unattached to a resource). 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) # Skip methods that are not decorated with @method 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) # Make sure the same method name isn't repeated. 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__ # Make sure the same HTTP method & path aren't repeated. 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 this method is part of a resource, note it and skip it for now 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) # Do another pass for methods attached to resources 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 # Add schemas, if any schemas = self.__schemas_descriptor() if schemas: descriptor['schemas'] = schemas return descriptor
[ "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", ")", "# Add namespace information, if provided", "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 the first pass, only process top-level methods (that is, those methods", "# that are unattached to a resource).", "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", ")", "# Skip methods that are not decorated with @method", "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", ")", "# Make sure the same method name isn't repeated.", "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__", "# Make sure the same HTTP method & path aren't repeated.", "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 this method is part of a resource, note it and skip it for now", "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", ")", "# Do another pass for methods attached to resources", "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", "# Add schemas, if any", "schemas", "=", "self", ".", "__schemas_descriptor", "(", ")", "if", "schemas", ":", "descriptor", "[", "'schemas'", "]", "=", "schemas", "return", "descriptor" ]
Builds a discovery doc for an API. Args: services: List of protorpc.remote.Service instances implementing an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: A dictionary that can be deserialized into JSON in discovery doc format. Raises: ApiConfigurationError: If there's something wrong with the API configuration, such as a multiclass API decorated with different API descriptors (see the docstring for api()), or a repeated method signature.
[ "Builds", "a", "discovery", "doc", "for", "an", "API", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_generator.py#L855-L964
train
cloudendpoints/endpoints-python
endpoints/discovery_generator.py
DiscoveryGenerator.get_discovery_doc
def get_discovery_doc(self, services, hostname=None): """JSON dict description of a protorpc.remote.Service in discovery format. Args: services: Either a single protorpc.remote.Service or a list of them that implements an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: dict, The discovery document as a JSON dict. """ 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)
python
def get_discovery_doc(self, services, hostname=None): """JSON dict description of a protorpc.remote.Service in discovery format. Args: services: Either a single protorpc.remote.Service or a list of them that implements an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: dict, The discovery document as a JSON dict. """ 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)
[ "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. Args: services: Either a single protorpc.remote.Service or a list of them that implements an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: dict, The discovery document as a JSON dict.
[ "JSON", "dict", "description", "of", "a", "protorpc", ".", "remote", ".", "Service", "in", "discovery", "format", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_generator.py#L1019-L1041
train
cloudendpoints/endpoints-python
endpoints/util.py
send_wsgi_response
def send_wsgi_response(status, headers, content, start_response, cors_handler=None): """Dump reformatted response to CGI start_response. This calls start_response and returns the response body. Args: status: A string containing the HTTP status code to send. headers: A list of (header, value) tuples, the headers to send in the response. content: A string containing the body content to write. start_response: A function with semantics defined in PEP-333. cors_handler: A handler to process CORS request headers and update the headers in the response. Or this can be None, to bypass CORS checks. Returns: A string containing the response body. """ 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
python
def send_wsgi_response(status, headers, content, start_response, cors_handler=None): """Dump reformatted response to CGI start_response. This calls start_response and returns the response body. Args: status: A string containing the HTTP status code to send. headers: A list of (header, value) tuples, the headers to send in the response. content: A string containing the body content to write. start_response: A function with semantics defined in PEP-333. cors_handler: A handler to process CORS request headers and update the headers in the response. Or this can be None, to bypass CORS checks. Returns: A string containing the response body. """ 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
[ "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. This calls start_response and returns the response body. Args: status: A string containing the HTTP status code to send. headers: A list of (header, value) tuples, the headers to send in the response. content: A string containing the body content to write. start_response: A function with semantics defined in PEP-333. cors_handler: A handler to process CORS request headers and update the headers in the response. Or this can be None, to bypass CORS checks. Returns: A string containing the response body.
[ "Dump", "reformatted", "response", "to", "CGI", "start_response", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L115-L143
train
cloudendpoints/endpoints-python
endpoints/util.py
get_headers_from_environ
def get_headers_from_environ(environ): """Get a wsgiref.headers.Headers object with headers from the environment. Headers in environ are prefixed with 'HTTP_', are all uppercase, and have had dashes replaced with underscores. This strips the HTTP_ prefix and changes underscores back to dashes before adding them to the returned set of headers. Args: environ: An environ dict for the request as defined in PEP-333. Returns: A wsgiref.headers.Headers object that's been filled in with any HTTP headers found in 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
python
def get_headers_from_environ(environ): """Get a wsgiref.headers.Headers object with headers from the environment. Headers in environ are prefixed with 'HTTP_', are all uppercase, and have had dashes replaced with underscores. This strips the HTTP_ prefix and changes underscores back to dashes before adding them to the returned set of headers. Args: environ: An environ dict for the request as defined in PEP-333. Returns: A wsgiref.headers.Headers object that's been filled in with any HTTP headers found in 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
[ "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. Headers in environ are prefixed with 'HTTP_', are all uppercase, and have had dashes replaced with underscores. This strips the HTTP_ prefix and changes underscores back to dashes before adding them to the returned set of headers. Args: environ: An environ dict for the request as defined in PEP-333. Returns: A wsgiref.headers.Headers object that's been filled in with any HTTP headers found in environ.
[ "Get", "a", "wsgiref", ".", "headers", ".", "Headers", "object", "with", "headers", "from", "the", "environment", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L146-L168
train
cloudendpoints/endpoints-python
endpoints/util.py
put_headers_in_environ
def put_headers_in_environ(headers, environ): """Given a list of headers, put them into environ based on PEP-333. This converts headers to uppercase, prefixes them with 'HTTP_', and converts dashes to underscores before adding them to the environ dict. Args: headers: A list of (header, value) tuples. The HTTP headers to add to the environment. environ: An environ dict for the request as defined in PEP-333. """ for key, value in headers: environ['HTTP_%s' % key.upper().replace('-', '_')] = value
python
def put_headers_in_environ(headers, environ): """Given a list of headers, put them into environ based on PEP-333. This converts headers to uppercase, prefixes them with 'HTTP_', and converts dashes to underscores before adding them to the environ dict. Args: headers: A list of (header, value) tuples. The HTTP headers to add to the environment. environ: An environ dict for the request as defined in PEP-333. """ for key, value in headers: environ['HTTP_%s' % key.upper().replace('-', '_')] = value
[ "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. This converts headers to uppercase, prefixes them with 'HTTP_', and converts dashes to underscores before adding them to the environ dict. Args: headers: A list of (header, value) tuples. The HTTP headers to add to the environment. environ: An environ dict for the request as defined in PEP-333.
[ "Given", "a", "list", "of", "headers", "put", "them", "into", "environ", "based", "on", "PEP", "-", "333", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L171-L183
train
cloudendpoints/endpoints-python
endpoints/util.py
get_hostname_prefix
def get_hostname_prefix(): """Returns the hostname prefix of a running Endpoints service. The prefix is the portion of the hostname that comes before the API name. For example, if a non-default version and a non-default service are in use, the returned result would be '{VERSION}-dot-{SERVICE}-'. Returns: str, the 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)
python
def get_hostname_prefix(): """Returns the hostname prefix of a running Endpoints service. The prefix is the portion of the hostname that comes before the API name. For example, if a non-default version and a non-default service are in use, the returned result would be '{VERSION}-dot-{SERVICE}-'. Returns: str, the 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)
[ "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. The prefix is the portion of the hostname that comes before the API name. For example, if a non-default version and a non-default service are in use, the returned result would be '{VERSION}-dot-{SERVICE}-'. Returns: str, the hostname prefix.
[ "Returns", "the", "hostname", "prefix", "of", "a", "running", "Endpoints", "service", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L200-L228
train
cloudendpoints/endpoints-python
endpoints/util.py
get_app_hostname
def get_app_hostname(): """Return hostname of a running Endpoints service. Returns hostname of an running Endpoints API. It can be 1) "localhost:PORT" if running on development server, or 2) "app_id.appspot.com" if running on external app engine prod, or "app_id.googleplex.com" if running as Google first-party Endpoints API, or 4) None if not running on App Engine (e.g. Tornado Endpoints API). Returns: A string representing the hostname of the service. """ 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)
python
def get_app_hostname(): """Return hostname of a running Endpoints service. Returns hostname of an running Endpoints API. It can be 1) "localhost:PORT" if running on development server, or 2) "app_id.appspot.com" if running on external app engine prod, or "app_id.googleplex.com" if running as Google first-party Endpoints API, or 4) None if not running on App Engine (e.g. Tornado Endpoints API). Returns: A string representing the hostname of the service. """ 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)
[ "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. Returns hostname of an running Endpoints API. It can be 1) "localhost:PORT" if running on development server, or 2) "app_id.appspot.com" if running on external app engine prod, or "app_id.googleplex.com" if running as Google first-party Endpoints API, or 4) None if not running on App Engine (e.g. Tornado Endpoints API). Returns: A string representing the hostname of the service.
[ "Return", "hostname", "of", "a", "running", "Endpoints", "service", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L231-L259
train
cloudendpoints/endpoints-python
endpoints/util.py
check_list_type
def check_list_type(objects, allowed_type, name, allow_none=True): """Verify that objects in list are of the allowed type or raise TypeError. Args: objects: The list of objects to check. allowed_type: The allowed type of items in 'settings'. name: Name of the list of objects, added to the exception. allow_none: If set, None is also allowed. Raises: TypeError: if object is not of the allowed type. Returns: The list of objects, for convenient use in assignment. """ 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
python
def check_list_type(objects, allowed_type, name, allow_none=True): """Verify that objects in list are of the allowed type or raise TypeError. Args: objects: The list of objects to check. allowed_type: The allowed type of items in 'settings'. name: Name of the list of objects, added to the exception. allow_none: If set, None is also allowed. Raises: TypeError: if object is not of the allowed type. Returns: The list of objects, for convenient use in assignment. """ 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
[ "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. Args: objects: The list of objects to check. allowed_type: The allowed type of items in 'settings'. name: Name of the list of objects, added to the exception. allow_none: If set, None is also allowed. Raises: TypeError: if object is not of the allowed type. Returns: The list of objects, for convenient use in assignment.
[ "Verify", "that", "objects", "in", "list", "are", "of", "the", "allowed", "type", "or", "raise", "TypeError", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L262-L287
train
cloudendpoints/endpoints-python
endpoints/util.py
snake_case_to_headless_camel_case
def snake_case_to_headless_camel_case(snake_string): """Convert snake_case to headlessCamelCase. Args: snake_string: The string to be converted. Returns: The input string converted to headlessCamelCase. """ return ''.join([snake_string.split('_')[0]] + list(sub_string.capitalize() for sub_string in snake_string.split('_')[1:]))
python
def snake_case_to_headless_camel_case(snake_string): """Convert snake_case to headlessCamelCase. Args: snake_string: The string to be converted. Returns: The input string converted to headlessCamelCase. """ return ''.join([snake_string.split('_')[0]] + list(sub_string.capitalize() for sub_string in snake_string.split('_')[1:]))
[ "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. Args: snake_string: The string to be converted. Returns: The input string converted to headlessCamelCase.
[ "Convert", "snake_case", "to", "headlessCamelCase", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L290-L300
train
cloudendpoints/endpoints-python
endpoints/util.py
StartResponseProxy.Proxy
def Proxy(self, status, headers, exc_info=None): """Save args, defer start_response until response body is parsed. Create output buffer for body to be written into. Note: this is not quite WSGI compliant: The body should come back as an iterator returned from calling service_app() but instead, StartResponse returns a writer that will be later called to output the body. See google/appengine/ext/webapp/__init__.py::Response.wsgi_write() write = start_response('%d %s' % self.__status, self.__wsgi_headers) write(body) Args: status: Http status to be sent with this response headers: Http headers to be sent with this response exc_info: Exception info to be displayed for this response Returns: callable that takes as an argument the body content """ self.call_context['status'] = status self.call_context['headers'] = headers self.call_context['exc_info'] = exc_info return self.body_buffer.write
python
def Proxy(self, status, headers, exc_info=None): """Save args, defer start_response until response body is parsed. Create output buffer for body to be written into. Note: this is not quite WSGI compliant: The body should come back as an iterator returned from calling service_app() but instead, StartResponse returns a writer that will be later called to output the body. See google/appengine/ext/webapp/__init__.py::Response.wsgi_write() write = start_response('%d %s' % self.__status, self.__wsgi_headers) write(body) Args: status: Http status to be sent with this response headers: Http headers to be sent with this response exc_info: Exception info to be displayed for this response Returns: callable that takes as an argument the body content """ self.call_context['status'] = status self.call_context['headers'] = headers self.call_context['exc_info'] = exc_info return self.body_buffer.write
[ "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. Create output buffer for body to be written into. Note: this is not quite WSGI compliant: The body should come back as an iterator returned from calling service_app() but instead, StartResponse returns a writer that will be later called to output the body. See google/appengine/ext/webapp/__init__.py::Response.wsgi_write() write = start_response('%d %s' % self.__status, self.__wsgi_headers) write(body) Args: status: Http status to be sent with this response headers: Http headers to be sent with this response exc_info: Exception info to be displayed for this response Returns: callable that takes as an argument the body content
[ "Save", "args", "defer", "start_response", "until", "response", "body", "is", "parsed", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L44-L66
train
cloudendpoints/endpoints-python
endpoints/discovery_service.py
DiscoveryService._send_success_response
def _send_success_response(self, response, start_response): """Sends an HTTP 200 json success response. This calls start_response and returns the response body. Args: response: A string containing the response body to return. start_response: A function with semantics defined in PEP-333. Returns: A string, the response body. """ headers = [('Content-Type', 'application/json; charset=UTF-8')] return util.send_wsgi_response('200 OK', headers, response, start_response)
python
def _send_success_response(self, response, start_response): """Sends an HTTP 200 json success response. This calls start_response and returns the response body. Args: response: A string containing the response body to return. start_response: A function with semantics defined in PEP-333. Returns: A string, the response body. """ headers = [('Content-Type', 'application/json; charset=UTF-8')] return util.send_wsgi_response('200 OK', headers, response, start_response)
[ "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. This calls start_response and returns the response body. Args: response: A string containing the response body to return. start_response: A function with semantics defined in PEP-333. Returns: A string, the response body.
[ "Sends", "an", "HTTP", "200", "json", "success", "response", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_service.py#L82-L95
train
cloudendpoints/endpoints-python
endpoints/discovery_service.py
DiscoveryService._get_rest_doc
def _get_rest_doc(self, request, start_response): """Sends back HTTP response with API directory. This calls start_response and returns the response body. It will return the discovery doc for the requested api/version. Args: request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns: A string, the response body. """ 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)
python
def _get_rest_doc(self, request, start_response): """Sends back HTTP response with API directory. This calls start_response and returns the response body. It will return the discovery doc for the requested api/version. Args: request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns: A string, the response body. """ 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)
[ "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. This calls start_response and returns the response body. It will return the discovery doc for the requested api/version. Args: request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns: A string, the response body.
[ "Sends", "back", "HTTP", "response", "with", "API", "directory", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_service.py#L97-L122
train
cloudendpoints/endpoints-python
endpoints/discovery_service.py
DiscoveryService._generate_api_config_with_root
def _generate_api_config_with_root(self, request): """Generate an API config with a specific root hostname. This uses the backend object and the ApiConfigGenerator to create an API config specific to the hostname of the incoming request. This allows for flexible API configs for non-standard environments, such as localhost. Args: request: An ApiRequest, the transformed request sent to the Discovery API. Returns: A string representation of the generated API config. """ 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
python
def _generate_api_config_with_root(self, request): """Generate an API config with a specific root hostname. This uses the backend object and the ApiConfigGenerator to create an API config specific to the hostname of the incoming request. This allows for flexible API configs for non-standard environments, such as localhost. Args: request: An ApiRequest, the transformed request sent to the Discovery API. Returns: A string representation of the generated API config. """ 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
[ "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. This uses the backend object and the ApiConfigGenerator to create an API config specific to the hostname of the incoming request. This allows for flexible API configs for non-standard environments, such as localhost. Args: request: An ApiRequest, the transformed request sent to the Discovery API. Returns: A string representation of the generated API config.
[ "Generate", "an", "API", "config", "with", "a", "specific", "root", "hostname", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_service.py#L124-L158
train
cloudendpoints/endpoints-python
endpoints/discovery_service.py
DiscoveryService._list
def _list(self, request, start_response): """Sends HTTP response containing the API directory. This calls start_response and returns the response body. Args: request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body. """ 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)
python
def _list(self, request, start_response): """Sends HTTP response containing the API directory. This calls start_response and returns the response body. Args: request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body. """ 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)
[ "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. This calls start_response and returns the response body. Args: request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body.
[ "Sends", "HTTP", "response", "containing", "the", "API", "directory", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_service.py#L170-L193
train
cloudendpoints/endpoints-python
endpoints/discovery_service.py
DiscoveryService.handle_discovery_request
def handle_discovery_request(self, path, request, start_response): """Returns the result of a discovery service request. This calls start_response and returns the response body. Args: path: A string containing the API path (the portion of the path after /_ah/api/). request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns: The response body. Or returns False if the request wasn't handled by DiscoveryService. """ 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
python
def handle_discovery_request(self, path, request, start_response): """Returns the result of a discovery service request. This calls start_response and returns the response body. Args: path: A string containing the API path (the portion of the path after /_ah/api/). request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns: The response body. Or returns False if the request wasn't handled by DiscoveryService. """ 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
[ "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. This calls start_response and returns the response body. Args: path: A string containing the API path (the portion of the path after /_ah/api/). request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns: The response body. Or returns False if the request wasn't handled by DiscoveryService.
[ "Returns", "the", "result", "of", "a", "discovery", "service", "request", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_service.py#L195-L220
train
cloudendpoints/endpoints-python
endpoints/api_request.py
ApiRequest._process_req_body
def _process_req_body(self, body): """Process the body of the HTTP request. If the body is valid JSON, return the JSON as a dict. Else, convert the key=value format to a dict and return that. Args: body: The body of the HTTP request. """ try: return json.loads(body) except ValueError: return urlparse.parse_qs(body, keep_blank_values=True)
python
def _process_req_body(self, body): """Process the body of the HTTP request. If the body is valid JSON, return the JSON as a dict. Else, convert the key=value format to a dict and return that. Args: body: The body of the HTTP request. """ try: return json.loads(body) except ValueError: return urlparse.parse_qs(body, keep_blank_values=True)
[ "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. If the body is valid JSON, return the JSON as a dict. Else, convert the key=value format to a dict and return that. Args: body: The body of the HTTP request.
[ "Process", "the", "body", "of", "the", "HTTP", "request", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_request.py#L118-L130
train
cloudendpoints/endpoints-python
endpoints/api_request.py
ApiRequest._reconstruct_relative_url
def _reconstruct_relative_url(self, environ): """Reconstruct the relative URL of this request. This is based on the URL reconstruction code in Python PEP 333: http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the URL from the pieces available in the environment. Args: environ: An environ dict for the request as defined in PEP-333 Returns: The portion of the URL from the request after the server and port. """ 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
python
def _reconstruct_relative_url(self, environ): """Reconstruct the relative URL of this request. This is based on the URL reconstruction code in Python PEP 333: http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the URL from the pieces available in the environment. Args: environ: An environ dict for the request as defined in PEP-333 Returns: The portion of the URL from the request after the server and port. """ 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
[ "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. This is based on the URL reconstruction code in Python PEP 333: http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the URL from the pieces available in the environment. Args: environ: An environ dict for the request as defined in PEP-333 Returns: The portion of the URL from the request after the server and port.
[ "Reconstruct", "the", "relative", "URL", "of", "this", "request", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_request.py#L132-L149
train
cloudendpoints/endpoints-python
endpoints/api_request.py
ApiRequest.reconstruct_hostname
def reconstruct_hostname(self, port_override=None): """Reconstruct the hostname of a request. This is based on the URL reconstruction code in Python PEP 333: http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the hostname from the pieces available in the environment. Args: port_override: str, An override for the port on the returned hostname. Returns: The hostname portion of the URL from the request, not including the URL scheme. """ 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
python
def reconstruct_hostname(self, port_override=None): """Reconstruct the hostname of a request. This is based on the URL reconstruction code in Python PEP 333: http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the hostname from the pieces available in the environment. Args: port_override: str, An override for the port on the returned hostname. Returns: The hostname portion of the URL from the request, not including the URL scheme. """ 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
[ "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. This is based on the URL reconstruction code in Python PEP 333: http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the hostname from the pieces available in the environment. Args: port_override: str, An override for the port on the returned hostname. Returns: The hostname portion of the URL from the request, not including the URL scheme.
[ "Reconstruct", "the", "hostname", "of", "a", "request", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_request.py#L151-L171
train
cloudendpoints/endpoints-python
endpoints/api_request.py
ApiRequest.reconstruct_full_url
def reconstruct_full_url(self, port_override=None): """Reconstruct the full URL of a request. This is based on the URL reconstruction code in Python PEP 333: http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the hostname from the pieces available in the environment. Args: port_override: str, An override for the port on the returned full URL. Returns: The full URL from the request, including the URL scheme. """ return '{0}://{1}{2}'.format(self.url_scheme, self.reconstruct_hostname(port_override), self.relative_url)
python
def reconstruct_full_url(self, port_override=None): """Reconstruct the full URL of a request. This is based on the URL reconstruction code in Python PEP 333: http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the hostname from the pieces available in the environment. Args: port_override: str, An override for the port on the returned full URL. Returns: The full URL from the request, including the URL scheme. """ return '{0}://{1}{2}'.format(self.url_scheme, self.reconstruct_hostname(port_override), self.relative_url)
[ "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. This is based on the URL reconstruction code in Python PEP 333: http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the hostname from the pieces available in the environment. Args: port_override: str, An override for the port on the returned full URL. Returns: The full URL from the request, including the URL scheme.
[ "Reconstruct", "the", "full", "URL", "of", "a", "request", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_request.py#L173-L188
train
cloudendpoints/endpoints-python
endpoints/openapi_generator.py
OpenApiGenerator._construct_operation_id
def _construct_operation_id(self, service_name, protorpc_method_name): """Return an operation id for a service method. Args: service_name: The name of the service. protorpc_method_name: The ProtoRPC method name. Returns: A string representing the operation id. """ # 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)
python
def _construct_operation_id(self, service_name, protorpc_method_name): """Return an operation id for a service method. Args: service_name: The name of the service. protorpc_method_name: The ProtoRPC method name. Returns: A string representing the operation id. """ # 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)
[ "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. Args: service_name: The name of the service. protorpc_method_name: The ProtoRPC method name. Returns: A string representing the operation id.
[ "Return", "an", "operation", "id", "for", "a", "service", "method", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/openapi_generator.py#L113-L128
train
cloudendpoints/endpoints-python
endpoints/openapi_generator.py
OpenApiGenerator.__definitions_descriptor
def __definitions_descriptor(self): """Describes the definitions section of the OpenAPI spec. Returns: Dictionary describing the definitions of the spec. """ # 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
python
def __definitions_descriptor(self): """Describes the definitions section of the OpenAPI spec. Returns: Dictionary describing the definitions of the spec. """ # 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
[ "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. Returns: Dictionary describing the definitions of the spec.
[ "Describes", "the", "definitions", "section", "of", "the", "OpenAPI", "spec", "." ]
00dd7c7a52a9ee39d5923191c2604b8eafdb3f24
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/openapi_generator.py#L613-L647
train