id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22,300 | cloudendpoints/endpoints-python | endpoints/_endpointscfg_impl.py | _GetAppYamlHostname | def _GetAppYamlHostname(application_path, open_func=open):
"""Build the hostname for this app based on the name in app.yaml.
Args:
application_path: A string with the path to the AppEngine application. This
should be the directory containing the app.yaml file.
open_func: Function to call to open a file. Used to override the default
open function in unit tests.
Returns:
A hostname, usually in the form of "myapp.appspot.com", based on the
application name in the app.yaml file. If the file can't be found or
there's a problem building the name, this will return None.
"""
try:
app_yaml_file = open_func(os.path.join(application_path or '.', 'app.yaml'))
config = yaml.safe_load(app_yaml_file.read())
except IOError:
# Couldn't open/read app.yaml.
return None
application = config.get('application')
if not application:
return None
if ':' in application:
# Don't try to deal with alternate domains.
return None
# If there's a prefix ending in a '~', strip it.
tilde_index = application.rfind('~')
if tilde_index >= 0:
application = application[tilde_index + 1:]
if not application:
return None
return '%s.appspot.com' % application | python | def _GetAppYamlHostname(application_path, open_func=open):
try:
app_yaml_file = open_func(os.path.join(application_path or '.', 'app.yaml'))
config = yaml.safe_load(app_yaml_file.read())
except IOError:
# Couldn't open/read app.yaml.
return None
application = config.get('application')
if not application:
return None
if ':' in application:
# Don't try to deal with alternate domains.
return None
# If there's a prefix ending in a '~', strip it.
tilde_index = application.rfind('~')
if tilde_index >= 0:
application = application[tilde_index + 1:]
if not application:
return None
return '%s.appspot.com' % application | [
"def",
"_GetAppYamlHostname",
"(",
"application_path",
",",
"open_func",
"=",
"open",
")",
":",
"try",
":",
"app_yaml_file",
"=",
"open_func",
"(",
"os",
".",
"path",
".",
"join",
"(",
"application_path",
"or",
"'.'",
",",
"'app.yaml'",
")",
")",
"config",
... | Build the hostname for this app based on the name in app.yaml.
Args:
application_path: A string with the path to the AppEngine application. This
should be the directory containing the app.yaml file.
open_func: Function to call to open a file. Used to override the default
open function in unit tests.
Returns:
A hostname, usually in the form of "myapp.appspot.com", based on the
application name in the app.yaml file. If the file can't be found or
there's a problem building the name, this will return None. | [
"Build",
"the",
"hostname",
"for",
"this",
"app",
"based",
"on",
"the",
"name",
"in",
"app",
".",
"yaml",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L221-L257 |
22,301 | cloudendpoints/endpoints-python | endpoints/_endpointscfg_impl.py | _GenDiscoveryDoc | def _GenDiscoveryDoc(service_class_names,
output_path, hostname=None,
application_path=None):
"""Write discovery documents generated from the service classes to file.
Args:
service_class_names: A list of fully qualified ProtoRPC service names.
output_path: The directory to output the discovery docs to.
hostname: A string hostname which will be used as the default version
hostname. If no hostname is specificied in the @endpoints.api decorator,
this value is the fallback. Defaults to None.
application_path: A string containing the path to the AppEngine app.
Returns:
A list of discovery doc filenames.
"""
output_files = []
service_configs = GenApiConfig(
service_class_names, hostname=hostname,
config_string_generator=discovery_generator.DiscoveryGenerator(),
application_path=application_path)
for api_name_version, config in service_configs.iteritems():
discovery_name = api_name_version + '.discovery'
output_files.append(_WriteFile(output_path, discovery_name, config))
return output_files | python | def _GenDiscoveryDoc(service_class_names,
output_path, hostname=None,
application_path=None):
output_files = []
service_configs = GenApiConfig(
service_class_names, hostname=hostname,
config_string_generator=discovery_generator.DiscoveryGenerator(),
application_path=application_path)
for api_name_version, config in service_configs.iteritems():
discovery_name = api_name_version + '.discovery'
output_files.append(_WriteFile(output_path, discovery_name, config))
return output_files | [
"def",
"_GenDiscoveryDoc",
"(",
"service_class_names",
",",
"output_path",
",",
"hostname",
"=",
"None",
",",
"application_path",
"=",
"None",
")",
":",
"output_files",
"=",
"[",
"]",
"service_configs",
"=",
"GenApiConfig",
"(",
"service_class_names",
",",
"hostna... | Write discovery documents generated from the service classes to file.
Args:
service_class_names: A list of fully qualified ProtoRPC service names.
output_path: The directory to output the discovery docs to.
hostname: A string hostname which will be used as the default version
hostname. If no hostname is specificied in the @endpoints.api decorator,
this value is the fallback. Defaults to None.
application_path: A string containing the path to the AppEngine app.
Returns:
A list of discovery doc filenames. | [
"Write",
"discovery",
"documents",
"generated",
"from",
"the",
"service",
"classes",
"to",
"file",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L260-L285 |
22,302 | cloudendpoints/endpoints-python | endpoints/_endpointscfg_impl.py | _GenOpenApiSpec | def _GenOpenApiSpec(service_class_names, output_path, hostname=None,
application_path=None, x_google_api_name=False):
"""Write openapi documents generated from the service classes to file.
Args:
service_class_names: A list of fully qualified ProtoRPC service names.
output_path: The directory to which to output the OpenAPI specs.
hostname: A string hostname which will be used as the default version
hostname. If no hostname is specified in the @endpoints.api decorator,
this value is the fallback. Defaults to None.
application_path: A string containing the path to the AppEngine app.
Returns:
A list of OpenAPI spec filenames.
"""
output_files = []
service_configs = GenApiConfig(
service_class_names, hostname=hostname,
config_string_generator=openapi_generator.OpenApiGenerator(),
application_path=application_path,
x_google_api_name=x_google_api_name)
for api_name_version, config in service_configs.iteritems():
openapi_name = api_name_version.replace('-', '') + 'openapi.json'
output_files.append(_WriteFile(output_path, openapi_name, config))
return output_files | python | def _GenOpenApiSpec(service_class_names, output_path, hostname=None,
application_path=None, x_google_api_name=False):
output_files = []
service_configs = GenApiConfig(
service_class_names, hostname=hostname,
config_string_generator=openapi_generator.OpenApiGenerator(),
application_path=application_path,
x_google_api_name=x_google_api_name)
for api_name_version, config in service_configs.iteritems():
openapi_name = api_name_version.replace('-', '') + 'openapi.json'
output_files.append(_WriteFile(output_path, openapi_name, config))
return output_files | [
"def",
"_GenOpenApiSpec",
"(",
"service_class_names",
",",
"output_path",
",",
"hostname",
"=",
"None",
",",
"application_path",
"=",
"None",
",",
"x_google_api_name",
"=",
"False",
")",
":",
"output_files",
"=",
"[",
"]",
"service_configs",
"=",
"GenApiConfig",
... | Write openapi documents generated from the service classes to file.
Args:
service_class_names: A list of fully qualified ProtoRPC service names.
output_path: The directory to which to output the OpenAPI specs.
hostname: A string hostname which will be used as the default version
hostname. If no hostname is specified in the @endpoints.api decorator,
this value is the fallback. Defaults to None.
application_path: A string containing the path to the AppEngine app.
Returns:
A list of OpenAPI spec filenames. | [
"Write",
"openapi",
"documents",
"generated",
"from",
"the",
"service",
"classes",
"to",
"file",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L288-L313 |
22,303 | cloudendpoints/endpoints-python | endpoints/_endpointscfg_impl.py | _GetClientLib | def _GetClientLib(service_class_names, language, output_path, build_system,
hostname=None, application_path=None):
"""Fetch client libraries from a cloud service.
Args:
service_class_names: A list of fully qualified ProtoRPC service names.
language: The client library language to generate. (java)
output_path: The directory to output the discovery docs to.
build_system: The target build system for the client library language.
hostname: A string hostname which will be used as the default version
hostname. If no hostname is specificied in the @endpoints.api decorator,
this value is the fallback. Defaults to None.
application_path: A string containing the path to the AppEngine app.
Returns:
A list of paths to client libraries.
"""
client_libs = []
service_configs = GenApiConfig(
service_class_names, hostname=hostname,
config_string_generator=discovery_generator.DiscoveryGenerator(),
application_path=application_path)
for api_name_version, config in service_configs.iteritems():
client_name = api_name_version + '.zip'
client_libs.append(
_GenClientLibFromContents(config, language, output_path,
build_system, client_name))
return client_libs | python | def _GetClientLib(service_class_names, language, output_path, build_system,
hostname=None, application_path=None):
client_libs = []
service_configs = GenApiConfig(
service_class_names, hostname=hostname,
config_string_generator=discovery_generator.DiscoveryGenerator(),
application_path=application_path)
for api_name_version, config in service_configs.iteritems():
client_name = api_name_version + '.zip'
client_libs.append(
_GenClientLibFromContents(config, language, output_path,
build_system, client_name))
return client_libs | [
"def",
"_GetClientLib",
"(",
"service_class_names",
",",
"language",
",",
"output_path",
",",
"build_system",
",",
"hostname",
"=",
"None",
",",
"application_path",
"=",
"None",
")",
":",
"client_libs",
"=",
"[",
"]",
"service_configs",
"=",
"GenApiConfig",
"(",... | Fetch client libraries from a cloud service.
Args:
service_class_names: A list of fully qualified ProtoRPC service names.
language: The client library language to generate. (java)
output_path: The directory to output the discovery docs to.
build_system: The target build system for the client library language.
hostname: A string hostname which will be used as the default version
hostname. If no hostname is specificied in the @endpoints.api decorator,
this value is the fallback. Defaults to None.
application_path: A string containing the path to the AppEngine app.
Returns:
A list of paths to client libraries. | [
"Fetch",
"client",
"libraries",
"from",
"a",
"cloud",
"service",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L374-L401 |
22,304 | cloudendpoints/endpoints-python | endpoints/_endpointscfg_impl.py | _GenApiConfigCallback | def _GenApiConfigCallback(args, api_func=GenApiConfig):
"""Generate an api file.
Args:
args: An argparse.Namespace object to extract parameters from.
api_func: A function that generates and returns an API configuration
for a list of services.
"""
service_configs = api_func(args.service,
hostname=args.hostname,
application_path=args.application)
for api_name_version, config in service_configs.iteritems():
_WriteFile(args.output, api_name_version + '.api', config) | python | def _GenApiConfigCallback(args, api_func=GenApiConfig):
service_configs = api_func(args.service,
hostname=args.hostname,
application_path=args.application)
for api_name_version, config in service_configs.iteritems():
_WriteFile(args.output, api_name_version + '.api', config) | [
"def",
"_GenApiConfigCallback",
"(",
"args",
",",
"api_func",
"=",
"GenApiConfig",
")",
":",
"service_configs",
"=",
"api_func",
"(",
"args",
".",
"service",
",",
"hostname",
"=",
"args",
".",
"hostname",
",",
"application_path",
"=",
"args",
".",
"application... | Generate an api file.
Args:
args: An argparse.Namespace object to extract parameters from.
api_func: A function that generates and returns an API configuration
for a list of services. | [
"Generate",
"an",
"api",
"file",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L404-L417 |
22,305 | cloudendpoints/endpoints-python | endpoints/_endpointscfg_impl.py | _GetClientLibCallback | def _GetClientLibCallback(args, client_func=_GetClientLib):
"""Generate discovery docs and client libraries to files.
Args:
args: An argparse.Namespace object to extract parameters from.
client_func: A function that generates client libraries and stores them to
files, accepting a list of service names, a client library language,
an output directory, a build system for the client library language, and
a hostname.
"""
client_paths = client_func(
args.service, args.language, args.output, args.build_system,
hostname=args.hostname, application_path=args.application)
for client_path in client_paths:
print 'API client library written to %s' % client_path | python | def _GetClientLibCallback(args, client_func=_GetClientLib):
client_paths = client_func(
args.service, args.language, args.output, args.build_system,
hostname=args.hostname, application_path=args.application)
for client_path in client_paths:
print 'API client library written to %s' % client_path | [
"def",
"_GetClientLibCallback",
"(",
"args",
",",
"client_func",
"=",
"_GetClientLib",
")",
":",
"client_paths",
"=",
"client_func",
"(",
"args",
".",
"service",
",",
"args",
".",
"language",
",",
"args",
".",
"output",
",",
"args",
".",
"build_system",
",",... | Generate discovery docs and client libraries to files.
Args:
args: An argparse.Namespace object to extract parameters from.
client_func: A function that generates client libraries and stores them to
files, accepting a list of service names, a client library language,
an output directory, a build system for the client library language, and
a hostname. | [
"Generate",
"discovery",
"docs",
"and",
"client",
"libraries",
"to",
"files",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L420-L435 |
22,306 | cloudendpoints/endpoints-python | endpoints/_endpointscfg_impl.py | _GenDiscoveryDocCallback | def _GenDiscoveryDocCallback(args, discovery_func=_GenDiscoveryDoc):
"""Generate discovery docs to files.
Args:
args: An argparse.Namespace object to extract parameters from
discovery_func: A function that generates discovery docs and stores them to
files, accepting a list of service names, a discovery doc format, and an
output directory.
"""
discovery_paths = discovery_func(args.service, args.output,
hostname=args.hostname,
application_path=args.application)
for discovery_path in discovery_paths:
print 'API discovery document written to %s' % discovery_path | python | def _GenDiscoveryDocCallback(args, discovery_func=_GenDiscoveryDoc):
discovery_paths = discovery_func(args.service, args.output,
hostname=args.hostname,
application_path=args.application)
for discovery_path in discovery_paths:
print 'API discovery document written to %s' % discovery_path | [
"def",
"_GenDiscoveryDocCallback",
"(",
"args",
",",
"discovery_func",
"=",
"_GenDiscoveryDoc",
")",
":",
"discovery_paths",
"=",
"discovery_func",
"(",
"args",
".",
"service",
",",
"args",
".",
"output",
",",
"hostname",
"=",
"args",
".",
"hostname",
",",
"ap... | Generate discovery docs to files.
Args:
args: An argparse.Namespace object to extract parameters from
discovery_func: A function that generates discovery docs and stores them to
files, accepting a list of service names, a discovery doc format, and an
output directory. | [
"Generate",
"discovery",
"docs",
"to",
"files",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L438-L451 |
22,307 | cloudendpoints/endpoints-python | endpoints/_endpointscfg_impl.py | _GenClientLibCallback | def _GenClientLibCallback(args, client_func=_GenClientLib):
"""Generate a client library to file.
Args:
args: An argparse.Namespace object to extract parameters from
client_func: A function that generates client libraries and stores them to
files, accepting a path to a discovery doc, a client library language, an
output directory, and a build system for the client library language.
"""
client_path = client_func(args.discovery_doc[0], args.language, args.output,
args.build_system)
print 'API client library written to %s' % client_path | python | def _GenClientLibCallback(args, client_func=_GenClientLib):
client_path = client_func(args.discovery_doc[0], args.language, args.output,
args.build_system)
print 'API client library written to %s' % client_path | [
"def",
"_GenClientLibCallback",
"(",
"args",
",",
"client_func",
"=",
"_GenClientLib",
")",
":",
"client_path",
"=",
"client_func",
"(",
"args",
".",
"discovery_doc",
"[",
"0",
"]",
",",
"args",
".",
"language",
",",
"args",
".",
"output",
",",
"args",
"."... | Generate a client library to file.
Args:
args: An argparse.Namespace object to extract parameters from
client_func: A function that generates client libraries and stores them to
files, accepting a path to a discovery doc, a client library language, an
output directory, and a build system for the client library language. | [
"Generate",
"a",
"client",
"library",
"to",
"file",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L470-L481 |
22,308 | cloudendpoints/endpoints-python | endpoints/_endpointscfg_impl.py | _EndpointsParser.error | def error(self, message):
"""Override superclass to support customized error message.
Error message needs to be rewritten in order to display visible commands
only, when invalid command is called by user. Otherwise, hidden commands
will be displayed in stderr, which is not expected.
Refer the following argparse python documentation for detailed method
information:
http://docs.python.org/2/library/argparse.html#exiting-methods
Args:
message: original error message that will be printed to stderr
"""
# subcommands_quoted is the same as subcommands, except each value is
# surrounded with double quotes. This is done to match the standard
# output of the ArgumentParser, while hiding commands we don't want users
# to use, as they are no longer documented and only here for legacy use.
subcommands_quoted = ', '.join(
[repr(command) for command in _VISIBLE_COMMANDS])
subcommands = ', '.join(_VISIBLE_COMMANDS)
message = re.sub(
r'(argument {%s}: invalid choice: .*) \(choose from (.*)\)$'
% subcommands, r'\1 (choose from %s)' % subcommands_quoted, message)
super(_EndpointsParser, self).error(message) | python | def error(self, message):
# subcommands_quoted is the same as subcommands, except each value is
# surrounded with double quotes. This is done to match the standard
# output of the ArgumentParser, while hiding commands we don't want users
# to use, as they are no longer documented and only here for legacy use.
subcommands_quoted = ', '.join(
[repr(command) for command in _VISIBLE_COMMANDS])
subcommands = ', '.join(_VISIBLE_COMMANDS)
message = re.sub(
r'(argument {%s}: invalid choice: .*) \(choose from (.*)\)$'
% subcommands, r'\1 (choose from %s)' % subcommands_quoted, message)
super(_EndpointsParser, self).error(message) | [
"def",
"error",
"(",
"self",
",",
"message",
")",
":",
"# subcommands_quoted is the same as subcommands, except each value is",
"# surrounded with double quotes. This is done to match the standard",
"# output of the ArgumentParser, while hiding commands we don't want users",
"# to use, as they... | Override superclass to support customized error message.
Error message needs to be rewritten in order to display visible commands
only, when invalid command is called by user. Otherwise, hidden commands
will be displayed in stderr, which is not expected.
Refer the following argparse python documentation for detailed method
information:
http://docs.python.org/2/library/argparse.html#exiting-methods
Args:
message: original error message that will be printed to stderr | [
"Override",
"superclass",
"to",
"support",
"customized",
"error",
"message",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_impl.py#L111-L135 |
22,309 | cloudendpoints/endpoints-python | endpoints/_endpointscfg_setup.py | _SetupPaths | def _SetupPaths():
"""Sets up the sys.path with special directories for endpointscfg.py."""
sdk_path = _FindSdkPath()
if sdk_path:
sys.path.append(sdk_path)
try:
import dev_appserver # pylint: disable=g-import-not-at-top
if hasattr(dev_appserver, 'fix_sys_path'):
dev_appserver.fix_sys_path()
else:
logging.warning(_NO_FIX_SYS_PATH_WARNING)
except ImportError:
logging.warning(_IMPORT_ERROR_WARNING)
else:
logging.warning(_NOT_FOUND_WARNING)
# Add the path above this directory, so we can import the endpoints package
# from the user's app code (rather than from another, possibly outdated SDK).
# pylint: disable=g-import-not-at-top
from google.appengine.ext import vendor
vendor.add(os.path.dirname(os.path.dirname(__file__))) | python | def _SetupPaths():
sdk_path = _FindSdkPath()
if sdk_path:
sys.path.append(sdk_path)
try:
import dev_appserver # pylint: disable=g-import-not-at-top
if hasattr(dev_appserver, 'fix_sys_path'):
dev_appserver.fix_sys_path()
else:
logging.warning(_NO_FIX_SYS_PATH_WARNING)
except ImportError:
logging.warning(_IMPORT_ERROR_WARNING)
else:
logging.warning(_NOT_FOUND_WARNING)
# Add the path above this directory, so we can import the endpoints package
# from the user's app code (rather than from another, possibly outdated SDK).
# pylint: disable=g-import-not-at-top
from google.appengine.ext import vendor
vendor.add(os.path.dirname(os.path.dirname(__file__))) | [
"def",
"_SetupPaths",
"(",
")",
":",
"sdk_path",
"=",
"_FindSdkPath",
"(",
")",
"if",
"sdk_path",
":",
"sys",
".",
"path",
".",
"append",
"(",
"sdk_path",
")",
"try",
":",
"import",
"dev_appserver",
"# pylint: disable=g-import-not-at-top",
"if",
"hasattr",
"("... | Sets up the sys.path with special directories for endpointscfg.py. | [
"Sets",
"up",
"the",
"sys",
".",
"path",
"with",
"special",
"directories",
"for",
"endpointscfg",
".",
"py",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/_endpointscfg_setup.py#L84-L104 |
22,310 | cloudendpoints/endpoints-python | endpoints/api_config.py | _Enum | def _Enum(docstring, *names):
"""Utility to generate enum classes used by annotations.
Args:
docstring: Docstring for the generated enum class.
*names: Enum names.
Returns:
A class that contains enum names as attributes.
"""
enums = dict(zip(names, range(len(names))))
reverse = dict((value, key) for key, value in enums.iteritems())
enums['reverse_mapping'] = reverse
enums['__doc__'] = docstring
return type('Enum', (object,), enums) | python | def _Enum(docstring, *names):
enums = dict(zip(names, range(len(names))))
reverse = dict((value, key) for key, value in enums.iteritems())
enums['reverse_mapping'] = reverse
enums['__doc__'] = docstring
return type('Enum', (object,), enums) | [
"def",
"_Enum",
"(",
"docstring",
",",
"*",
"names",
")",
":",
"enums",
"=",
"dict",
"(",
"zip",
"(",
"names",
",",
"range",
"(",
"len",
"(",
"names",
")",
")",
")",
")",
"reverse",
"=",
"dict",
"(",
"(",
"value",
",",
"key",
")",
"for",
"key",... | Utility to generate enum classes used by annotations.
Args:
docstring: Docstring for the generated enum class.
*names: Enum names.
Returns:
A class that contains enum names as attributes. | [
"Utility",
"to",
"generate",
"enum",
"classes",
"used",
"by",
"annotations",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L102-L116 |
22,311 | cloudendpoints/endpoints-python | endpoints/api_config.py | _CheckType | def _CheckType(value, check_type, name, allow_none=True):
"""Check that the type of an object is acceptable.
Args:
value: The object whose type is to be checked.
check_type: The type that the object must be an instance of.
name: Name of the object, to be placed in any error messages.
allow_none: True if value can be None, false if not.
Raises:
TypeError: If value is not an acceptable type.
"""
if value is None and allow_none:
return
if not isinstance(value, check_type):
raise TypeError('%s type doesn\'t match %s.' % (name, check_type)) | python | def _CheckType(value, check_type, name, allow_none=True):
if value is None and allow_none:
return
if not isinstance(value, check_type):
raise TypeError('%s type doesn\'t match %s.' % (name, check_type)) | [
"def",
"_CheckType",
"(",
"value",
",",
"check_type",
",",
"name",
",",
"allow_none",
"=",
"True",
")",
":",
"if",
"value",
"is",
"None",
"and",
"allow_none",
":",
"return",
"if",
"not",
"isinstance",
"(",
"value",
",",
"check_type",
")",
":",
"raise",
... | Check that the type of an object is acceptable.
Args:
value: The object whose type is to be checked.
check_type: The type that the object must be an instance of.
name: Name of the object, to be placed in any error messages.
allow_none: True if value can be None, false if not.
Raises:
TypeError: If value is not an acceptable type. | [
"Check",
"that",
"the",
"type",
"of",
"an",
"object",
"is",
"acceptable",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L190-L205 |
22,312 | cloudendpoints/endpoints-python | endpoints/api_config.py | api | def api(name, version, description=None, hostname=None, audiences=None,
scopes=None, allowed_client_ids=None, canonical_name=None,
auth=None, owner_domain=None, owner_name=None, package_path=None,
frontend_limits=None, title=None, documentation=None, auth_level=None,
issuers=None, namespace=None, api_key_required=None, base_path=None,
limit_definitions=None, use_request_uri=None):
"""Decorate a ProtoRPC Service class for use by the framework above.
This decorator can be used to specify an API name, version, description, and
hostname for your API.
Sample usage (python 2.7):
@endpoints.api(name='guestbook', version='v0.2',
description='Guestbook API')
class PostService(remote.Service):
...
Sample usage (python 2.5):
class PostService(remote.Service):
...
endpoints.api(name='guestbook', version='v0.2',
description='Guestbook API')(PostService)
Sample usage if multiple classes implement one API:
api_root = endpoints.api(name='library', version='v1.0')
@api_root.api_class(resource_name='shelves')
class Shelves(remote.Service):
...
@api_root.api_class(resource_name='books', path='books')
class Books(remote.Service):
...
Args:
name: string, Name of the API.
version: string, Version of the API.
description: string, Short description of the API (Default: None)
hostname: string, Hostname of the API (Default: app engine default host)
audiences: list of strings, Acceptable audiences for authentication.
scopes: list of strings, Acceptable scopes for authentication.
allowed_client_ids: list of strings, Acceptable client IDs for auth.
canonical_name: string, the canonical name for the API, a more human
readable version of the name.
auth: ApiAuth instance, the authentication configuration information
for this API.
owner_domain: string, the domain of the person or company that owns
this API. Along with owner_name, this provides hints to properly
name client libraries for this API.
owner_name: string, the name of the owner of this API. Along with
owner_domain, this provides hints to properly name client libraries
for this API.
package_path: string, the "package" this API belongs to. This '/'
delimited value specifies logical groupings of APIs. This is used by
client libraries of this API.
frontend_limits: ApiFrontEndLimits, optional query limits for unregistered
developers.
title: string, the human readable title of your API. It is exposed in the
discovery service.
documentation: string, a URL where users can find documentation about this
version of the API. This will be surfaced in the API Explorer and GPE
plugin to allow users to learn about your service.
auth_level: enum from AUTH_LEVEL, frontend authentication level.
issuers: dict, mapping auth issuer names to endpoints.Issuer objects.
namespace: endpoints.Namespace, the namespace for the API.
api_key_required: bool, whether a key is required to call into this API.
base_path: string, the base path for all endpoints in this API.
limit_definitions: list of endpoints.LimitDefinition objects, quota metric
definitions for this API.
use_request_uri: if true, match requests against REQUEST_URI instead of PATH_INFO
Returns:
Class decorated with api_info attribute, an instance of ApiInfo.
"""
if auth_level is not None:
_logger.warn(_AUTH_LEVEL_WARNING)
return _ApiDecorator(name, version, description=description,
hostname=hostname, audiences=audiences, scopes=scopes,
allowed_client_ids=allowed_client_ids,
canonical_name=canonical_name, auth=auth,
owner_domain=owner_domain, owner_name=owner_name,
package_path=package_path,
frontend_limits=frontend_limits, title=title,
documentation=documentation, auth_level=auth_level,
issuers=issuers, namespace=namespace,
api_key_required=api_key_required, base_path=base_path,
limit_definitions=limit_definitions,
use_request_uri=use_request_uri) | python | def api(name, version, description=None, hostname=None, audiences=None,
scopes=None, allowed_client_ids=None, canonical_name=None,
auth=None, owner_domain=None, owner_name=None, package_path=None,
frontend_limits=None, title=None, documentation=None, auth_level=None,
issuers=None, namespace=None, api_key_required=None, base_path=None,
limit_definitions=None, use_request_uri=None):
if auth_level is not None:
_logger.warn(_AUTH_LEVEL_WARNING)
return _ApiDecorator(name, version, description=description,
hostname=hostname, audiences=audiences, scopes=scopes,
allowed_client_ids=allowed_client_ids,
canonical_name=canonical_name, auth=auth,
owner_domain=owner_domain, owner_name=owner_name,
package_path=package_path,
frontend_limits=frontend_limits, title=title,
documentation=documentation, auth_level=auth_level,
issuers=issuers, namespace=namespace,
api_key_required=api_key_required, base_path=base_path,
limit_definitions=limit_definitions,
use_request_uri=use_request_uri) | [
"def",
"api",
"(",
"name",
",",
"version",
",",
"description",
"=",
"None",
",",
"hostname",
"=",
"None",
",",
"audiences",
"=",
"None",
",",
"scopes",
"=",
"None",
",",
"allowed_client_ids",
"=",
"None",
",",
"canonical_name",
"=",
"None",
",",
"auth",
... | Decorate a ProtoRPC Service class for use by the framework above.
This decorator can be used to specify an API name, version, description, and
hostname for your API.
Sample usage (python 2.7):
@endpoints.api(name='guestbook', version='v0.2',
description='Guestbook API')
class PostService(remote.Service):
...
Sample usage (python 2.5):
class PostService(remote.Service):
...
endpoints.api(name='guestbook', version='v0.2',
description='Guestbook API')(PostService)
Sample usage if multiple classes implement one API:
api_root = endpoints.api(name='library', version='v1.0')
@api_root.api_class(resource_name='shelves')
class Shelves(remote.Service):
...
@api_root.api_class(resource_name='books', path='books')
class Books(remote.Service):
...
Args:
name: string, Name of the API.
version: string, Version of the API.
description: string, Short description of the API (Default: None)
hostname: string, Hostname of the API (Default: app engine default host)
audiences: list of strings, Acceptable audiences for authentication.
scopes: list of strings, Acceptable scopes for authentication.
allowed_client_ids: list of strings, Acceptable client IDs for auth.
canonical_name: string, the canonical name for the API, a more human
readable version of the name.
auth: ApiAuth instance, the authentication configuration information
for this API.
owner_domain: string, the domain of the person or company that owns
this API. Along with owner_name, this provides hints to properly
name client libraries for this API.
owner_name: string, the name of the owner of this API. Along with
owner_domain, this provides hints to properly name client libraries
for this API.
package_path: string, the "package" this API belongs to. This '/'
delimited value specifies logical groupings of APIs. This is used by
client libraries of this API.
frontend_limits: ApiFrontEndLimits, optional query limits for unregistered
developers.
title: string, the human readable title of your API. It is exposed in the
discovery service.
documentation: string, a URL where users can find documentation about this
version of the API. This will be surfaced in the API Explorer and GPE
plugin to allow users to learn about your service.
auth_level: enum from AUTH_LEVEL, frontend authentication level.
issuers: dict, mapping auth issuer names to endpoints.Issuer objects.
namespace: endpoints.Namespace, the namespace for the API.
api_key_required: bool, whether a key is required to call into this API.
base_path: string, the base path for all endpoints in this API.
limit_definitions: list of endpoints.LimitDefinition objects, quota metric
definitions for this API.
use_request_uri: if true, match requests against REQUEST_URI instead of PATH_INFO
Returns:
Class decorated with api_info attribute, an instance of ApiInfo. | [
"Decorate",
"a",
"ProtoRPC",
"Service",
"class",
"for",
"use",
"by",
"the",
"framework",
"above",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L988-L1077 |
22,313 | cloudendpoints/endpoints-python | endpoints/api_config.py | method | def method(request_message=message_types.VoidMessage,
response_message=message_types.VoidMessage,
name=None,
path=None,
http_method='POST',
scopes=None,
audiences=None,
allowed_client_ids=None,
auth_level=None,
api_key_required=None,
metric_costs=None,
use_request_uri=None):
"""Decorate a ProtoRPC Method for use by the framework above.
This decorator can be used to specify a method name, path, http method,
scopes, audiences, client ids and auth_level.
Sample usage:
@api_config.method(RequestMessage, ResponseMessage,
name='insert', http_method='PUT')
def greeting_insert(request):
...
return response
Args:
request_message: Message type of expected request.
response_message: Message type of expected response.
name: string, Name of the method, prepended with <apiname>. to make it
unique. (Default: python method name)
path: string, Path portion of the URL to the method, for RESTful methods.
http_method: string, HTTP method supported by the method. (Default: POST)
scopes: list of string, OAuth2 token must contain one of these scopes.
audiences: list of string, IdToken must contain one of these audiences.
allowed_client_ids: list of string, Client IDs allowed to call the method.
If None and auth_level is REQUIRED, no calls will be allowed.
auth_level: enum from AUTH_LEVEL, Frontend auth level for the method.
api_key_required: bool, whether a key is required to call the method
metric_costs: dict with keys matching an API limit metric and values
representing the cost for each successful call against that metric.
use_request_uri: if true, match requests against REQUEST_URI instead of PATH_INFO
Returns:
'apiserving_method_wrapper' function.
Raises:
TypeError: if the request_type or response_type parameters are not
proper subclasses of messages.Message.
"""
if auth_level is not None:
_logger.warn(_AUTH_LEVEL_WARNING)
# Default HTTP method if one is not specified.
DEFAULT_HTTP_METHOD = 'POST'
def apiserving_method_decorator(api_method):
"""Decorator for ProtoRPC method that configures Google's API server.
Args:
api_method: Original method being wrapped.
Returns:
Function responsible for actual invocation.
Assigns the following attributes to invocation function:
remote: Instance of RemoteInfo, contains remote method information.
remote.request_type: Expected request type for remote method.
remote.response_type: Response type returned from remote method.
method_info: Instance of _MethodInfo, api method configuration.
It is also assigned attributes corresponding to the aforementioned kwargs.
Raises:
TypeError: if the request_type or response_type parameters are not
proper subclasses of messages.Message.
KeyError: if the request_message is a ResourceContainer and the newly
created remote method has been reference by the container before. This
should never occur because a remote method is created once.
"""
request_body_class = None
request_params_class = None
if isinstance(request_message, resource_container.ResourceContainer):
remote_decorator = remote.method(request_message.combined_message_class,
response_message)
request_body_class = request_message.body_message_class()
request_params_class = request_message.parameters_message_class()
else:
remote_decorator = remote.method(request_message, response_message)
remote_method = remote_decorator(api_method)
def invoke_remote(service_instance, request):
# If the server didn't specify any auth information, build it now.
# pylint: disable=protected-access
users_id_token._maybe_set_current_user_vars(
invoke_remote, api_info=getattr(service_instance, 'api_info', None),
request=request)
# pylint: enable=protected-access
return remote_method(service_instance, request)
invoke_remote.remote = remote_method.remote
if isinstance(request_message, resource_container.ResourceContainer):
resource_container.ResourceContainer.add_to_cache(
invoke_remote.remote, request_message)
invoke_remote.method_info = _MethodInfo(
name=name or api_method.__name__, path=path or api_method.__name__,
http_method=http_method or DEFAULT_HTTP_METHOD,
scopes=scopes, audiences=audiences,
allowed_client_ids=allowed_client_ids, auth_level=auth_level,
api_key_required=api_key_required, metric_costs=metric_costs,
use_request_uri=use_request_uri,
request_body_class=request_body_class,
request_params_class=request_params_class)
invoke_remote.__name__ = invoke_remote.method_info.name
return invoke_remote
endpoints_util.check_list_type(scopes, (basestring, endpoints_types.OAuth2Scope), 'scopes')
endpoints_util.check_list_type(allowed_client_ids, basestring,
'allowed_client_ids')
_CheckEnum(auth_level, AUTH_LEVEL, 'auth_level')
_CheckAudiences(audiences)
_CheckType(metric_costs, dict, 'metric_costs')
return apiserving_method_decorator | python | def method(request_message=message_types.VoidMessage,
response_message=message_types.VoidMessage,
name=None,
path=None,
http_method='POST',
scopes=None,
audiences=None,
allowed_client_ids=None,
auth_level=None,
api_key_required=None,
metric_costs=None,
use_request_uri=None):
if auth_level is not None:
_logger.warn(_AUTH_LEVEL_WARNING)
# Default HTTP method if one is not specified.
DEFAULT_HTTP_METHOD = 'POST'
def apiserving_method_decorator(api_method):
"""Decorator for ProtoRPC method that configures Google's API server.
Args:
api_method: Original method being wrapped.
Returns:
Function responsible for actual invocation.
Assigns the following attributes to invocation function:
remote: Instance of RemoteInfo, contains remote method information.
remote.request_type: Expected request type for remote method.
remote.response_type: Response type returned from remote method.
method_info: Instance of _MethodInfo, api method configuration.
It is also assigned attributes corresponding to the aforementioned kwargs.
Raises:
TypeError: if the request_type or response_type parameters are not
proper subclasses of messages.Message.
KeyError: if the request_message is a ResourceContainer and the newly
created remote method has been reference by the container before. This
should never occur because a remote method is created once.
"""
request_body_class = None
request_params_class = None
if isinstance(request_message, resource_container.ResourceContainer):
remote_decorator = remote.method(request_message.combined_message_class,
response_message)
request_body_class = request_message.body_message_class()
request_params_class = request_message.parameters_message_class()
else:
remote_decorator = remote.method(request_message, response_message)
remote_method = remote_decorator(api_method)
def invoke_remote(service_instance, request):
# If the server didn't specify any auth information, build it now.
# pylint: disable=protected-access
users_id_token._maybe_set_current_user_vars(
invoke_remote, api_info=getattr(service_instance, 'api_info', None),
request=request)
# pylint: enable=protected-access
return remote_method(service_instance, request)
invoke_remote.remote = remote_method.remote
if isinstance(request_message, resource_container.ResourceContainer):
resource_container.ResourceContainer.add_to_cache(
invoke_remote.remote, request_message)
invoke_remote.method_info = _MethodInfo(
name=name or api_method.__name__, path=path or api_method.__name__,
http_method=http_method or DEFAULT_HTTP_METHOD,
scopes=scopes, audiences=audiences,
allowed_client_ids=allowed_client_ids, auth_level=auth_level,
api_key_required=api_key_required, metric_costs=metric_costs,
use_request_uri=use_request_uri,
request_body_class=request_body_class,
request_params_class=request_params_class)
invoke_remote.__name__ = invoke_remote.method_info.name
return invoke_remote
endpoints_util.check_list_type(scopes, (basestring, endpoints_types.OAuth2Scope), 'scopes')
endpoints_util.check_list_type(allowed_client_ids, basestring,
'allowed_client_ids')
_CheckEnum(auth_level, AUTH_LEVEL, 'auth_level')
_CheckAudiences(audiences)
_CheckType(metric_costs, dict, 'metric_costs')
return apiserving_method_decorator | [
"def",
"method",
"(",
"request_message",
"=",
"message_types",
".",
"VoidMessage",
",",
"response_message",
"=",
"message_types",
".",
"VoidMessage",
",",
"name",
"=",
"None",
",",
"path",
"=",
"None",
",",
"http_method",
"=",
"'POST'",
",",
"scopes",
"=",
"... | Decorate a ProtoRPC Method for use by the framework above.
This decorator can be used to specify a method name, path, http method,
scopes, audiences, client ids and auth_level.
Sample usage:
@api_config.method(RequestMessage, ResponseMessage,
name='insert', http_method='PUT')
def greeting_insert(request):
...
return response
Args:
request_message: Message type of expected request.
response_message: Message type of expected response.
name: string, Name of the method, prepended with <apiname>. to make it
unique. (Default: python method name)
path: string, Path portion of the URL to the method, for RESTful methods.
http_method: string, HTTP method supported by the method. (Default: POST)
scopes: list of string, OAuth2 token must contain one of these scopes.
audiences: list of string, IdToken must contain one of these audiences.
allowed_client_ids: list of string, Client IDs allowed to call the method.
If None and auth_level is REQUIRED, no calls will be allowed.
auth_level: enum from AUTH_LEVEL, Frontend auth level for the method.
api_key_required: bool, whether a key is required to call the method
metric_costs: dict with keys matching an API limit metric and values
representing the cost for each successful call against that metric.
use_request_uri: if true, match requests against REQUEST_URI instead of PATH_INFO
Returns:
'apiserving_method_wrapper' function.
Raises:
TypeError: if the request_type or response_type parameters are not
proper subclasses of messages.Message. | [
"Decorate",
"a",
"ProtoRPC",
"Method",
"for",
"use",
"by",
"the",
"framework",
"above",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1257-L1379 |
22,314 | cloudendpoints/endpoints-python | endpoints/api_config.py | _ApiInfo.is_same_api | def is_same_api(self, other):
"""Check if this implements the same API as another _ApiInfo instance."""
if not isinstance(other, _ApiInfo):
return False
# pylint: disable=protected-access
return self.__common_info is other.__common_info | python | def is_same_api(self, other):
if not isinstance(other, _ApiInfo):
return False
# pylint: disable=protected-access
return self.__common_info is other.__common_info | [
"def",
"is_same_api",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"_ApiInfo",
")",
":",
"return",
"False",
"# pylint: disable=protected-access",
"return",
"self",
".",
"__common_info",
"is",
"other",
".",
"__common_info"
] | Check if this implements the same API as another _ApiInfo instance. | [
"Check",
"if",
"this",
"implements",
"the",
"same",
"API",
"as",
"another",
"_ApiInfo",
"instance",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L307-L312 |
22,315 | cloudendpoints/endpoints-python | endpoints/api_config.py | _ApiDecorator.api_class | def api_class(self, resource_name=None, path=None, audiences=None,
scopes=None, allowed_client_ids=None, auth_level=None,
api_key_required=None):
"""Get a decorator for a class that implements an API.
This can be used for single-class or multi-class implementations. It's
used implicitly in simple single-class APIs that only use @api directly.
Args:
resource_name: string, Resource name for the class this decorates.
(Default: None)
path: string, Base path prepended to any method paths in the class this
decorates. (Default: None)
audiences: list of strings, Acceptable audiences for authentication.
(Default: None)
scopes: list of strings, Acceptable scopes for authentication.
(Default: None)
allowed_client_ids: list of strings, Acceptable client IDs for auth.
(Default: None)
auth_level: enum from AUTH_LEVEL, Frontend authentication level.
(Default: None)
api_key_required: bool, Whether a key is required to call into this API.
(Default: None)
Returns:
A decorator function to decorate a class that implements an API.
"""
if auth_level is not None:
_logger.warn(_AUTH_LEVEL_WARNING)
def apiserving_api_decorator(api_class):
"""Decorator for ProtoRPC class that configures Google's API server.
Args:
api_class: remote.Service class, ProtoRPC service class being wrapped.
Returns:
Same class with API attributes assigned in api_info.
"""
self.__classes.append(api_class)
api_class.api_info = _ApiInfo(
self.__common_info, resource_name=resource_name,
path=path, audiences=audiences, scopes=scopes,
allowed_client_ids=allowed_client_ids, auth_level=auth_level,
api_key_required=api_key_required)
return api_class
return apiserving_api_decorator | python | def api_class(self, resource_name=None, path=None, audiences=None,
scopes=None, allowed_client_ids=None, auth_level=None,
api_key_required=None):
if auth_level is not None:
_logger.warn(_AUTH_LEVEL_WARNING)
def apiserving_api_decorator(api_class):
"""Decorator for ProtoRPC class that configures Google's API server.
Args:
api_class: remote.Service class, ProtoRPC service class being wrapped.
Returns:
Same class with API attributes assigned in api_info.
"""
self.__classes.append(api_class)
api_class.api_info = _ApiInfo(
self.__common_info, resource_name=resource_name,
path=path, audiences=audiences, scopes=scopes,
allowed_client_ids=allowed_client_ids, auth_level=auth_level,
api_key_required=api_key_required)
return api_class
return apiserving_api_decorator | [
"def",
"api_class",
"(",
"self",
",",
"resource_name",
"=",
"None",
",",
"path",
"=",
"None",
",",
"audiences",
"=",
"None",
",",
"scopes",
"=",
"None",
",",
"allowed_client_ids",
"=",
"None",
",",
"auth_level",
"=",
"None",
",",
"api_key_required",
"=",
... | Get a decorator for a class that implements an API.
This can be used for single-class or multi-class implementations. It's
used implicitly in simple single-class APIs that only use @api directly.
Args:
resource_name: string, Resource name for the class this decorates.
(Default: None)
path: string, Base path prepended to any method paths in the class this
decorates. (Default: None)
audiences: list of strings, Acceptable audiences for authentication.
(Default: None)
scopes: list of strings, Acceptable scopes for authentication.
(Default: None)
allowed_client_ids: list of strings, Acceptable client IDs for auth.
(Default: None)
auth_level: enum from AUTH_LEVEL, Frontend authentication level.
(Default: None)
api_key_required: bool, Whether a key is required to call into this API.
(Default: None)
Returns:
A decorator function to decorate a class that implements an API. | [
"Get",
"a",
"decorator",
"for",
"a",
"class",
"that",
"implements",
"an",
"API",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L795-L842 |
22,316 | cloudendpoints/endpoints-python | endpoints/api_config.py | _MethodInfo.__safe_name | def __safe_name(self, method_name):
"""Restrict method name to a-zA-Z0-9_, first char lowercase."""
# Endpoints backend restricts what chars are allowed in a method name.
safe_name = re.sub(r'[^\.a-zA-Z0-9_]', '', method_name)
# Strip any number of leading underscores.
safe_name = safe_name.lstrip('_')
# Ensure the first character is lowercase.
# Slice from 0:1 rather than indexing [0] in case safe_name is length 0.
return safe_name[0:1].lower() + safe_name[1:] | python | def __safe_name(self, method_name):
# Endpoints backend restricts what chars are allowed in a method name.
safe_name = re.sub(r'[^\.a-zA-Z0-9_]', '', method_name)
# Strip any number of leading underscores.
safe_name = safe_name.lstrip('_')
# Ensure the first character is lowercase.
# Slice from 0:1 rather than indexing [0] in case safe_name is length 0.
return safe_name[0:1].lower() + safe_name[1:] | [
"def",
"__safe_name",
"(",
"self",
",",
"method_name",
")",
":",
"# Endpoints backend restricts what chars are allowed in a method name.",
"safe_name",
"=",
"re",
".",
"sub",
"(",
"r'[^\\.a-zA-Z0-9_]'",
",",
"''",
",",
"method_name",
")",
"# Strip any number of leading unde... | Restrict method name to a-zA-Z0-9_, first char lowercase. | [
"Restrict",
"method",
"name",
"to",
"a",
"-",
"zA",
"-",
"Z0",
"-",
"9_",
"first",
"char",
"lowercase",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1126-L1136 |
22,317 | cloudendpoints/endpoints-python | endpoints/api_config.py | _MethodInfo.method_id | def method_id(self, api_info):
"""Computed method name."""
# This is done here for now because at __init__ time, the method is known
# but not the api, and thus not the api name. Later, in
# ApiConfigGenerator.__method_descriptor, the api name is known.
if api_info.resource_name:
resource_part = '.%s' % self.__safe_name(api_info.resource_name)
else:
resource_part = ''
return '%s%s.%s' % (self.__safe_name(api_info.name), resource_part,
self.__safe_name(self.name)) | python | def method_id(self, api_info):
# This is done here for now because at __init__ time, the method is known
# but not the api, and thus not the api name. Later, in
# ApiConfigGenerator.__method_descriptor, the api name is known.
if api_info.resource_name:
resource_part = '.%s' % self.__safe_name(api_info.resource_name)
else:
resource_part = ''
return '%s%s.%s' % (self.__safe_name(api_info.name), resource_part,
self.__safe_name(self.name)) | [
"def",
"method_id",
"(",
"self",
",",
"api_info",
")",
":",
"# This is done here for now because at __init__ time, the method is known",
"# but not the api, and thus not the api name. Later, in",
"# ApiConfigGenerator.__method_descriptor, the api name is known.",
"if",
"api_info",
".",
... | Computed method name. | [
"Computed",
"method",
"name",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1243-L1253 |
22,318 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.__field_to_subfields | def __field_to_subfields(self, field):
"""Fully describes data represented by field, including the nested case.
In the case that the field is not a message field, we have no fields nested
within a message definition, so we can simply return that field. However, in
the nested case, we can't simply describe the data with one field or even
with one chain of fields.
For example, if we have a message field
m_field = messages.MessageField(RefClass, 1)
which references a class with two fields:
class RefClass(messages.Message):
one = messages.StringField(1)
two = messages.IntegerField(2)
then we would need to include both one and two to represent all the
data contained.
Calling __field_to_subfields(m_field) would return:
[
[<MessageField "m_field">, <StringField "one">],
[<MessageField "m_field">, <StringField "two">],
]
If the second field was instead a message field
class RefClass(messages.Message):
one = messages.StringField(1)
two = messages.MessageField(OtherRefClass, 2)
referencing another class with two fields
class OtherRefClass(messages.Message):
three = messages.BooleanField(1)
four = messages.FloatField(2)
then we would need to recurse one level deeper for two.
With this change, calling __field_to_subfields(m_field) would return:
[
[<MessageField "m_field">, <StringField "one">],
[<MessageField "m_field">, <StringField "two">, <StringField "three">],
[<MessageField "m_field">, <StringField "two">, <StringField "four">],
]
Args:
field: An instance of a subclass of messages.Field.
Returns:
A list of lists, where each sublist is a list of fields.
"""
# Termination condition
if not isinstance(field, messages.MessageField):
return [[field]]
result = []
for subfield in sorted(field.message_type.all_fields(),
key=lambda f: f.number):
subfield_results = self.__field_to_subfields(subfield)
for subfields_list in subfield_results:
subfields_list.insert(0, field)
result.append(subfields_list)
return result | python | def __field_to_subfields(self, field):
# Termination condition
if not isinstance(field, messages.MessageField):
return [[field]]
result = []
for subfield in sorted(field.message_type.all_fields(),
key=lambda f: f.number):
subfield_results = self.__field_to_subfields(subfield)
for subfields_list in subfield_results:
subfields_list.insert(0, field)
result.append(subfields_list)
return result | [
"def",
"__field_to_subfields",
"(",
"self",
",",
"field",
")",
":",
"# Termination condition",
"if",
"not",
"isinstance",
"(",
"field",
",",
"messages",
".",
"MessageField",
")",
":",
"return",
"[",
"[",
"field",
"]",
"]",
"result",
"=",
"[",
"]",
"for",
... | Fully describes data represented by field, including the nested case.
In the case that the field is not a message field, we have no fields nested
within a message definition, so we can simply return that field. However, in
the nested case, we can't simply describe the data with one field or even
with one chain of fields.
For example, if we have a message field
m_field = messages.MessageField(RefClass, 1)
which references a class with two fields:
class RefClass(messages.Message):
one = messages.StringField(1)
two = messages.IntegerField(2)
then we would need to include both one and two to represent all the
data contained.
Calling __field_to_subfields(m_field) would return:
[
[<MessageField "m_field">, <StringField "one">],
[<MessageField "m_field">, <StringField "two">],
]
If the second field was instead a message field
class RefClass(messages.Message):
one = messages.StringField(1)
two = messages.MessageField(OtherRefClass, 2)
referencing another class with two fields
class OtherRefClass(messages.Message):
three = messages.BooleanField(1)
four = messages.FloatField(2)
then we would need to recurse one level deeper for two.
With this change, calling __field_to_subfields(m_field) would return:
[
[<MessageField "m_field">, <StringField "one">],
[<MessageField "m_field">, <StringField "two">, <StringField "three">],
[<MessageField "m_field">, <StringField "two">, <StringField "four">],
]
Args:
field: An instance of a subclass of messages.Field.
Returns:
A list of lists, where each sublist is a list of fields. | [
"Fully",
"describes",
"data",
"represented",
"by",
"field",
"including",
"the",
"nested",
"case",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1438-L1503 |
22,319 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.__field_to_parameter_type | def __field_to_parameter_type(self, field):
"""Converts the field variant type into a string describing the parameter.
Args:
field: An instance of a subclass of messages.Field.
Returns:
A string corresponding to the variant enum of the field, with a few
exceptions. In the case of signed ints, the 's' is dropped; for the BOOL
variant, 'boolean' is used; and for the ENUM variant, 'string' is used.
Raises:
TypeError: if the field variant is a message variant.
"""
# We use lowercase values for types (e.g. 'string' instead of 'STRING').
variant = field.variant
if variant == messages.Variant.MESSAGE:
raise TypeError('A message variant can\'t be used in a parameter.')
custom_variant_map = {
messages.Variant.SINT32: 'int32',
messages.Variant.SINT64: 'int64',
messages.Variant.BOOL: 'boolean',
messages.Variant.ENUM: 'string',
}
return custom_variant_map.get(variant) or variant.name.lower() | python | def __field_to_parameter_type(self, field):
# We use lowercase values for types (e.g. 'string' instead of 'STRING').
variant = field.variant
if variant == messages.Variant.MESSAGE:
raise TypeError('A message variant can\'t be used in a parameter.')
custom_variant_map = {
messages.Variant.SINT32: 'int32',
messages.Variant.SINT64: 'int64',
messages.Variant.BOOL: 'boolean',
messages.Variant.ENUM: 'string',
}
return custom_variant_map.get(variant) or variant.name.lower() | [
"def",
"__field_to_parameter_type",
"(",
"self",
",",
"field",
")",
":",
"# We use lowercase values for types (e.g. 'string' instead of 'STRING').",
"variant",
"=",
"field",
".",
"variant",
"if",
"variant",
"==",
"messages",
".",
"Variant",
".",
"MESSAGE",
":",
"raise",... | Converts the field variant type into a string describing the parameter.
Args:
field: An instance of a subclass of messages.Field.
Returns:
A string corresponding to the variant enum of the field, with a few
exceptions. In the case of signed ints, the 's' is dropped; for the BOOL
variant, 'boolean' is used; and for the ENUM variant, 'string' is used.
Raises:
TypeError: if the field variant is a message variant. | [
"Converts",
"the",
"field",
"variant",
"type",
"into",
"a",
"string",
"describing",
"the",
"parameter",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1507-L1532 |
22,320 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.__get_path_parameters | def __get_path_parameters(self, path):
"""Parses path paremeters from a URI path and organizes them by parameter.
Some of the parameters may correspond to message fields, and so will be
represented as segments corresponding to each subfield; e.g. first.second if
the field "second" in the message field "first" is pulled from the path.
The resulting dictionary uses the first segments as keys and each key has as
value the list of full parameter values with first segment equal to the key.
If the match path parameter is null, that part of the path template is
ignored; this occurs if '{}' is used in a template.
Args:
path: String; a URI path, potentially with some parameters.
Returns:
A dictionary with strings as keys and list of strings as values.
"""
path_parameters_by_segment = {}
for format_var_name in re.findall(_PATH_VARIABLE_PATTERN, path):
first_segment = format_var_name.split('.', 1)[0]
matches = path_parameters_by_segment.setdefault(first_segment, [])
matches.append(format_var_name)
return path_parameters_by_segment | python | def __get_path_parameters(self, path):
path_parameters_by_segment = {}
for format_var_name in re.findall(_PATH_VARIABLE_PATTERN, path):
first_segment = format_var_name.split('.', 1)[0]
matches = path_parameters_by_segment.setdefault(first_segment, [])
matches.append(format_var_name)
return path_parameters_by_segment | [
"def",
"__get_path_parameters",
"(",
"self",
",",
"path",
")",
":",
"path_parameters_by_segment",
"=",
"{",
"}",
"for",
"format_var_name",
"in",
"re",
".",
"findall",
"(",
"_PATH_VARIABLE_PATTERN",
",",
"path",
")",
":",
"first_segment",
"=",
"format_var_name",
... | Parses path paremeters from a URI path and organizes them by parameter.
Some of the parameters may correspond to message fields, and so will be
represented as segments corresponding to each subfield; e.g. first.second if
the field "second" in the message field "first" is pulled from the path.
The resulting dictionary uses the first segments as keys and each key has as
value the list of full parameter values with first segment equal to the key.
If the match path parameter is null, that part of the path template is
ignored; this occurs if '{}' is used in a template.
Args:
path: String; a URI path, potentially with some parameters.
Returns:
A dictionary with strings as keys and list of strings as values. | [
"Parses",
"path",
"paremeters",
"from",
"a",
"URI",
"path",
"and",
"organizes",
"them",
"by",
"parameter",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1534-L1559 |
22,321 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.__validate_simple_subfield | def __validate_simple_subfield(self, parameter, field, segment_list,
_segment_index=0):
"""Verifies that a proposed subfield actually exists and is a simple field.
Here, simple means it is not a MessageField (nested).
Args:
parameter: String; the '.' delimited name of the current field being
considered. This is relative to some root.
field: An instance of a subclass of messages.Field. Corresponds to the
previous segment in the path (previous relative to _segment_index),
since this field should be a message field with the current segment
as a field in the message class.
segment_list: The full list of segments from the '.' delimited subfield
being validated.
_segment_index: Integer; used to hold the position of current segment so
that segment_list can be passed as a reference instead of having to
copy using segment_list[1:] at each step.
Raises:
TypeError: If the final subfield (indicated by _segment_index relative
to the length of segment_list) is a MessageField.
TypeError: If at any stage the lookup at a segment fails, e.g if a.b
exists but a.b.c does not exist. This can happen either if a.b is not
a message field or if a.b.c is not a property on the message class from
a.b.
"""
if _segment_index >= len(segment_list):
# In this case, the field is the final one, so should be simple type
if isinstance(field, messages.MessageField):
field_class = field.__class__.__name__
raise TypeError('Can\'t use messages in path. Subfield %r was '
'included but is a %s.' % (parameter, field_class))
return
segment = segment_list[_segment_index]
parameter += '.' + segment
try:
field = field.type.field_by_name(segment)
except (AttributeError, KeyError):
raise TypeError('Subfield %r from path does not exist.' % (parameter,))
self.__validate_simple_subfield(parameter, field, segment_list,
_segment_index=_segment_index + 1) | python | def __validate_simple_subfield(self, parameter, field, segment_list,
_segment_index=0):
if _segment_index >= len(segment_list):
# In this case, the field is the final one, so should be simple type
if isinstance(field, messages.MessageField):
field_class = field.__class__.__name__
raise TypeError('Can\'t use messages in path. Subfield %r was '
'included but is a %s.' % (parameter, field_class))
return
segment = segment_list[_segment_index]
parameter += '.' + segment
try:
field = field.type.field_by_name(segment)
except (AttributeError, KeyError):
raise TypeError('Subfield %r from path does not exist.' % (parameter,))
self.__validate_simple_subfield(parameter, field, segment_list,
_segment_index=_segment_index + 1) | [
"def",
"__validate_simple_subfield",
"(",
"self",
",",
"parameter",
",",
"field",
",",
"segment_list",
",",
"_segment_index",
"=",
"0",
")",
":",
"if",
"_segment_index",
">=",
"len",
"(",
"segment_list",
")",
":",
"# In this case, the field is the final one, so should... | Verifies that a proposed subfield actually exists and is a simple field.
Here, simple means it is not a MessageField (nested).
Args:
parameter: String; the '.' delimited name of the current field being
considered. This is relative to some root.
field: An instance of a subclass of messages.Field. Corresponds to the
previous segment in the path (previous relative to _segment_index),
since this field should be a message field with the current segment
as a field in the message class.
segment_list: The full list of segments from the '.' delimited subfield
being validated.
_segment_index: Integer; used to hold the position of current segment so
that segment_list can be passed as a reference instead of having to
copy using segment_list[1:] at each step.
Raises:
TypeError: If the final subfield (indicated by _segment_index relative
to the length of segment_list) is a MessageField.
TypeError: If at any stage the lookup at a segment fails, e.g if a.b
exists but a.b.c does not exist. This can happen either if a.b is not
a message field or if a.b.c is not a property on the message class from
a.b. | [
"Verifies",
"that",
"a",
"proposed",
"subfield",
"actually",
"exists",
"and",
"is",
"a",
"simple",
"field",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1561-L1604 |
22,322 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.__validate_path_parameters | def __validate_path_parameters(self, field, path_parameters):
"""Verifies that all path parameters correspond to an existing subfield.
Args:
field: An instance of a subclass of messages.Field. Should be the root
level property name in each path parameter in path_parameters. For
example, if the field is called 'foo', then each path parameter should
begin with 'foo.'.
path_parameters: A list of Strings representing URI parameter variables.
Raises:
TypeError: If one of the path parameters does not start with field.name.
"""
for param in path_parameters:
segment_list = param.split('.')
if segment_list[0] != field.name:
raise TypeError('Subfield %r can\'t come from field %r.'
% (param, field.name))
self.__validate_simple_subfield(field.name, field, segment_list[1:]) | python | def __validate_path_parameters(self, field, path_parameters):
for param in path_parameters:
segment_list = param.split('.')
if segment_list[0] != field.name:
raise TypeError('Subfield %r can\'t come from field %r.'
% (param, field.name))
self.__validate_simple_subfield(field.name, field, segment_list[1:]) | [
"def",
"__validate_path_parameters",
"(",
"self",
",",
"field",
",",
"path_parameters",
")",
":",
"for",
"param",
"in",
"path_parameters",
":",
"segment_list",
"=",
"param",
".",
"split",
"(",
"'.'",
")",
"if",
"segment_list",
"[",
"0",
"]",
"!=",
"field",
... | Verifies that all path parameters correspond to an existing subfield.
Args:
field: An instance of a subclass of messages.Field. Should be the root
level property name in each path parameter in path_parameters. For
example, if the field is called 'foo', then each path parameter should
begin with 'foo.'.
path_parameters: A list of Strings representing URI parameter variables.
Raises:
TypeError: If one of the path parameters does not start with field.name. | [
"Verifies",
"that",
"all",
"path",
"parameters",
"correspond",
"to",
"an",
"existing",
"subfield",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1606-L1624 |
22,323 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.__parameter_default | def __parameter_default(self, final_subfield):
"""Returns default value of final subfield if it has one.
If this subfield comes from a field list returned from __field_to_subfields,
none of the fields in the subfield list can have a default except the final
one since they all must be message fields.
Args:
final_subfield: A simple field from the end of a subfield list.
Returns:
The default value of the subfield, if any exists, with the exception of an
enum field, which will have its value cast to a string.
"""
if final_subfield.default:
if isinstance(final_subfield, messages.EnumField):
return final_subfield.default.name
else:
return final_subfield.default | python | def __parameter_default(self, final_subfield):
if final_subfield.default:
if isinstance(final_subfield, messages.EnumField):
return final_subfield.default.name
else:
return final_subfield.default | [
"def",
"__parameter_default",
"(",
"self",
",",
"final_subfield",
")",
":",
"if",
"final_subfield",
".",
"default",
":",
"if",
"isinstance",
"(",
"final_subfield",
",",
"messages",
".",
"EnumField",
")",
":",
"return",
"final_subfield",
".",
"default",
".",
"n... | Returns default value of final subfield if it has one.
If this subfield comes from a field list returned from __field_to_subfields,
none of the fields in the subfield list can have a default except the final
one since they all must be message fields.
Args:
final_subfield: A simple field from the end of a subfield list.
Returns:
The default value of the subfield, if any exists, with the exception of an
enum field, which will have its value cast to a string. | [
"Returns",
"default",
"value",
"of",
"final",
"subfield",
"if",
"it",
"has",
"one",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1626-L1644 |
22,324 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.__parameter_enum | def __parameter_enum(self, final_subfield):
"""Returns enum descriptor of final subfield if it is an enum.
An enum descriptor is a dictionary with keys as the names from the enum and
each value is a dictionary with a single key "backendValue" and value equal
to the same enum name used to stored it in the descriptor.
The key "description" can also be used next to "backendValue", but protorpc
Enum classes have no way of supporting a description for each value.
Args:
final_subfield: A simple field from the end of a subfield list.
Returns:
The enum descriptor for the field, if it's an enum descriptor, else
returns None.
"""
if isinstance(final_subfield, messages.EnumField):
enum_descriptor = {}
for enum_value in final_subfield.type.to_dict().keys():
enum_descriptor[enum_value] = {'backendValue': enum_value}
return enum_descriptor | python | def __parameter_enum(self, final_subfield):
if isinstance(final_subfield, messages.EnumField):
enum_descriptor = {}
for enum_value in final_subfield.type.to_dict().keys():
enum_descriptor[enum_value] = {'backendValue': enum_value}
return enum_descriptor | [
"def",
"__parameter_enum",
"(",
"self",
",",
"final_subfield",
")",
":",
"if",
"isinstance",
"(",
"final_subfield",
",",
"messages",
".",
"EnumField",
")",
":",
"enum_descriptor",
"=",
"{",
"}",
"for",
"enum_value",
"in",
"final_subfield",
".",
"type",
".",
... | Returns enum descriptor of final subfield if it is an enum.
An enum descriptor is a dictionary with keys as the names from the enum and
each value is a dictionary with a single key "backendValue" and value equal
to the same enum name used to stored it in the descriptor.
The key "description" can also be used next to "backendValue", but protorpc
Enum classes have no way of supporting a description for each value.
Args:
final_subfield: A simple field from the end of a subfield list.
Returns:
The enum descriptor for the field, if it's an enum descriptor, else
returns None. | [
"Returns",
"enum",
"descriptor",
"of",
"final",
"subfield",
"if",
"it",
"is",
"an",
"enum",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1646-L1667 |
22,325 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.__parameter_descriptor | def __parameter_descriptor(self, subfield_list):
"""Creates descriptor for a parameter using the subfields that define it.
Each parameter is defined by a list of fields, with all but the last being
a message field and the final being a simple (non-message) field.
Many of the fields in the descriptor are determined solely by the simple
field at the end, though some (such as repeated and required) take the whole
chain of fields into consideration.
Args:
subfield_list: List of fields describing the parameter.
Returns:
Dictionary containing a descriptor for the parameter described by the list
of fields.
"""
descriptor = {}
final_subfield = subfield_list[-1]
# Required
if all(subfield.required for subfield in subfield_list):
descriptor['required'] = True
# Type
descriptor['type'] = self.__field_to_parameter_type(final_subfield)
# Default
default = self.__parameter_default(final_subfield)
if default is not None:
descriptor['default'] = default
# Repeated
if any(subfield.repeated for subfield in subfield_list):
descriptor['repeated'] = True
# Enum
enum_descriptor = self.__parameter_enum(final_subfield)
if enum_descriptor is not None:
descriptor['enum'] = enum_descriptor
return descriptor | python | def __parameter_descriptor(self, subfield_list):
descriptor = {}
final_subfield = subfield_list[-1]
# Required
if all(subfield.required for subfield in subfield_list):
descriptor['required'] = True
# Type
descriptor['type'] = self.__field_to_parameter_type(final_subfield)
# Default
default = self.__parameter_default(final_subfield)
if default is not None:
descriptor['default'] = default
# Repeated
if any(subfield.repeated for subfield in subfield_list):
descriptor['repeated'] = True
# Enum
enum_descriptor = self.__parameter_enum(final_subfield)
if enum_descriptor is not None:
descriptor['enum'] = enum_descriptor
return descriptor | [
"def",
"__parameter_descriptor",
"(",
"self",
",",
"subfield_list",
")",
":",
"descriptor",
"=",
"{",
"}",
"final_subfield",
"=",
"subfield_list",
"[",
"-",
"1",
"]",
"# Required",
"if",
"all",
"(",
"subfield",
".",
"required",
"for",
"subfield",
"in",
"subf... | Creates descriptor for a parameter using the subfields that define it.
Each parameter is defined by a list of fields, with all but the last being
a message field and the final being a simple (non-message) field.
Many of the fields in the descriptor are determined solely by the simple
field at the end, though some (such as repeated and required) take the whole
chain of fields into consideration.
Args:
subfield_list: List of fields describing the parameter.
Returns:
Dictionary containing a descriptor for the parameter described by the list
of fields. | [
"Creates",
"descriptor",
"for",
"a",
"parameter",
"using",
"the",
"subfields",
"that",
"define",
"it",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1669-L1710 |
22,326 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.__schema_descriptor | def __schema_descriptor(self, services):
"""Descriptor for the all the JSON Schema used.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
Returns:
Dictionary containing all the JSON Schema used in the service.
"""
methods_desc = {}
for service in services:
protorpc_methods = service.all_remote_methods()
for protorpc_method_name in protorpc_methods.iterkeys():
rosy_method = '%s.%s' % (service.__name__, protorpc_method_name)
method_id = self.__id_from_name[rosy_method]
request_response = {}
request_schema_id = self.__request_schema.get(method_id)
if request_schema_id:
request_response['request'] = {
'$ref': request_schema_id
}
response_schema_id = self.__response_schema.get(method_id)
if response_schema_id:
request_response['response'] = {
'$ref': response_schema_id
}
methods_desc[rosy_method] = request_response
descriptor = {
'methods': methods_desc,
'schemas': self.__parser.schemas(),
}
return descriptor | python | def __schema_descriptor(self, services):
methods_desc = {}
for service in services:
protorpc_methods = service.all_remote_methods()
for protorpc_method_name in protorpc_methods.iterkeys():
rosy_method = '%s.%s' % (service.__name__, protorpc_method_name)
method_id = self.__id_from_name[rosy_method]
request_response = {}
request_schema_id = self.__request_schema.get(method_id)
if request_schema_id:
request_response['request'] = {
'$ref': request_schema_id
}
response_schema_id = self.__response_schema.get(method_id)
if response_schema_id:
request_response['response'] = {
'$ref': response_schema_id
}
methods_desc[rosy_method] = request_response
descriptor = {
'methods': methods_desc,
'schemas': self.__parser.schemas(),
}
return descriptor | [
"def",
"__schema_descriptor",
"(",
"self",
",",
"services",
")",
":",
"methods_desc",
"=",
"{",
"}",
"for",
"service",
"in",
"services",
":",
"protorpc_methods",
"=",
"service",
".",
"all_remote_methods",
"(",
")",
"for",
"protorpc_method_name",
"in",
"protorpc_... | Descriptor for the all the JSON Schema used.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
Returns:
Dictionary containing all the JSON Schema used in the service. | [
"Descriptor",
"for",
"the",
"all",
"the",
"JSON",
"Schema",
"used",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L1960-L1999 |
22,327 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.__auth_descriptor | def __auth_descriptor(self, api_info):
"""Builds an auth descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A dictionary with 'allowCookieAuth' and/or 'blockedRegions' keys.
"""
if api_info.auth is None:
return None
auth_descriptor = {}
if api_info.auth.allow_cookie_auth is not None:
auth_descriptor['allowCookieAuth'] = api_info.auth.allow_cookie_auth
if api_info.auth.blocked_regions:
auth_descriptor['blockedRegions'] = api_info.auth.blocked_regions
return auth_descriptor | python | def __auth_descriptor(self, api_info):
if api_info.auth is None:
return None
auth_descriptor = {}
if api_info.auth.allow_cookie_auth is not None:
auth_descriptor['allowCookieAuth'] = api_info.auth.allow_cookie_auth
if api_info.auth.blocked_regions:
auth_descriptor['blockedRegions'] = api_info.auth.blocked_regions
return auth_descriptor | [
"def",
"__auth_descriptor",
"(",
"self",
",",
"api_info",
")",
":",
"if",
"api_info",
".",
"auth",
"is",
"None",
":",
"return",
"None",
"auth_descriptor",
"=",
"{",
"}",
"if",
"api_info",
".",
"auth",
".",
"allow_cookie_auth",
"is",
"not",
"None",
":",
"... | Builds an auth descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A dictionary with 'allowCookieAuth' and/or 'blockedRegions' keys. | [
"Builds",
"an",
"auth",
"descriptor",
"from",
"API",
"info",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L2028-L2046 |
22,328 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.__frontend_limit_descriptor | def __frontend_limit_descriptor(self, api_info):
"""Builds a frontend limit descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A dictionary with frontend limit information.
"""
if api_info.frontend_limits is None:
return None
descriptor = {}
for propname, descname in (('unregistered_user_qps', 'unregisteredUserQps'),
('unregistered_qps', 'unregisteredQps'),
('unregistered_daily', 'unregisteredDaily')):
if getattr(api_info.frontend_limits, propname) is not None:
descriptor[descname] = getattr(api_info.frontend_limits, propname)
rules = self.__frontend_limit_rules_descriptor(api_info)
if rules:
descriptor['rules'] = rules
return descriptor | python | def __frontend_limit_descriptor(self, api_info):
if api_info.frontend_limits is None:
return None
descriptor = {}
for propname, descname in (('unregistered_user_qps', 'unregisteredUserQps'),
('unregistered_qps', 'unregisteredQps'),
('unregistered_daily', 'unregisteredDaily')):
if getattr(api_info.frontend_limits, propname) is not None:
descriptor[descname] = getattr(api_info.frontend_limits, propname)
rules = self.__frontend_limit_rules_descriptor(api_info)
if rules:
descriptor['rules'] = rules
return descriptor | [
"def",
"__frontend_limit_descriptor",
"(",
"self",
",",
"api_info",
")",
":",
"if",
"api_info",
".",
"frontend_limits",
"is",
"None",
":",
"return",
"None",
"descriptor",
"=",
"{",
"}",
"for",
"propname",
",",
"descname",
"in",
"(",
"(",
"'unregistered_user_qp... | Builds a frontend limit descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A dictionary with frontend limit information. | [
"Builds",
"a",
"frontend",
"limit",
"descriptor",
"from",
"API",
"info",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L2048-L2071 |
22,329 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.__frontend_limit_rules_descriptor | def __frontend_limit_rules_descriptor(self, api_info):
"""Builds a frontend limit rules descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A list of dictionaries with frontend limit rules information.
"""
if not api_info.frontend_limits.rules:
return None
rules = []
for rule in api_info.frontend_limits.rules:
descriptor = {}
for propname, descname in (('match', 'match'),
('qps', 'qps'),
('user_qps', 'userQps'),
('daily', 'daily'),
('analytics_id', 'analyticsId')):
if getattr(rule, propname) is not None:
descriptor[descname] = getattr(rule, propname)
if descriptor:
rules.append(descriptor)
return rules | python | def __frontend_limit_rules_descriptor(self, api_info):
if not api_info.frontend_limits.rules:
return None
rules = []
for rule in api_info.frontend_limits.rules:
descriptor = {}
for propname, descname in (('match', 'match'),
('qps', 'qps'),
('user_qps', 'userQps'),
('daily', 'daily'),
('analytics_id', 'analyticsId')):
if getattr(rule, propname) is not None:
descriptor[descname] = getattr(rule, propname)
if descriptor:
rules.append(descriptor)
return rules | [
"def",
"__frontend_limit_rules_descriptor",
"(",
"self",
",",
"api_info",
")",
":",
"if",
"not",
"api_info",
".",
"frontend_limits",
".",
"rules",
":",
"return",
"None",
"rules",
"=",
"[",
"]",
"for",
"rule",
"in",
"api_info",
".",
"frontend_limits",
".",
"r... | Builds a frontend limit rules descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A list of dictionaries with frontend limit rules information. | [
"Builds",
"a",
"frontend",
"limit",
"rules",
"descriptor",
"from",
"API",
"info",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L2073-L2098 |
22,330 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.get_config_dict | def get_config_dict(self, services, hostname=None):
"""JSON dict description of a protorpc.remote.Service in API format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
dict, The API descriptor document as a JSON dict.
"""
if not isinstance(services, (tuple, list)):
services = [services]
# The type of a class that inherits from remote.Service is actually
# remote._ServiceClass, thanks to metaclass strangeness.
# pylint: disable=protected-access
endpoints_util.check_list_type(services, remote._ServiceClass, 'services',
allow_none=False)
return self.__api_descriptor(services, hostname=hostname) | python | def get_config_dict(self, services, hostname=None):
if not isinstance(services, (tuple, list)):
services = [services]
# The type of a class that inherits from remote.Service is actually
# remote._ServiceClass, thanks to metaclass strangeness.
# pylint: disable=protected-access
endpoints_util.check_list_type(services, remote._ServiceClass, 'services',
allow_none=False)
return self.__api_descriptor(services, hostname=hostname) | [
"def",
"get_config_dict",
"(",
"self",
",",
"services",
",",
"hostname",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"services",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"services",
"=",
"[",
"services",
"]",
"# The type of a class that in... | JSON dict description of a protorpc.remote.Service in API format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
dict, The API descriptor document as a JSON dict. | [
"JSON",
"dict",
"description",
"of",
"a",
"protorpc",
".",
"remote",
".",
"Service",
"in",
"API",
"format",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L2226-L2246 |
22,331 | cloudendpoints/endpoints-python | endpoints/api_config.py | ApiConfigGenerator.pretty_print_config_to_json | def pretty_print_config_to_json(self, services, hostname=None):
"""JSON string description of a protorpc.remote.Service in API format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
string, The API descriptor document as a JSON string.
"""
descriptor = self.get_config_dict(services, hostname)
return json.dumps(descriptor, sort_keys=True, indent=2,
separators=(',', ': ')) | python | def pretty_print_config_to_json(self, services, hostname=None):
descriptor = self.get_config_dict(services, hostname)
return json.dumps(descriptor, sort_keys=True, indent=2,
separators=(',', ': ')) | [
"def",
"pretty_print_config_to_json",
"(",
"self",
",",
"services",
",",
"hostname",
"=",
"None",
")",
":",
"descriptor",
"=",
"self",
".",
"get_config_dict",
"(",
"services",
",",
"hostname",
")",
"return",
"json",
".",
"dumps",
"(",
"descriptor",
",",
"sor... | JSON string description of a protorpc.remote.Service in API format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
string, The API descriptor document as a JSON string. | [
"JSON",
"string",
"description",
"of",
"a",
"protorpc",
".",
"remote",
".",
"Service",
"in",
"API",
"format",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L2248-L2262 |
22,332 | cloudendpoints/endpoints-python | endpoints/discovery_generator.py | DiscoveryGenerator.__parameter_enum | def __parameter_enum(self, param):
"""Returns enum descriptor of a parameter if it is an enum.
An enum descriptor is a list of keys.
Args:
param: A simple field.
Returns:
The enum descriptor for the field, if it's an enum descriptor, else
returns None.
"""
if isinstance(param, messages.EnumField):
return [enum_entry[0] for enum_entry in sorted(
param.type.to_dict().items(), key=lambda v: v[1])] | python | def __parameter_enum(self, param):
if isinstance(param, messages.EnumField):
return [enum_entry[0] for enum_entry in sorted(
param.type.to_dict().items(), key=lambda v: v[1])] | [
"def",
"__parameter_enum",
"(",
"self",
",",
"param",
")",
":",
"if",
"isinstance",
"(",
"param",
",",
"messages",
".",
"EnumField",
")",
":",
"return",
"[",
"enum_entry",
"[",
"0",
"]",
"for",
"enum_entry",
"in",
"sorted",
"(",
"param",
".",
"type",
"... | Returns enum descriptor of a parameter if it is an enum.
An enum descriptor is a list of keys.
Args:
param: A simple field.
Returns:
The enum descriptor for the field, if it's an enum descriptor, else
returns None. | [
"Returns",
"enum",
"descriptor",
"of",
"a",
"parameter",
"if",
"it",
"is",
"an",
"enum",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_generator.py#L332-L346 |
22,333 | cloudendpoints/endpoints-python | endpoints/discovery_generator.py | DiscoveryGenerator.__params_order_descriptor | def __params_order_descriptor(self, message_type, path, is_params_class=False):
"""Describe the order of path parameters.
Args:
message_type: messages.Message class, Message with parameters to describe.
path: string, HTTP path to method.
is_params_class: boolean, Whether the message represents URL parameters.
Returns:
Descriptor list for the parameter order.
"""
path_params = []
query_params = []
path_parameter_dict = self.__get_path_parameters(path)
for field in sorted(message_type.all_fields(), key=lambda f: f.number):
matched_path_parameters = path_parameter_dict.get(field.name, [])
if not isinstance(field, messages.MessageField):
name = field.name
if name in matched_path_parameters:
path_params.append(name)
elif is_params_class and field.required:
query_params.append(name)
else:
for subfield_list in self.__field_to_subfields(field):
name = '.'.join(subfield.name for subfield in subfield_list)
if name in matched_path_parameters:
path_params.append(name)
elif is_params_class and field.required:
query_params.append(name)
return path_params + sorted(query_params) | python | def __params_order_descriptor(self, message_type, path, is_params_class=False):
path_params = []
query_params = []
path_parameter_dict = self.__get_path_parameters(path)
for field in sorted(message_type.all_fields(), key=lambda f: f.number):
matched_path_parameters = path_parameter_dict.get(field.name, [])
if not isinstance(field, messages.MessageField):
name = field.name
if name in matched_path_parameters:
path_params.append(name)
elif is_params_class and field.required:
query_params.append(name)
else:
for subfield_list in self.__field_to_subfields(field):
name = '.'.join(subfield.name for subfield in subfield_list)
if name in matched_path_parameters:
path_params.append(name)
elif is_params_class and field.required:
query_params.append(name)
return path_params + sorted(query_params) | [
"def",
"__params_order_descriptor",
"(",
"self",
",",
"message_type",
",",
"path",
",",
"is_params_class",
"=",
"False",
")",
":",
"path_params",
"=",
"[",
"]",
"query_params",
"=",
"[",
"]",
"path_parameter_dict",
"=",
"self",
".",
"__get_path_parameters",
"(",... | Describe the order of path parameters.
Args:
message_type: messages.Message class, Message with parameters to describe.
path: string, HTTP path to method.
is_params_class: boolean, Whether the message represents URL parameters.
Returns:
Descriptor list for the parameter order. | [
"Describe",
"the",
"order",
"of",
"path",
"parameters",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_generator.py#L514-L545 |
22,334 | cloudendpoints/endpoints-python | endpoints/discovery_generator.py | DiscoveryGenerator.__schemas_descriptor | def __schemas_descriptor(self):
"""Describes the schemas section of the discovery document.
Returns:
Dictionary describing the schemas of the document.
"""
# Filter out any keys that aren't 'properties', 'type', or 'id'
result = {}
for schema_key, schema_value in self.__parser.schemas().iteritems():
field_keys = schema_value.keys()
key_result = {}
# Some special processing for the properties value
if 'properties' in field_keys:
key_result['properties'] = schema_value['properties'].copy()
# Add in enumDescriptions for any enum properties and strip out
# the required tag for consistency with Java framework
for prop_key, prop_value in schema_value['properties'].iteritems():
if 'enum' in prop_value:
num_enums = len(prop_value['enum'])
key_result['properties'][prop_key]['enumDescriptions'] = (
[''] * num_enums)
elif 'default' in prop_value:
# stringify default values
if prop_value.get('type') == 'boolean':
prop_value['default'] = 'true' if prop_value['default'] else 'false'
else:
prop_value['default'] = str(prop_value['default'])
key_result['properties'][prop_key].pop('required', None)
for key in ('type', 'id', 'description'):
if key in field_keys:
key_result[key] = schema_value[key]
if key_result:
result[schema_key] = key_result
# Add 'type': 'object' to all object properties
for schema_value in result.itervalues():
for field_value in schema_value.itervalues():
if isinstance(field_value, dict):
if '$ref' in field_value:
field_value['type'] = 'object'
return result | python | def __schemas_descriptor(self):
# Filter out any keys that aren't 'properties', 'type', or 'id'
result = {}
for schema_key, schema_value in self.__parser.schemas().iteritems():
field_keys = schema_value.keys()
key_result = {}
# Some special processing for the properties value
if 'properties' in field_keys:
key_result['properties'] = schema_value['properties'].copy()
# Add in enumDescriptions for any enum properties and strip out
# the required tag for consistency with Java framework
for prop_key, prop_value in schema_value['properties'].iteritems():
if 'enum' in prop_value:
num_enums = len(prop_value['enum'])
key_result['properties'][prop_key]['enumDescriptions'] = (
[''] * num_enums)
elif 'default' in prop_value:
# stringify default values
if prop_value.get('type') == 'boolean':
prop_value['default'] = 'true' if prop_value['default'] else 'false'
else:
prop_value['default'] = str(prop_value['default'])
key_result['properties'][prop_key].pop('required', None)
for key in ('type', 'id', 'description'):
if key in field_keys:
key_result[key] = schema_value[key]
if key_result:
result[schema_key] = key_result
# Add 'type': 'object' to all object properties
for schema_value in result.itervalues():
for field_value in schema_value.itervalues():
if isinstance(field_value, dict):
if '$ref' in field_value:
field_value['type'] = 'object'
return result | [
"def",
"__schemas_descriptor",
"(",
"self",
")",
":",
"# Filter out any keys that aren't 'properties', 'type', or 'id'",
"result",
"=",
"{",
"}",
"for",
"schema_key",
",",
"schema_value",
"in",
"self",
".",
"__parser",
".",
"schemas",
"(",
")",
".",
"iteritems",
"("... | Describes the schemas section of the discovery document.
Returns:
Dictionary describing the schemas of the document. | [
"Describes",
"the",
"schemas",
"section",
"of",
"the",
"discovery",
"document",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_generator.py#L547-L591 |
22,335 | cloudendpoints/endpoints-python | endpoints/discovery_generator.py | DiscoveryGenerator.__resource_descriptor | def __resource_descriptor(self, resource_path, methods):
"""Describes a resource.
Args:
resource_path: string, the path of the resource (e.g., 'entries.items')
methods: list of tuples of type
(endpoints.Service, protorpc.remote._RemoteMethodInfo), the methods
that serve this resource.
Returns:
Dictionary describing the resource.
"""
descriptor = {}
method_map = {}
sub_resource_index = collections.defaultdict(list)
sub_resource_map = {}
resource_path_tokens = resource_path.split('.')
for service, protorpc_meth_info in methods:
method_info = getattr(protorpc_meth_info, 'method_info', None)
path = method_info.get_path(service.api_info)
method_id = method_info.method_id(service.api_info)
canonical_method_id = self._get_canonical_method_id(method_id)
current_resource_path = self._get_resource_path(method_id)
# Sanity-check that this method belongs to the resource path
if (current_resource_path[:len(resource_path_tokens)] !=
resource_path_tokens):
raise api_exceptions.ToolError(
'Internal consistency error in resource path {0}'.format(
current_resource_path))
# Remove the portion of the current method's resource path that's already
# part of the resource path at this level.
effective_resource_path = current_resource_path[
len(resource_path_tokens):]
# If this method is part of a sub-resource, note it and skip it for now
if effective_resource_path:
sub_resource_name = effective_resource_path[0]
new_resource_path = '.'.join([resource_path, sub_resource_name])
sub_resource_index[new_resource_path].append(
(service, protorpc_meth_info))
else:
method_map[canonical_method_id] = self.__method_descriptor(
service, method_info, protorpc_meth_info)
# Process any sub-resources
for sub_resource, sub_resource_methods in sub_resource_index.items():
sub_resource_name = sub_resource.split('.')[-1]
sub_resource_map[sub_resource_name] = self.__resource_descriptor(
sub_resource, sub_resource_methods)
if method_map:
descriptor['methods'] = method_map
if sub_resource_map:
descriptor['resources'] = sub_resource_map
return descriptor | python | def __resource_descriptor(self, resource_path, methods):
descriptor = {}
method_map = {}
sub_resource_index = collections.defaultdict(list)
sub_resource_map = {}
resource_path_tokens = resource_path.split('.')
for service, protorpc_meth_info in methods:
method_info = getattr(protorpc_meth_info, 'method_info', None)
path = method_info.get_path(service.api_info)
method_id = method_info.method_id(service.api_info)
canonical_method_id = self._get_canonical_method_id(method_id)
current_resource_path = self._get_resource_path(method_id)
# Sanity-check that this method belongs to the resource path
if (current_resource_path[:len(resource_path_tokens)] !=
resource_path_tokens):
raise api_exceptions.ToolError(
'Internal consistency error in resource path {0}'.format(
current_resource_path))
# Remove the portion of the current method's resource path that's already
# part of the resource path at this level.
effective_resource_path = current_resource_path[
len(resource_path_tokens):]
# If this method is part of a sub-resource, note it and skip it for now
if effective_resource_path:
sub_resource_name = effective_resource_path[0]
new_resource_path = '.'.join([resource_path, sub_resource_name])
sub_resource_index[new_resource_path].append(
(service, protorpc_meth_info))
else:
method_map[canonical_method_id] = self.__method_descriptor(
service, method_info, protorpc_meth_info)
# Process any sub-resources
for sub_resource, sub_resource_methods in sub_resource_index.items():
sub_resource_name = sub_resource.split('.')[-1]
sub_resource_map[sub_resource_name] = self.__resource_descriptor(
sub_resource, sub_resource_methods)
if method_map:
descriptor['methods'] = method_map
if sub_resource_map:
descriptor['resources'] = sub_resource_map
return descriptor | [
"def",
"__resource_descriptor",
"(",
"self",
",",
"resource_path",
",",
"methods",
")",
":",
"descriptor",
"=",
"{",
"}",
"method_map",
"=",
"{",
"}",
"sub_resource_index",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"sub_resource_map",
"=",
"{",... | Describes a resource.
Args:
resource_path: string, the path of the resource (e.g., 'entries.items')
methods: list of tuples of type
(endpoints.Service, protorpc.remote._RemoteMethodInfo), the methods
that serve this resource.
Returns:
Dictionary describing the resource. | [
"Describes",
"a",
"resource",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_generator.py#L706-L766 |
22,336 | cloudendpoints/endpoints-python | endpoints/discovery_generator.py | DiscoveryGenerator.__discovery_doc_descriptor | def __discovery_doc_descriptor(self, services, hostname=None):
"""Builds a discovery doc for an API.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dictionary that can be deserialized into JSON in discovery doc format.
Raises:
ApiConfigurationError: If there's something wrong with the API
configuration, such as a multiclass API decorated with different API
descriptors (see the docstring for api()), or a repeated method
signature.
"""
merged_api_info = self.__get_merged_api_info(services)
descriptor = self.get_descriptor_defaults(merged_api_info,
hostname=hostname)
description = merged_api_info.description
if not description and len(services) == 1:
description = services[0].__doc__
if description:
descriptor['description'] = description
descriptor['parameters'] = self.__standard_parameters_descriptor()
descriptor['auth'] = self.__standard_auth_descriptor(services)
# Add namespace information, if provided
if merged_api_info.namespace:
descriptor['ownerDomain'] = merged_api_info.namespace.owner_domain
descriptor['ownerName'] = merged_api_info.namespace.owner_name
descriptor['packagePath'] = merged_api_info.namespace.package_path or ''
else:
if merged_api_info.owner_domain is not None:
descriptor['ownerDomain'] = merged_api_info.owner_domain
if merged_api_info.owner_name is not None:
descriptor['ownerName'] = merged_api_info.owner_name
if merged_api_info.package_path is not None:
descriptor['packagePath'] = merged_api_info.package_path
method_map = {}
method_collision_tracker = {}
rest_collision_tracker = {}
resource_index = collections.defaultdict(list)
resource_map = {}
# For the first pass, only process top-level methods (that is, those methods
# that are unattached to a resource).
for service in services:
remote_methods = service.all_remote_methods()
for protorpc_meth_name, protorpc_meth_info in remote_methods.iteritems():
method_info = getattr(protorpc_meth_info, 'method_info', None)
# Skip methods that are not decorated with @method
if method_info is None:
continue
path = method_info.get_path(service.api_info)
method_id = method_info.method_id(service.api_info)
canonical_method_id = self._get_canonical_method_id(method_id)
resource_path = self._get_resource_path(method_id)
# Make sure the same method name isn't repeated.
if method_id in method_collision_tracker:
raise api_exceptions.ApiConfigurationError(
'Method %s used multiple times, in classes %s and %s' %
(method_id, method_collision_tracker[method_id],
service.__name__))
else:
method_collision_tracker[method_id] = service.__name__
# Make sure the same HTTP method & path aren't repeated.
rest_identifier = (method_info.http_method, path)
if rest_identifier in rest_collision_tracker:
raise api_exceptions.ApiConfigurationError(
'%s path "%s" used multiple times, in classes %s and %s' %
(method_info.http_method, path,
rest_collision_tracker[rest_identifier],
service.__name__))
else:
rest_collision_tracker[rest_identifier] = service.__name__
# If this method is part of a resource, note it and skip it for now
if resource_path:
resource_index[resource_path[0]].append((service, protorpc_meth_info))
else:
method_map[canonical_method_id] = self.__method_descriptor(
service, method_info, protorpc_meth_info)
# Do another pass for methods attached to resources
for resource, resource_methods in resource_index.items():
resource_map[resource] = self.__resource_descriptor(resource,
resource_methods)
if method_map:
descriptor['methods'] = method_map
if resource_map:
descriptor['resources'] = resource_map
# Add schemas, if any
schemas = self.__schemas_descriptor()
if schemas:
descriptor['schemas'] = schemas
return descriptor | python | def __discovery_doc_descriptor(self, services, hostname=None):
merged_api_info = self.__get_merged_api_info(services)
descriptor = self.get_descriptor_defaults(merged_api_info,
hostname=hostname)
description = merged_api_info.description
if not description and len(services) == 1:
description = services[0].__doc__
if description:
descriptor['description'] = description
descriptor['parameters'] = self.__standard_parameters_descriptor()
descriptor['auth'] = self.__standard_auth_descriptor(services)
# Add namespace information, if provided
if merged_api_info.namespace:
descriptor['ownerDomain'] = merged_api_info.namespace.owner_domain
descriptor['ownerName'] = merged_api_info.namespace.owner_name
descriptor['packagePath'] = merged_api_info.namespace.package_path or ''
else:
if merged_api_info.owner_domain is not None:
descriptor['ownerDomain'] = merged_api_info.owner_domain
if merged_api_info.owner_name is not None:
descriptor['ownerName'] = merged_api_info.owner_name
if merged_api_info.package_path is not None:
descriptor['packagePath'] = merged_api_info.package_path
method_map = {}
method_collision_tracker = {}
rest_collision_tracker = {}
resource_index = collections.defaultdict(list)
resource_map = {}
# For the first pass, only process top-level methods (that is, those methods
# that are unattached to a resource).
for service in services:
remote_methods = service.all_remote_methods()
for protorpc_meth_name, protorpc_meth_info in remote_methods.iteritems():
method_info = getattr(protorpc_meth_info, 'method_info', None)
# Skip methods that are not decorated with @method
if method_info is None:
continue
path = method_info.get_path(service.api_info)
method_id = method_info.method_id(service.api_info)
canonical_method_id = self._get_canonical_method_id(method_id)
resource_path = self._get_resource_path(method_id)
# Make sure the same method name isn't repeated.
if method_id in method_collision_tracker:
raise api_exceptions.ApiConfigurationError(
'Method %s used multiple times, in classes %s and %s' %
(method_id, method_collision_tracker[method_id],
service.__name__))
else:
method_collision_tracker[method_id] = service.__name__
# Make sure the same HTTP method & path aren't repeated.
rest_identifier = (method_info.http_method, path)
if rest_identifier in rest_collision_tracker:
raise api_exceptions.ApiConfigurationError(
'%s path "%s" used multiple times, in classes %s and %s' %
(method_info.http_method, path,
rest_collision_tracker[rest_identifier],
service.__name__))
else:
rest_collision_tracker[rest_identifier] = service.__name__
# If this method is part of a resource, note it and skip it for now
if resource_path:
resource_index[resource_path[0]].append((service, protorpc_meth_info))
else:
method_map[canonical_method_id] = self.__method_descriptor(
service, method_info, protorpc_meth_info)
# Do another pass for methods attached to resources
for resource, resource_methods in resource_index.items():
resource_map[resource] = self.__resource_descriptor(resource,
resource_methods)
if method_map:
descriptor['methods'] = method_map
if resource_map:
descriptor['resources'] = resource_map
# Add schemas, if any
schemas = self.__schemas_descriptor()
if schemas:
descriptor['schemas'] = schemas
return descriptor | [
"def",
"__discovery_doc_descriptor",
"(",
"self",
",",
"services",
",",
"hostname",
"=",
"None",
")",
":",
"merged_api_info",
"=",
"self",
".",
"__get_merged_api_info",
"(",
"services",
")",
"descriptor",
"=",
"self",
".",
"get_descriptor_defaults",
"(",
"merged_a... | Builds a discovery doc for an API.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dictionary that can be deserialized into JSON in discovery doc format.
Raises:
ApiConfigurationError: If there's something wrong with the API
configuration, such as a multiclass API decorated with different API
descriptors (see the docstring for api()), or a repeated method
signature. | [
"Builds",
"a",
"discovery",
"doc",
"for",
"an",
"API",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_generator.py#L855-L964 |
22,337 | cloudendpoints/endpoints-python | endpoints/discovery_generator.py | DiscoveryGenerator.get_discovery_doc | def get_discovery_doc(self, services, hostname=None):
"""JSON dict description of a protorpc.remote.Service in discovery format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
dict, The discovery document as a JSON dict.
"""
if not isinstance(services, (tuple, list)):
services = [services]
# The type of a class that inherits from remote.Service is actually
# remote._ServiceClass, thanks to metaclass strangeness.
# pylint: disable=protected-access
util.check_list_type(services, remote._ServiceClass, 'services',
allow_none=False)
return self.__discovery_doc_descriptor(services, hostname=hostname) | python | def get_discovery_doc(self, services, hostname=None):
if not isinstance(services, (tuple, list)):
services = [services]
# The type of a class that inherits from remote.Service is actually
# remote._ServiceClass, thanks to metaclass strangeness.
# pylint: disable=protected-access
util.check_list_type(services, remote._ServiceClass, 'services',
allow_none=False)
return self.__discovery_doc_descriptor(services, hostname=hostname) | [
"def",
"get_discovery_doc",
"(",
"self",
",",
"services",
",",
"hostname",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"services",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"services",
"=",
"[",
"services",
"]",
"# The type of a class that ... | JSON dict description of a protorpc.remote.Service in discovery format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
dict, The discovery document as a JSON dict. | [
"JSON",
"dict",
"description",
"of",
"a",
"protorpc",
".",
"remote",
".",
"Service",
"in",
"discovery",
"format",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_generator.py#L1019-L1041 |
22,338 | cloudendpoints/endpoints-python | endpoints/util.py | send_wsgi_response | def send_wsgi_response(status, headers, content, start_response,
cors_handler=None):
"""Dump reformatted response to CGI start_response.
This calls start_response and returns the response body.
Args:
status: A string containing the HTTP status code to send.
headers: A list of (header, value) tuples, the headers to send in the
response.
content: A string containing the body content to write.
start_response: A function with semantics defined in PEP-333.
cors_handler: A handler to process CORS request headers and update the
headers in the response. Or this can be None, to bypass CORS checks.
Returns:
A string containing the response body.
"""
if cors_handler:
cors_handler.update_headers(headers)
# Update content length.
content_len = len(content) if content else 0
headers = [(header, value) for header, value in headers
if header.lower() != 'content-length']
headers.append(('Content-Length', '%s' % content_len))
start_response(status, headers)
return content | python | def send_wsgi_response(status, headers, content, start_response,
cors_handler=None):
if cors_handler:
cors_handler.update_headers(headers)
# Update content length.
content_len = len(content) if content else 0
headers = [(header, value) for header, value in headers
if header.lower() != 'content-length']
headers.append(('Content-Length', '%s' % content_len))
start_response(status, headers)
return content | [
"def",
"send_wsgi_response",
"(",
"status",
",",
"headers",
",",
"content",
",",
"start_response",
",",
"cors_handler",
"=",
"None",
")",
":",
"if",
"cors_handler",
":",
"cors_handler",
".",
"update_headers",
"(",
"headers",
")",
"# Update content length.",
"conte... | Dump reformatted response to CGI start_response.
This calls start_response and returns the response body.
Args:
status: A string containing the HTTP status code to send.
headers: A list of (header, value) tuples, the headers to send in the
response.
content: A string containing the body content to write.
start_response: A function with semantics defined in PEP-333.
cors_handler: A handler to process CORS request headers and update the
headers in the response. Or this can be None, to bypass CORS checks.
Returns:
A string containing the response body. | [
"Dump",
"reformatted",
"response",
"to",
"CGI",
"start_response",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L115-L143 |
22,339 | cloudendpoints/endpoints-python | endpoints/util.py | get_headers_from_environ | def get_headers_from_environ(environ):
"""Get a wsgiref.headers.Headers object with headers from the environment.
Headers in environ are prefixed with 'HTTP_', are all uppercase, and have
had dashes replaced with underscores. This strips the HTTP_ prefix and
changes underscores back to dashes before adding them to the returned set
of headers.
Args:
environ: An environ dict for the request as defined in PEP-333.
Returns:
A wsgiref.headers.Headers object that's been filled in with any HTTP
headers found in environ.
"""
headers = wsgiref.headers.Headers([])
for header, value in environ.iteritems():
if header.startswith('HTTP_'):
headers[header[5:].replace('_', '-')] = value
# Content-Type is special; it does not start with 'HTTP_'.
if 'CONTENT_TYPE' in environ:
headers['CONTENT-TYPE'] = environ['CONTENT_TYPE']
return headers | python | def get_headers_from_environ(environ):
headers = wsgiref.headers.Headers([])
for header, value in environ.iteritems():
if header.startswith('HTTP_'):
headers[header[5:].replace('_', '-')] = value
# Content-Type is special; it does not start with 'HTTP_'.
if 'CONTENT_TYPE' in environ:
headers['CONTENT-TYPE'] = environ['CONTENT_TYPE']
return headers | [
"def",
"get_headers_from_environ",
"(",
"environ",
")",
":",
"headers",
"=",
"wsgiref",
".",
"headers",
".",
"Headers",
"(",
"[",
"]",
")",
"for",
"header",
",",
"value",
"in",
"environ",
".",
"iteritems",
"(",
")",
":",
"if",
"header",
".",
"startswith"... | Get a wsgiref.headers.Headers object with headers from the environment.
Headers in environ are prefixed with 'HTTP_', are all uppercase, and have
had dashes replaced with underscores. This strips the HTTP_ prefix and
changes underscores back to dashes before adding them to the returned set
of headers.
Args:
environ: An environ dict for the request as defined in PEP-333.
Returns:
A wsgiref.headers.Headers object that's been filled in with any HTTP
headers found in environ. | [
"Get",
"a",
"wsgiref",
".",
"headers",
".",
"Headers",
"object",
"with",
"headers",
"from",
"the",
"environment",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L146-L168 |
22,340 | cloudendpoints/endpoints-python | endpoints/util.py | put_headers_in_environ | def put_headers_in_environ(headers, environ):
"""Given a list of headers, put them into environ based on PEP-333.
This converts headers to uppercase, prefixes them with 'HTTP_', and
converts dashes to underscores before adding them to the environ dict.
Args:
headers: A list of (header, value) tuples. The HTTP headers to add to the
environment.
environ: An environ dict for the request as defined in PEP-333.
"""
for key, value in headers:
environ['HTTP_%s' % key.upper().replace('-', '_')] = value | python | def put_headers_in_environ(headers, environ):
for key, value in headers:
environ['HTTP_%s' % key.upper().replace('-', '_')] = value | [
"def",
"put_headers_in_environ",
"(",
"headers",
",",
"environ",
")",
":",
"for",
"key",
",",
"value",
"in",
"headers",
":",
"environ",
"[",
"'HTTP_%s'",
"%",
"key",
".",
"upper",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"]",
"=",
"valu... | Given a list of headers, put them into environ based on PEP-333.
This converts headers to uppercase, prefixes them with 'HTTP_', and
converts dashes to underscores before adding them to the environ dict.
Args:
headers: A list of (header, value) tuples. The HTTP headers to add to the
environment.
environ: An environ dict for the request as defined in PEP-333. | [
"Given",
"a",
"list",
"of",
"headers",
"put",
"them",
"into",
"environ",
"based",
"on",
"PEP",
"-",
"333",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L171-L183 |
22,341 | cloudendpoints/endpoints-python | endpoints/util.py | get_hostname_prefix | def get_hostname_prefix():
"""Returns the hostname prefix of a running Endpoints service.
The prefix is the portion of the hostname that comes before the API name.
For example, if a non-default version and a non-default service are in use,
the returned result would be '{VERSION}-dot-{SERVICE}-'.
Returns:
str, the hostname prefix.
"""
parts = []
# Check if this is the default version
version = modules.get_current_version_name()
default_version = modules.get_default_version()
if version != default_version:
parts.append(version)
# Check if this is the default module
module = modules.get_current_module_name()
if module != 'default':
parts.append(module)
# If there is anything to prepend, add an extra blank entry for the trailing
# -dot-
if parts:
parts.append('')
return '-dot-'.join(parts) | python | def get_hostname_prefix():
parts = []
# Check if this is the default version
version = modules.get_current_version_name()
default_version = modules.get_default_version()
if version != default_version:
parts.append(version)
# Check if this is the default module
module = modules.get_current_module_name()
if module != 'default':
parts.append(module)
# If there is anything to prepend, add an extra blank entry for the trailing
# -dot-
if parts:
parts.append('')
return '-dot-'.join(parts) | [
"def",
"get_hostname_prefix",
"(",
")",
":",
"parts",
"=",
"[",
"]",
"# Check if this is the default version",
"version",
"=",
"modules",
".",
"get_current_version_name",
"(",
")",
"default_version",
"=",
"modules",
".",
"get_default_version",
"(",
")",
"if",
"versi... | Returns the hostname prefix of a running Endpoints service.
The prefix is the portion of the hostname that comes before the API name.
For example, if a non-default version and a non-default service are in use,
the returned result would be '{VERSION}-dot-{SERVICE}-'.
Returns:
str, the hostname prefix. | [
"Returns",
"the",
"hostname",
"prefix",
"of",
"a",
"running",
"Endpoints",
"service",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L200-L228 |
22,342 | cloudendpoints/endpoints-python | endpoints/util.py | get_app_hostname | def get_app_hostname():
"""Return hostname of a running Endpoints service.
Returns hostname of an running Endpoints API. It can be 1) "localhost:PORT"
if running on development server, or 2) "app_id.appspot.com" if running on
external app engine prod, or "app_id.googleplex.com" if running as Google
first-party Endpoints API, or 4) None if not running on App Engine
(e.g. Tornado Endpoints API).
Returns:
A string representing the hostname of the service.
"""
if not is_running_on_app_engine() or is_running_on_localhost():
return None
app_id = app_identity.get_application_id()
prefix = get_hostname_prefix()
suffix = 'appspot.com'
if ':' in app_id:
tokens = app_id.split(':')
api_name = tokens[1]
if tokens[0] == 'google.com':
suffix = 'googleplex.com'
else:
api_name = app_id
return '{0}{1}.{2}'.format(prefix, api_name, suffix) | python | def get_app_hostname():
if not is_running_on_app_engine() or is_running_on_localhost():
return None
app_id = app_identity.get_application_id()
prefix = get_hostname_prefix()
suffix = 'appspot.com'
if ':' in app_id:
tokens = app_id.split(':')
api_name = tokens[1]
if tokens[0] == 'google.com':
suffix = 'googleplex.com'
else:
api_name = app_id
return '{0}{1}.{2}'.format(prefix, api_name, suffix) | [
"def",
"get_app_hostname",
"(",
")",
":",
"if",
"not",
"is_running_on_app_engine",
"(",
")",
"or",
"is_running_on_localhost",
"(",
")",
":",
"return",
"None",
"app_id",
"=",
"app_identity",
".",
"get_application_id",
"(",
")",
"prefix",
"=",
"get_hostname_prefix",... | Return hostname of a running Endpoints service.
Returns hostname of an running Endpoints API. It can be 1) "localhost:PORT"
if running on development server, or 2) "app_id.appspot.com" if running on
external app engine prod, or "app_id.googleplex.com" if running as Google
first-party Endpoints API, or 4) None if not running on App Engine
(e.g. Tornado Endpoints API).
Returns:
A string representing the hostname of the service. | [
"Return",
"hostname",
"of",
"a",
"running",
"Endpoints",
"service",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L231-L259 |
22,343 | cloudendpoints/endpoints-python | endpoints/util.py | check_list_type | def check_list_type(objects, allowed_type, name, allow_none=True):
"""Verify that objects in list are of the allowed type or raise TypeError.
Args:
objects: The list of objects to check.
allowed_type: The allowed type of items in 'settings'.
name: Name of the list of objects, added to the exception.
allow_none: If set, None is also allowed.
Raises:
TypeError: if object is not of the allowed type.
Returns:
The list of objects, for convenient use in assignment.
"""
if objects is None:
if not allow_none:
raise TypeError('%s is None, which is not allowed.' % name)
return objects
if not isinstance(objects, (tuple, list)):
raise TypeError('%s is not a list.' % name)
if not all(isinstance(i, allowed_type) for i in objects):
type_list = sorted(list(set(type(obj) for obj in objects)))
raise TypeError('%s contains types that don\'t match %s: %s' %
(name, allowed_type.__name__, type_list))
return objects | python | def check_list_type(objects, allowed_type, name, allow_none=True):
if objects is None:
if not allow_none:
raise TypeError('%s is None, which is not allowed.' % name)
return objects
if not isinstance(objects, (tuple, list)):
raise TypeError('%s is not a list.' % name)
if not all(isinstance(i, allowed_type) for i in objects):
type_list = sorted(list(set(type(obj) for obj in objects)))
raise TypeError('%s contains types that don\'t match %s: %s' %
(name, allowed_type.__name__, type_list))
return objects | [
"def",
"check_list_type",
"(",
"objects",
",",
"allowed_type",
",",
"name",
",",
"allow_none",
"=",
"True",
")",
":",
"if",
"objects",
"is",
"None",
":",
"if",
"not",
"allow_none",
":",
"raise",
"TypeError",
"(",
"'%s is None, which is not allowed.'",
"%",
"na... | Verify that objects in list are of the allowed type or raise TypeError.
Args:
objects: The list of objects to check.
allowed_type: The allowed type of items in 'settings'.
name: Name of the list of objects, added to the exception.
allow_none: If set, None is also allowed.
Raises:
TypeError: if object is not of the allowed type.
Returns:
The list of objects, for convenient use in assignment. | [
"Verify",
"that",
"objects",
"in",
"list",
"are",
"of",
"the",
"allowed",
"type",
"or",
"raise",
"TypeError",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L262-L287 |
22,344 | cloudendpoints/endpoints-python | endpoints/util.py | snake_case_to_headless_camel_case | def snake_case_to_headless_camel_case(snake_string):
"""Convert snake_case to headlessCamelCase.
Args:
snake_string: The string to be converted.
Returns:
The input string converted to headlessCamelCase.
"""
return ''.join([snake_string.split('_')[0]] +
list(sub_string.capitalize()
for sub_string in snake_string.split('_')[1:])) | python | def snake_case_to_headless_camel_case(snake_string):
return ''.join([snake_string.split('_')[0]] +
list(sub_string.capitalize()
for sub_string in snake_string.split('_')[1:])) | [
"def",
"snake_case_to_headless_camel_case",
"(",
"snake_string",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"snake_string",
".",
"split",
"(",
"'_'",
")",
"[",
"0",
"]",
"]",
"+",
"list",
"(",
"sub_string",
".",
"capitalize",
"(",
")",
"for",
"sub_... | Convert snake_case to headlessCamelCase.
Args:
snake_string: The string to be converted.
Returns:
The input string converted to headlessCamelCase. | [
"Convert",
"snake_case",
"to",
"headlessCamelCase",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L290-L300 |
22,345 | cloudendpoints/endpoints-python | endpoints/util.py | StartResponseProxy.Proxy | def Proxy(self, status, headers, exc_info=None):
"""Save args, defer start_response until response body is parsed.
Create output buffer for body to be written into.
Note: this is not quite WSGI compliant: The body should come back as an
iterator returned from calling service_app() but instead, StartResponse
returns a writer that will be later called to output the body.
See google/appengine/ext/webapp/__init__.py::Response.wsgi_write()
write = start_response('%d %s' % self.__status, self.__wsgi_headers)
write(body)
Args:
status: Http status to be sent with this response
headers: Http headers to be sent with this response
exc_info: Exception info to be displayed for this response
Returns:
callable that takes as an argument the body content
"""
self.call_context['status'] = status
self.call_context['headers'] = headers
self.call_context['exc_info'] = exc_info
return self.body_buffer.write | python | def Proxy(self, status, headers, exc_info=None):
self.call_context['status'] = status
self.call_context['headers'] = headers
self.call_context['exc_info'] = exc_info
return self.body_buffer.write | [
"def",
"Proxy",
"(",
"self",
",",
"status",
",",
"headers",
",",
"exc_info",
"=",
"None",
")",
":",
"self",
".",
"call_context",
"[",
"'status'",
"]",
"=",
"status",
"self",
".",
"call_context",
"[",
"'headers'",
"]",
"=",
"headers",
"self",
".",
"call... | Save args, defer start_response until response body is parsed.
Create output buffer for body to be written into.
Note: this is not quite WSGI compliant: The body should come back as an
iterator returned from calling service_app() but instead, StartResponse
returns a writer that will be later called to output the body.
See google/appengine/ext/webapp/__init__.py::Response.wsgi_write()
write = start_response('%d %s' % self.__status, self.__wsgi_headers)
write(body)
Args:
status: Http status to be sent with this response
headers: Http headers to be sent with this response
exc_info: Exception info to be displayed for this response
Returns:
callable that takes as an argument the body content | [
"Save",
"args",
"defer",
"start_response",
"until",
"response",
"body",
"is",
"parsed",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L44-L66 |
22,346 | cloudendpoints/endpoints-python | endpoints/discovery_service.py | DiscoveryService._send_success_response | def _send_success_response(self, response, start_response):
"""Sends an HTTP 200 json success response.
This calls start_response and returns the response body.
Args:
response: A string containing the response body to return.
start_response: A function with semantics defined in PEP-333.
Returns:
A string, the response body.
"""
headers = [('Content-Type', 'application/json; charset=UTF-8')]
return util.send_wsgi_response('200 OK', headers, response, start_response) | python | def _send_success_response(self, response, start_response):
headers = [('Content-Type', 'application/json; charset=UTF-8')]
return util.send_wsgi_response('200 OK', headers, response, start_response) | [
"def",
"_send_success_response",
"(",
"self",
",",
"response",
",",
"start_response",
")",
":",
"headers",
"=",
"[",
"(",
"'Content-Type'",
",",
"'application/json; charset=UTF-8'",
")",
"]",
"return",
"util",
".",
"send_wsgi_response",
"(",
"'200 OK'",
",",
"head... | Sends an HTTP 200 json success response.
This calls start_response and returns the response body.
Args:
response: A string containing the response body to return.
start_response: A function with semantics defined in PEP-333.
Returns:
A string, the response body. | [
"Sends",
"an",
"HTTP",
"200",
"json",
"success",
"response",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_service.py#L82-L95 |
22,347 | cloudendpoints/endpoints-python | endpoints/discovery_service.py | DiscoveryService._get_rest_doc | def _get_rest_doc(self, request, start_response):
"""Sends back HTTP response with API directory.
This calls start_response and returns the response body. It will return
the discovery doc for the requested api/version.
Args:
request: An ApiRequest, the transformed request sent to the Discovery API.
start_response: A function with semantics defined in PEP-333.
Returns:
A string, the response body.
"""
api = request.body_json['api']
version = request.body_json['version']
generator = discovery_generator.DiscoveryGenerator(request=request)
services = [s for s in self._backend.api_services if
s.api_info.name == api and s.api_info.api_version == version]
doc = generator.pretty_print_config_to_json(services)
if not doc:
error_msg = ('Failed to convert .api to discovery doc for '
'version %s of api %s') % (version, api)
_logger.error('%s', error_msg)
return util.send_wsgi_error_response(error_msg, start_response)
return self._send_success_response(doc, start_response) | python | def _get_rest_doc(self, request, start_response):
api = request.body_json['api']
version = request.body_json['version']
generator = discovery_generator.DiscoveryGenerator(request=request)
services = [s for s in self._backend.api_services if
s.api_info.name == api and s.api_info.api_version == version]
doc = generator.pretty_print_config_to_json(services)
if not doc:
error_msg = ('Failed to convert .api to discovery doc for '
'version %s of api %s') % (version, api)
_logger.error('%s', error_msg)
return util.send_wsgi_error_response(error_msg, start_response)
return self._send_success_response(doc, start_response) | [
"def",
"_get_rest_doc",
"(",
"self",
",",
"request",
",",
"start_response",
")",
":",
"api",
"=",
"request",
".",
"body_json",
"[",
"'api'",
"]",
"version",
"=",
"request",
".",
"body_json",
"[",
"'version'",
"]",
"generator",
"=",
"discovery_generator",
"."... | Sends back HTTP response with API directory.
This calls start_response and returns the response body. It will return
the discovery doc for the requested api/version.
Args:
request: An ApiRequest, the transformed request sent to the Discovery API.
start_response: A function with semantics defined in PEP-333.
Returns:
A string, the response body. | [
"Sends",
"back",
"HTTP",
"response",
"with",
"API",
"directory",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_service.py#L97-L122 |
22,348 | cloudendpoints/endpoints-python | endpoints/discovery_service.py | DiscoveryService._generate_api_config_with_root | def _generate_api_config_with_root(self, request):
"""Generate an API config with a specific root hostname.
This uses the backend object and the ApiConfigGenerator to create an API
config specific to the hostname of the incoming request. This allows for
flexible API configs for non-standard environments, such as localhost.
Args:
request: An ApiRequest, the transformed request sent to the Discovery API.
Returns:
A string representation of the generated API config.
"""
actual_root = self._get_actual_root(request)
generator = api_config.ApiConfigGenerator()
api = request.body_json['api']
version = request.body_json['version']
lookup_key = (api, version)
service_factories = self._backend.api_name_version_map.get(lookup_key)
if not service_factories:
return None
service_classes = [service_factory.service_class
for service_factory in service_factories]
config_dict = generator.get_config_dict(
service_classes, hostname=actual_root)
# Save to cache
for config in config_dict.get('items', []):
lookup_key_with_root = (
config.get('name', ''), config.get('version', ''), actual_root)
self._config_manager.save_config(lookup_key_with_root, config)
return config_dict | python | def _generate_api_config_with_root(self, request):
actual_root = self._get_actual_root(request)
generator = api_config.ApiConfigGenerator()
api = request.body_json['api']
version = request.body_json['version']
lookup_key = (api, version)
service_factories = self._backend.api_name_version_map.get(lookup_key)
if not service_factories:
return None
service_classes = [service_factory.service_class
for service_factory in service_factories]
config_dict = generator.get_config_dict(
service_classes, hostname=actual_root)
# Save to cache
for config in config_dict.get('items', []):
lookup_key_with_root = (
config.get('name', ''), config.get('version', ''), actual_root)
self._config_manager.save_config(lookup_key_with_root, config)
return config_dict | [
"def",
"_generate_api_config_with_root",
"(",
"self",
",",
"request",
")",
":",
"actual_root",
"=",
"self",
".",
"_get_actual_root",
"(",
"request",
")",
"generator",
"=",
"api_config",
".",
"ApiConfigGenerator",
"(",
")",
"api",
"=",
"request",
".",
"body_json"... | Generate an API config with a specific root hostname.
This uses the backend object and the ApiConfigGenerator to create an API
config specific to the hostname of the incoming request. This allows for
flexible API configs for non-standard environments, such as localhost.
Args:
request: An ApiRequest, the transformed request sent to the Discovery API.
Returns:
A string representation of the generated API config. | [
"Generate",
"an",
"API",
"config",
"with",
"a",
"specific",
"root",
"hostname",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_service.py#L124-L158 |
22,349 | cloudendpoints/endpoints-python | endpoints/discovery_service.py | DiscoveryService._list | def _list(self, request, start_response):
"""Sends HTTP response containing the API directory.
This calls start_response and returns the response body.
Args:
request: An ApiRequest, the transformed request sent to the Discovery API.
start_response: A function with semantics defined in PEP-333.
Returns:
A string containing the response body.
"""
configs = []
generator = directory_list_generator.DirectoryListGenerator(request)
for config in self._config_manager.configs.itervalues():
if config != self.API_CONFIG:
configs.append(config)
directory = generator.pretty_print_config_to_json(configs)
if not directory:
_logger.error('Failed to get API directory')
# By returning a 404, code explorer still works if you select the
# API in the URL
return util.send_wsgi_not_found_response(start_response)
return self._send_success_response(directory, start_response) | python | def _list(self, request, start_response):
configs = []
generator = directory_list_generator.DirectoryListGenerator(request)
for config in self._config_manager.configs.itervalues():
if config != self.API_CONFIG:
configs.append(config)
directory = generator.pretty_print_config_to_json(configs)
if not directory:
_logger.error('Failed to get API directory')
# By returning a 404, code explorer still works if you select the
# API in the URL
return util.send_wsgi_not_found_response(start_response)
return self._send_success_response(directory, start_response) | [
"def",
"_list",
"(",
"self",
",",
"request",
",",
"start_response",
")",
":",
"configs",
"=",
"[",
"]",
"generator",
"=",
"directory_list_generator",
".",
"DirectoryListGenerator",
"(",
"request",
")",
"for",
"config",
"in",
"self",
".",
"_config_manager",
"."... | Sends HTTP response containing the API directory.
This calls start_response and returns the response body.
Args:
request: An ApiRequest, the transformed request sent to the Discovery API.
start_response: A function with semantics defined in PEP-333.
Returns:
A string containing the response body. | [
"Sends",
"HTTP",
"response",
"containing",
"the",
"API",
"directory",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_service.py#L170-L193 |
22,350 | cloudendpoints/endpoints-python | endpoints/discovery_service.py | DiscoveryService.handle_discovery_request | def handle_discovery_request(self, path, request, start_response):
"""Returns the result of a discovery service request.
This calls start_response and returns the response body.
Args:
path: A string containing the API path (the portion of the path
after /_ah/api/).
request: An ApiRequest, the transformed request sent to the Discovery API.
start_response: A function with semantics defined in PEP-333.
Returns:
The response body. Or returns False if the request wasn't handled by
DiscoveryService.
"""
if path == self._GET_REST_API:
return self._get_rest_doc(request, start_response)
elif path == self._GET_RPC_API:
error_msg = ('RPC format documents are no longer supported with the '
'Endpoints Framework for Python. Please use the REST '
'format.')
_logger.error('%s', error_msg)
return util.send_wsgi_error_response(error_msg, start_response)
elif path == self._LIST_API:
return self._list(request, start_response)
return False | python | def handle_discovery_request(self, path, request, start_response):
if path == self._GET_REST_API:
return self._get_rest_doc(request, start_response)
elif path == self._GET_RPC_API:
error_msg = ('RPC format documents are no longer supported with the '
'Endpoints Framework for Python. Please use the REST '
'format.')
_logger.error('%s', error_msg)
return util.send_wsgi_error_response(error_msg, start_response)
elif path == self._LIST_API:
return self._list(request, start_response)
return False | [
"def",
"handle_discovery_request",
"(",
"self",
",",
"path",
",",
"request",
",",
"start_response",
")",
":",
"if",
"path",
"==",
"self",
".",
"_GET_REST_API",
":",
"return",
"self",
".",
"_get_rest_doc",
"(",
"request",
",",
"start_response",
")",
"elif",
"... | Returns the result of a discovery service request.
This calls start_response and returns the response body.
Args:
path: A string containing the API path (the portion of the path
after /_ah/api/).
request: An ApiRequest, the transformed request sent to the Discovery API.
start_response: A function with semantics defined in PEP-333.
Returns:
The response body. Or returns False if the request wasn't handled by
DiscoveryService. | [
"Returns",
"the",
"result",
"of",
"a",
"discovery",
"service",
"request",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/discovery_service.py#L195-L220 |
22,351 | cloudendpoints/endpoints-python | endpoints/api_request.py | ApiRequest._process_req_body | def _process_req_body(self, body):
"""Process the body of the HTTP request.
If the body is valid JSON, return the JSON as a dict.
Else, convert the key=value format to a dict and return that.
Args:
body: The body of the HTTP request.
"""
try:
return json.loads(body)
except ValueError:
return urlparse.parse_qs(body, keep_blank_values=True) | python | def _process_req_body(self, body):
try:
return json.loads(body)
except ValueError:
return urlparse.parse_qs(body, keep_blank_values=True) | [
"def",
"_process_req_body",
"(",
"self",
",",
"body",
")",
":",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"body",
")",
"except",
"ValueError",
":",
"return",
"urlparse",
".",
"parse_qs",
"(",
"body",
",",
"keep_blank_values",
"=",
"True",
")"
] | Process the body of the HTTP request.
If the body is valid JSON, return the JSON as a dict.
Else, convert the key=value format to a dict and return that.
Args:
body: The body of the HTTP request. | [
"Process",
"the",
"body",
"of",
"the",
"HTTP",
"request",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_request.py#L118-L130 |
22,352 | cloudendpoints/endpoints-python | endpoints/api_request.py | ApiRequest._reconstruct_relative_url | def _reconstruct_relative_url(self, environ):
"""Reconstruct the relative URL of this request.
This is based on the URL reconstruction code in Python PEP 333:
http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the
URL from the pieces available in the environment.
Args:
environ: An environ dict for the request as defined in PEP-333
Returns:
The portion of the URL from the request after the server and port.
"""
url = urllib.quote(environ.get('SCRIPT_NAME', ''))
url += urllib.quote(environ.get('PATH_INFO', ''))
if environ.get('QUERY_STRING'):
url += '?' + environ['QUERY_STRING']
return url | python | def _reconstruct_relative_url(self, environ):
url = urllib.quote(environ.get('SCRIPT_NAME', ''))
url += urllib.quote(environ.get('PATH_INFO', ''))
if environ.get('QUERY_STRING'):
url += '?' + environ['QUERY_STRING']
return url | [
"def",
"_reconstruct_relative_url",
"(",
"self",
",",
"environ",
")",
":",
"url",
"=",
"urllib",
".",
"quote",
"(",
"environ",
".",
"get",
"(",
"'SCRIPT_NAME'",
",",
"''",
")",
")",
"url",
"+=",
"urllib",
".",
"quote",
"(",
"environ",
".",
"get",
"(",
... | Reconstruct the relative URL of this request.
This is based on the URL reconstruction code in Python PEP 333:
http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the
URL from the pieces available in the environment.
Args:
environ: An environ dict for the request as defined in PEP-333
Returns:
The portion of the URL from the request after the server and port. | [
"Reconstruct",
"the",
"relative",
"URL",
"of",
"this",
"request",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_request.py#L132-L149 |
22,353 | cloudendpoints/endpoints-python | endpoints/api_request.py | ApiRequest.reconstruct_hostname | def reconstruct_hostname(self, port_override=None):
"""Reconstruct the hostname of a request.
This is based on the URL reconstruction code in Python PEP 333:
http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the
hostname from the pieces available in the environment.
Args:
port_override: str, An override for the port on the returned hostname.
Returns:
The hostname portion of the URL from the request, not including the
URL scheme.
"""
url = self.server
port = port_override or self.port
if port and ((self.url_scheme == 'https' and str(port) != '443') or
(self.url_scheme != 'https' and str(port) != '80')):
url += ':{0}'.format(port)
return url | python | def reconstruct_hostname(self, port_override=None):
url = self.server
port = port_override or self.port
if port and ((self.url_scheme == 'https' and str(port) != '443') or
(self.url_scheme != 'https' and str(port) != '80')):
url += ':{0}'.format(port)
return url | [
"def",
"reconstruct_hostname",
"(",
"self",
",",
"port_override",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"server",
"port",
"=",
"port_override",
"or",
"self",
".",
"port",
"if",
"port",
"and",
"(",
"(",
"self",
".",
"url_scheme",
"==",
"'https'"... | Reconstruct the hostname of a request.
This is based on the URL reconstruction code in Python PEP 333:
http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the
hostname from the pieces available in the environment.
Args:
port_override: str, An override for the port on the returned hostname.
Returns:
The hostname portion of the URL from the request, not including the
URL scheme. | [
"Reconstruct",
"the",
"hostname",
"of",
"a",
"request",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_request.py#L151-L171 |
22,354 | cloudendpoints/endpoints-python | endpoints/api_request.py | ApiRequest.reconstruct_full_url | def reconstruct_full_url(self, port_override=None):
"""Reconstruct the full URL of a request.
This is based on the URL reconstruction code in Python PEP 333:
http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the
hostname from the pieces available in the environment.
Args:
port_override: str, An override for the port on the returned full URL.
Returns:
The full URL from the request, including the URL scheme.
"""
return '{0}://{1}{2}'.format(self.url_scheme,
self.reconstruct_hostname(port_override),
self.relative_url) | python | def reconstruct_full_url(self, port_override=None):
return '{0}://{1}{2}'.format(self.url_scheme,
self.reconstruct_hostname(port_override),
self.relative_url) | [
"def",
"reconstruct_full_url",
"(",
"self",
",",
"port_override",
"=",
"None",
")",
":",
"return",
"'{0}://{1}{2}'",
".",
"format",
"(",
"self",
".",
"url_scheme",
",",
"self",
".",
"reconstruct_hostname",
"(",
"port_override",
")",
",",
"self",
".",
"relative... | Reconstruct the full URL of a request.
This is based on the URL reconstruction code in Python PEP 333:
http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the
hostname from the pieces available in the environment.
Args:
port_override: str, An override for the port on the returned full URL.
Returns:
The full URL from the request, including the URL scheme. | [
"Reconstruct",
"the",
"full",
"URL",
"of",
"a",
"request",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_request.py#L173-L188 |
22,355 | cloudendpoints/endpoints-python | endpoints/openapi_generator.py | OpenApiGenerator._construct_operation_id | def _construct_operation_id(self, service_name, protorpc_method_name):
"""Return an operation id for a service method.
Args:
service_name: The name of the service.
protorpc_method_name: The ProtoRPC method name.
Returns:
A string representing the operation id.
"""
# camelCase the ProtoRPC method name
method_name_camel = util.snake_case_to_headless_camel_case(
protorpc_method_name)
return '{0}_{1}'.format(service_name, method_name_camel) | python | def _construct_operation_id(self, service_name, protorpc_method_name):
# camelCase the ProtoRPC method name
method_name_camel = util.snake_case_to_headless_camel_case(
protorpc_method_name)
return '{0}_{1}'.format(service_name, method_name_camel) | [
"def",
"_construct_operation_id",
"(",
"self",
",",
"service_name",
",",
"protorpc_method_name",
")",
":",
"# camelCase the ProtoRPC method name",
"method_name_camel",
"=",
"util",
".",
"snake_case_to_headless_camel_case",
"(",
"protorpc_method_name",
")",
"return",
"'{0}_{1}... | Return an operation id for a service method.
Args:
service_name: The name of the service.
protorpc_method_name: The ProtoRPC method name.
Returns:
A string representing the operation id. | [
"Return",
"an",
"operation",
"id",
"for",
"a",
"service",
"method",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/openapi_generator.py#L113-L128 |
22,356 | cloudendpoints/endpoints-python | endpoints/openapi_generator.py | OpenApiGenerator.__definitions_descriptor | def __definitions_descriptor(self):
"""Describes the definitions section of the OpenAPI spec.
Returns:
Dictionary describing the definitions of the spec.
"""
# Filter out any keys that aren't 'properties' or 'type'
result = {}
for def_key, def_value in self.__parser.schemas().iteritems():
if 'properties' in def_value or 'type' in def_value:
key_result = {}
required_keys = set()
if 'type' in def_value:
key_result['type'] = def_value['type']
if 'properties' in def_value:
for prop_key, prop_value in def_value['properties'].items():
if isinstance(prop_value, dict) and 'required' in prop_value:
required_keys.add(prop_key)
del prop_value['required']
key_result['properties'] = def_value['properties']
# Add in the required fields, if any
if required_keys:
key_result['required'] = sorted(required_keys)
result[def_key] = key_result
# Add 'type': 'object' to all object properties
# Also, recursively add relative path to all $ref values
for def_value in result.itervalues():
for prop_value in def_value.itervalues():
if isinstance(prop_value, dict):
if '$ref' in prop_value:
prop_value['type'] = 'object'
self._add_def_paths(prop_value)
return result | python | def __definitions_descriptor(self):
# Filter out any keys that aren't 'properties' or 'type'
result = {}
for def_key, def_value in self.__parser.schemas().iteritems():
if 'properties' in def_value or 'type' in def_value:
key_result = {}
required_keys = set()
if 'type' in def_value:
key_result['type'] = def_value['type']
if 'properties' in def_value:
for prop_key, prop_value in def_value['properties'].items():
if isinstance(prop_value, dict) and 'required' in prop_value:
required_keys.add(prop_key)
del prop_value['required']
key_result['properties'] = def_value['properties']
# Add in the required fields, if any
if required_keys:
key_result['required'] = sorted(required_keys)
result[def_key] = key_result
# Add 'type': 'object' to all object properties
# Also, recursively add relative path to all $ref values
for def_value in result.itervalues():
for prop_value in def_value.itervalues():
if isinstance(prop_value, dict):
if '$ref' in prop_value:
prop_value['type'] = 'object'
self._add_def_paths(prop_value)
return result | [
"def",
"__definitions_descriptor",
"(",
"self",
")",
":",
"# Filter out any keys that aren't 'properties' or 'type'",
"result",
"=",
"{",
"}",
"for",
"def_key",
",",
"def_value",
"in",
"self",
".",
"__parser",
".",
"schemas",
"(",
")",
".",
"iteritems",
"(",
")",
... | Describes the definitions section of the OpenAPI spec.
Returns:
Dictionary describing the definitions of the spec. | [
"Describes",
"the",
"definitions",
"section",
"of",
"the",
"OpenAPI",
"spec",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/openapi_generator.py#L613-L647 |
22,357 | cloudendpoints/endpoints-python | endpoints/openapi_generator.py | OpenApiGenerator.__response_message_descriptor | def __response_message_descriptor(self, message_type, method_id):
"""Describes the response.
Args:
message_type: messages.Message class, The message to describe.
method_id: string, Unique method identifier (e.g. 'myapi.items.method')
Returns:
Dictionary describing the response.
"""
# Skeleton response descriptor, common to all response objects
descriptor = {'200': {'description': 'A successful response'}}
if message_type != message_types.VoidMessage():
self.__parser.add_message(message_type.__class__)
self.__response_schema[method_id] = self.__parser.ref_for_message_type(
message_type.__class__)
descriptor['200']['schema'] = {'$ref': '#/definitions/{0}'.format(
self.__response_schema[method_id])}
return dict(descriptor) | python | def __response_message_descriptor(self, message_type, method_id):
# Skeleton response descriptor, common to all response objects
descriptor = {'200': {'description': 'A successful response'}}
if message_type != message_types.VoidMessage():
self.__parser.add_message(message_type.__class__)
self.__response_schema[method_id] = self.__parser.ref_for_message_type(
message_type.__class__)
descriptor['200']['schema'] = {'$ref': '#/definitions/{0}'.format(
self.__response_schema[method_id])}
return dict(descriptor) | [
"def",
"__response_message_descriptor",
"(",
"self",
",",
"message_type",
",",
"method_id",
")",
":",
"# Skeleton response descriptor, common to all response objects",
"descriptor",
"=",
"{",
"'200'",
":",
"{",
"'description'",
":",
"'A successful response'",
"}",
"}",
"i... | Describes the response.
Args:
message_type: messages.Message class, The message to describe.
method_id: string, Unique method identifier (e.g. 'myapi.items.method')
Returns:
Dictionary describing the response. | [
"Describes",
"the",
"response",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/openapi_generator.py#L649-L670 |
22,358 | cloudendpoints/endpoints-python | endpoints/openapi_generator.py | OpenApiGenerator.__x_google_quota_descriptor | def __x_google_quota_descriptor(self, metric_costs):
"""Describes the metric costs for a call.
Args:
metric_costs: Dict of metric definitions to the integer cost value against
that metric.
Returns:
A dict descriptor describing the Quota limits for the endpoint.
"""
return {
'metricCosts': {
metric: cost for (metric, cost) in metric_costs.items()
}
} if metric_costs else None | python | def __x_google_quota_descriptor(self, metric_costs):
return {
'metricCosts': {
metric: cost for (metric, cost) in metric_costs.items()
}
} if metric_costs else None | [
"def",
"__x_google_quota_descriptor",
"(",
"self",
",",
"metric_costs",
")",
":",
"return",
"{",
"'metricCosts'",
":",
"{",
"metric",
":",
"cost",
"for",
"(",
"metric",
",",
"cost",
")",
"in",
"metric_costs",
".",
"items",
"(",
")",
"}",
"}",
"if",
"metr... | Describes the metric costs for a call.
Args:
metric_costs: Dict of metric definitions to the integer cost value against
that metric.
Returns:
A dict descriptor describing the Quota limits for the endpoint. | [
"Describes",
"the",
"metric",
"costs",
"for",
"a",
"call",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/openapi_generator.py#L672-L686 |
22,359 | cloudendpoints/endpoints-python | endpoints/openapi_generator.py | OpenApiGenerator.__x_google_quota_definitions_descriptor | def __x_google_quota_definitions_descriptor(self, limit_definitions):
"""Describes the quota limit definitions for an API.
Args:
limit_definitions: List of endpoints.LimitDefinition tuples
Returns:
A dict descriptor of the API's quota limit definitions.
"""
if not limit_definitions:
return None
definitions_list = [{
'name': ld.metric_name,
'metric': ld.metric_name,
'unit': '1/min/{project}',
'values': {'STANDARD': ld.default_limit},
'displayName': ld.display_name,
} for ld in limit_definitions]
metrics = [{
'name': ld.metric_name,
'valueType': 'INT64',
'metricKind': 'GAUGE',
} for ld in limit_definitions]
return {
'quota': {'limits': definitions_list},
'metrics': metrics,
} | python | 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': {'STANDARD': ld.default_limit},
'displayName': ld.display_name,
} for ld in limit_definitions]
metrics = [{
'name': ld.metric_name,
'valueType': 'INT64',
'metricKind': 'GAUGE',
} for ld in limit_definitions]
return {
'quota': {'limits': definitions_list},
'metrics': metrics,
} | [
"def",
"__x_google_quota_definitions_descriptor",
"(",
"self",
",",
"limit_definitions",
")",
":",
"if",
"not",
"limit_definitions",
":",
"return",
"None",
"definitions_list",
"=",
"[",
"{",
"'name'",
":",
"ld",
".",
"metric_name",
",",
"'metric'",
":",
"ld",
".... | Describes the quota limit definitions for an API.
Args:
limit_definitions: List of endpoints.LimitDefinition tuples
Returns:
A dict descriptor of the API's quota limit definitions. | [
"Describes",
"the",
"quota",
"limit",
"definitions",
"for",
"an",
"API",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/openapi_generator.py#L688-L717 |
22,360 | cloudendpoints/endpoints-python | endpoints/openapi_generator.py | OpenApiGenerator.__security_definitions_descriptor | def __security_definitions_descriptor(self, issuers):
"""Create a descriptor for the security definitions.
Args:
issuers: dict, mapping issuer names to Issuer tuples
Returns:
The dict representing the security definitions descriptor.
"""
if not issuers:
result = {
_DEFAULT_SECURITY_DEFINITION: {
'authorizationUrl': '',
'flow': 'implicit',
'type': 'oauth2',
'x-google-issuer': 'https://accounts.google.com',
'x-google-jwks_uri': 'https://www.googleapis.com/oauth2/v3/certs',
}
}
return result
result = {}
for issuer_key, issuer_value in issuers.items():
result[issuer_key] = {
'authorizationUrl': '',
'flow': 'implicit',
'type': 'oauth2',
'x-google-issuer': issuer_value.issuer,
}
# If jwks_uri is omitted, the auth library will use OpenID discovery
# to find it. Otherwise, include it in the descriptor explicitly.
if issuer_value.jwks_uri:
result[issuer_key]['x-google-jwks_uri'] = issuer_value.jwks_uri
return result | python | def __security_definitions_descriptor(self, issuers):
if not issuers:
result = {
_DEFAULT_SECURITY_DEFINITION: {
'authorizationUrl': '',
'flow': 'implicit',
'type': 'oauth2',
'x-google-issuer': 'https://accounts.google.com',
'x-google-jwks_uri': 'https://www.googleapis.com/oauth2/v3/certs',
}
}
return result
result = {}
for issuer_key, issuer_value in issuers.items():
result[issuer_key] = {
'authorizationUrl': '',
'flow': 'implicit',
'type': 'oauth2',
'x-google-issuer': issuer_value.issuer,
}
# If jwks_uri is omitted, the auth library will use OpenID discovery
# to find it. Otherwise, include it in the descriptor explicitly.
if issuer_value.jwks_uri:
result[issuer_key]['x-google-jwks_uri'] = issuer_value.jwks_uri
return result | [
"def",
"__security_definitions_descriptor",
"(",
"self",
",",
"issuers",
")",
":",
"if",
"not",
"issuers",
":",
"result",
"=",
"{",
"_DEFAULT_SECURITY_DEFINITION",
":",
"{",
"'authorizationUrl'",
":",
"''",
",",
"'flow'",
":",
"'implicit'",
",",
"'type'",
":",
... | Create a descriptor for the security definitions.
Args:
issuers: dict, mapping issuer names to Issuer tuples
Returns:
The dict representing the security definitions descriptor. | [
"Create",
"a",
"descriptor",
"for",
"the",
"security",
"definitions",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/openapi_generator.py#L818-L854 |
22,361 | cloudendpoints/endpoints-python | endpoints/openapi_generator.py | OpenApiGenerator.__api_openapi_descriptor | def __api_openapi_descriptor(self, services, hostname=None, x_google_api_name=False):
"""Builds an OpenAPI description of an API.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dictionary that can be deserialized into JSON and stored as an API
description document in OpenAPI format.
Raises:
ApiConfigurationError: If there's something wrong with the API
configuration, such as a multiclass API decorated with different API
descriptors (see the docstring for api()), or a repeated method
signature.
"""
merged_api_info = self.__get_merged_api_info(services)
descriptor = self.get_descriptor_defaults(merged_api_info,
hostname=hostname,
x_google_api_name=x_google_api_name)
description = merged_api_info.description
if not description and len(services) == 1:
description = services[0].__doc__
if description:
descriptor['info']['description'] = description
security_definitions = self.__security_definitions_descriptor(
merged_api_info.issuers)
method_map = {}
method_collision_tracker = {}
rest_collision_tracker = {}
for service in services:
remote_methods = service.all_remote_methods()
for protorpc_meth_name in sorted(remote_methods.iterkeys()):
protorpc_meth_info = remote_methods[protorpc_meth_name]
method_info = getattr(protorpc_meth_info, 'method_info', None)
# Skip methods that are not decorated with @method
if method_info is None:
continue
method_id = method_info.method_id(service.api_info)
is_api_key_required = method_info.is_api_key_required(service.api_info)
path = '/{0}/{1}/{2}'.format(merged_api_info.name,
merged_api_info.path_version,
method_info.get_path(service.api_info))
verb = method_info.http_method.lower()
if path not in method_map:
method_map[path] = {}
# If an API key is required and the security definitions don't already
# have the apiKey issuer, add the appropriate notation now
if is_api_key_required and _API_KEY not in security_definitions:
security_definitions[_API_KEY] = {
'type': 'apiKey',
'name': _API_KEY_PARAM,
'in': 'query'
}
# Derive an OperationId from the method name data
operation_id = self._construct_operation_id(
service.__name__, protorpc_meth_name)
method_map[path][verb] = self.__method_descriptor(
service, method_info, operation_id, protorpc_meth_info,
security_definitions)
# Make sure the same method name isn't repeated.
if method_id in method_collision_tracker:
raise api_exceptions.ApiConfigurationError(
'Method %s used multiple times, in classes %s and %s' %
(method_id, method_collision_tracker[method_id],
service.__name__))
else:
method_collision_tracker[method_id] = service.__name__
# Make sure the same HTTP method & path aren't repeated.
rest_identifier = (method_info.http_method,
method_info.get_path(service.api_info))
if rest_identifier in rest_collision_tracker:
raise api_exceptions.ApiConfigurationError(
'%s path "%s" used multiple times, in classes %s and %s' %
(method_info.http_method, method_info.get_path(service.api_info),
rest_collision_tracker[rest_identifier],
service.__name__))
else:
rest_collision_tracker[rest_identifier] = service.__name__
if method_map:
descriptor['paths'] = method_map
# Add request and/or response definitions, if any
definitions = self.__definitions_descriptor()
if definitions:
descriptor['definitions'] = definitions
descriptor['securityDefinitions'] = security_definitions
# Add quota limit metric definitions, if any
limit_definitions = self.__x_google_quota_definitions_descriptor(
merged_api_info.limit_definitions)
if limit_definitions:
descriptor['x-google-management'] = limit_definitions
return descriptor | python | 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=hostname,
x_google_api_name=x_google_api_name)
description = merged_api_info.description
if not description and len(services) == 1:
description = services[0].__doc__
if description:
descriptor['info']['description'] = description
security_definitions = self.__security_definitions_descriptor(
merged_api_info.issuers)
method_map = {}
method_collision_tracker = {}
rest_collision_tracker = {}
for service in services:
remote_methods = service.all_remote_methods()
for protorpc_meth_name in sorted(remote_methods.iterkeys()):
protorpc_meth_info = remote_methods[protorpc_meth_name]
method_info = getattr(protorpc_meth_info, 'method_info', None)
# Skip methods that are not decorated with @method
if method_info is None:
continue
method_id = method_info.method_id(service.api_info)
is_api_key_required = method_info.is_api_key_required(service.api_info)
path = '/{0}/{1}/{2}'.format(merged_api_info.name,
merged_api_info.path_version,
method_info.get_path(service.api_info))
verb = method_info.http_method.lower()
if path not in method_map:
method_map[path] = {}
# If an API key is required and the security definitions don't already
# have the apiKey issuer, add the appropriate notation now
if is_api_key_required and _API_KEY not in security_definitions:
security_definitions[_API_KEY] = {
'type': 'apiKey',
'name': _API_KEY_PARAM,
'in': 'query'
}
# Derive an OperationId from the method name data
operation_id = self._construct_operation_id(
service.__name__, protorpc_meth_name)
method_map[path][verb] = self.__method_descriptor(
service, method_info, operation_id, protorpc_meth_info,
security_definitions)
# Make sure the same method name isn't repeated.
if method_id in method_collision_tracker:
raise api_exceptions.ApiConfigurationError(
'Method %s used multiple times, in classes %s and %s' %
(method_id, method_collision_tracker[method_id],
service.__name__))
else:
method_collision_tracker[method_id] = service.__name__
# Make sure the same HTTP method & path aren't repeated.
rest_identifier = (method_info.http_method,
method_info.get_path(service.api_info))
if rest_identifier in rest_collision_tracker:
raise api_exceptions.ApiConfigurationError(
'%s path "%s" used multiple times, in classes %s and %s' %
(method_info.http_method, method_info.get_path(service.api_info),
rest_collision_tracker[rest_identifier],
service.__name__))
else:
rest_collision_tracker[rest_identifier] = service.__name__
if method_map:
descriptor['paths'] = method_map
# Add request and/or response definitions, if any
definitions = self.__definitions_descriptor()
if definitions:
descriptor['definitions'] = definitions
descriptor['securityDefinitions'] = security_definitions
# Add quota limit metric definitions, if any
limit_definitions = self.__x_google_quota_definitions_descriptor(
merged_api_info.limit_definitions)
if limit_definitions:
descriptor['x-google-management'] = limit_definitions
return descriptor | [
"def",
"__api_openapi_descriptor",
"(",
"self",
",",
"services",
",",
"hostname",
"=",
"None",
",",
"x_google_api_name",
"=",
"False",
")",
":",
"merged_api_info",
"=",
"self",
".",
"__get_merged_api_info",
"(",
"services",
")",
"descriptor",
"=",
"self",
".",
... | Builds an OpenAPI description of an API.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dictionary that can be deserialized into JSON and stored as an API
description document in OpenAPI format.
Raises:
ApiConfigurationError: If there's something wrong with the API
configuration, such as a multiclass API decorated with different API
descriptors (see the docstring for api()), or a repeated method
signature. | [
"Builds",
"an",
"OpenAPI",
"description",
"of",
"an",
"API",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/openapi_generator.py#L883-L993 |
22,362 | cloudendpoints/endpoints-python | endpoints/openapi_generator.py | OpenApiGenerator.get_openapi_dict | def get_openapi_dict(self, services, hostname=None, x_google_api_name=False):
"""JSON dict description of a protorpc.remote.Service in OpenAPI format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
dict, The OpenAPI descriptor document as a JSON dict.
"""
if not isinstance(services, (tuple, list)):
services = [services]
# The type of a class that inherits from remote.Service is actually
# remote._ServiceClass, thanks to metaclass strangeness.
# pylint: disable=protected-access
util.check_list_type(services, remote._ServiceClass, 'services',
allow_none=False)
return self.__api_openapi_descriptor(services, hostname=hostname, x_google_api_name=x_google_api_name) | python | 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 metaclass strangeness.
# pylint: disable=protected-access
util.check_list_type(services, remote._ServiceClass, 'services',
allow_none=False)
return self.__api_openapi_descriptor(services, hostname=hostname, x_google_api_name=x_google_api_name) | [
"def",
"get_openapi_dict",
"(",
"self",
",",
"services",
",",
"hostname",
"=",
"None",
",",
"x_google_api_name",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"services",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"services",
"=",
"[",
"s... | JSON dict description of a protorpc.remote.Service in OpenAPI format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
dict, The OpenAPI descriptor document as a JSON dict. | [
"JSON",
"dict",
"description",
"of",
"a",
"protorpc",
".",
"remote",
".",
"Service",
"in",
"OpenAPI",
"format",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/openapi_generator.py#L1031-L1053 |
22,363 | cloudendpoints/endpoints-python | endpoints/openapi_generator.py | OpenApiGenerator.pretty_print_config_to_json | def pretty_print_config_to_json(self, services, hostname=None, x_google_api_name=False):
"""JSON string description of a protorpc.remote.Service in OpenAPI format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
string, The OpenAPI descriptor document as a JSON string.
"""
descriptor = self.get_openapi_dict(services, hostname, x_google_api_name=x_google_api_name)
return json.dumps(descriptor, sort_keys=True, indent=2,
separators=(',', ': ')) | python | 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,
separators=(',', ': ')) | [
"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",
"=... | JSON string description of a protorpc.remote.Service in OpenAPI format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
string, The OpenAPI descriptor document as a JSON string. | [
"JSON",
"string",
"description",
"of",
"a",
"protorpc",
".",
"remote",
".",
"Service",
"in",
"OpenAPI",
"format",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/openapi_generator.py#L1055-L1069 |
22,364 | cloudendpoints/endpoints-python | endpoints/protojson.py | EndpointsProtoJson.__pad_value | def __pad_value(value, pad_len_multiple, pad_char):
"""Add padding characters to the value if needed.
Args:
value: The string value to be padded.
pad_len_multiple: Pad the result so its length is a multiple
of pad_len_multiple.
pad_char: The character to use for padding.
Returns:
The string value with padding characters added.
"""
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_length | python | 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_length | [
"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",
... | Add padding characters to the value if needed.
Args:
value: The string value to be padded.
pad_len_multiple: Pad the result so its length is a multiple
of pad_len_multiple.
pad_char: The character to use for padding.
Returns:
The string value with padding characters added. | [
"Add",
"padding",
"characters",
"to",
"the",
"value",
"if",
"needed",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/protojson.py#L68-L84 |
22,365 | cloudendpoints/endpoints-python | endpoints/message_parser.py | MessageTypeToJsonSchema.add_message | def add_message(self, message_type):
"""Add a new message.
Args:
message_type: protorpc.message.Message class to be parsed.
Returns:
string, The JSON Schema id.
Raises:
KeyError if the Schema id for this message_type would collide with the
Schema id of a different message_type that was already added.
"""
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)
self.__schemas[name] = schema
return name | python | 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)
self.__schemas[name] = schema
return name | [
"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",
".",
... | Add a new message.
Args:
message_type: protorpc.message.Message class to be parsed.
Returns:
string, The JSON Schema id.
Raises:
KeyError if the Schema id for this message_type would collide with the
Schema id of a different message_type that was already added. | [
"Add",
"a",
"new",
"message",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/message_parser.py#L74-L93 |
22,366 | cloudendpoints/endpoints-python | endpoints/message_parser.py | MessageTypeToJsonSchema.ref_for_message_type | def ref_for_message_type(self, message_type):
"""Returns the JSON Schema id for the given message.
Args:
message_type: protorpc.message.Message class to be parsed.
Returns:
string, The JSON Schema id.
Raises:
KeyError: if the message hasn't been parsed via add_message().
"""
name = self.__normalized_name(message_type)
if name not in self.__schemas:
raise KeyError('Message has not been parsed: %s', name)
return name | python | 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 | [
"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:... | Returns the JSON Schema id for the given message.
Args:
message_type: protorpc.message.Message class to be parsed.
Returns:
string, The JSON Schema id.
Raises:
KeyError: if the message hasn't been parsed via add_message(). | [
"Returns",
"the",
"JSON",
"Schema",
"id",
"for",
"the",
"given",
"message",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/message_parser.py#L95-L110 |
22,367 | cloudendpoints/endpoints-python | endpoints/message_parser.py | MessageTypeToJsonSchema.__normalized_name | def __normalized_name(self, message_type):
"""Normalized schema name.
Generate a normalized schema name, taking the class name and stripping out
everything but alphanumerics, and camel casing the remaining words.
A normalized schema name is a name that matches [a-zA-Z][a-zA-Z0-9]*
Args:
message_type: protorpc.message.Message class being parsed.
Returns:
A string, the normalized schema name.
Raises:
KeyError: A collision was found between normalized names.
"""
# 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(
part[0].upper() + part[1:] for part in split_name if part)
previous = self.__normalized_names.get(normalized)
if previous:
if previous != name:
raise KeyError('Both %s and %s normalize to the same schema name: %s' %
(name, previous, normalized))
else:
self.__normalized_names[normalized] = name
return normalized | python | 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(
part[0].upper() + part[1:] for part in split_name if part)
previous = self.__normalized_names.get(normalized)
if previous:
if previous != name:
raise KeyError('Both %s and %s normalize to the same schema name: %s' %
(name, previous, normalized))
else:
self.__normalized_names[normalized] = name
return normalized | [
"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",
... | Normalized schema name.
Generate a normalized schema name, taking the class name and stripping out
everything but alphanumerics, and camel casing the remaining words.
A normalized schema name is a name that matches [a-zA-Z][a-zA-Z0-9]*
Args:
message_type: protorpc.message.Message class being parsed.
Returns:
A string, the normalized schema name.
Raises:
KeyError: A collision was found between normalized names. | [
"Normalized",
"schema",
"name",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/message_parser.py#L120-L152 |
22,368 | cloudendpoints/endpoints-python | endpoints/message_parser.py | MessageTypeToJsonSchema.__message_to_schema | def __message_to_schema(self, message_type):
"""Parse a single message into JSON Schema.
Will recursively descend the message structure
and also parse other messages references via MessageFields.
Args:
message_type: protorpc.messages.Message class to parse.
Returns:
An object representation of the schema.
"""
name = self.__normalized_name(message_type)
schema = {
'id': name,
'type': 'object',
}
if message_type.__doc__:
schema['description'] = message_type.__doc__
properties = {}
for field in message_type.all_fields():
descriptor = {}
# Info about the type of this field. This is either merged with
# the descriptor or it's placed within the descriptor's 'items'
# property, depending on whether this is a repeated field or not.
type_info = {}
if type(field) == messages.MessageField:
field_type = field.type().__class__
type_info['$ref'] = self.add_message(field_type)
if field_type.__doc__:
descriptor['description'] = field_type.__doc__
else:
schema_type = self.__FIELD_TO_SCHEMA_TYPE_MAP.get(
type(field), self.__DEFAULT_SCHEMA_TYPE)
# If the map pointed to a dictionary, check if the field's variant
# is in that dictionary and use the type specified there.
if isinstance(schema_type, dict):
variant_map = schema_type
variant = getattr(field, 'variant', None)
if variant in variant_map:
schema_type = variant_map[variant]
else:
# The variant map needs to specify a default value, mapped by None.
schema_type = variant_map[None]
type_info['type'] = schema_type[0]
if schema_type[1]:
type_info['format'] = schema_type[1]
if type(field) == messages.EnumField:
sorted_enums = sorted([enum_info for enum_info in field.type],
key=lambda enum_info: enum_info.number)
type_info['enum'] = [enum_info.name for enum_info in sorted_enums]
if field.required:
descriptor['required'] = True
if field.default:
if type(field) == messages.EnumField:
descriptor['default'] = str(field.default)
else:
descriptor['default'] = field.default
if field.repeated:
descriptor['items'] = type_info
descriptor['type'] = 'array'
else:
descriptor.update(type_info)
properties[field.name] = descriptor
schema['properties'] = properties
return schema | python | 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 = {}
for field in message_type.all_fields():
descriptor = {}
# Info about the type of this field. This is either merged with
# the descriptor or it's placed within the descriptor's 'items'
# property, depending on whether this is a repeated field or not.
type_info = {}
if type(field) == messages.MessageField:
field_type = field.type().__class__
type_info['$ref'] = self.add_message(field_type)
if field_type.__doc__:
descriptor['description'] = field_type.__doc__
else:
schema_type = self.__FIELD_TO_SCHEMA_TYPE_MAP.get(
type(field), self.__DEFAULT_SCHEMA_TYPE)
# If the map pointed to a dictionary, check if the field's variant
# is in that dictionary and use the type specified there.
if isinstance(schema_type, dict):
variant_map = schema_type
variant = getattr(field, 'variant', None)
if variant in variant_map:
schema_type = variant_map[variant]
else:
# The variant map needs to specify a default value, mapped by None.
schema_type = variant_map[None]
type_info['type'] = schema_type[0]
if schema_type[1]:
type_info['format'] = schema_type[1]
if type(field) == messages.EnumField:
sorted_enums = sorted([enum_info for enum_info in field.type],
key=lambda enum_info: enum_info.number)
type_info['enum'] = [enum_info.name for enum_info in sorted_enums]
if field.required:
descriptor['required'] = True
if field.default:
if type(field) == messages.EnumField:
descriptor['default'] = str(field.default)
else:
descriptor['default'] = field.default
if field.repeated:
descriptor['items'] = type_info
descriptor['type'] = 'array'
else:
descriptor.update(type_info)
properties[field.name] = descriptor
schema['properties'] = properties
return schema | [
"def",
"__message_to_schema",
"(",
"self",
",",
"message_type",
")",
":",
"name",
"=",
"self",
".",
"__normalized_name",
"(",
"message_type",
")",
"schema",
"=",
"{",
"'id'",
":",
"name",
",",
"'type'",
":",
"'object'",
",",
"}",
"if",
"message_type",
".",... | Parse a single message into JSON Schema.
Will recursively descend the message structure
and also parse other messages references via MessageFields.
Args:
message_type: protorpc.messages.Message class to parse.
Returns:
An object representation of the schema. | [
"Parse",
"a",
"single",
"message",
"into",
"JSON",
"Schema",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/message_parser.py#L154-L227 |
22,369 | cloudendpoints/endpoints-python | endpoints/parameter_converter.py | _check_enum | def _check_enum(parameter_name, value, parameter_config):
"""Checks if an enum value is valid.
This is called by the transform_parameter_value function and shouldn't be
called directly.
This verifies that the value of an enum parameter is valid.
Args:
parameter_name: A string containing the name of the parameter, which is
either just a variable name or the name with the index appended. For
example 'var' or 'var[2]'.
value: A string containing the value passed in for the parameter.
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in
the method config.
Raises:
EnumRejectionError: If the given value is not among the accepted
enum values in the field parameter.
"""
enum_values = [enum['backendValue']
for enum in parameter_config['enum'].values()
if 'backendValue' in enum]
if value not in enum_values:
raise errors.EnumRejectionError(parameter_name, value, enum_values) | python | 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(parameter_name, value, enum_values) | [
"def",
"_check_enum",
"(",
"parameter_name",
",",
"value",
",",
"parameter_config",
")",
":",
"enum_values",
"=",
"[",
"enum",
"[",
"'backendValue'",
"]",
"for",
"enum",
"in",
"parameter_config",
"[",
"'enum'",
"]",
".",
"values",
"(",
")",
"if",
"'backendVa... | Checks if an enum value is valid.
This is called by the transform_parameter_value function and shouldn't be
called directly.
This verifies that the value of an enum parameter is valid.
Args:
parameter_name: A string containing the name of the parameter, which is
either just a variable name or the name with the index appended. For
example 'var' or 'var[2]'.
value: A string containing the value passed in for the parameter.
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in
the method config.
Raises:
EnumRejectionError: If the given value is not among the accepted
enum values in the field parameter. | [
"Checks",
"if",
"an",
"enum",
"value",
"is",
"valid",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/parameter_converter.py#L30-L55 |
22,370 | cloudendpoints/endpoints-python | endpoints/parameter_converter.py | _check_boolean | def _check_boolean(parameter_name, value, parameter_config):
"""Checks if a boolean value is valid.
This is called by the transform_parameter_value function and shouldn't be
called directly.
This checks that the string value passed in can be converted to a valid
boolean value.
Args:
parameter_name: A string containing the name of the parameter, which is
either just a variable name or the name with the index appended. For
example 'var' or 'var[2]'.
value: A string containing the value passed in for the parameter.
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in
the method config.
Raises:
BasicTypeParameterError: If the given value is not a valid boolean
value.
"""
if parameter_config.get('type') != 'boolean':
return
if value.lower() not in ('1', 'true', '0', 'false'):
raise errors.BasicTypeParameterError(parameter_name, value, 'boolean') | python | 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') | [
"def",
"_check_boolean",
"(",
"parameter_name",
",",
"value",
",",
"parameter_config",
")",
":",
"if",
"parameter_config",
".",
"get",
"(",
"'type'",
")",
"!=",
"'boolean'",
":",
"return",
"if",
"value",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'1'",
"... | Checks if a boolean value is valid.
This is called by the transform_parameter_value function and shouldn't be
called directly.
This checks that the string value passed in can be converted to a valid
boolean value.
Args:
parameter_name: A string containing the name of the parameter, which is
either just a variable name or the name with the index appended. For
example 'var' or 'var[2]'.
value: A string containing the value passed in for the parameter.
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in
the method config.
Raises:
BasicTypeParameterError: If the given value is not a valid boolean
value. | [
"Checks",
"if",
"a",
"boolean",
"value",
"is",
"valid",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/parameter_converter.py#L58-L84 |
22,371 | cloudendpoints/endpoints-python | endpoints/parameter_converter.py | _get_parameter_conversion_entry | def _get_parameter_conversion_entry(parameter_config):
"""Get information needed to convert the given parameter to its API type.
Args:
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in the
method config.
Returns:
The entry from _PARAM_CONVERSION_MAP with functions/information needed to
validate and convert the given parameter from a string to the type expected
by the API.
"""
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
# configuration.
if entry is None and 'enum' in parameter_config:
entry = _PARAM_CONVERSION_MAP['enum']
return entry | python | 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
# configuration.
if entry is None and 'enum' in parameter_config:
entry = _PARAM_CONVERSION_MAP['enum']
return entry | [
"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 ... | Get information needed to convert the given parameter to its API type.
Args:
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in the
method config.
Returns:
The entry from _PARAM_CONVERSION_MAP with functions/information needed to
validate and convert the given parameter from a string to the type expected
by the API. | [
"Get",
"information",
"needed",
"to",
"convert",
"the",
"given",
"parameter",
"to",
"its",
"API",
"type",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/parameter_converter.py#L126-L147 |
22,372 | cloudendpoints/endpoints-python | endpoints/parameter_converter.py | transform_parameter_value | def transform_parameter_value(parameter_name, value, parameter_config):
"""Validates and transforms parameters to the type expected by the API.
If the value is a list this will recursively call _transform_parameter_value
on the values in the list. Otherwise, it checks all parameter rules for the
the current value and converts its type from a string to whatever format
the API expects.
In the list case, '[index-of-value]' is appended to the parameter name for
error reporting purposes.
Args:
parameter_name: A string containing the name of the parameter, which is
either just a variable name or the name with the index appended, in the
recursive case. For example 'var' or 'var[2]'.
value: A string or list of strings containing the value(s) passed in for
the parameter. These are the values from the request, to be validated,
transformed, and passed along to the backend.
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in the
method config.
Returns:
The converted parameter value(s). Not all types are converted, so this
may be the same string that's passed in.
"""
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 single values or singly-nested lists (no lists nested within
# lists). But even if there are nested lists, we'd want to preserve that
# structure. These recursive calls should preserve it and convert all
# parameter values. See the docstring for information about the parameter
# renaming done here.
return [transform_parameter_value('%s[%d]' % (parameter_name, index),
element, parameter_config)
for index, element in enumerate(value)]
# Validate and convert the parameter value.
entry = _get_parameter_conversion_entry(parameter_config)
if entry:
validation_func, conversion_func, type_name = entry
if validation_func:
validation_func(parameter_name, value, parameter_config)
if conversion_func:
try:
return conversion_func(value)
except ValueError:
raise errors.BasicTypeParameterError(parameter_name, value, type_name)
return value | python | 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 single values or singly-nested lists (no lists nested within
# lists). But even if there are nested lists, we'd want to preserve that
# structure. These recursive calls should preserve it and convert all
# parameter values. See the docstring for information about the parameter
# renaming done here.
return [transform_parameter_value('%s[%d]' % (parameter_name, index),
element, parameter_config)
for index, element in enumerate(value)]
# Validate and convert the parameter value.
entry = _get_parameter_conversion_entry(parameter_config)
if entry:
validation_func, conversion_func, type_name = entry
if validation_func:
validation_func(parameter_name, value, parameter_config)
if conversion_func:
try:
return conversion_func(value)
except ValueError:
raise errors.BasicTypeParameterError(parameter_name, value, type_name)
return value | [
"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 param... | Validates and transforms parameters to the type expected by the API.
If the value is a list this will recursively call _transform_parameter_value
on the values in the list. Otherwise, it checks all parameter rules for the
the current value and converts its type from a string to whatever format
the API expects.
In the list case, '[index-of-value]' is appended to the parameter name for
error reporting purposes.
Args:
parameter_name: A string containing the name of the parameter, which is
either just a variable name or the name with the index appended, in the
recursive case. For example 'var' or 'var[2]'.
value: A string or list of strings containing the value(s) passed in for
the parameter. These are the values from the request, to be validated,
transformed, and passed along to the backend.
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in the
method config.
Returns:
The converted parameter value(s). Not all types are converted, so this
may be the same string that's passed in. | [
"Validates",
"and",
"transforms",
"parameters",
"to",
"the",
"type",
"expected",
"by",
"the",
"API",
"."
] | 00dd7c7a52a9ee39d5923191c2604b8eafdb3f24 | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/parameter_converter.py#L150-L200 |
22,373 | django-leonardo/django-leonardo | leonardo/module/nav/mixins.py | NavigationWidgetMixin.filter_items | def filter_items(self, items):
'''perform filtering items by specific criteria'''
items = self._filter_active(items)
items = self._filter_in_nav(items)
return items | python | def filter_items(self, items):
'''perform filtering items by specific criteria'''
items = self._filter_active(items)
items = self._filter_in_nav(items)
return items | [
"def",
"filter_items",
"(",
"self",
",",
"items",
")",
":",
"items",
"=",
"self",
".",
"_filter_active",
"(",
"items",
")",
"items",
"=",
"self",
".",
"_filter_in_nav",
"(",
"items",
")",
"return",
"items"
] | perform filtering items by specific criteria | [
"perform",
"filtering",
"items",
"by",
"specific",
"criteria"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/nav/mixins.py#L38-L42 |
22,374 | django-leonardo/django-leonardo | leonardo/utils/__init__.py | is_leonardo_module | def is_leonardo_module(mod):
"""returns True if is leonardo module
"""
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 | python | 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 | [
"def",
"is_leonardo_module",
"(",
"mod",
")",
":",
"if",
"hasattr",
"(",
"mod",
",",
"'default'",
")",
"or",
"hasattr",
"(",
"mod",
",",
"'leonardo_module_conf'",
")",
":",
"return",
"True",
"for",
"key",
"in",
"dir",
"(",
"mod",
")",
":",
"if",
"'LEON... | returns True if is leonardo module | [
"returns",
"True",
"if",
"is",
"leonardo",
"module"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/__init__.py#L12-L22 |
22,375 | django-leonardo/django-leonardo | leonardo/module/nav/templatetags/webcms_nav_tags.py | _translate_page_into | def _translate_page_into(page, language, default=None):
"""
Return the translation for a given page
"""
# 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_translations())
translations[page.language] = page
if language in translations:
return translations[language]
else:
if hasattr(default, '__call__'):
return default(page=page)
return default | python | 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_translations())
translations[page.language] = page
if language in translations:
return translations[language]
else:
if hasattr(default, '__call__'):
return default(page=page)
return default | [
"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",
"translat... | Return the translation for a given page | [
"Return",
"the",
"translation",
"for",
"a",
"given",
"page"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/nav/templatetags/webcms_nav_tags.py#L182-L198 |
22,376 | django-leonardo/django-leonardo | leonardo/module/nav/templatetags/webcms_nav_tags.py | feincms_breadcrumbs | def feincms_breadcrumbs(page, include_self=True):
"""
Generate a list of the page's ancestors suitable for use as breadcrumb navigation.
By default, generates an unordered list with the id "breadcrumbs" -
override breadcrumbs.html to change this.
::
{% feincms_breadcrumbs feincms_page %}
"""
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()) for anc in ancs]
if include_self:
bc.append((None, page.short_title()))
return {"trail": bc} | python | 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()) for anc in ancs]
if include_self:
bc.append((None, page.short_title()))
return {"trail": bc} | [
"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\"",
... | Generate a list of the page's ancestors suitable for use as breadcrumb navigation.
By default, generates an unordered list with the id "breadcrumbs" -
override breadcrumbs.html to change this.
::
{% feincms_breadcrumbs feincms_page %} | [
"Generate",
"a",
"list",
"of",
"the",
"page",
"s",
"ancestors",
"suitable",
"for",
"use",
"as",
"breadcrumb",
"navigation",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/nav/templatetags/webcms_nav_tags.py#L245-L267 |
22,377 | django-leonardo/django-leonardo | leonardo/module/nav/templatetags/webcms_nav_tags.py | is_parent_of | def is_parent_of(page1, page2):
"""
Determines whether a given page is the parent of another page
Example::
{% if page|is_parent_of:feincms_page %} ... {% endif %}
"""
try:
return page1.tree_id == page2.tree_id and page1.lft < page2.lft and page1.rght > page2.rght
except AttributeError:
return False | python | 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 | [
"def",
"is_parent_of",
"(",
"page1",
",",
"page2",
")",
":",
"try",
":",
"return",
"page1",
".",
"tree_id",
"==",
"page2",
".",
"tree_id",
"and",
"page1",
".",
"lft",
"<",
"page2",
".",
"lft",
"and",
"page1",
".",
"rght",
">",
"page2",
".",
"rght",
... | Determines whether a given page is the parent of another page
Example::
{% if page|is_parent_of:feincms_page %} ... {% endif %} | [
"Determines",
"whether",
"a",
"given",
"page",
"is",
"the",
"parent",
"of",
"another",
"page"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/nav/templatetags/webcms_nav_tags.py#L271-L283 |
22,378 | django-leonardo/django-leonardo | leonardo/module/web/page/views.py | PageCreateView.parent | 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 Exception as e:
raise e
else:
if hasattr(self.request, 'leonardo_page'):
self._parent = self.request.leonardo_page
else:
return None
return self._parent | python | 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 Exception as e:
raise e
else:
if hasattr(self.request, 'leonardo_page'):
self._parent = self.request.leonardo_page
else:
return None
return self._parent | [
"def",
"parent",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_parent'",
")",
":",
"if",
"'parent'",
"in",
"self",
".",
"kwargs",
":",
"try",
":",
"self",
".",
"_parent",
"=",
"Page",
".",
"objects",
".",
"get",
"(",
"id",
"... | We use parent for some initial data | [
"We",
"use",
"parent",
"for",
"some",
"initial",
"data"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/page/views.py#L23-L40 |
22,379 | django-leonardo/django-leonardo | leonardo/module/web/models/page.py | Page.tree_label | 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))) | python | 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))) | [
"def",
"tree_label",
"(",
"self",
")",
":",
"titles",
"=",
"[",
"]",
"page",
"=",
"self",
"while",
"page",
":",
"titles",
".",
"append",
"(",
"page",
".",
"title",
")",
"page",
"=",
"page",
".",
"parent",
"return",
"smart_text",
"(",
"' > '",
".",
... | render tree label like as `root > child > child` | [
"render",
"tree",
"label",
"like",
"as",
"root",
">",
"child",
">",
"child"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/models/page.py#L104-L111 |
22,380 | django-leonardo/django-leonardo | leonardo/module/web/models/page.py | Page.flush_ct_inventory | def flush_ct_inventory(self):
"""internal method used only if ct_inventory is enabled
"""
if hasattr(self, '_ct_inventory'):
# skip self from update
self._ct_inventory = None
self.update_view = False
self.save() | python | def flush_ct_inventory(self):
if hasattr(self, '_ct_inventory'):
# skip self from update
self._ct_inventory = None
self.update_view = False
self.save() | [
"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 | [
"internal",
"method",
"used",
"only",
"if",
"ct_inventory",
"is",
"enabled"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/models/page.py#L164-L172 |
22,381 | django-leonardo/django-leonardo | leonardo/module/web/models/page.py | Page.register_default_processors | def register_default_processors(cls, frontend_editing=None):
"""
Register our default request processors for the out-of-the-box
Page experience.
Since FeinCMS 1.11 was removed from core.
"""
super(Page, cls).register_default_processors()
if frontend_editing:
cls.register_request_processor(
edit_processors.frontendediting_request_processor,
key='frontend_editing')
cls.register_response_processor(
edit_processors.frontendediting_response_processor,
key='frontend_editing') | python | 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,
key='frontend_editing')
cls.register_response_processor(
edit_processors.frontendediting_response_processor,
key='frontend_editing') | [
"def",
"register_default_processors",
"(",
"cls",
",",
"frontend_editing",
"=",
"None",
")",
":",
"super",
"(",
"Page",
",",
"cls",
")",
".",
"register_default_processors",
"(",
")",
"if",
"frontend_editing",
":",
"cls",
".",
"register_request_processor",
"(",
"... | Register our default request processors for the out-of-the-box
Page experience.
Since FeinCMS 1.11 was removed from core. | [
"Register",
"our",
"default",
"request",
"processors",
"for",
"the",
"out",
"-",
"of",
"-",
"the",
"-",
"box",
"Page",
"experience",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/models/page.py#L179-L195 |
22,382 | django-leonardo/django-leonardo | leonardo/module/web/models/page.py | Page.run_request_processors | def run_request_processors(self, request):
"""
Before rendering a page, run all registered request processors. A
request processor may peruse and modify the page or the request. It can
also return a ``HttpResponse`` for shortcutting the rendering and
returning that response immediately to the client.
"""
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 | python | 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 | [
"def",
"run_request_processors",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"'request_processors'",
",",
"None",
")",
":",
"return",
"for",
"fn",
"in",
"reversed",
"(",
"list",
"(",
"self",
".",
"request_processors",
"... | Before rendering a page, run all registered request processors. A
request processor may peruse and modify the page or the request. It can
also return a ``HttpResponse`` for shortcutting the rendering and
returning that response immediately to the client. | [
"Before",
"rendering",
"a",
"page",
"run",
"all",
"registered",
"request",
"processors",
".",
"A",
"request",
"processor",
"may",
"peruse",
"and",
"modify",
"the",
"page",
"or",
"the",
"request",
".",
"It",
"can",
"also",
"return",
"a",
"HttpResponse",
"for"... | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/models/page.py#L197-L210 |
22,383 | django-leonardo/django-leonardo | leonardo/module/web/models/page.py | Page.as_text | def as_text(self):
'''Fetch and render all regions
For search and test purposes
just a prototype
'''
from leonardo.templatetags.leonardo_tags import _render_content
request = get_anonymous_request(self)
content = ''
try:
for region in [region.key
for region in self._feincms_all_regions]:
content += ''.join(
_render_content(content, request=request, context={})
for content in getattr(self.content, region))
except PermissionDenied:
pass
except Exception as e:
LOG.exception(e)
return content | python | def as_text(self):
'''Fetch and render all regions
For search and test purposes
just a prototype
'''
from leonardo.templatetags.leonardo_tags import _render_content
request = get_anonymous_request(self)
content = ''
try:
for region in [region.key
for region in self._feincms_all_regions]:
content += ''.join(
_render_content(content, request=request, context={})
for content in getattr(self.content, region))
except PermissionDenied:
pass
except Exception as e:
LOG.exception(e)
return content | [
"def",
"as_text",
"(",
"self",
")",
":",
"from",
"leonardo",
".",
"templatetags",
".",
"leonardo_tags",
"import",
"_render_content",
"request",
"=",
"get_anonymous_request",
"(",
"self",
")",
"content",
"=",
"''",
"try",
":",
"for",
"region",
"in",
"[",
"reg... | Fetch and render all regions
For search and test purposes
just a prototype | [
"Fetch",
"and",
"render",
"all",
"regions"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/models/page.py#L213-L238 |
22,384 | django-leonardo/django-leonardo | leonardo/views/debug.py | technical_404_response | 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:] # Trim leading slash
try:
tried = exception.args[0]['tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried # empty URLconf
or (request.path == '/'
and len(tried) == 1 # default URLconf
and len(tried[0]) == 1
and getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin')):
return default_urlconf(request)
urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
if isinstance(urlconf, types.ModuleType):
urlconf = urlconf.__name__
caller = ''
try:
resolver_match = resolve(request.path)
except Resolver404:
pass
else:
obj = resolver_match.func
if hasattr(obj, '__name__'):
caller = obj.__name__
elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
caller = obj.__class__.__name__
if hasattr(obj, '__module__'):
module = obj.__module__
caller = '%s.%s' % (module, caller)
feincms_page = slug = template = None
try:
from leonardo.module.web.models import Page
feincms_page = Page.objects.for_request(request, best_match=True)
template = feincms_page.theme.template
except:
if Page.objects.exists():
feincms_page = Page.objects.filter(parent=None).first()
template = feincms_page.theme.template
else:
# nested path is not allowed for this time
try:
slug = request.path_info.split("/")[-2:-1][0]
except KeyError:
raise Exception("Nested path is not allowed !")
c = RequestContext(request, {
'urlconf': urlconf,
'root_urlconf': settings.ROOT_URLCONF,
'request_path': error_url,
'urlpatterns': tried,
'reason': force_bytes(exception, errors='replace'),
'request': request,
'settings': get_safe_settings(),
'raising_view_name': caller,
'feincms_page': feincms_page,
'template': template or 'base.html',
'standalone': True,
'slug': slug,
})
try:
t = render_to_string('404_technical.html', c)
except:
from django.views.debug import TECHNICAL_404_TEMPLATE
t = Template(TECHNICAL_404_TEMPLATE).render(c)
return HttpResponseNotFound(t, content_type='text/html') | python | 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:] # Trim leading slash
try:
tried = exception.args[0]['tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried # empty URLconf
or (request.path == '/'
and len(tried) == 1 # default URLconf
and len(tried[0]) == 1
and getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin')):
return default_urlconf(request)
urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
if isinstance(urlconf, types.ModuleType):
urlconf = urlconf.__name__
caller = ''
try:
resolver_match = resolve(request.path)
except Resolver404:
pass
else:
obj = resolver_match.func
if hasattr(obj, '__name__'):
caller = obj.__name__
elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
caller = obj.__class__.__name__
if hasattr(obj, '__module__'):
module = obj.__module__
caller = '%s.%s' % (module, caller)
feincms_page = slug = template = None
try:
from leonardo.module.web.models import Page
feincms_page = Page.objects.for_request(request, best_match=True)
template = feincms_page.theme.template
except:
if Page.objects.exists():
feincms_page = Page.objects.filter(parent=None).first()
template = feincms_page.theme.template
else:
# nested path is not allowed for this time
try:
slug = request.path_info.split("/")[-2:-1][0]
except KeyError:
raise Exception("Nested path is not allowed !")
c = RequestContext(request, {
'urlconf': urlconf,
'root_urlconf': settings.ROOT_URLCONF,
'request_path': error_url,
'urlpatterns': tried,
'reason': force_bytes(exception, errors='replace'),
'request': request,
'settings': get_safe_settings(),
'raising_view_name': caller,
'feincms_page': feincms_page,
'template': template or 'base.html',
'standalone': True,
'slug': slug,
})
try:
t = render_to_string('404_technical.html', c)
except:
from django.views.debug import TECHNICAL_404_TEMPLATE
t = Template(TECHNICAL_404_TEMPLATE).render(c)
return HttpResponseNotFound(t, content_type='text/html') | [
"def",
"technical_404_response",
"(",
"request",
",",
"exception",
")",
":",
"try",
":",
"error_url",
"=",
"exception",
".",
"args",
"[",
"0",
"]",
"[",
"'path'",
"]",
"except",
"(",
"IndexError",
",",
"TypeError",
",",
"KeyError",
")",
":",
"error_url",
... | Create a technical 404 error response. The exception should be the Http404. | [
"Create",
"a",
"technical",
"404",
"error",
"response",
".",
"The",
"exception",
"should",
"be",
"the",
"Http404",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/debug.py#L21-L98 |
22,385 | django-leonardo/django-leonardo | leonardo/module/web/widgets/mixins.py | ListMixin.items | 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) | python | 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) | [
"def",
"items",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_items'",
")",
":",
"return",
"self",
".",
"filter_items",
"(",
"self",
".",
"_items",
")",
"self",
".",
"_items",
"=",
"self",
".",
"get_items",
"(",
")",
"return",
"self",
... | access for filtered items | [
"access",
"for",
"filtered",
"items"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L77-L82 |
22,386 | django-leonardo/django-leonardo | leonardo/module/web/widgets/mixins.py | ListMixin.populate_items | def populate_items(self, request):
'''populate and returns filtered items'''
self._items = self.get_items(request)
return self.items | python | def populate_items(self, request):
'''populate and returns filtered items'''
self._items = self.get_items(request)
return self.items | [
"def",
"populate_items",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"_items",
"=",
"self",
".",
"get_items",
"(",
"request",
")",
"return",
"self",
".",
"items"
] | populate and returns filtered items | [
"populate",
"and",
"returns",
"filtered",
"items"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L84-L87 |
22,387 | django-leonardo/django-leonardo | leonardo/module/web/widgets/mixins.py | ListMixin.columns_classes | 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 | python | 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 | [
"def",
"columns_classes",
"(",
"self",
")",
":",
"md",
"=",
"12",
"/",
"self",
".",
"objects_per_row",
"sm",
"=",
"None",
"if",
"self",
".",
"objects_per_row",
">",
"2",
":",
"sm",
"=",
"12",
"/",
"(",
"self",
".",
"objects_per_row",
"/",
"2",
")",
... | returns columns count | [
"returns",
"columns",
"count"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L104-L110 |
22,388 | django-leonardo/django-leonardo | leonardo/module/web/widgets/mixins.py | ListMixin.get_pages | 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 = []
page.append(item)
pages.append(page)
return pages | python | 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 = []
page.append(item)
pages.append(page)
return pages | [
"def",
"get_pages",
"(",
"self",
")",
":",
"pages",
"=",
"[",
"]",
"page",
"=",
"[",
"]",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"self",
".",
"get_rows",
")",
":",
"if",
"i",
">",
"0",
"and",
"i",
"%",
"self",
".",
"objects_per_page",
... | returns pages with rows | [
"returns",
"pages",
"with",
"rows"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L120-L130 |
22,389 | django-leonardo/django-leonardo | leonardo/module/web/widgets/mixins.py | ListMixin.needs_pagination | def needs_pagination(self):
"""Calculate needs pagination"""
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 | python | 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 | [
"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",
"... | Calculate needs pagination | [
"Calculate",
"needs",
"pagination"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L133-L140 |
22,390 | django-leonardo/django-leonardo | leonardo/module/web/widgets/mixins.py | ListMixin.get_item_template | 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.html
_item.html is obsolete use _default.html
'''
content_template = self.content_theme.name
# _item.html is obsolete use _default.html
# TODO: remove this condition after all _item.html will be converted
if content_template == "default":
return "widget/%s/_item.html" % self.widget_name
# TODO: support more template suffixes
return "widget/%s/_%s.html" % (self.widget_name, content_template) | python | 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.html
_item.html is obsolete use _default.html
'''
content_template = self.content_theme.name
# _item.html is obsolete use _default.html
# TODO: remove this condition after all _item.html will be converted
if content_template == "default":
return "widget/%s/_item.html" % self.widget_name
# TODO: support more template suffixes
return "widget/%s/_%s.html" % (self.widget_name, content_template) | [
"def",
"get_item_template",
"(",
"self",
")",
":",
"content_template",
"=",
"self",
".",
"content_theme",
".",
"name",
"# _item.html is obsolete use _default.html",
"# TODO: remove this condition after all _item.html will be converted",
"if",
"content_template",
"==",
"\"default\... | 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.html
_item.html is obsolete use _default.html | [
"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"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L148-L165 |
22,391 | django-leonardo/django-leonardo | leonardo/module/web/widgets/mixins.py | ContentProxyWidgetMixin.is_obsolete | def is_obsolete(self):
"""returns True is data is obsolete and needs revalidation
"""
if self.cache_updated:
now = timezone.now()
delta = now - self.cache_updated
if delta.seconds < self.cache_validity:
return False
return True | python | def is_obsolete(self):
if self.cache_updated:
now = timezone.now()
delta = now - self.cache_updated
if delta.seconds < self.cache_validity:
return False
return True | [
"def",
"is_obsolete",
"(",
"self",
")",
":",
"if",
"self",
".",
"cache_updated",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"delta",
"=",
"now",
"-",
"self",
".",
"cache_updated",
"if",
"delta",
".",
"seconds",
"<",
"self",
".",
"cache_validity... | returns True is data is obsolete and needs revalidation | [
"returns",
"True",
"is",
"data",
"is",
"obsolete",
"and",
"needs",
"revalidation"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L224-L232 |
22,392 | django-leonardo/django-leonardo | leonardo/module/web/widgets/mixins.py | ContentProxyWidgetMixin.update_cache | def update_cache(self, data=None):
"""call with new data or set data to self.cache_data and call this
"""
if data:
self.cache_data = data
self.cache_updated = timezone.now()
self.save() | python | def update_cache(self, data=None):
if data:
self.cache_data = data
self.cache_updated = timezone.now()
self.save() | [
"def",
"update_cache",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"if",
"data",
":",
"self",
".",
"cache_data",
"=",
"data",
"self",
".",
"cache_updated",
"=",
"timezone",
".",
"now",
"(",
")",
"self",
".",
"save",
"(",
")"
] | call with new data or set data to self.cache_data and call this | [
"call",
"with",
"new",
"data",
"or",
"set",
"data",
"to",
"self",
".",
"cache_data",
"and",
"call",
"this"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L234-L240 |
22,393 | django-leonardo/django-leonardo | leonardo/module/web/widgets/mixins.py | ContentProxyWidgetMixin.data | def data(self):
"""this property just calls ``get_data``
but here you can serilalize your data or render as html
these data will be saved to self.cached_content
also will be accessable from template
"""
if self.is_obsolete():
self.update_cache(self.get_data())
return self.cache_data | python | def data(self):
if self.is_obsolete():
self.update_cache(self.get_data())
return self.cache_data | [
"def",
"data",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_obsolete",
"(",
")",
":",
"self",
".",
"update_cache",
"(",
"self",
".",
"get_data",
"(",
")",
")",
"return",
"self",
".",
"cache_data"
] | this property just calls ``get_data``
but here you can serilalize your data or render as html
these data will be saved to self.cached_content
also will be accessable from template | [
"this",
"property",
"just",
"calls",
"get_data",
"but",
"here",
"you",
"can",
"serilalize",
"your",
"data",
"or",
"render",
"as",
"html",
"these",
"data",
"will",
"be",
"saved",
"to",
"self",
".",
"cached_content",
"also",
"will",
"be",
"accessable",
"from",... | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L251-L259 |
22,394 | django-leonardo/django-leonardo | leonardo/module/web/widgets/mixins.py | JSONContentMixin.data | def data(self):
"""load and cache data in json format
"""
if self.is_obsolete():
data = self.get_data()
for datum in data:
if 'published_parsed' in datum:
datum['published_parsed'] = \
self.parse_time(datum['published_parsed'])
try:
dumped_data = json.dumps(data)
except:
self.update_cache(data)
else:
self.update_cache(dumped_data)
return data
try:
return json.loads(self.cache_data)
except:
return self.cache_data
return self.get_data() | python | def data(self):
if self.is_obsolete():
data = self.get_data()
for datum in data:
if 'published_parsed' in datum:
datum['published_parsed'] = \
self.parse_time(datum['published_parsed'])
try:
dumped_data = json.dumps(data)
except:
self.update_cache(data)
else:
self.update_cache(dumped_data)
return data
try:
return json.loads(self.cache_data)
except:
return self.cache_data
return self.get_data() | [
"def",
"data",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_obsolete",
"(",
")",
":",
"data",
"=",
"self",
".",
"get_data",
"(",
")",
"for",
"datum",
"in",
"data",
":",
"if",
"'published_parsed'",
"in",
"datum",
":",
"datum",
"[",
"'published_parsed'"... | load and cache data in json format | [
"load",
"and",
"cache",
"data",
"in",
"json",
"format"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L274-L298 |
22,395 | django-leonardo/django-leonardo | leonardo/utils/settings.py | get_loaded_modules | def get_loaded_modules(modules):
'''load modules and order it by ordering key'''
_modules = []
for mod in modules:
mod_cfg = get_conf_from_module(mod)
_modules.append((mod, mod_cfg,))
_modules = sorted(_modules, key=lambda m: m[1].get('ordering'))
return _modules | python | def get_loaded_modules(modules):
'''load modules and order it by ordering key'''
_modules = []
for mod in modules:
mod_cfg = get_conf_from_module(mod)
_modules.append((mod, mod_cfg,))
_modules = sorted(_modules, key=lambda m: m[1].get('ordering'))
return _modules | [
"def",
"get_loaded_modules",
"(",
"modules",
")",
":",
"_modules",
"=",
"[",
"]",
"for",
"mod",
"in",
"modules",
":",
"mod_cfg",
"=",
"get_conf_from_module",
"(",
"mod",
")",
"_modules",
".",
"append",
"(",
"(",
"mod",
",",
"mod_cfg",
",",
")",
")",
"_... | load modules and order it by ordering key | [
"load",
"modules",
"and",
"order",
"it",
"by",
"ordering",
"key"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/settings.py#L14-L25 |
22,396 | django-leonardo/django-leonardo | leonardo/utils/settings.py | _is_leonardo_module | def _is_leonardo_module(whatever):
'''check if is leonardo module'''
# check if is python module
if hasattr(whatever, 'default') \
or hasattr(whatever, 'leonardo_module_conf'):
return True
# check if is python object
for key in dir(whatever):
if 'LEONARDO' in key:
return True | python | def _is_leonardo_module(whatever):
'''check if is leonardo module'''
# check if is python module
if hasattr(whatever, 'default') \
or hasattr(whatever, 'leonardo_module_conf'):
return True
# check if is python object
for key in dir(whatever):
if 'LEONARDO' in key:
return True | [
"def",
"_is_leonardo_module",
"(",
"whatever",
")",
":",
"# check if is python module",
"if",
"hasattr",
"(",
"whatever",
",",
"'default'",
")",
"or",
"hasattr",
"(",
"whatever",
",",
"'leonardo_module_conf'",
")",
":",
"return",
"True",
"# check if is python object",... | check if is leonardo module | [
"check",
"if",
"is",
"leonardo",
"module"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/settings.py#L69-L80 |
22,397 | django-leonardo/django-leonardo | leonardo/utils/settings.py | extract_conf_from | def extract_conf_from(mod, conf=ModuleConfig(CONF_SPEC), depth=0, max_depth=2):
"""recursively extract keys from module or object
by passed config scheme
"""
# extract config keys from module or object
for key, default_value in six.iteritems(conf):
conf[key] = _get_key_from_module(mod, key, default_value)
# support for recursive dependecies
try:
filtered_apps = [app for app in conf['apps'] if app not in BLACKLIST]
except TypeError:
pass
except Exception as e:
warnings.warn('Error %s during loading %s' % (e, conf['apps']))
for app in filtered_apps:
try:
app_module = import_module(app)
if app_module != mod:
app_module = _get_correct_module(app_module)
if depth < max_depth:
mod_conf = extract_conf_from(app_module, depth=depth+1)
for k, v in six.iteritems(mod_conf):
# prevent config duplicity
# skip config merge
if k == 'config':
continue
if isinstance(v, dict):
conf[k].update(v)
elif isinstance(v, (list, tuple)):
conf[k] = merge(conf[k], v)
except Exception as e:
pass # swallow, but maybe log for info what happens
return conf | python | def extract_conf_from(mod, conf=ModuleConfig(CONF_SPEC), depth=0, max_depth=2):
# extract config keys from module or object
for key, default_value in six.iteritems(conf):
conf[key] = _get_key_from_module(mod, key, default_value)
# support for recursive dependecies
try:
filtered_apps = [app for app in conf['apps'] if app not in BLACKLIST]
except TypeError:
pass
except Exception as e:
warnings.warn('Error %s during loading %s' % (e, conf['apps']))
for app in filtered_apps:
try:
app_module = import_module(app)
if app_module != mod:
app_module = _get_correct_module(app_module)
if depth < max_depth:
mod_conf = extract_conf_from(app_module, depth=depth+1)
for k, v in six.iteritems(mod_conf):
# prevent config duplicity
# skip config merge
if k == 'config':
continue
if isinstance(v, dict):
conf[k].update(v)
elif isinstance(v, (list, tuple)):
conf[k] = merge(conf[k], v)
except Exception as e:
pass # swallow, but maybe log for info what happens
return conf | [
"def",
"extract_conf_from",
"(",
"mod",
",",
"conf",
"=",
"ModuleConfig",
"(",
"CONF_SPEC",
")",
",",
"depth",
"=",
"0",
",",
"max_depth",
"=",
"2",
")",
":",
"# extract config keys from module or object",
"for",
"key",
",",
"default_value",
"in",
"six",
".",
... | recursively extract keys from module or object
by passed config scheme | [
"recursively",
"extract",
"keys",
"from",
"module",
"or",
"object",
"by",
"passed",
"config",
"scheme"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/settings.py#L83-L118 |
22,398 | django-leonardo/django-leonardo | leonardo/utils/settings.py | _get_correct_module | def _get_correct_module(mod):
"""returns imported module
check if is ``leonardo_module_conf`` specified and then import them
"""
module_location = getattr(
mod, 'leonardo_module_conf',
getattr(mod, "LEONARDO_MODULE_CONF", None))
if module_location:
mod = import_module(module_location)
elif hasattr(mod, 'default_app_config'):
# use django behavior
mod_path, _, cls_name = mod.default_app_config.rpartition('.')
_mod = import_module(mod_path)
config_class = getattr(_mod, cls_name)
# check if is leonardo config compliant
if _is_leonardo_module(config_class):
mod = config_class
return mod | python | def _get_correct_module(mod):
module_location = getattr(
mod, 'leonardo_module_conf',
getattr(mod, "LEONARDO_MODULE_CONF", None))
if module_location:
mod = import_module(module_location)
elif hasattr(mod, 'default_app_config'):
# use django behavior
mod_path, _, cls_name = mod.default_app_config.rpartition('.')
_mod = import_module(mod_path)
config_class = getattr(_mod, cls_name)
# check if is leonardo config compliant
if _is_leonardo_module(config_class):
mod = config_class
return mod | [
"def",
"_get_correct_module",
"(",
"mod",
")",
":",
"module_location",
"=",
"getattr",
"(",
"mod",
",",
"'leonardo_module_conf'",
",",
"getattr",
"(",
"mod",
",",
"\"LEONARDO_MODULE_CONF\"",
",",
"None",
")",
")",
"if",
"module_location",
":",
"mod",
"=",
"imp... | returns imported module
check if is ``leonardo_module_conf`` specified and then import them | [
"returns",
"imported",
"module",
"check",
"if",
"is",
"leonardo_module_conf",
"specified",
"and",
"then",
"import",
"them"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/settings.py#L121-L141 |
22,399 | django-leonardo/django-leonardo | leonardo/utils/settings.py | get_conf_from_module | def get_conf_from_module(mod):
"""return configuration from module with defaults no worry about None type
"""
conf = ModuleConfig(CONF_SPEC)
# get imported module
mod = _get_correct_module(mod)
conf.set_module(mod)
# extarct from default object or from module
if hasattr(mod, 'default'):
default = mod.default
conf = extract_conf_from(default, conf)
else:
conf = extract_conf_from(mod, conf)
return conf | python | def get_conf_from_module(mod):
conf = ModuleConfig(CONF_SPEC)
# get imported module
mod = _get_correct_module(mod)
conf.set_module(mod)
# extarct from default object or from module
if hasattr(mod, 'default'):
default = mod.default
conf = extract_conf_from(default, conf)
else:
conf = extract_conf_from(mod, conf)
return conf | [
"def",
"get_conf_from_module",
"(",
"mod",
")",
":",
"conf",
"=",
"ModuleConfig",
"(",
"CONF_SPEC",
")",
"# get imported module",
"mod",
"=",
"_get_correct_module",
"(",
"mod",
")",
"conf",
".",
"set_module",
"(",
"mod",
")",
"# extarct from default object or from m... | return configuration from module with defaults no worry about None type | [
"return",
"configuration",
"from",
"module",
"with",
"defaults",
"no",
"worry",
"about",
"None",
"type"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/settings.py#L144-L162 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.