Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def get_request_message(cls, remote_info): # pylint: disable=g-bad-name
if remote_info in cls.__remote_info_cache:
return cls.__remote_info_cache[remote_info]
else:
return remote_info.request_type() | [
"Gets request message or container from remote info.\n\n Args:\n remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding\n to a method.\n\n Returns:\n Either an instance of the request type from the remote or the\n ResourceContainer that was cached with the remote ... |
Please provide a description of the function:def get_current_user():
if not _is_auth_info_available():
raise InvalidGetUserCall('No valid endpoints user in environment.')
if _ENDPOINTS_USER_INFO in os.environ:
user_info = os.environ[_ENDPOINTS_USER_INFO]
return users.User(user_info.email)
if _ENV... | [
"Get user information from the id_token or oauth token in the request.\n\n This should only be called from within an Endpoints request handler,\n decorated with an @endpoints.method decorator. The decorator should include\n the https://www.googleapis.com/auth/userinfo.email scope.\n\n If `endpoints_management.... |
Please provide a description of the function:def _is_auth_info_available():
return (_ENDPOINTS_USER_INFO in os.environ or
(_ENV_AUTH_EMAIL in os.environ and _ENV_AUTH_DOMAIN in os.environ) or
_ENV_USE_OAUTH_SCOPE in os.environ) | [
"Check if user auth info has been set in environment variables."
] |
Please provide a description of the function:def _maybe_set_current_user_vars(method, api_info=None, request=None):
if _is_auth_info_available():
return
# By default, there's no user.
os.environ[_ENV_AUTH_EMAIL] = ''
os.environ[_ENV_AUTH_DOMAIN] = ''
# Choose settings on the method, if specified. Ot... | [
"Get user information from the id_token or oauth token in the request.\n\n Used internally by Endpoints to set up environment variables for user\n authentication.\n\n Args:\n method: The class method that's handling this request. This method\n should be annotated with @endpoints.method.\n api_info: A... |
Please provide a description of the function:def _get_token(
request=None, allowed_auth_schemes=('OAuth', 'Bearer'),
allowed_query_keys=('bearer_token', 'access_token')):
allowed_auth_schemes = _listlike_guard(
allowed_auth_schemes, 'allowed_auth_schemes', iterable_only=True)
# Check if the token i... | [
"Get the auth token for this request.\n\n Auth token may be specified in either the Authorization header or\n as a query param (either access_token or bearer_token). We'll check in\n this order:\n 1. Authorization header.\n 2. bearer_token query param.\n 3. access_token query param.\n\n Args:\n req... |
Please provide a description of the function:def _get_id_token_user(token, issuers, audiences, allowed_client_ids, time_now, cache):
# Verify that the token is valid before we try to extract anything from it.
# This verifies the signature and some of the basic info in the token.
for issuer_key, issuer in issue... | [
"Get a User for the given id token, if the token is valid.\n\n Args:\n token: The id_token to check.\n issuers: dict of Issuers\n audiences: List of audiences that are acceptable.\n allowed_client_ids: List of client IDs that are acceptable.\n time_now: The current time as a long (eg. long(time.time... |
Please provide a description of the function:def _process_scopes(scopes):
all_scopes = set()
sufficient_scopes = set()
for scope_set in scopes:
scope_set_scopes = frozenset(scope_set.split())
all_scopes.update(scope_set_scopes)
sufficient_scopes.add(scope_set_scopes)
return all_scopes, sufficient... | [
"Parse a scopes list into a set of all scopes and a set of sufficient scope sets.\n\n scopes: A list of strings, each of which is a space-separated list of scopes.\n Examples: ['scope1']\n ['scope1', 'scope2']\n ['scope1', 'scope2 scope3']\n\n Returns:\n all_scope... |
Please provide a description of the function:def _are_scopes_sufficient(authorized_scopes, sufficient_scopes):
for sufficient_scope_set in sufficient_scopes:
if sufficient_scope_set.issubset(authorized_scopes):
return True
return False | [
"Check if a list of authorized scopes satisfies any set of sufficient scopes.\n\n Args:\n authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes\n sufficient_scopes: a set of sets of strings, return value from _process_scopes\n "
] |
Please provide a description of the function:def _set_bearer_user_vars(allowed_client_ids, scopes):
all_scopes, sufficient_scopes = _process_scopes(scopes)
try:
authorized_scopes = oauth.get_authorized_scopes(sorted(all_scopes))
except oauth.Error:
_logger.debug('Unable to get authorized scopes.', exc_... | [
"Validate the oauth bearer token and set endpoints auth user variables.\n\n If the bearer token is valid, this sets ENDPOINTS_USE_OAUTH_SCOPE. This\n provides enough information that our endpoints.get_current_user() function\n can get the user.\n\n Args:\n allowed_client_ids: List of client IDs that are acc... |
Please provide a description of the function:def _set_bearer_user_vars_local(token, allowed_client_ids, scopes):
# Get token info from the tokeninfo endpoint.
result = urlfetch.fetch(
'%s?%s' % (_TOKENINFO_URL, urllib.urlencode({'access_token': token})))
if result.status_code != 200:
try:
error... | [
"Validate the oauth bearer token on the dev server.\n\n Since the functions in the oauth module return only example results in local\n development, this hits the tokeninfo endpoint and attempts to validate the\n token. If it's valid, we'll set _ENV_AUTH_EMAIL and _ENV_AUTH_DOMAIN so we\n can get the user from ... |
Please provide a description of the function:def _verify_parsed_token(parsed_token, issuers, audiences, allowed_client_ids, is_legacy_google_auth=True):
# Verify the issuer.
if parsed_token.get('iss') not in issuers:
_logger.warning('Issuer was not valid: %s', parsed_token.get('iss'))
return False
# C... | [
"Verify a parsed user ID token.\n\n Args:\n parsed_token: The parsed token information.\n issuers: A list of allowed issuers\n audiences: The allowed audiences.\n allowed_client_ids: The allowed client IDs.\n\n Returns:\n True if the token is verified, False otherwise.\n "
] |
Please provide a description of the function:def _get_cert_expiration_time(headers):
# Check the max age of the cert.
cache_control = headers.get('Cache-Control', '')
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 indicates only
# a comma-separated header is valid, so it should be fine to spl... | [
"Get the expiration time for a cert, given the response headers.\n\n Get expiration time from the headers in the result. If we can't get\n a time from the headers, this returns 0, indicating that the cert\n shouldn't be cached.\n\n Args:\n headers: A dict containing the response headers from the request to ... |
Please provide a description of the function:def _get_cached_certs(cert_uri, cache):
certs = cache.get(cert_uri, namespace=_CERT_NAMESPACE)
if certs is None:
_logger.debug('Cert cache miss for %s', cert_uri)
try:
result = urlfetch.fetch(cert_uri)
except AssertionError:
# This happens in u... | [
"Get certs from cache if present; otherwise, gets from URI and caches them.\n\n Args:\n cert_uri: URI from which to retrieve certs if cache is stale or empty.\n cache: Cache of pre-fetched certs.\n\n Returns:\n The retrieved certs.\n "
] |
Please provide a description of the function:def _verify_signed_jwt_with_certs(
jwt, time_now, cache,
cert_uri=_DEFAULT_CERT_URI):
segments = jwt.split('.')
if len(segments) != 3:
# Note that anywhere we print the jwt or its json body, we need to use
# %r instead of %s, so that non-printable ch... | [
"Verify a JWT against public certs.\n\n See http://self-issued.info/docs/draft-jones-json-web-token.html.\n\n The PyCrypto library included with Google App Engine is severely limited and\n so you have to use it very carefully to verify JWT signatures. The first\n issue is that the library can't read X.509 files... |
Please provide a description of the function:def convert_jwks_uri(jwks_uri):
if not jwks_uri.startswith(_TEXT_CERT_PREFIX):
return jwks_uri
return jwks_uri.replace(_TEXT_CERT_PREFIX, _JSON_CERT_PREFIX) | [
"\n The PyCrypto library included with Google App Engine is severely limited and\n can't read X.509 files, so we change the URI to a special URI that has the\n public cert in modulus/exponent form in JSON.\n "
] |
Please provide a description of the function: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 ... | [
"\n This function will extract, verify, and parse a JWT token from the\n Authorization header or access_token query argument.\n\n The JWT is assumed to contain an issuer and audience claim, as well\n as issued-at and expiration timestamps. The signature will be\n cryptographically verified, the claims and time... |
Please provide a description of the function:def _listlike_guard(obj, name, iterable_only=False, log_warning=True):
required_type = (_Iterable,) if iterable_only else (_Container, _Iterable)
required_type_name = ' or '.join(t.__name__ for t in required_type)
if not isinstance(obj, required_type):
raise Va... | [
"\n We frequently require passed objects to support iteration or\n containment expressions, but not be strings. (Of course, strings\n support iteration and containment, but not usefully.) If the passed\n object is a string, we'll wrap it in a tuple and return it. If it's\n already an iterable, we'll return it... |
Please provide a description of the function: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.... | [
"Builds an item descriptor for a service configuration.\n\n Args:\n config: A dictionary containing the service configuration to describe.\n\n Returns:\n A dictionary that describes the service configuration.\n "
] |
Please provide a description of the function: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_descript... | [
"Builds a directory list for an API.\n\n Args:\n configs: List of dicts containing the service configurations to list.\n\n Returns:\n A dictionary that can be deserialized into JSON in discovery list format.\n\n Raises:\n ApiConfigurationError: If there's something wrong with the API\n ... |
Please provide a description of the function: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.\n\n Args:\n configs: Either a single dict or a list of dicts containing the service\n configurations to list.\n\n Returns:\n dict, The directory list document as a JSON dict.\n "
] |
Please provide a description of the function: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.\n\n Args:\n configs: Either a single dict or a list of dicts containing the service\n configurations to list.\n\n Returns:\n string, The directory list document as a JSON string.\n "
] |
Please provide a description of the function: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],
... | [
"Format this error into a JSON response.\n\n Args:\n error_list_tag: A string specifying the name of the tag to use for the\n error list.\n\n Returns:\n A dict containing the reformatted JSON error response.\n "
] |
Please provide a description of the function: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.\n\n Returns:\n A string containing the reformatted error response.\n "
] |
Please provide a description of the function: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.\n\n Args:\n http_status: A string containing a HTTP status code and reason.\n\n Returns:\n An integer with the status code number from http_status.\n "
] |
Please provide a description of the function: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] ... | [
"Parses a JSON API config and registers methods for dispatch.\n\n Side effects:\n Parses method name, etc. for all methods and updates the indexing\n data structures with the information.\n\n Args:\n config_json: A dict, the JSON body of the getApiConfigs response.\n "
] |
Please provide a description of the function: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):
def _score_path(path):
score = 0
... | [
"Get a copy of 'methods' sorted the way they would be on the live server.\n\n Args:\n methods: JSON configuration of an API's methods.\n\n Returns:\n The same configuration with the methods sorted based on what order\n they'll be checked by the server.\n ",
"Sort method info by path and ht... |
Please provide a description of the function: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.\n\n Args:\n match: A regular expression Match object for a path.\n\n Returns:\n A dictionary containing the variable names converted from base64.\n "
] |
Please provide a description of the function: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
c... | [
"Look up the rest method at call time.\n\n The method is looked up in self._rest_methods, the list it is saved\n in for SaveRestMethod.\n\n Args:\n path: A string containing the path from the URL of the request.\n http_method: A string containing HTTP method of the request.\n\n Returns:\n ... |
Please provide a description of the function: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.\n\n This should only be called with self._config_lock. The code here assumes\n the lock is held.\n "
] |
Please provide a description of the function:def save_config(self, lookup_key, config):
with self._config_lock:
self._configs[lookup_key] = config | [
"Save a configuration to the cache of configs.\n\n Args:\n lookup_key: A string containing the cache lookup key.\n config: The dict containing the configuration to save to the cache.\n "
] |
Please provide a description of the function: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_para... | [
"Takes a safe regex group name and converts it back to the original value.\n\n Only alphanumeric characters and underscore are allowed in variable name\n tokens, and numeric are not allowed as the first character.\n\n The safe_parameter is a base32 representation of the actual value.\n\n Args:\n sa... |
Please provide a description of the function:def _compile_path_pattern(pattern):
r
def replace_variable(match):
if match.lastindex > 1:
var_name = ApiConfigManager._to_safe_path_param_name(match.group(2))
return '%s(?P<%s>%s)' % (match.group(1), var_name,
... | [
"Generates a compiled regex pattern for a path pattern.\n\n e.g. '/MyApi/v1/notes/{id}'\n returns re.compile(r'/MyApi/v1/notes/(?P<id>[^/?#\\[\\]{}]*)')\n\n Args:\n pattern: A string, the parameterized path pattern to be checked.\n\n Returns:\n A compiled regex object to match this path patter... |
Please provide a description of the function: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_pat... | [
"Store Rest api methods in a list for lookup at call time.\n\n The list is self._rest_methods, a list of tuples:\n [(<compiled_path>, <path_pattern>, <method_dict>), ...]\n where:\n <compiled_path> is a compiled regex to match against the incoming URL\n <path_pattern> is a string representing t... |
Please provide a description of the function: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 . impor... | [
"Create an api_server.\n\n The primary function of this method is to set up the WSGIApplication\n instance for the service handlers described by the services passed in.\n Additionally, it registers each API in ApiConfigRegistry for later use\n in the BackendService.getApiConfigs() (API config enumeration servic... |
Please provide a description of the function: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.\n\n Args:\n config_contents: Dict containing API configuration.\n "
] |
Please provide a description of the function: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():
ro... | [
"Register the class implementing this config, so we only add it once.\n\n Args:\n parsed_config: The JSON object with the API configuration being added.\n\n Raises:\n ApiConfigurationError: If the class has already been registered.\n "
] |
Please provide a description of the function: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.\n\n Methods are stored in a map from method_name to rosyMethod,\n the name of the ProtoRPC method to be called on the backend.\n If no rosyMethod was specified the value will be None.\n\n Args:\n parsed_config: The JSON object with the API confi... |
Please provide a description of the function:def __create_name_version_map(api_services):
api_name_version_map = {}
for service_factory in api_services:
try:
service_class = service_factory.service_class
except AttributeError:
service_class = service_factory
service_fact... | [
"Create a map from API name/version to Service class/factory.\n\n This creates a map from an API name and version to a list of remote.Service\n factories that implement that API.\n\n Args:\n api_services: A list of remote.Service-derived classes or factories\n created with remote.Service.new_fa... |
Please provide a description of the function: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
... | [
"Register & return a list of each URL and class that handles that URL.\n\n This finds every service class in api_name_version_map, registers it with\n the given ApiConfigRegistry, builds the URL for that class, and adds\n the URL and its factory to a list that's returned.\n\n Args:\n api_name_versi... |
Please provide a description of the function: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.\n\n Args:\n status: HTTP status code.\n headers: Dictionary of (lowercase) header name to value.\n\n Returns:\n True if the response was an error, else False.\n "
] |
Please provide a description of the function: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=Endpoints... | [
"Return the HTTP status line and body for a given error code and message.\n\n Args:\n status_code: HTTP status code to be returned.\n error_message: Error message to be returned.\n\n Returns:\n Tuple (http_status, body):\n http_status: HTTP status line, e.g. 200 OK.\n body: Body o... |
Please provide a description of the function: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.St... | [
"Convert a ProtoRPC error to the format expected by Google Endpoints.\n\n If the body does not contain an ProtoRPC message in state APPLICATION_ERROR\n the status and body will be returned unchanged.\n\n Args:\n status: HTTP status of the response from the backend\n body: JSON-encoded error in fo... |
Please provide a description of the 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.\n\n Args:\n path_regex: A string regex, the path to match against incoming requests.\n dispatch_function: The function to call for these requests. The function\n should take (request, start_response) as arguments and\n return the contents of the ... |
Please provide a description of the function: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... | [
"Handles dispatch to apiserver handlers.\n\n This typically ends up calling start_response and returning the entire\n body of the response.\n\n Args:\n request: An ApiRequest, the request from the user.\n start_response: A function with semantics defined in PEP-333.\n\n Returns:\n A str... |
Please provide a description of the function: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':... | [
"Dispatch this request if this is a request to a reserved URL.\n\n If the request matches one of our reserved URLs, this calls\n start_response and returns the response body. This also handles OPTIONS\n CORS requests.\n\n Args:\n request: An ApiRequest, the request from the user.\n start_resp... |
Please provide a description of the function:def handle_api_explorer_request(self, request, start_response):
redirect_url = self._get_explorer_redirect_url(
request.server, request.port, request.base_path)
return util.send_wsgi_redirect_response(redirect_url, start_response) | [
"Handler for requests to {base_path}/explorer.\n\n This calls start_response and returns the response body.\n\n Args:\n request: An ApiRequest, the request from the user.\n start_response: A function with semantics defined in PEP-333.\n\n Returns:\n A string containing the response body (whi... |
Please provide a description of the function:def handle_api_static_request(self, request, start_response):
if request.path == PROXY_PATH:
return util.send_wsgi_response('200 OK',
[('Content-Type',
'text/html')],
... | [
"Handler for requests to {base_path}/static/.*.\n\n This calls start_response and returns the response body.\n\n Args:\n request: An ApiRequest, the request from the user.\n start_response: A function with semantics defined in PEP-333.\n\n Returns:\n A string containing the response body.\n ... |
Please provide a description of the function: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... | [
"Verifies that a response has the expected status and content type.\n\n Args:\n response: The ResponseTuple to be checked.\n status_code: An int, the HTTP status code to be compared with response\n status.\n content_type: A string with the acceptable Content-Type header value.\n None... |
Please provide a description of the function: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 = '%... | [
"Build an environ object for the backend to consume.\n\n Args:\n host: A string containing the host serving the request.\n method: A string containing the HTTP method of the request.\n relative_url: A string containing path and query string of the request.\n headers: A list of (key, value) tu... |
Please provide a description of the function:def call_backend(self, orig_request, start_response):
method_config, params = self.lookup_rest_method(orig_request)
if not method_config:
cors_handler = self._create_cors_handler(orig_request)
return util.send_wsgi_not_found_response(start_response,
... | [
"Generate API call (from earlier-saved request).\n\n This calls start_response and returns the response body.\n\n Args:\n orig_request: An ApiRequest, the original request from the user.\n start_response: A function with semantics defined in PEP-333.\n\n Returns:\n A string containing the re... |
Please provide a description of the function: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... | [
"Handle backend response, transforming output as needed.\n\n This calls start_response and returns the response body.\n\n Args:\n orig_request: An ApiRequest, the original request from the user.\n backend_request: An ApiRequest, the transformed request that was\n sent to the ba... |
Please provide a description of the function: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.\n\n This calls start_response and returns the error body.\n\n Args:\n orig_request: An ApiRequest, the original request from the user.\n message: A string containing the error message to be displayed to user.\n start_response: A func... |
Please provide a description of the function: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.\n\n Args:\n orig_request: An ApiRequest, the original request from the user.\n\n Returns:\n A tuple of (method descriptor, parameters), or (None, None) if no method\n was found for the current request.\n "
] |
Please provide a description of the function: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',... | [
"Transforms orig_request to apiserving request.\n\n This method uses orig_request to determine the currently-pending request\n and returns a new transformed request ready to send to the backend. This\n method accepts a rest-style or RPC-style request.\n\n Args:\n orig_request: An ApiRequest, the o... |
Please provide a description of the function: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... | [
"Converts a . delimitied field name to a message field in parameters.\n\n This adds the field to the params dict, broken out so that message\n parameters appear as sub-dicts within the outer param.\n\n For example:\n {'a.b.c': ['foo']}\n becomes:\n {'a': {'b': {'c': ['foo']}}}\n\n Args:\n ... |
Please provide a description of the function: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)
... | [
"Updates the dictionary for an API payload with the request body.\n\n The values from the body should override those already in the payload, but\n for nested fields (message objects) the values can be combined\n recursively.\n\n Args:\n destination: A dictionary containing an API payload parsed fro... |
Please provide a description of the function: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 que... | [
"Translates a Rest request into an apiserving request.\n\n This makes a copy of orig_request and transforms it to apiserving\n format (moving request parameters to the body).\n\n The request can receive values from the path, query and body and combine\n them before sending them along to the backend. In ... |
Please provide a description of the function: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.\n\n Args:\n body: A string containing the backend response body.\n status: A string containing the backend response status.\n\n Raises:\n BackendError if the response is an error.\n "
] |
Please provide a description of the function: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.
# No... | [
"If the response from the backend is empty, return a HTTP 204 No Content.\n\n Args:\n orig_request: An ApiRequest, the original request from the user.\n method_config: A dict, the API config of the method to be called.\n start_response: A function with semantics defined in PEP-333.\n\n Returns:... |
Please provide a description of the function: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.\n\n Currently, the only thing that needs to be fixed here is indentation,\n so it's consistent with what the live app will return.\n\n Args:\n response_body: A string containing the backend response.\n\n Returns:\n A reformatted ... |
Please provide a description of the function: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,
... | [
"Handle a request error, converting it to a WSGI response.\n\n Args:\n orig_request: An ApiRequest, the original request from the user.\n error: A RequestError containing information about the error.\n start_response: A function with semantics defined in PEP-333.\n\n Returns:\n A string co... |
Please provide a description of the function: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.\n\n Args:\n output_path: The directory to store the file in.\n name: The name of the file to store the content in.\n content: The content to write to the file.close\n\n Returns:\n The full path to the written file.\n "
] |
Please provide a description of the function: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 class... | [
"Write an API configuration for endpoints annotated ProtoRPC services.\n\n Args:\n service_class_names: A list of fully qualified ProtoRPC service classes.\n config_string_generator: A generator object that produces API config strings\n using its pretty_print_config_to_json method.\n hostname: A stri... |
Please provide a description of the function: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
app... | [
"Build the hostname for this app based on the name in app.yaml.\n\n Args:\n application_path: A string with the path to the AppEngine application. This\n should be the directory containing the app.yaml file.\n open_func: Function to call to open a file. Used to override the default\n open functio... |
Please provide a description of the function: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=discov... | [
"Write discovery documents generated from the service classes to file.\n\n Args:\n service_class_names: A list of fully qualified ProtoRPC service names.\n output_path: The directory to output the discovery docs to.\n hostname: A string hostname which will be used as the default version\n hostname. I... |
Please provide a description of the function: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=open... | [
"Write openapi documents generated from the service classes to file.\n\n Args:\n service_class_names: A list of fully qualified ProtoRPC service names.\n output_path: The directory to which to output the OpenAPI specs.\n hostname: A string hostname which will be used as the default version\n hostname... |
Please provide a description of the function:def _GenClientLib(discovery_path, language, output_path, build_system):
with open(discovery_path) as f:
discovery_doc = f.read()
client_name = re.sub(r'\.discovery$', '.zip',
os.path.basename(discovery_path))
return _GenClientLibFromCont... | [
"Write a client library from a discovery doc.\n\n Args:\n discovery_path: Path to the discovery doc used to generate the client\n library.\n language: The client library language to generate. (java)\n output_path: The directory to output the client library zip to.\n build_system: The target build ... |
Please provide a description of the function:def _GenClientLibFromContents(discovery_doc, language, output_path,
build_system, client_name):
body = urllib.urlencode({'lang': language, 'content': discovery_doc,
'layout': build_system})
request = urllib2.Re... | [
"Write a client library from a discovery doc.\n\n Args:\n discovery_doc: A string, the contents of the discovery doc used to\n generate the client library.\n language: A string, the client library language to generate. (java)\n output_path: A string, the directory to output the client library zip to.... |
Please provide a description of the function: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_... | [
"Fetch client libraries from a cloud service.\n\n Args:\n service_class_names: A list of fully qualified ProtoRPC service names.\n language: The client library language to generate. (java)\n output_path: The directory to output the discovery docs to.\n build_system: The target build system for the clie... |
Please provide a description of the function: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.iteri... | [
"Generate an api file.\n\n Args:\n args: An argparse.Namespace object to extract parameters from.\n api_func: A function that generates and returns an API configuration\n for a list of services.\n "
] |
Please provide a description of the function: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... | [
"Generate discovery docs and client libraries to files.\n\n Args:\n args: An argparse.Namespace object to extract parameters from.\n client_func: A function that generates client libraries and stores them to\n files, accepting a list of service names, a client library language,\n an output director... |
Please provide a description of the function:def _GenDiscoveryDocCallback(args, discovery_func=_GenDiscoveryDoc):
discovery_paths = discovery_func(args.service, args.output,
hostname=args.hostname,
application_path=args.application)
for discov... | [
"Generate discovery docs to files.\n\n Args:\n args: An argparse.Namespace object to extract parameters from\n discovery_func: A function that generates discovery docs and stores them to\n files, accepting a list of service names, a discovery doc format, and an\n output directory.\n "
] |
Please provide a description of the function:def _GenOpenApiSpecCallback(args, openapi_func=_GenOpenApiSpec):
openapi_paths = openapi_func(args.service, args.output,
hostname=args.hostname,
application_path=args.application,
... | [
"Generate OpenAPI (Swagger) specs to files.\n\n Args:\n args: An argparse.Namespace object to extract parameters from\n openapi_func: A function that generates OpenAPI specs and stores them to\n files, accepting a list of service names and an output directory.\n "
] |
Please provide a description of the function: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.\n\n Args:\n args: An argparse.Namespace object to extract parameters from\n client_func: A function that generates client libraries and stores them to\n files, accepting a path to a discovery doc, a client library language, an\n output directory, and a build syst... |
Please provide a description of the function:def MakeParser(prog):
def AddStandardOptions(parser, *args):
if 'application' in args:
parser.add_argument('-a', '--application', default='.',
help='The path to the Python App Engine App')
if 'format' in args:
# This u... | [
"Create an argument parser.\n\n Args:\n prog: The name of the program to use when outputting help text.\n\n Returns:\n An argparse.ArgumentParser built to specification.\n ",
"Add common endpoints options to a parser.\n\n Args:\n parser: The parser to add options to.\n *args: A list of optio... |
Please provide a description of the function: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 the... | [
"Override superclass to support customized error message.\n\n Error message needs to be rewritten in order to display visible commands\n only, when invalid command is called by user. Otherwise, hidden commands\n will be displayed in stderr, which is not expected.\n\n Refer the following argparse python ... |
Please provide a description of the function: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:
... | [
"Sets up the sys.path with special directories for endpointscfg.py."
] |
Please provide a description of the function: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.\n\n Args:\n docstring: Docstring for the generated enum class.\n *names: Enum names.\n\n Returns:\n A class that contains enum names as attributes.\n "
] |
Please provide a description of the function: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.\n\n Args:\n value: The object whose type is to be checked.\n check_type: The type that the object must be an instance of.\n name: Name of the object, to be placed in any error messages.\n allow_none: True if value can be None, false if not.\n\n Raises:\... |
Please provide a description of the function: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, ... | [
"Decorate a ProtoRPC Service class for use by the framework above.\n\n This decorator can be used to specify an API name, version, description, and\n hostname for your API.\n\n Sample usage (python 2.7):\n @endpoints.api(name='guestbook', version='v0.2',\n description='Guestbook API')\n c... |
Please provide a description of the function: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,
... | [
"Decorate a ProtoRPC Method for use by the framework above.\n\n This decorator can be used to specify a method name, path, http method,\n scopes, audiences, client ids and auth_level.\n\n Sample usage:\n @api_config.method(RequestMessage, ResponseMessage,\n name='insert', http_method='PU... |
Please provide a description of the function: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."
] |
Please provide a description of the function: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_a... | [
"Get a decorator for a class that implements an API.\n\n This can be used for single-class or multi-class implementations. It's\n used implicitly in simple single-class APIs that only use @api directly.\n\n Args:\n resource_name: string, Resource name for the class this decorates.\n (Default: ... |
Please provide a description of the function: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... | [
"Restrict method name to a-zA-Z0-9_, first char lowercase."
] |
Please provide a description of the function:def get_path(self, api_info):
path = self.__path or ''
if path and path[0] == '/':
# Absolute path, ignoring any prefixes. Just strip off the leading /.
path = path[1:]
else:
# Relative path.
if api_info.path:
path = '%s%s%s'... | [
"Get the path portion of the URL to the method (for RESTful methods).\n\n Request path can be specified in the method, and it could have a base\n path prepended to it.\n\n Args:\n api_info: API information for this API, possibly including a base path.\n This is the api_info property on the clas... |
Please provide a description of the function: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:
... | [
"Computed method name."
] |
Please provide a description of the function: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)... | [
"Fully describes data represented by field, including the nested case.\n\n In the case that the field is not a message field, we have no fields nested\n within a message definition, so we can simply return that field. However, in\n the nested case, we can't simply describe the data with one field or even\n... |
Please provide a description of the function: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.')
... | [
"Converts the field variant type into a string describing the parameter.\n\n Args:\n field: An instance of a subclass of messages.Field.\n\n Returns:\n A string corresponding to the variant enum of the field, with a few\n exceptions. In the case of signed ints, the 's' is dropped; for the BOO... |
Please provide a description of the function: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, []... | [
"Parses path paremeters from a URI path and organizes them by parameter.\n\n Some of the parameters may correspond to message fields, and so will be\n represented as segments corresponding to each subfield; e.g. first.second if\n the field \"second\" in the message field \"first\" is pulled from the path.\... |
Please provide a description of the function: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, mes... | [
"Verifies that a proposed subfield actually exists and is a simple field.\n\n Here, simple means it is not a MessageField (nested).\n\n Args:\n parameter: String; the '.' delimited name of the current field being\n considered. This is relative to some root.\n field: An instance of a subclas... |
Please provide a description of the function: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.'
% (para... | [
"Verifies that all path parameters correspond to an existing subfield.\n\n Args:\n field: An instance of a subclass of messages.Field. Should be the root\n level property name in each path parameter in path_parameters. For\n example, if the field is called 'foo', then each path parameter s... |
Please provide a description of the function: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.\n\n If this subfield comes from a field list returned from __field_to_subfields,\n none of the fields in the subfield list can have a default except the final\n one since they all must be message fields.\n\n Args:\n final_subfield: A simple fi... |
Please provide a description of the function: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 en... | [
"Returns enum descriptor of final subfield if it is an enum.\n\n An enum descriptor is a dictionary with keys as the names from the enum and\n each value is a dictionary with a single key \"backendValue\" and value equal\n to the same enum name used to stored it in the descriptor.\n\n The key \"descript... |
Please provide a description of the function: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... | [
"Creates descriptor for a parameter using the subfields that define it.\n\n Each parameter is defined by a list of fields, with all but the last being\n a message field and the final being a simple (non-message) field.\n\n Many of the fields in the descriptor are determined solely by the simple\n field ... |
Please provide a description of the function:def __add_parameters_from_field(self, field, path_parameters,
params, param_order):
for subfield_list in self.__field_to_subfields(field):
descriptor = self.__parameter_descriptor(subfield_list)
qualified_name = '.'.joi... | [
"Adds all parameters in a field to a method parameters descriptor.\n\n Simple fields will only have one parameter, but a message field 'x' that\n corresponds to a message class with fields 'y' and 'z' will result in\n parameters 'x.y' and 'x.z', for example. The mapping from field to\n parameters is mos... |
Please provide a description of the function:def __params_descriptor(self, message_type, request_kind, path, method_id):
path_parameter_dict = self.__get_path_parameters(path)
if not isinstance(message_type, resource_container.ResourceContainer):
if path_parameter_dict:
_logger.warning('Meth... | [
"Describe the parameters of a method.\n\n If the message_type is not a ResourceContainer, will fall back to\n __params_descriptor_without_container (which will eventually be deprecated).\n\n If the message type is a ResourceContainer, then all path/query parameters\n will come from the ResourceContainer... |
Please provide a description of the function:def __request_message_descriptor(self, request_kind, message_type, method_id,
path):
descriptor = {}
params, param_order = self.__params_descriptor(message_type, request_kind,
... | [
"Describes the parameters and body of the request.\n\n Args:\n request_kind: The type of request being made.\n message_type: messages.Message or ResourceContainer class. The message to\n describe.\n method_id: string, Unique method identifier (e.g. 'myapi.items.method')\n path: strin... |
Please provide a description of the function:def __method_descriptor(self, service, method_info,
rosy_method, protorpc_method_info):
descriptor = {}
request_message_type = (resource_container.ResourceContainer.
get_request_message(protorpc_method_info.... | [
"Describes a method.\n\n Args:\n service: endpoints.Service, Implementation of the API as a service.\n method_info: _MethodInfo, Configuration for the method.\n rosy_method: string, ProtoRPC method name prefixed with the\n name of the service.\n protorpc_method_info: protorpc.remote._R... |
Please provide a description of the function: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_... | [
"Descriptor for the all the JSON Schema used.\n\n Args:\n services: List of protorpc.remote.Service instances implementing an\n api/version.\n\n Returns:\n Dictionary containing all the JSON Schema used in the service.\n "
] |
Please provide a description of the function:def __get_merged_api_info(self, services):
merged_api_info = services[0].api_info
# Verify that, if there are multiple classes here, they're allowed to
# implement the same API.
for service in services[1:]:
if not merged_api_info.is_same_api(servi... | [
"Builds a description of an API.\n\n Args:\n services: List of protorpc.remote.Service instances implementing an\n api/version.\n\n Returns:\n The _ApiInfo object to use for the API that the given services implement.\n\n Raises:\n ApiConfigurationError: If there's something wrong with... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.