Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function: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_r...
[ "Builds an auth descriptor from API info.\n\n Args:\n api_info: An _ApiInfo object.\n\n Returns:\n A dictionary with 'allowCookieAuth' and/or 'blockedRegions' keys.\n " ]
Please provide a description of the function: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', 'unregis...
[ "Builds a frontend limit descriptor from API info.\n\n Args:\n api_info: An _ApiInfo object.\n\n Returns:\n A dictionary with frontend limit information.\n " ]
Please provide a description of the function: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'), ...
[ "Builds a frontend limit rules descriptor from API info.\n\n Args:\n api_info: An _ApiInfo object.\n\n Returns:\n A list of dictionaries with frontend limit rules information.\n " ]
Please provide a description of the function:def __api_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_i...
[ "Builds a description of an API.\n\n Args:\n services: List of protorpc.remote.Service instances implementing an\n api/version.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults to None.\n\n Returns:\n A dictionary that can be de...
Please provide a description of the function:def get_descriptor_defaults(self, api_info, hostname=None): hostname = (hostname or endpoints_util.get_app_hostname() or api_info.hostname) protocol = 'http' if ((hostname and hostname.startswith('localhost')) or endpoin...
[ "Gets a default configuration for a service.\n\n Args:\n api_info: _ApiInfo object for this service.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults to None.\n\n Returns:\n A dictionary with the default configuration.\n " ]
Please provide a description of the function: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. # pyl...
[ "JSON dict description of a protorpc.remote.Service in API format.\n\n Args:\n services: Either a single protorpc.remote.Service or a list of them\n that implements an api/version.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults to Non...
Please provide a description of the function: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.\n\n Args:\n services: Either a single protorpc.remote.Service or a list of them\n that implements an api/version.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults to N...
Please provide a description of the function:def __field_to_parameter_type_and_format(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 cannot be used in a param...
[ "Converts the field variant type into a tuple describing the parameter.\n\n Args:\n field: An instance of a subclass of messages.Field.\n\n Returns:\n A tuple with the type and format of the field, respectively.\n\n Raises:\n TypeError: if the field variant is a message variant.\n " ]
Please provide a description of the function:def __parameter_default(self, field): if field.default: if isinstance(field, messages.EnumField): return field.default.name elif isinstance(field, messages.BooleanField): # The Python standard representation of a boolean value causes prob...
[ "Returns default value of field if it has one.\n\n Args:\n field: A simple field.\n\n Returns:\n The default value of the field, if any exists, with the exception of an\n enum field, which will have its value cast to a string.\n " ]
Please provide a description of the function: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.\n\n An enum descriptor is a list of keys.\n\n Args:\n param: A simple field.\n\n Returns:\n The enum descriptor for the field, if it's an enum descriptor, else\n returns None.\n " ]
Please provide a description of the function:def __parameter_descriptor(self, param): descriptor = {} param_type, param_format = self.__field_to_parameter_type_and_format(param) # Required if param.required: descriptor['required'] = True # Type descriptor['type'] = param_type ...
[ "Creates descriptor for a parameter.\n\n Args:\n param: The parameter to be described.\n\n Returns:\n Dictionary containing a descriptor for the parameter.\n " ]
Please provide a description of the function:def __add_parameter(self, param, path_parameters, params): # If this is a simple field, just build the descriptor and append it. # Otherwise, build a schema and assign it to this descriptor descriptor = None if not isinstance(param, messages.MessageField...
[ "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_without_container(self, message_type, request_kind, path): params = {} path_parameter_dict = self.__get_path_parameters(path) for field in sorted(message_type.all_fields(), key=lambda f: f....
[ "Describe parameters of a method which does not use a ResourceContainer.\n\n Makes sure that the path parameters are included in the message definition\n and adds any required fields and URL query parameters.\n\n This method is to preserve backwards compatibility and will be removed in\n a future releas...
Please provide a description of the function:def __params_descriptor(self, message_type, request_kind, path, method_id, request_params_class): path_parameter_dict = self.__get_path_parameters(path) if request_params_class is None: if path_parameter_dict: _logger.war...
[ "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 __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): match...
[ "Describe the order of path parameters.\n\n Args:\n message_type: messages.Message class, Message with parameters to describe.\n path: string, HTTP path to method.\n is_params_class: boolean, Whether the message represents URL parameters.\n\n Returns:\n Descriptor list for the parameter or...
Please provide a description of the function: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 specia...
[ "Describes the schemas section of the discovery document.\n\n Returns:\n Dictionary describing the schemas of the document.\n " ]
Please provide a description of the function:def __request_message_descriptor(self, request_kind, message_type, method_id, request_body_class): if request_body_class: message_type = request_body_class if (request_kind != self.__NO_BODY and message_type != m...
[ "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 request_bod...
Please provide a description of the function:def __method_descriptor(self, service, method_info, protorpc_method_info): descriptor = {} request_message_type = (resource_container.ResourceContainer. get_request_message(protorpc_method_info.remote)) ...
[ "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 protorpc_method_info: protorpc.remote._RemoteMethodInfo, ProtoRPC\n description of the method.\n\n Returns:\n Dictionary d...
Please provide a description of the function: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 ...
[ "Describes a resource.\n\n Args:\n resource_path: string, the path of the resource (e.g., 'entries.items')\n methods: list of tuples of type\n (endpoints.Service, protorpc.remote._RemoteMethodInfo), the methods\n that serve this resource.\n\n Returns:\n Dictionary describing the r...
Please provide a description of the function:def __get_merged_api_info(self, services): base_paths = sorted(set(s.api_info.base_path for s in services)) if len(base_paths) != 1: raise api_exceptions.ApiConfigurationError( 'Multiple base_paths found: {!r}'.format(base_paths)) names_versi...
[ "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 " ]
Please provide a description of the function: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 = m...
[ "Builds a discovery doc for an API.\n\n Args:\n services: List of protorpc.remote.Service instances implementing an\n api/version.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults to None.\n\n Returns:\n A dictionary that can be...
Please provide a description of the function:def get_descriptor_defaults(self, api_info, hostname=None): if self.__request: hostname = self.__request.reconstruct_hostname() protocol = self.__request.url_scheme else: hostname = (hostname or util.get_app_hostname() or api_...
[ "Gets a default configuration for a service.\n\n Args:\n api_info: _ApiInfo object for this service.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults to None.\n\n Returns:\n A dictionary with the default configuration.\n " ]
Please provide a description of the function: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. #...
[ "JSON dict description of a protorpc.remote.Service in discovery format.\n\n Args:\n services: Either a single protorpc.remote.Service or a list of them\n that implements an api/version.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults ...
Please provide a description of the function: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) ...
[ "Dump reformatted response to CGI start_response.\n\n This calls start_response and returns the response body.\n\n Args:\n status: A string containing the HTTP status code to send.\n headers: A list of (header, value) tuples, the headers to send in the\n response.\n content: A string containing the ...
Please provide a description of the function: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_'. ...
[ "Get a wsgiref.headers.Headers object with headers from the environment.\n\n Headers in environ are prefixed with 'HTTP_', are all uppercase, and have\n had dashes replaced with underscores. This strips the HTTP_ prefix and\n changes underscores back to dashes before adding them to the returned set\n of header...
Please provide a description of the function: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.\n\n This converts headers to uppercase, prefixes them with 'HTTP_', and\n converts dashes to underscores before adding them to the environ dict.\n\n Args:\n headers: A list of (header, value) tuples. The HTTP headers to add to the\n envir...
Please provide a description of the function: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 ...
[ "Returns the hostname prefix of a running Endpoints service.\n\n The prefix is the portion of the hostname that comes before the API name.\n For example, if a non-default version and a non-default service are in use,\n the returned result would be '{VERSION}-dot-{SERVICE}-'.\n\n Returns:\n str, the hostname ...
Please provide a description of the function: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_n...
[ "Return hostname of a running Endpoints service.\n\n Returns hostname of an running Endpoints API. It can be 1) \"localhost:PORT\"\n if running on development server, or 2) \"app_id.appspot.com\" if running on\n external app engine prod, or \"app_id.googleplex.com\" if running as Google\n first-party Endpoints ...
Please provide a description of the function: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...
[ "Verify that objects in list are of the allowed type or raise TypeError.\n\n Args:\n objects: The list of objects to check.\n allowed_type: The allowed type of items in 'settings'.\n name: Name of the list of objects, added to the exception.\n allow_none: If set, None is also allowed.\n\n Raises:\n ...
Please provide a description of the function: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.\n\n Args:\n snake_string: The string to be converted.\n Returns:\n The input string converted to headlessCamelCase.\n " ]
Please provide a description of the function: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.\n\n Create output buffer for body to be written into.\n Note: this is not quite WSGI compliant: The body should come back as an\n iterator returned from calling service_app() but instead, StartResponse\n returns a writer that will be la...
Please provide a description of the function: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.\n\n This calls start_response and returns the response body.\n\n Args:\n response: A string containing the response body to return.\n start_response: A function with semantics defined in PEP-333.\n\n Returns:\n A string, the response body.\n " ]
Please provide a description of the function: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 ...
[ "Sends back HTTP response with API directory.\n\n This calls start_response and returns the response body. It will return\n the discovery doc for the requested api/version.\n\n Args:\n request: An ApiRequest, the transformed request sent to the Discovery API.\n start_response: A function with se...
Please provide a description of the function: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...
[ "Generate an API config with a specific root hostname.\n\n This uses the backend object and the ApiConfigGenerator to create an API\n config specific to the hostname of the incoming request. This allows for\n flexible API configs for non-standard environments, such as localhost.\n\n Args:\n request...
Please provide a description of the function: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) direct...
[ "Sends HTTP response containing the API directory.\n\n This calls start_response and returns the response body.\n\n Args:\n request: An ApiRequest, the transformed request sent to the Discovery API.\n start_response: A function with semantics defined in PEP-333.\n\n Returns:\n A string conta...
Please provide a description of the function: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 '...
[ "Returns the result of a discovery service request.\n\n This calls start_response and returns the response body.\n\n Args:\n path: A string containing the API path (the portion of the path\n after /_ah/api/).\n request: An ApiRequest, the transformed request sent to the Discovery API.\n ...
Please provide a description of the function: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.\n\n If the body is valid JSON, return the JSON as a dict.\n Else, convert the key=value format to a dict and return that.\n\n Args:\n body: The body of the HTTP request.\n " ]
Please provide a description of the function: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.\n\n This is based on the URL reconstruction code in Python PEP 333:\n http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the\n URL from the pieces available in the environment.\n\n Args:\n environ: An environ dict for the request as ...
Please provide a description of the function: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 += ':{...
[ "Reconstruct the hostname of a request.\n\n This is based on the URL reconstruction code in Python PEP 333:\n http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the\n hostname from the pieces available in the environment.\n\n Args:\n port_override: str, An override for the port o...
Please provide a description of the function: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.\n\n This is based on the URL reconstruction code in Python PEP 333:\n http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the\n hostname from the pieces available in the environment.\n\n Args:\n port_override: str, An override for the port o...
Please provide a description of the function:def _add_def_paths(self, prop_dict): for prop_key, prop_value in prop_dict.iteritems(): if prop_key == '$ref' and not 'prop_value'.startswith('#'): prop_dict[prop_key] = '#/definitions/' + prop_dict[prop_key] elif isinstance(prop_value, dict): ...
[ "Recursive method to add relative paths for any $ref objects.\n\n Args:\n prop_dict: The property dict to alter.\n\n Side Effects:\n Alters prop_dict in-place.\n " ]
Please provide a description of the function: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.\n\n Args:\n service_name: The name of the service.\n protorpc_method_name: The ProtoRPC method name.\n\n Returns:\n A string representing the operation id.\n " ]
Please provide a description of the function:def __field_to_parameter_type_and_format(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 param...
[ "Converts the field variant type into a tuple describing the parameter.\n\n Args:\n field: An instance of a subclass of messages.Field.\n\n Returns:\n A tuple with the type and format of the field, respectively.\n\n Raises:\n TypeError: if the field variant is a message variant.\n " ]
Please provide a description of the function:def __parameter_default(self, field): if field.default: if isinstance(field, messages.EnumField): return field.default.name else: return field.default
[ "Returns default value of field if it has one.\n\n Args:\n field: A simple field.\n\n Returns:\n The default value of the field, if any exists, with the exception of an\n enum field, which will have its value cast to a string.\n " ]
Please provide a description of the function:def __non_body_parameter_descriptor(self, param): descriptor = {} descriptor['name'] = param.name param_type, param_format = self.__field_to_parameter_type_and_format(param) # Required if param.required: descriptor['required'] = True # ...
[ "Creates descriptor for a parameter.\n\n Args:\n param: The parameter to be described.\n\n Returns:\n Dictionary containing a descriptor for the parameter.\n " ]
Please provide a description of the function:def __add_parameter(self, param, path_parameters, params): # If this is a simple field, just build the descriptor and append it. # Otherwise, build a schema and assign it to this descriptor if not isinstance(param, messages.MessageField): if param.name...
[ "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_without_container(self, message_type, request_kind, method_id, path): params = [] path_parameter_dict = self.__get_path_parameters(path) for field in sorted(message_type.all_fields(), key=l...
[ "Describe parameters of a method which does not use a ResourceContainer.\n\n Makes sure that the path parameters are included in the message definition\n and adds any required fields and URL query parameters.\n\n This method is to preserve backwards compatibility and will be removed in\n a future releas...
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): if isinstance(message_type, resource_container.ResourceContainer): base_message_type = message_type.body_message_class() if (request_k...
[ "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 __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 = {} ...
[ "Describes the definitions section of the OpenAPI spec.\n\n Returns:\n Dictionary describing the definitions of the spec.\n " ]
Please provide a description of the function:def __response_message_descriptor(self, message_type, method_id): # Skeleton response descriptor, common to all response objects descriptor = {'200': {'description': 'A successful response'}} if message_type != message_types.VoidMessage(): self.__par...
[ "Describes the response.\n\n Args:\n message_type: messages.Message class, The message to describe.\n method_id: string, Unique method identifier (e.g. 'myapi.items.method')\n\n Returns:\n Dictionary describing the response.\n " ]
Please provide a description of the function:def __x_google_quota_descriptor(self, metric_costs): return { 'metricCosts': { metric: cost for (metric, cost) in metric_costs.items() } } if metric_costs else None
[ "Describes the metric costs for a call.\n\n Args:\n metric_costs: Dict of metric definitions to the integer cost value against\n that metric.\n\n Returns:\n A dict descriptor describing the Quota limits for the endpoint.\n " ]
Please provide a description of the function:def __x_google_quota_definitions_descriptor(self, limit_definitions): if not limit_definitions: return None definitions_list = [{ 'name': ld.metric_name, 'metric': ld.metric_name, 'unit': '1/min/{project}', 'values': {'STAN...
[ "Describes the quota limit definitions for an API.\n\n Args:\n limit_definitions: List of endpoints.LimitDefinition tuples\n\n Returns:\n A dict descriptor of the API's quota limit definitions.\n " ]
Please provide a description of the function:def __method_descriptor(self, service, method_info, operation_id, protorpc_method_info, security_definitions): descriptor = {} request_message_type = (resource_container.ResourceContainer. get_request_messag...
[ "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 operation_id: string, Operation ID of the method\n protorpc_method_info: protorpc.remote._RemoteMethodInfo, ProtoRPC\n descri...
Please provide a description of the function:def __security_definitions_descriptor(self, issuers): if not issuers: result = { _DEFAULT_SECURITY_DEFINITION: { 'authorizationUrl': '', 'flow': 'implicit', 'type': 'oauth2', 'x-google-issuer': ...
[ "Create a descriptor for the security definitions.\n\n Args:\n issuers: dict, mapping issuer names to Issuer tuples\n\n Returns:\n The dict representing the security definitions descriptor.\n " ]
Please provide a description of the function:def __api_openapi_descriptor(self, services, hostname=None, x_google_api_name=False): merged_api_info = self.__get_merged_api_info(services) descriptor = self.get_descriptor_defaults(merged_api_info, hostname=hostnam...
[ "Builds an OpenAPI description of an API.\n\n Args:\n services: List of protorpc.remote.Service instances implementing an\n api/version.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults to None.\n\n Returns:\n A dictionary that ...
Please provide a description of the function:def get_descriptor_defaults(self, api_info, hostname=None, x_google_api_name=False): hostname = (hostname or util.get_app_hostname() or api_info.hostname) protocol = 'http' if ((hostname and hostname.startswith('localhost')) or ...
[ "Gets a default configuration for a service.\n\n Args:\n api_info: _ApiInfo object for this service.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults to None.\n\n Returns:\n A dictionary with the default configuration.\n " ]
Please provide a description of the function:def get_openapi_dict(self, services, hostname=None, x_google_api_name=False): if not isinstance(services, (tuple, list)): services = [services] # The type of a class that inherits from remote.Service is actually # remote._ServiceClass, thanks to meta...
[ "JSON dict description of a protorpc.remote.Service in OpenAPI format.\n\n Args:\n services: Either a single protorpc.remote.Service or a list of them\n that implements an api/version.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults to...
Please provide a description of the function:def pretty_print_config_to_json(self, services, hostname=None, x_google_api_name=False): descriptor = self.get_openapi_dict(services, hostname, x_google_api_name=x_google_api_name) return json.dumps(descriptor, sort_keys=True, indent=2, sep...
[ "JSON string description of a protorpc.remote.Service in OpenAPI format.\n\n Args:\n services: Either a single protorpc.remote.Service or a list of them\n that implements an api/version.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults ...
Please provide a description of the function:def encode_field(self, field, value): # Override the handling of 64-bit integers, so they're always encoded # as strings. if (isinstance(field, messages.IntegerField) and field.variant in (messages.Variant.INT64, messages.Va...
[ "Encode a python field value to a JSON value.\n\n Args:\n field: A ProtoRPC field instance.\n value: A python value supported by field.\n\n Returns:\n A JSON serializable value appropriate for field.\n " ]
Please provide a description of the function:def __pad_value(value, pad_len_multiple, pad_char): assert pad_len_multiple > 0 assert len(pad_char) == 1 padding_length = (pad_len_multiple - (len(value) % pad_len_multiple)) % pad_len_multiple return value + pad_char * padding_len...
[ "Add padding characters to the value if needed.\n\n Args:\n value: The string value to be padded.\n pad_len_multiple: Pad the result so its length is a multiple\n of pad_len_multiple.\n pad_char: The character to use for padding.\n\n Returns:\n The string value with padding charac...
Please provide a description of the function:def decode_field(self, field, value): # Override BytesField handling. Client libraries typically use a url-safe # encoding. b64decode doesn't handle these gracefully. urlsafe_b64decode # handles both cases safely. Also add padding if the padding is incor...
[ "Decode a JSON value to a python value.\n\n Args:\n field: A ProtoRPC field instance.\n value: A serialized JSON value.\n\n Returns:\n A Python value compatible with field.\n " ]
Please provide a description of the function:def add_message(self, message_type): name = self.__normalized_name(message_type) if name not in self.__schemas: # Set a placeholder to prevent infinite recursion. self.__schemas[name] = None schema = self.__message_to_schema(message_type) ...
[ "Add a new message.\n\n Args:\n message_type: protorpc.message.Message class to be parsed.\n\n Returns:\n string, The JSON Schema id.\n\n Raises:\n KeyError if the Schema id for this message_type would collide with the\n Schema id of a different message_type that was already added.\n ...
Please provide a description of the function:def ref_for_message_type(self, message_type): name = self.__normalized_name(message_type) if name not in self.__schemas: raise KeyError('Message has not been parsed: %s', name) return name
[ "Returns the JSON Schema id for the given message.\n\n Args:\n message_type: protorpc.message.Message class to be parsed.\n\n Returns:\n string, The JSON Schema id.\n\n Raises:\n KeyError: if the message hasn't been parsed via add_message().\n " ]
Please provide a description of the function:def __normalized_name(self, message_type): # Normalization is applied to match the constraints that Discovery applies # to Schema names. name = message_type.definition_name() split_name = re.split(r'[^0-9a-zA-Z]', name) normalized = ''.join( ...
[ "Normalized schema name.\n\n Generate a normalized schema name, taking the class name and stripping out\n everything but alphanumerics, and camel casing the remaining words.\n A normalized schema name is a name that matches [a-zA-Z][a-zA-Z0-9]*\n\n Args:\n message_type: protorpc.message.Message cla...
Please provide a description of the function:def __message_to_schema(self, message_type): name = self.__normalized_name(message_type) schema = { 'id': name, 'type': 'object', } if message_type.__doc__: schema['description'] = message_type.__doc__ properties = {} fo...
[ "Parse a single message into JSON Schema.\n\n Will recursively descend the message structure\n and also parse other messages references via MessageFields.\n\n Args:\n message_type: protorpc.messages.Message class to parse.\n\n Returns:\n An object representation of the schema.\n " ]
Please provide a description of the function:def _check_enum(parameter_name, value, parameter_config): enum_values = [enum['backendValue'] for enum in parameter_config['enum'].values() if 'backendValue' in enum] if value not in enum_values: raise errors.EnumRejectionError(pa...
[ "Checks if an enum value is valid.\n\n This is called by the transform_parameter_value function and shouldn't be\n called directly.\n\n This verifies that the value of an enum parameter is valid.\n\n Args:\n parameter_name: A string containing the name of the parameter, which is\n either just a variable...
Please provide a description of the function:def _check_boolean(parameter_name, value, parameter_config): if parameter_config.get('type') != 'boolean': return if value.lower() not in ('1', 'true', '0', 'false'): raise errors.BasicTypeParameterError(parameter_name, value, 'boolean')
[ "Checks if a boolean value is valid.\n\n This is called by the transform_parameter_value function and shouldn't be\n called directly.\n\n This checks that the string value passed in can be converted to a valid\n boolean value.\n\n Args:\n parameter_name: A string containing the name of the parameter, which ...
Please provide a description of the function:def _get_parameter_conversion_entry(parameter_config): entry = _PARAM_CONVERSION_MAP.get(parameter_config.get('type')) # Special handling for enum parameters. An enum's type is 'string', so we # need to detect them by the presence of an 'enum' property in their ...
[ "Get information needed to convert the given parameter to its API type.\n\n Args:\n parameter_config: The dictionary containing information specific to the\n parameter in question. This is retrieved from request.parameters in the\n method config.\n\n Returns:\n The entry from _PARAM_CONVERSION_MAP...
Please provide a description of the function:def transform_parameter_value(parameter_name, value, parameter_config): if isinstance(value, list): # We're only expecting to handle path and query string parameters here. # The way path and query string parameters are passed in, they'll likely # only be sin...
[ "Validates and transforms parameters to the type expected by the API.\n\n If the value is a list this will recursively call _transform_parameter_value\n on the values in the list. Otherwise, it checks all parameter rules for the\n the current value and converts its type from a string to whatever format\n the AP...
Please provide a description of the function:def sort_dependencies(app_list): # Process the list of models, and get the list of dependencies model_dependencies = [] models = set() for app_config, model_list in app_list: if model_list is None: model_list = app_config.get_models()...
[ "Sort a list of (app_config, models) pairs into a single list of models.\n The single list of models is sorted so that any model with a natural key\n is serialized before a normal model, and any model with a natural key\n dependency has it's dependencies serialized first.\n " ]
Please provide a description of the function:def filter_items(self, items): '''perform filtering items by specific criteria''' items = self._filter_active(items) items = self._filter_in_nav(items) return items
[]
Please provide a description of the function:def get_formset(self): if self.folder: queryset = self.folder.files.all() else: queryset = File.objects.none() if self._formset is None: self._formset = self.formset_class( self.request.POST...
[ "Provide the formset corresponding to this DataTable.\n\n Use this to validate the formset and to get the submitted data back.\n " ]
Please provide a description of the function:def import_file(self, file_obj, folder): created = False for cls in MEDIA_MODELS: if cls.matches_file_type(file_obj.name): obj, created = cls.objects.get_or_create( original_filename=file_obj.name, ...
[ "\n Create a File or an Image into the given folder\n " ]
Please provide a description of the function:def is_leonardo_module(mod): if hasattr(mod, 'default') \ or hasattr(mod, 'leonardo_module_conf'): return True for key in dir(mod): if 'LEONARDO' in key: return True return False
[ "returns True if is leonardo module\n " ]
Please provide a description of the function:def _translate_page_into(page, language, default=None): # Optimisation shortcut: No need to dive into translations if page already what we want if page.language == language: return page translations = dict((t.language, t) for t in page.available_tra...
[ "\n Return the translation for a given page\n " ]
Please provide a description of the function:def feincms_breadcrumbs(page, include_self=True): if not page or not isinstance(page, Page): raise ValueError("feincms_breadcrumbs must be called with a valid Page object") ancs = page.get_ancestors() bc = [(anc.get_absolute_url(), anc.short_title...
[ "\n Generate a list of the page's ancestors suitable for use as breadcrumb navigation.\n\n By default, generates an unordered list with the id \"breadcrumbs\" -\n override breadcrumbs.html to change this.\n\n ::\n\n {% feincms_breadcrumbs feincms_page %}\n " ]
Please provide a description of the function:def is_parent_of(page1, page2): try: return page1.tree_id == page2.tree_id and page1.lft < page2.lft and page1.rght > page2.rght except AttributeError: return False
[ "\n Determines whether a given page is the parent of another page\n\n Example::\n\n {% if page|is_parent_of:feincms_page %} ... {% endif %}\n " ]
Please provide a description of the function:def parent(self): '''We use parent for some initial data''' if not hasattr(self, '_parent'): if 'parent' in self.kwargs: try: self._parent = Page.objects.get(id=self.kwargs["parent"]) except E...
[]
Please provide a description of the function:def head_title(request): try: fragments = request._feincms_fragments except: fragments = {} if '_head_title' in fragments and fragments.get("_head_title"): return fragments.get("_head_title") else: # append site name ...
[ "\n {% head_title request %}\n " ]
Please provide a description of the function:def meta_description(request): try: fragments = request._feincms_fragments except: fragments = {} if '_meta_description' in fragments and fragments.get("_meta_description"): return fragments.get("_meta_description") else: ...
[ "\n {% meta_description request %}\n " ]
Please provide a description of the function:def render_region_tools(context, feincms_object, region, request=None): if context.get('standalone', False) or not feincms_object: return {} edit = False if getattr(settings, 'LEONARDO_USE_PAGE_ADMIN', False): request = context.get('reques...
[ "\n {% render_region_tools feincms_page \"main\" request %}\n\n skip rendering in standalone mode\n " ]
Please provide a description of the function:def feincms_render_region(context, feincms_object, region, request=None, classes='', wrapper=True): if not feincms_object: return '' if not context.get('standalone', False) or region in STANDALONE_REGIONS: region_conten...
[ "\n {% feincms_render_region feincms_page \"main\" request %}\n\n Support for rendering Page without some regions especialy for modals\n this feature is driven by context variable\n " ]
Please provide a description of the function:def app_reverse(parser, token): bits = token.split_contents() if len(bits) < 3: raise TemplateSyntaxError( "'%s' takes at least two arguments" " (path to a view and a urlconf)" % bits[0]) viewname = parser.compile_filter(bits[...
[ "\n Returns an absolute URL for applications integrated with ApplicationContent\n The tag mostly works the same way as Django's own {% url %} tag::\n {% load leonardo_tags %}\n {% app_reverse \"mymodel_detail\" \"myapp.urls\" arg1 arg2 %}\n or\n {% load leonardo_tags %}\n {%...
Please provide a description of the function:def feincms_object_tools(context, cls_name): if context.get('standalone', False): return {} edit = False if getattr(settings, 'LEONARDO_USE_PAGE_ADMIN', False): request = context.get('request', None) frontend_edit = request.COOKIES.ge...
[ "\n {% feincms_object_tools 'article' %}\n {% feincms_object_tools 'web.page' %}\n\n render add feincms object entry\n " ]
Please provide a description of the function:def image_name(image, key='name', clear=True): if hasattr(image, 'translation') and image.translation: return getattr(image.translation, key) if hasattr(image, key) and getattr(image, key): return getattr(image, key) try: name = IMA...
[ "\n {{ image|image_name }}\n {{ image|image_name:\"description\" }}\n {{ image|image_name:\"default_caption\" }}\n {{ image|image_name:\"default_caption\" False }}\n\n Return translation or image name\n " ]
Please provide a description of the function:def tree_label(self): '''render tree label like as `root > child > child`''' titles = [] page = self while page: titles.append(page.title) page = page.parent return smart_text(' > '.join(reversed(titles)))
[]
Please provide a description of the function:def flush_ct_inventory(self): if hasattr(self, '_ct_inventory'): # skip self from update self._ct_inventory = None self.update_view = False self.save()
[ "internal method used only if ct_inventory is enabled\n " ]
Please provide a description of the function:def register_default_processors(cls, frontend_editing=None): super(Page, cls).register_default_processors() if frontend_editing: cls.register_request_processor( edit_processors.frontendediting_request_processor, ...
[ "\n Register our default request processors for the out-of-the-box\n Page experience.\n\n Since FeinCMS 1.11 was removed from core.\n\n " ]
Please provide a description of the function:def run_request_processors(self, request): if not getattr(self, 'request_processors', None): return for fn in reversed(list(self.request_processors.values())): r = fn(self, request) if r: return r
[ "\n Before rendering a page, run all registered request processors. A\n request processor may peruse and modify the page or the request. It can\n also return a ``HttpResponse`` for shortcutting the rendering and\n returning that response immediately to the client.\n " ]
Please provide a description of the function:def technical_404_response(request, exception): "Create a technical 404 error response. The exception should be the Http404." try: error_url = exception.args[0]['path'] except (IndexError, TypeError, KeyError): error_url = request.path_info[1:] #...
[]
Please provide a description of the function:def response_change(self, request, obj): r = super(FileAdmin, self).response_change(request, obj) if 'Location' in r and r['Location']: # it was a successful save if (r['Location'] in ['../'] or r['Location...
[ "\n Overrides the default to be able to forward to the directory listing\n instead of the default change_list_view\n " ]
Please provide a description of the function:def delete_view(self, request, object_id, extra_context=None): parent_folder = None try: obj = self.get_queryset(request).get(pk=unquote(object_id)) parent_folder = obj.folder except self.model.DoesNotExist: ...
[ "\n Overrides the default to enable redirecting to the directory view after\n deletion of a image.\n\n we need to fetch the object and find out who the parent is\n before super, because super will delete the object and make it\n impossible to find out the parent folder to redirect...
Please provide a description of the function:def items(self): '''access for filtered items''' if hasattr(self, '_items'): return self.filter_items(self._items) self._items = self.get_items() return self.filter_items(self._items)
[]
Please provide a description of the function:def populate_items(self, request): '''populate and returns filtered items''' self._items = self.get_items(request) return self.items
[]
Please provide a description of the function:def get_rows(self): '''returns rows with items [[item1 item2], [item3 item4], [item5]]''' rows = [] row = [] for i, item in enumerate(self.items): if i > 0 and i % self.objects_per_row == 0: rows.append(row)...
[]
Please provide a description of the function:def columns_classes(self): '''returns columns count''' md = 12 / self.objects_per_row sm = None if self.objects_per_row > 2: sm = 12 / (self.objects_per_row / 2) return md, (sm or md), 12
[]
Please provide a description of the function:def get_pages(self): '''returns pages with rows''' pages = [] page = [] for i, item in enumerate(self.get_rows): if i > 0 and i % self.objects_per_page == 0: pages.append(page) page = [] ...
[]
Please provide a description of the function:def needs_pagination(self): if self.objects_per_page == 0: return False if len(self.items) > self.objects_per_page \ or len(self.get_pages[0]) > self.objects_per_page: return True return False
[ "Calculate needs pagination" ]
Please provide a description of the function:def get_item_template(self): '''returns template for signle object from queryset If you have a template name my_list_template.html then template for a single object will be _my_list_template.html Now only for default generates _item.h...
[]