repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
cloudendpoints/endpoints-python
|
endpoints/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):
"""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)
|
[
"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",
")"
] |
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
|
train
|
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):
"""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
|
[
"def",
"__x_google_quota_descriptor",
"(",
"self",
",",
"metric_costs",
")",
":",
"return",
"{",
"'metricCosts'",
":",
"{",
"metric",
":",
"cost",
"for",
"(",
"metric",
",",
"cost",
")",
"in",
"metric_costs",
".",
"items",
"(",
")",
"}",
"}",
"if",
"metric_costs",
"else",
"None"
] |
Describes the metric costs for a call.
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
|
train
|
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):
"""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,
}
|
[
"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",
",",
"}"
] |
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
|
train
|
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):
"""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
|
[
"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"
] |
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
|
train
|
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):
"""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
|
[
"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"
] |
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
|
train
|
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):
"""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)
|
[
"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",
")"
] |
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
|
train
|
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):
"""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=(',', ': '))
|
[
"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",
"=",
"(",
"','",
",",
"': '",
")",
")"
] |
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
|
train
|
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):
"""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
|
[
"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"
] |
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
|
train
|
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):
"""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
|
[
"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"
] |
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
|
train
|
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):
"""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
|
[
"def",
"ref_for_message_type",
"(",
"self",
",",
"message_type",
")",
":",
"name",
"=",
"self",
".",
"__normalized_name",
"(",
"message_type",
")",
"if",
"name",
"not",
"in",
"self",
".",
"__schemas",
":",
"raise",
"KeyError",
"(",
"'Message has not been parsed: %s'",
",",
"name",
")",
"return",
"name"
] |
Returns the JSON Schema id for the given message.
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
|
train
|
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):
"""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
|
[
"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"
] |
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
|
train
|
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):
"""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
|
[
"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"
] |
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
|
train
|
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):
"""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)
|
[
"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",
")"
] |
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
|
train
|
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):
"""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')
|
[
"def",
"_check_boolean",
"(",
"parameter_name",
",",
"value",
",",
"parameter_config",
")",
":",
"if",
"parameter_config",
".",
"get",
"(",
"'type'",
")",
"!=",
"'boolean'",
":",
"return",
"if",
"value",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'1'",
",",
"'true'",
",",
"'0'",
",",
"'false'",
")",
":",
"raise",
"errors",
".",
"BasicTypeParameterError",
"(",
"parameter_name",
",",
"value",
",",
"'boolean'",
")"
] |
Checks if a boolean value is valid.
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
|
train
|
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):
"""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
|
[
"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"
] |
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
|
train
|
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):
"""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
|
[
"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"
] |
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
|
train
|
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
|
train
|
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):
"""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
|
[
"def",
"is_leonardo_module",
"(",
"mod",
")",
":",
"if",
"hasattr",
"(",
"mod",
",",
"'default'",
")",
"or",
"hasattr",
"(",
"mod",
",",
"'leonardo_module_conf'",
")",
":",
"return",
"True",
"for",
"key",
"in",
"dir",
"(",
"mod",
")",
":",
"if",
"'LEONARDO'",
"in",
"key",
":",
"return",
"True",
"return",
"False"
] |
returns True if is leonardo module
|
[
"returns",
"True",
"if",
"is",
"leonardo",
"module"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/__init__.py#L12-L22
|
train
|
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):
"""
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
|
[
"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"
] |
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
|
train
|
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):
"""
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}
|
[
"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",
"}"
] |
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
|
train
|
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):
"""
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
|
[
"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"
] |
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
|
train
|
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",
"=",
"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"
] |
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
|
train
|
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",
"(",
"' > '",
".",
"join",
"(",
"reversed",
"(",
"titles",
")",
")",
")"
] |
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
|
train
|
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):
"""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()
|
[
"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
|
train
|
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):
"""
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')
|
[
"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'",
")"
] |
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
|
train
|
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):
"""
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
|
[
"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"
] |
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",
"shortcutting",
"the",
"rendering",
"and",
"returning",
"that",
"response",
"immediately",
"to",
"the",
"client",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/models/page.py#L197-L210
|
train
|
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",
"[",
"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"
] |
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
|
train
|
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",
"=",
"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'",
")"
] |
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
|
train
|
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",
".",
"filter_items",
"(",
"self",
".",
"_items",
")"
] |
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
|
train
|
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
|
train
|
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",
")",
"return",
"md",
",",
"(",
"sm",
"or",
"md",
")",
",",
"12"
] |
returns columns count
|
[
"returns",
"columns",
"count"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L104-L110
|
train
|
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",
"==",
"0",
":",
"pages",
".",
"append",
"(",
"page",
")",
"page",
"=",
"[",
"]",
"page",
".",
"append",
"(",
"item",
")",
"pages",
".",
"append",
"(",
"page",
")",
"return",
"pages"
] |
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
|
train
|
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):
"""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
|
[
"def",
"needs_pagination",
"(",
"self",
")",
":",
"if",
"self",
".",
"objects_per_page",
"==",
"0",
":",
"return",
"False",
"if",
"len",
"(",
"self",
".",
"items",
")",
">",
"self",
".",
"objects_per_page",
"or",
"len",
"(",
"self",
".",
"get_pages",
"[",
"0",
"]",
")",
">",
"self",
".",
"objects_per_page",
":",
"return",
"True",
"return",
"False"
] |
Calculate needs pagination
|
[
"Calculate",
"needs",
"pagination"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L133-L140
|
train
|
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\"",
":",
"return",
"\"widget/%s/_item.html\"",
"%",
"self",
".",
"widget_name",
"# TODO: support more template suffixes",
"return",
"\"widget/%s/_%s.html\"",
"%",
"(",
"self",
".",
"widget_name",
",",
"content_template",
")"
] |
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
|
train
|
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):
"""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
|
[
"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"
] |
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
|
train
|
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):
"""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()
|
[
"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
|
train
|
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):
"""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
|
[
"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",
"template"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/mixins.py#L251-L259
|
train
|
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):
"""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()
|
[
"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",
"(",
")"
] |
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
|
train
|
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",
",",
")",
")",
"_modules",
"=",
"sorted",
"(",
"_modules",
",",
"key",
"=",
"lambda",
"m",
":",
"m",
"[",
"1",
"]",
".",
"get",
"(",
"'ordering'",
")",
")",
"return",
"_modules"
] |
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
|
train
|
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",
"for",
"key",
"in",
"dir",
"(",
"whatever",
")",
":",
"if",
"'LEONARDO'",
"in",
"key",
":",
"return",
"True"
] |
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
|
train
|
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):
"""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
|
[
"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"
] |
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
|
train
|
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):
"""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
|
[
"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"
] |
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
|
train
|
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):
"""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
|
[
"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"
] |
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
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/page/utils.py
|
get_anonymous_request
|
def get_anonymous_request(leonardo_page):
"""returns inicialized request
"""
request_factory = RequestFactory()
request = request_factory.get(
leonardo_page.get_absolute_url(), data={})
request.feincms_page = request.leonardo_page = leonardo_page
request.frontend_editing = False
request.user = AnonymousUser()
if not hasattr(request, '_feincms_extra_context'):
request._feincms_extra_context = {}
request.path = leonardo_page.get_absolute_url()
request.frontend_editing = False
leonardo_page.run_request_processors(request)
request.LEONARDO_CONFIG = ContextConfig(request)
handler = BaseHandler()
handler.load_middleware()
# Apply request middleware
for middleware_method in handler._request_middleware:
try:
middleware_method(request)
except:
pass
# call processors
for fn in reversed(list(leonardo_page.request_processors.values())):
fn(leonardo_page, request)
return request
|
python
|
def get_anonymous_request(leonardo_page):
"""returns inicialized request
"""
request_factory = RequestFactory()
request = request_factory.get(
leonardo_page.get_absolute_url(), data={})
request.feincms_page = request.leonardo_page = leonardo_page
request.frontend_editing = False
request.user = AnonymousUser()
if not hasattr(request, '_feincms_extra_context'):
request._feincms_extra_context = {}
request.path = leonardo_page.get_absolute_url()
request.frontend_editing = False
leonardo_page.run_request_processors(request)
request.LEONARDO_CONFIG = ContextConfig(request)
handler = BaseHandler()
handler.load_middleware()
# Apply request middleware
for middleware_method in handler._request_middleware:
try:
middleware_method(request)
except:
pass
# call processors
for fn in reversed(list(leonardo_page.request_processors.values())):
fn(leonardo_page, request)
return request
|
[
"def",
"get_anonymous_request",
"(",
"leonardo_page",
")",
":",
"request_factory",
"=",
"RequestFactory",
"(",
")",
"request",
"=",
"request_factory",
".",
"get",
"(",
"leonardo_page",
".",
"get_absolute_url",
"(",
")",
",",
"data",
"=",
"{",
"}",
")",
"request",
".",
"feincms_page",
"=",
"request",
".",
"leonardo_page",
"=",
"leonardo_page",
"request",
".",
"frontend_editing",
"=",
"False",
"request",
".",
"user",
"=",
"AnonymousUser",
"(",
")",
"if",
"not",
"hasattr",
"(",
"request",
",",
"'_feincms_extra_context'",
")",
":",
"request",
".",
"_feincms_extra_context",
"=",
"{",
"}",
"request",
".",
"path",
"=",
"leonardo_page",
".",
"get_absolute_url",
"(",
")",
"request",
".",
"frontend_editing",
"=",
"False",
"leonardo_page",
".",
"run_request_processors",
"(",
"request",
")",
"request",
".",
"LEONARDO_CONFIG",
"=",
"ContextConfig",
"(",
"request",
")",
"handler",
"=",
"BaseHandler",
"(",
")",
"handler",
".",
"load_middleware",
"(",
")",
"# Apply request middleware",
"for",
"middleware_method",
"in",
"handler",
".",
"_request_middleware",
":",
"try",
":",
"middleware_method",
"(",
"request",
")",
"except",
":",
"pass",
"# call processors",
"for",
"fn",
"in",
"reversed",
"(",
"list",
"(",
"leonardo_page",
".",
"request_processors",
".",
"values",
"(",
")",
")",
")",
":",
"fn",
"(",
"leonardo_page",
",",
"request",
")",
"return",
"request"
] |
returns inicialized request
|
[
"returns",
"inicialized",
"request"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/page/utils.py#L8-L43
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/processors/font.py
|
webfont_cookie
|
def webfont_cookie(request):
'''Adds WEBFONT Flag to the context'''
if hasattr(request, 'COOKIES') and request.COOKIES.get(WEBFONT_COOKIE_NAME, None):
return {
WEBFONT_COOKIE_NAME.upper(): True
}
return {
WEBFONT_COOKIE_NAME.upper(): False
}
|
python
|
def webfont_cookie(request):
'''Adds WEBFONT Flag to the context'''
if hasattr(request, 'COOKIES') and request.COOKIES.get(WEBFONT_COOKIE_NAME, None):
return {
WEBFONT_COOKIE_NAME.upper(): True
}
return {
WEBFONT_COOKIE_NAME.upper(): False
}
|
[
"def",
"webfont_cookie",
"(",
"request",
")",
":",
"if",
"hasattr",
"(",
"request",
",",
"'COOKIES'",
")",
"and",
"request",
".",
"COOKIES",
".",
"get",
"(",
"WEBFONT_COOKIE_NAME",
",",
"None",
")",
":",
"return",
"{",
"WEBFONT_COOKIE_NAME",
".",
"upper",
"(",
")",
":",
"True",
"}",
"return",
"{",
"WEBFONT_COOKIE_NAME",
".",
"upper",
"(",
")",
":",
"False",
"}"
] |
Adds WEBFONT Flag to the context
|
[
"Adds",
"WEBFONT",
"Flag",
"to",
"the",
"context"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/processors/font.py#L10-L21
|
train
|
django-leonardo/django-leonardo
|
leonardo/utils/widgets.py
|
get_all_widget_classes
|
def get_all_widget_classes():
"""returns collected Leonardo Widgets
if not declared in settings is used __subclasses__
which not supports widget subclassing
"""
from leonardo.module.web.models import Widget
_widgets = getattr(settings,
'WIDGETS', Widget.__subclasses__())
widgets = []
if isinstance(_widgets, dict):
for group, widget_cls in six.iteritems(_widgets):
widgets.extend(widget_cls)
elif isinstance(_widgets, list):
widgets = _widgets
return load_widget_classes(widgets)
|
python
|
def get_all_widget_classes():
"""returns collected Leonardo Widgets
if not declared in settings is used __subclasses__
which not supports widget subclassing
"""
from leonardo.module.web.models import Widget
_widgets = getattr(settings,
'WIDGETS', Widget.__subclasses__())
widgets = []
if isinstance(_widgets, dict):
for group, widget_cls in six.iteritems(_widgets):
widgets.extend(widget_cls)
elif isinstance(_widgets, list):
widgets = _widgets
return load_widget_classes(widgets)
|
[
"def",
"get_all_widget_classes",
"(",
")",
":",
"from",
"leonardo",
".",
"module",
".",
"web",
".",
"models",
"import",
"Widget",
"_widgets",
"=",
"getattr",
"(",
"settings",
",",
"'WIDGETS'",
",",
"Widget",
".",
"__subclasses__",
"(",
")",
")",
"widgets",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"_widgets",
",",
"dict",
")",
":",
"for",
"group",
",",
"widget_cls",
"in",
"six",
".",
"iteritems",
"(",
"_widgets",
")",
":",
"widgets",
".",
"extend",
"(",
"widget_cls",
")",
"elif",
"isinstance",
"(",
"_widgets",
",",
"list",
")",
":",
"widgets",
"=",
"_widgets",
"return",
"load_widget_classes",
"(",
"widgets",
")"
] |
returns collected Leonardo Widgets
if not declared in settings is used __subclasses__
which not supports widget subclassing
|
[
"returns",
"collected",
"Leonardo",
"Widgets"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/widgets.py#L45-L61
|
train
|
django-leonardo/django-leonardo
|
leonardo/utils/widgets.py
|
render_region
|
def render_region(widget=None, request=None, view=None,
page=None, region=None):
"""returns rendered content
this is not too clear and little tricky,
because external apps needs calling process method
"""
# change the request
if not isinstance(request, dict):
request.query_string = None
request.method = "GET"
if not hasattr(request, '_feincms_extra_context'):
request._feincms_extra_context = {}
leonardo_page = widget.parent if widget else page
render_region = widget.region if widget else region
# call processors
for fn in reversed(list(leonardo_page.request_processors.values())):
try:
r = fn(leonardo_page, request)
except:
pass
contents = {}
for content in leonardo_page.content.all_of_type(tuple(
leonardo_page._feincms_content_types_with_process)):
try:
r = content.process(request, view=view)
except:
pass
else:
# this is HttpResponse object or string
if not isinstance(r, six.string_types):
r.render()
contents[content.fe_identifier] = getattr(r, 'content', r)
else:
contents[content.fe_identifier] = r
from leonardo.templatetags.leonardo_tags import _render_content
region_content = ''.join(
contents[content.fe_identifier] if content.fe_identifier in contents else _render_content(
content, request=request, context={})
for content in getattr(leonardo_page.content, render_region))
return region_content
|
python
|
def render_region(widget=None, request=None, view=None,
page=None, region=None):
"""returns rendered content
this is not too clear and little tricky,
because external apps needs calling process method
"""
# change the request
if not isinstance(request, dict):
request.query_string = None
request.method = "GET"
if not hasattr(request, '_feincms_extra_context'):
request._feincms_extra_context = {}
leonardo_page = widget.parent if widget else page
render_region = widget.region if widget else region
# call processors
for fn in reversed(list(leonardo_page.request_processors.values())):
try:
r = fn(leonardo_page, request)
except:
pass
contents = {}
for content in leonardo_page.content.all_of_type(tuple(
leonardo_page._feincms_content_types_with_process)):
try:
r = content.process(request, view=view)
except:
pass
else:
# this is HttpResponse object or string
if not isinstance(r, six.string_types):
r.render()
contents[content.fe_identifier] = getattr(r, 'content', r)
else:
contents[content.fe_identifier] = r
from leonardo.templatetags.leonardo_tags import _render_content
region_content = ''.join(
contents[content.fe_identifier] if content.fe_identifier in contents else _render_content(
content, request=request, context={})
for content in getattr(leonardo_page.content, render_region))
return region_content
|
[
"def",
"render_region",
"(",
"widget",
"=",
"None",
",",
"request",
"=",
"None",
",",
"view",
"=",
"None",
",",
"page",
"=",
"None",
",",
"region",
"=",
"None",
")",
":",
"# change the request",
"if",
"not",
"isinstance",
"(",
"request",
",",
"dict",
")",
":",
"request",
".",
"query_string",
"=",
"None",
"request",
".",
"method",
"=",
"\"GET\"",
"if",
"not",
"hasattr",
"(",
"request",
",",
"'_feincms_extra_context'",
")",
":",
"request",
".",
"_feincms_extra_context",
"=",
"{",
"}",
"leonardo_page",
"=",
"widget",
".",
"parent",
"if",
"widget",
"else",
"page",
"render_region",
"=",
"widget",
".",
"region",
"if",
"widget",
"else",
"region",
"# call processors",
"for",
"fn",
"in",
"reversed",
"(",
"list",
"(",
"leonardo_page",
".",
"request_processors",
".",
"values",
"(",
")",
")",
")",
":",
"try",
":",
"r",
"=",
"fn",
"(",
"leonardo_page",
",",
"request",
")",
"except",
":",
"pass",
"contents",
"=",
"{",
"}",
"for",
"content",
"in",
"leonardo_page",
".",
"content",
".",
"all_of_type",
"(",
"tuple",
"(",
"leonardo_page",
".",
"_feincms_content_types_with_process",
")",
")",
":",
"try",
":",
"r",
"=",
"content",
".",
"process",
"(",
"request",
",",
"view",
"=",
"view",
")",
"except",
":",
"pass",
"else",
":",
"# this is HttpResponse object or string",
"if",
"not",
"isinstance",
"(",
"r",
",",
"six",
".",
"string_types",
")",
":",
"r",
".",
"render",
"(",
")",
"contents",
"[",
"content",
".",
"fe_identifier",
"]",
"=",
"getattr",
"(",
"r",
",",
"'content'",
",",
"r",
")",
"else",
":",
"contents",
"[",
"content",
".",
"fe_identifier",
"]",
"=",
"r",
"from",
"leonardo",
".",
"templatetags",
".",
"leonardo_tags",
"import",
"_render_content",
"region_content",
"=",
"''",
".",
"join",
"(",
"contents",
"[",
"content",
".",
"fe_identifier",
"]",
"if",
"content",
".",
"fe_identifier",
"in",
"contents",
"else",
"_render_content",
"(",
"content",
",",
"request",
"=",
"request",
",",
"context",
"=",
"{",
"}",
")",
"for",
"content",
"in",
"getattr",
"(",
"leonardo_page",
".",
"content",
",",
"render_region",
")",
")",
"return",
"region_content"
] |
returns rendered content
this is not too clear and little tricky,
because external apps needs calling process method
|
[
"returns",
"rendered",
"content",
"this",
"is",
"not",
"too",
"clear",
"and",
"little",
"tricky",
"because",
"external",
"apps",
"needs",
"calling",
"process",
"method"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/widgets.py#L124-L173
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/admin.py
|
PageAdmin.get_feincms_inlines
|
def get_feincms_inlines(self, model, request):
""" Generate genuine django inlines for registered content types. """
model._needs_content_types()
inlines = []
for content_type in model._feincms_content_types:
if not self.can_add_content(request, content_type):
continue
attrs = {
'__module__': model.__module__,
'model': content_type,
}
if hasattr(content_type, 'feincms_item_editor_inline'):
inline = content_type.feincms_item_editor_inline
attrs['form'] = inline.form
#if hasattr(content_type, 'feincms_item_editor_form'):
# warnings.warn(
# 'feincms_item_editor_form on %s is ignored because '
# 'feincms_item_editor_inline is set too' % content_type,
# RuntimeWarning)
else:
inline = FeinCMSInline
attrs['form'] = getattr(
content_type, 'feincms_item_editor_form', inline.form)
name = '%sFeinCMSInline' % content_type.__name__
# TODO: We generate a new class every time. Is that really wanted?
inline_class = type(str(name), (inline,), attrs)
inlines.append(inline_class)
return inlines
|
python
|
def get_feincms_inlines(self, model, request):
""" Generate genuine django inlines for registered content types. """
model._needs_content_types()
inlines = []
for content_type in model._feincms_content_types:
if not self.can_add_content(request, content_type):
continue
attrs = {
'__module__': model.__module__,
'model': content_type,
}
if hasattr(content_type, 'feincms_item_editor_inline'):
inline = content_type.feincms_item_editor_inline
attrs['form'] = inline.form
#if hasattr(content_type, 'feincms_item_editor_form'):
# warnings.warn(
# 'feincms_item_editor_form on %s is ignored because '
# 'feincms_item_editor_inline is set too' % content_type,
# RuntimeWarning)
else:
inline = FeinCMSInline
attrs['form'] = getattr(
content_type, 'feincms_item_editor_form', inline.form)
name = '%sFeinCMSInline' % content_type.__name__
# TODO: We generate a new class every time. Is that really wanted?
inline_class = type(str(name), (inline,), attrs)
inlines.append(inline_class)
return inlines
|
[
"def",
"get_feincms_inlines",
"(",
"self",
",",
"model",
",",
"request",
")",
":",
"model",
".",
"_needs_content_types",
"(",
")",
"inlines",
"=",
"[",
"]",
"for",
"content_type",
"in",
"model",
".",
"_feincms_content_types",
":",
"if",
"not",
"self",
".",
"can_add_content",
"(",
"request",
",",
"content_type",
")",
":",
"continue",
"attrs",
"=",
"{",
"'__module__'",
":",
"model",
".",
"__module__",
",",
"'model'",
":",
"content_type",
",",
"}",
"if",
"hasattr",
"(",
"content_type",
",",
"'feincms_item_editor_inline'",
")",
":",
"inline",
"=",
"content_type",
".",
"feincms_item_editor_inline",
"attrs",
"[",
"'form'",
"]",
"=",
"inline",
".",
"form",
"#if hasattr(content_type, 'feincms_item_editor_form'):",
"# warnings.warn(",
"# 'feincms_item_editor_form on %s is ignored because '",
"# 'feincms_item_editor_inline is set too' % content_type,",
"# RuntimeWarning)",
"else",
":",
"inline",
"=",
"FeinCMSInline",
"attrs",
"[",
"'form'",
"]",
"=",
"getattr",
"(",
"content_type",
",",
"'feincms_item_editor_form'",
",",
"inline",
".",
"form",
")",
"name",
"=",
"'%sFeinCMSInline'",
"%",
"content_type",
".",
"__name__",
"# TODO: We generate a new class every time. Is that really wanted?",
"inline_class",
"=",
"type",
"(",
"str",
"(",
"name",
")",
",",
"(",
"inline",
",",
")",
",",
"attrs",
")",
"inlines",
".",
"append",
"(",
"inline_class",
")",
"return",
"inlines"
] |
Generate genuine django inlines for registered content types.
|
[
"Generate",
"genuine",
"django",
"inlines",
"for",
"registered",
"content",
"types",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/admin.py#L49-L82
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/admin.py
|
PageAdmin.get_changeform_initial_data
|
def get_changeform_initial_data(self, request):
'''Copy initial data from parent'''
initial = super(PageAdmin, self).get_changeform_initial_data(request)
if ('translation_of' in request.GET):
original = self.model._tree_manager.get(
pk=request.GET.get('translation_of'))
initial['layout'] = original.layout
initial['theme'] = original.theme
initial['color_scheme'] = original.color_scheme
# optionaly translate title and make slug
old_lang = translation.get_language()
translation.activate(request.GET.get('language'))
title = _(original.title)
if title != original.title:
initial['title'] = title
initial['slug'] = slugify(title)
translation.activate(old_lang)
return initial
|
python
|
def get_changeform_initial_data(self, request):
'''Copy initial data from parent'''
initial = super(PageAdmin, self).get_changeform_initial_data(request)
if ('translation_of' in request.GET):
original = self.model._tree_manager.get(
pk=request.GET.get('translation_of'))
initial['layout'] = original.layout
initial['theme'] = original.theme
initial['color_scheme'] = original.color_scheme
# optionaly translate title and make slug
old_lang = translation.get_language()
translation.activate(request.GET.get('language'))
title = _(original.title)
if title != original.title:
initial['title'] = title
initial['slug'] = slugify(title)
translation.activate(old_lang)
return initial
|
[
"def",
"get_changeform_initial_data",
"(",
"self",
",",
"request",
")",
":",
"initial",
"=",
"super",
"(",
"PageAdmin",
",",
"self",
")",
".",
"get_changeform_initial_data",
"(",
"request",
")",
"if",
"(",
"'translation_of'",
"in",
"request",
".",
"GET",
")",
":",
"original",
"=",
"self",
".",
"model",
".",
"_tree_manager",
".",
"get",
"(",
"pk",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'translation_of'",
")",
")",
"initial",
"[",
"'layout'",
"]",
"=",
"original",
".",
"layout",
"initial",
"[",
"'theme'",
"]",
"=",
"original",
".",
"theme",
"initial",
"[",
"'color_scheme'",
"]",
"=",
"original",
".",
"color_scheme",
"# optionaly translate title and make slug",
"old_lang",
"=",
"translation",
".",
"get_language",
"(",
")",
"translation",
".",
"activate",
"(",
"request",
".",
"GET",
".",
"get",
"(",
"'language'",
")",
")",
"title",
"=",
"_",
"(",
"original",
".",
"title",
")",
"if",
"title",
"!=",
"original",
".",
"title",
":",
"initial",
"[",
"'title'",
"]",
"=",
"title",
"initial",
"[",
"'slug'",
"]",
"=",
"slugify",
"(",
"title",
")",
"translation",
".",
"activate",
"(",
"old_lang",
")",
"return",
"initial"
] |
Copy initial data from parent
|
[
"Copy",
"initial",
"data",
"from",
"parent"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/admin.py#L84-L103
|
train
|
django-leonardo/django-leonardo
|
leonardo/utils/package.py
|
install_package
|
def install_package(package, upgrade=True,
target=None):
"""Install a package on PyPi. Accepts pip compatible package strings.
Return boolean if install successful.
"""
# Not using 'import pip; pip.main([])' because it breaks the logger
with INSTALL_LOCK:
if check_package_exists(package, target):
return True
_LOGGER.info('Attempting install of %s', package)
args = [sys.executable, '-m', 'pip', 'install', '--quiet', package]
if upgrade:
args.append('--upgrade')
if target:
args += ['--target', os.path.abspath(target)]
try:
return subprocess.call(args) == 0
except subprocess.SubprocessError:
_LOGGER.exception('Unable to install pacakge %s', package)
return False
|
python
|
def install_package(package, upgrade=True,
target=None):
"""Install a package on PyPi. Accepts pip compatible package strings.
Return boolean if install successful.
"""
# Not using 'import pip; pip.main([])' because it breaks the logger
with INSTALL_LOCK:
if check_package_exists(package, target):
return True
_LOGGER.info('Attempting install of %s', package)
args = [sys.executable, '-m', 'pip', 'install', '--quiet', package]
if upgrade:
args.append('--upgrade')
if target:
args += ['--target', os.path.abspath(target)]
try:
return subprocess.call(args) == 0
except subprocess.SubprocessError:
_LOGGER.exception('Unable to install pacakge %s', package)
return False
|
[
"def",
"install_package",
"(",
"package",
",",
"upgrade",
"=",
"True",
",",
"target",
"=",
"None",
")",
":",
"# Not using 'import pip; pip.main([])' because it breaks the logger",
"with",
"INSTALL_LOCK",
":",
"if",
"check_package_exists",
"(",
"package",
",",
"target",
")",
":",
"return",
"True",
"_LOGGER",
".",
"info",
"(",
"'Attempting install of %s'",
",",
"package",
")",
"args",
"=",
"[",
"sys",
".",
"executable",
",",
"'-m'",
",",
"'pip'",
",",
"'install'",
",",
"'--quiet'",
",",
"package",
"]",
"if",
"upgrade",
":",
"args",
".",
"append",
"(",
"'--upgrade'",
")",
"if",
"target",
":",
"args",
"+=",
"[",
"'--target'",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"target",
")",
"]",
"try",
":",
"return",
"subprocess",
".",
"call",
"(",
"args",
")",
"==",
"0",
"except",
"subprocess",
".",
"SubprocessError",
":",
"_LOGGER",
".",
"exception",
"(",
"'Unable to install pacakge %s'",
",",
"package",
")",
"return",
"False"
] |
Install a package on PyPi. Accepts pip compatible package strings.
Return boolean if install successful.
|
[
"Install",
"a",
"package",
"on",
"PyPi",
".",
"Accepts",
"pip",
"compatible",
"package",
"strings",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/package.py#L19-L41
|
train
|
django-leonardo/django-leonardo
|
leonardo/utils/package.py
|
check_package_exists
|
def check_package_exists(package, lib_dir):
"""Check if a package is installed globally or in lib_dir.
Returns True when the requirement is met.
Returns False when the package is not installed or doesn't meet req.
"""
try:
req = pkg_resources.Requirement.parse(package)
except ValueError:
# This is a zip file
req = pkg_resources.Requirement.parse(urlparse(package).fragment)
# Check packages from lib dir
if lib_dir is not None:
if any(dist in req for dist in
pkg_resources.find_distributions(lib_dir)):
return True
# Check packages from global + virtual environment
# pylint: disable=not-an-iterable
return any(dist in req for dist in pkg_resources.working_set)
|
python
|
def check_package_exists(package, lib_dir):
"""Check if a package is installed globally or in lib_dir.
Returns True when the requirement is met.
Returns False when the package is not installed or doesn't meet req.
"""
try:
req = pkg_resources.Requirement.parse(package)
except ValueError:
# This is a zip file
req = pkg_resources.Requirement.parse(urlparse(package).fragment)
# Check packages from lib dir
if lib_dir is not None:
if any(dist in req for dist in
pkg_resources.find_distributions(lib_dir)):
return True
# Check packages from global + virtual environment
# pylint: disable=not-an-iterable
return any(dist in req for dist in pkg_resources.working_set)
|
[
"def",
"check_package_exists",
"(",
"package",
",",
"lib_dir",
")",
":",
"try",
":",
"req",
"=",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"package",
")",
"except",
"ValueError",
":",
"# This is a zip file",
"req",
"=",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"urlparse",
"(",
"package",
")",
".",
"fragment",
")",
"# Check packages from lib dir",
"if",
"lib_dir",
"is",
"not",
"None",
":",
"if",
"any",
"(",
"dist",
"in",
"req",
"for",
"dist",
"in",
"pkg_resources",
".",
"find_distributions",
"(",
"lib_dir",
")",
")",
":",
"return",
"True",
"# Check packages from global + virtual environment",
"# pylint: disable=not-an-iterable",
"return",
"any",
"(",
"dist",
"in",
"req",
"for",
"dist",
"in",
"pkg_resources",
".",
"working_set",
")"
] |
Check if a package is installed globally or in lib_dir.
Returns True when the requirement is met.
Returns False when the package is not installed or doesn't meet req.
|
[
"Check",
"if",
"a",
"package",
"is",
"installed",
"globally",
"or",
"in",
"lib_dir",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/package.py#L44-L64
|
train
|
django-leonardo/django-leonardo
|
leonardo/views/ajax.py
|
AJAXMixin.render_widget
|
def render_widget(self, request, widget_id):
'''Returns rendered widget in JSON response'''
widget = get_widget_from_id(widget_id)
response = widget.render(**{'request': request})
return JsonResponse({'result': response, 'id': widget_id})
|
python
|
def render_widget(self, request, widget_id):
'''Returns rendered widget in JSON response'''
widget = get_widget_from_id(widget_id)
response = widget.render(**{'request': request})
return JsonResponse({'result': response, 'id': widget_id})
|
[
"def",
"render_widget",
"(",
"self",
",",
"request",
",",
"widget_id",
")",
":",
"widget",
"=",
"get_widget_from_id",
"(",
"widget_id",
")",
"response",
"=",
"widget",
".",
"render",
"(",
"*",
"*",
"{",
"'request'",
":",
"request",
"}",
")",
"return",
"JsonResponse",
"(",
"{",
"'result'",
":",
"response",
",",
"'id'",
":",
"widget_id",
"}",
")"
] |
Returns rendered widget in JSON response
|
[
"Returns",
"rendered",
"widget",
"in",
"JSON",
"response"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/ajax.py#L31-L38
|
train
|
django-leonardo/django-leonardo
|
leonardo/views/ajax.py
|
AJAXMixin.render_region
|
def render_region(self, request):
'''Returns rendered region in JSON response'''
page = self.get_object()
try:
region = request.POST['region']
except KeyError:
region = request.GET['region']
request.query_string = None
from leonardo.utils.widgets import render_region
result = render_region(page=page, request=request, region=region)
return JsonResponse({'result': result, 'region': region})
|
python
|
def render_region(self, request):
'''Returns rendered region in JSON response'''
page = self.get_object()
try:
region = request.POST['region']
except KeyError:
region = request.GET['region']
request.query_string = None
from leonardo.utils.widgets import render_region
result = render_region(page=page, request=request, region=region)
return JsonResponse({'result': result, 'region': region})
|
[
"def",
"render_region",
"(",
"self",
",",
"request",
")",
":",
"page",
"=",
"self",
".",
"get_object",
"(",
")",
"try",
":",
"region",
"=",
"request",
".",
"POST",
"[",
"'region'",
"]",
"except",
"KeyError",
":",
"region",
"=",
"request",
".",
"GET",
"[",
"'region'",
"]",
"request",
".",
"query_string",
"=",
"None",
"from",
"leonardo",
".",
"utils",
".",
"widgets",
"import",
"render_region",
"result",
"=",
"render_region",
"(",
"page",
"=",
"page",
",",
"request",
"=",
"request",
",",
"region",
"=",
"region",
")",
"return",
"JsonResponse",
"(",
"{",
"'result'",
":",
"result",
",",
"'region'",
":",
"region",
"}",
")"
] |
Returns rendered region in JSON response
|
[
"Returns",
"rendered",
"region",
"in",
"JSON",
"response"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/ajax.py#L40-L56
|
train
|
django-leonardo/django-leonardo
|
leonardo/views/ajax.py
|
AJAXMixin.handle_ajax_method
|
def handle_ajax_method(self, request, method):
"""handle ajax methods and return serialized reponse
in the default state allows only authentificated users
- Depends on method parameter render whole region or single widget
- If widget_id is present then try to load this widget
and call method on them
- If class_name is present then try to load class
and then call static method on this class
- If class_name is present then try to load class
and if method_name == render_preview then
render widget preview without instance
"""
response = {}
def get_param(request, name):
try:
return request.POST[name]
except KeyError:
return request.GET.get(name, None)
widget_id = get_param(request, "widget_id")
class_name = get_param(request, "class_name")
if method in 'widget_content':
return self.render_widget(request, widget_id)
if method == 'region':
return self.render_region(request)
# handle methods called directly on widget
if widget_id:
widget = get_widget_from_id(widget_id)
try:
func = getattr(widget, method)
except AttributeError:
response["exception"] = "%s method is not implmented on %s" % (
method, widget)
else:
response["result"] = func(request)
elif class_name:
# handle calling classmethod without instance
try:
cls = get_model(*class_name.split('.'))
except Exception as e:
response["exception"] = str(e)
return JsonResponse(data=response)
if method == "render_preview":
# TODO: i think that we need only simple form
# for loading relations but maybe this would be need it
# custom_form_cls = getattr(
# cls, 'feincms_item_editor_form', None)
# if custom_form_cls:
# FormCls = modelform_factory(cls, form=custom_form_cls,
# exclude=('pk', 'id'))
FormCls = modelform_factory(cls, exclude=('pk', 'id'))
form = FormCls(request.POST)
if form.is_valid():
widget = cls(**form.cleaned_data)
request.frontend_editing = False
try:
content = widget.render(**{'request': request})
except Exception as e:
response['result'] = widget.handle_exception(request, e)
else:
response['result'] = content
response['id'] = widget_id
else:
response['result'] = form.errors
response['id'] = widget_id
else:
# standard method
try:
func = getattr(cls, method)
except Exception as e:
response["exception"] = str(e)
else:
response["result"] = func(request)
return JsonResponse(data=response)
|
python
|
def handle_ajax_method(self, request, method):
"""handle ajax methods and return serialized reponse
in the default state allows only authentificated users
- Depends on method parameter render whole region or single widget
- If widget_id is present then try to load this widget
and call method on them
- If class_name is present then try to load class
and then call static method on this class
- If class_name is present then try to load class
and if method_name == render_preview then
render widget preview without instance
"""
response = {}
def get_param(request, name):
try:
return request.POST[name]
except KeyError:
return request.GET.get(name, None)
widget_id = get_param(request, "widget_id")
class_name = get_param(request, "class_name")
if method in 'widget_content':
return self.render_widget(request, widget_id)
if method == 'region':
return self.render_region(request)
# handle methods called directly on widget
if widget_id:
widget = get_widget_from_id(widget_id)
try:
func = getattr(widget, method)
except AttributeError:
response["exception"] = "%s method is not implmented on %s" % (
method, widget)
else:
response["result"] = func(request)
elif class_name:
# handle calling classmethod without instance
try:
cls = get_model(*class_name.split('.'))
except Exception as e:
response["exception"] = str(e)
return JsonResponse(data=response)
if method == "render_preview":
# TODO: i think that we need only simple form
# for loading relations but maybe this would be need it
# custom_form_cls = getattr(
# cls, 'feincms_item_editor_form', None)
# if custom_form_cls:
# FormCls = modelform_factory(cls, form=custom_form_cls,
# exclude=('pk', 'id'))
FormCls = modelform_factory(cls, exclude=('pk', 'id'))
form = FormCls(request.POST)
if form.is_valid():
widget = cls(**form.cleaned_data)
request.frontend_editing = False
try:
content = widget.render(**{'request': request})
except Exception as e:
response['result'] = widget.handle_exception(request, e)
else:
response['result'] = content
response['id'] = widget_id
else:
response['result'] = form.errors
response['id'] = widget_id
else:
# standard method
try:
func = getattr(cls, method)
except Exception as e:
response["exception"] = str(e)
else:
response["result"] = func(request)
return JsonResponse(data=response)
|
[
"def",
"handle_ajax_method",
"(",
"self",
",",
"request",
",",
"method",
")",
":",
"response",
"=",
"{",
"}",
"def",
"get_param",
"(",
"request",
",",
"name",
")",
":",
"try",
":",
"return",
"request",
".",
"POST",
"[",
"name",
"]",
"except",
"KeyError",
":",
"return",
"request",
".",
"GET",
".",
"get",
"(",
"name",
",",
"None",
")",
"widget_id",
"=",
"get_param",
"(",
"request",
",",
"\"widget_id\"",
")",
"class_name",
"=",
"get_param",
"(",
"request",
",",
"\"class_name\"",
")",
"if",
"method",
"in",
"'widget_content'",
":",
"return",
"self",
".",
"render_widget",
"(",
"request",
",",
"widget_id",
")",
"if",
"method",
"==",
"'region'",
":",
"return",
"self",
".",
"render_region",
"(",
"request",
")",
"# handle methods called directly on widget",
"if",
"widget_id",
":",
"widget",
"=",
"get_widget_from_id",
"(",
"widget_id",
")",
"try",
":",
"func",
"=",
"getattr",
"(",
"widget",
",",
"method",
")",
"except",
"AttributeError",
":",
"response",
"[",
"\"exception\"",
"]",
"=",
"\"%s method is not implmented on %s\"",
"%",
"(",
"method",
",",
"widget",
")",
"else",
":",
"response",
"[",
"\"result\"",
"]",
"=",
"func",
"(",
"request",
")",
"elif",
"class_name",
":",
"# handle calling classmethod without instance",
"try",
":",
"cls",
"=",
"get_model",
"(",
"*",
"class_name",
".",
"split",
"(",
"'.'",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"response",
"[",
"\"exception\"",
"]",
"=",
"str",
"(",
"e",
")",
"return",
"JsonResponse",
"(",
"data",
"=",
"response",
")",
"if",
"method",
"==",
"\"render_preview\"",
":",
"# TODO: i think that we need only simple form",
"# for loading relations but maybe this would be need it",
"# custom_form_cls = getattr(",
"# cls, 'feincms_item_editor_form', None)",
"# if custom_form_cls:",
"# FormCls = modelform_factory(cls, form=custom_form_cls,",
"# exclude=('pk', 'id'))",
"FormCls",
"=",
"modelform_factory",
"(",
"cls",
",",
"exclude",
"=",
"(",
"'pk'",
",",
"'id'",
")",
")",
"form",
"=",
"FormCls",
"(",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"widget",
"=",
"cls",
"(",
"*",
"*",
"form",
".",
"cleaned_data",
")",
"request",
".",
"frontend_editing",
"=",
"False",
"try",
":",
"content",
"=",
"widget",
".",
"render",
"(",
"*",
"*",
"{",
"'request'",
":",
"request",
"}",
")",
"except",
"Exception",
"as",
"e",
":",
"response",
"[",
"'result'",
"]",
"=",
"widget",
".",
"handle_exception",
"(",
"request",
",",
"e",
")",
"else",
":",
"response",
"[",
"'result'",
"]",
"=",
"content",
"response",
"[",
"'id'",
"]",
"=",
"widget_id",
"else",
":",
"response",
"[",
"'result'",
"]",
"=",
"form",
".",
"errors",
"response",
"[",
"'id'",
"]",
"=",
"widget_id",
"else",
":",
"# standard method",
"try",
":",
"func",
"=",
"getattr",
"(",
"cls",
",",
"method",
")",
"except",
"Exception",
"as",
"e",
":",
"response",
"[",
"\"exception\"",
"]",
"=",
"str",
"(",
"e",
")",
"else",
":",
"response",
"[",
"\"result\"",
"]",
"=",
"func",
"(",
"request",
")",
"return",
"JsonResponse",
"(",
"data",
"=",
"response",
")"
] |
handle ajax methods and return serialized reponse
in the default state allows only authentificated users
- Depends on method parameter render whole region or single widget
- If widget_id is present then try to load this widget
and call method on them
- If class_name is present then try to load class
and then call static method on this class
- If class_name is present then try to load class
and if method_name == render_preview then
render widget preview without instance
|
[
"handle",
"ajax",
"methods",
"and",
"return",
"serialized",
"reponse",
"in",
"the",
"default",
"state",
"allows",
"only",
"authentificated",
"users"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/ajax.py#L59-L160
|
train
|
django-leonardo/django-leonardo
|
leonardo/templatetags/form_helpers.py
|
add_bootstrap_class
|
def add_bootstrap_class(field):
"""Add a "form-control" CSS class to the field's widget.
This is so that Bootstrap styles it properly.
"""
if not isinstance(field.field.widget, (
django.forms.widgets.CheckboxInput,
django.forms.widgets.CheckboxSelectMultiple,
django.forms.widgets.RadioSelect,
django.forms.widgets.FileInput,
str
)):
field_classes = set(field.field.widget.attrs.get('class', '').split())
field_classes.add('form-control')
field.field.widget.attrs['class'] = ' '.join(field_classes)
return field
|
python
|
def add_bootstrap_class(field):
"""Add a "form-control" CSS class to the field's widget.
This is so that Bootstrap styles it properly.
"""
if not isinstance(field.field.widget, (
django.forms.widgets.CheckboxInput,
django.forms.widgets.CheckboxSelectMultiple,
django.forms.widgets.RadioSelect,
django.forms.widgets.FileInput,
str
)):
field_classes = set(field.field.widget.attrs.get('class', '').split())
field_classes.add('form-control')
field.field.widget.attrs['class'] = ' '.join(field_classes)
return field
|
[
"def",
"add_bootstrap_class",
"(",
"field",
")",
":",
"if",
"not",
"isinstance",
"(",
"field",
".",
"field",
".",
"widget",
",",
"(",
"django",
".",
"forms",
".",
"widgets",
".",
"CheckboxInput",
",",
"django",
".",
"forms",
".",
"widgets",
".",
"CheckboxSelectMultiple",
",",
"django",
".",
"forms",
".",
"widgets",
".",
"RadioSelect",
",",
"django",
".",
"forms",
".",
"widgets",
".",
"FileInput",
",",
"str",
")",
")",
":",
"field_classes",
"=",
"set",
"(",
"field",
".",
"field",
".",
"widget",
".",
"attrs",
".",
"get",
"(",
"'class'",
",",
"''",
")",
".",
"split",
"(",
")",
")",
"field_classes",
".",
"add",
"(",
"'form-control'",
")",
"field",
".",
"field",
".",
"widget",
".",
"attrs",
"[",
"'class'",
"]",
"=",
"' '",
".",
"join",
"(",
"field_classes",
")",
"return",
"field"
] |
Add a "form-control" CSS class to the field's widget.
This is so that Bootstrap styles it properly.
|
[
"Add",
"a",
"form",
"-",
"control",
"CSS",
"class",
"to",
"the",
"field",
"s",
"widget",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/templatetags/form_helpers.py#L20-L35
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/media/admin/clipboardadmin.py
|
ClipboardAdmin.ajax_upload
|
def ajax_upload(self, request, folder_id=None):
"""
receives an upload from the uploader. Receives only one file at the time.
"""
mimetype = "application/json" if request.is_ajax() else "text/html"
content_type_key = 'content_type'
response_params = {content_type_key: mimetype}
folder = None
if folder_id:
try:
# Get folder
folder = Folder.objects.get(pk=folder_id)
except Folder.DoesNotExist:
return HttpResponse(json.dumps({'error': NO_FOLDER_ERROR}),
**response_params)
# check permissions
if folder and not folder.has_add_children_permission(request):
return HttpResponse(
json.dumps({'error': NO_PERMISSIONS_FOR_FOLDER}),
**response_params)
try:
if len(request.FILES) == 1:
# dont check if request is ajax or not, just grab the file
upload, filename, is_raw = handle_request_files_upload(request)
else:
# else process the request as usual
upload, filename, is_raw = handle_upload(request)
# Get clipboad
# TODO: Deprecated/refactor
# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]
# find the file type
for filer_class in media_settings.MEDIA_FILE_MODELS:
FileSubClass = load_object(filer_class)
# TODO: What if there are more than one that qualify?
if FileSubClass.matches_file_type(filename, upload, request):
FileForm = modelform_factory(
model=FileSubClass,
fields=('original_filename', 'owner', 'file')
)
break
uploadform = FileForm({'original_filename': filename,
'owner': request.user.pk},
{'file': upload})
if uploadform.is_valid():
file_obj = uploadform.save(commit=False)
# Enforce the FILER_IS_PUBLIC_DEFAULT
file_obj.is_public = settings.MEDIA_IS_PUBLIC_DEFAULT
file_obj.folder = folder
file_obj.save()
# TODO: Deprecated/refactor
# clipboard_item = ClipboardItem(
# clipboard=clipboard, file=file_obj)
# clipboard_item.save()
json_response = {
'thumbnail': file_obj.icons['32'],
'alt_text': '',
'label': str(file_obj),
'file_id': file_obj.pk,
}
return HttpResponse(json.dumps(json_response),
**response_params)
else:
form_errors = '; '.join(['%s: %s' % (
field,
', '.join(errors)) for field, errors in list(uploadform.errors.items())
])
raise UploadException(
"AJAX request not valid: form invalid '%s'" % (form_errors,))
except UploadException as e:
return HttpResponse(json.dumps({'error': str(e)}),
**response_params)
|
python
|
def ajax_upload(self, request, folder_id=None):
"""
receives an upload from the uploader. Receives only one file at the time.
"""
mimetype = "application/json" if request.is_ajax() else "text/html"
content_type_key = 'content_type'
response_params = {content_type_key: mimetype}
folder = None
if folder_id:
try:
# Get folder
folder = Folder.objects.get(pk=folder_id)
except Folder.DoesNotExist:
return HttpResponse(json.dumps({'error': NO_FOLDER_ERROR}),
**response_params)
# check permissions
if folder and not folder.has_add_children_permission(request):
return HttpResponse(
json.dumps({'error': NO_PERMISSIONS_FOR_FOLDER}),
**response_params)
try:
if len(request.FILES) == 1:
# dont check if request is ajax or not, just grab the file
upload, filename, is_raw = handle_request_files_upload(request)
else:
# else process the request as usual
upload, filename, is_raw = handle_upload(request)
# Get clipboad
# TODO: Deprecated/refactor
# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]
# find the file type
for filer_class in media_settings.MEDIA_FILE_MODELS:
FileSubClass = load_object(filer_class)
# TODO: What if there are more than one that qualify?
if FileSubClass.matches_file_type(filename, upload, request):
FileForm = modelform_factory(
model=FileSubClass,
fields=('original_filename', 'owner', 'file')
)
break
uploadform = FileForm({'original_filename': filename,
'owner': request.user.pk},
{'file': upload})
if uploadform.is_valid():
file_obj = uploadform.save(commit=False)
# Enforce the FILER_IS_PUBLIC_DEFAULT
file_obj.is_public = settings.MEDIA_IS_PUBLIC_DEFAULT
file_obj.folder = folder
file_obj.save()
# TODO: Deprecated/refactor
# clipboard_item = ClipboardItem(
# clipboard=clipboard, file=file_obj)
# clipboard_item.save()
json_response = {
'thumbnail': file_obj.icons['32'],
'alt_text': '',
'label': str(file_obj),
'file_id': file_obj.pk,
}
return HttpResponse(json.dumps(json_response),
**response_params)
else:
form_errors = '; '.join(['%s: %s' % (
field,
', '.join(errors)) for field, errors in list(uploadform.errors.items())
])
raise UploadException(
"AJAX request not valid: form invalid '%s'" % (form_errors,))
except UploadException as e:
return HttpResponse(json.dumps({'error': str(e)}),
**response_params)
|
[
"def",
"ajax_upload",
"(",
"self",
",",
"request",
",",
"folder_id",
"=",
"None",
")",
":",
"mimetype",
"=",
"\"application/json\"",
"if",
"request",
".",
"is_ajax",
"(",
")",
"else",
"\"text/html\"",
"content_type_key",
"=",
"'content_type'",
"response_params",
"=",
"{",
"content_type_key",
":",
"mimetype",
"}",
"folder",
"=",
"None",
"if",
"folder_id",
":",
"try",
":",
"# Get folder",
"folder",
"=",
"Folder",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"folder_id",
")",
"except",
"Folder",
".",
"DoesNotExist",
":",
"return",
"HttpResponse",
"(",
"json",
".",
"dumps",
"(",
"{",
"'error'",
":",
"NO_FOLDER_ERROR",
"}",
")",
",",
"*",
"*",
"response_params",
")",
"# check permissions",
"if",
"folder",
"and",
"not",
"folder",
".",
"has_add_children_permission",
"(",
"request",
")",
":",
"return",
"HttpResponse",
"(",
"json",
".",
"dumps",
"(",
"{",
"'error'",
":",
"NO_PERMISSIONS_FOR_FOLDER",
"}",
")",
",",
"*",
"*",
"response_params",
")",
"try",
":",
"if",
"len",
"(",
"request",
".",
"FILES",
")",
"==",
"1",
":",
"# dont check if request is ajax or not, just grab the file",
"upload",
",",
"filename",
",",
"is_raw",
"=",
"handle_request_files_upload",
"(",
"request",
")",
"else",
":",
"# else process the request as usual",
"upload",
",",
"filename",
",",
"is_raw",
"=",
"handle_upload",
"(",
"request",
")",
"# Get clipboad",
"# TODO: Deprecated/refactor",
"# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]",
"# find the file type",
"for",
"filer_class",
"in",
"media_settings",
".",
"MEDIA_FILE_MODELS",
":",
"FileSubClass",
"=",
"load_object",
"(",
"filer_class",
")",
"# TODO: What if there are more than one that qualify?",
"if",
"FileSubClass",
".",
"matches_file_type",
"(",
"filename",
",",
"upload",
",",
"request",
")",
":",
"FileForm",
"=",
"modelform_factory",
"(",
"model",
"=",
"FileSubClass",
",",
"fields",
"=",
"(",
"'original_filename'",
",",
"'owner'",
",",
"'file'",
")",
")",
"break",
"uploadform",
"=",
"FileForm",
"(",
"{",
"'original_filename'",
":",
"filename",
",",
"'owner'",
":",
"request",
".",
"user",
".",
"pk",
"}",
",",
"{",
"'file'",
":",
"upload",
"}",
")",
"if",
"uploadform",
".",
"is_valid",
"(",
")",
":",
"file_obj",
"=",
"uploadform",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"# Enforce the FILER_IS_PUBLIC_DEFAULT",
"file_obj",
".",
"is_public",
"=",
"settings",
".",
"MEDIA_IS_PUBLIC_DEFAULT",
"file_obj",
".",
"folder",
"=",
"folder",
"file_obj",
".",
"save",
"(",
")",
"# TODO: Deprecated/refactor",
"# clipboard_item = ClipboardItem(",
"# clipboard=clipboard, file=file_obj)",
"# clipboard_item.save()",
"json_response",
"=",
"{",
"'thumbnail'",
":",
"file_obj",
".",
"icons",
"[",
"'32'",
"]",
",",
"'alt_text'",
":",
"''",
",",
"'label'",
":",
"str",
"(",
"file_obj",
")",
",",
"'file_id'",
":",
"file_obj",
".",
"pk",
",",
"}",
"return",
"HttpResponse",
"(",
"json",
".",
"dumps",
"(",
"json_response",
")",
",",
"*",
"*",
"response_params",
")",
"else",
":",
"form_errors",
"=",
"'; '",
".",
"join",
"(",
"[",
"'%s: %s'",
"%",
"(",
"field",
",",
"', '",
".",
"join",
"(",
"errors",
")",
")",
"for",
"field",
",",
"errors",
"in",
"list",
"(",
"uploadform",
".",
"errors",
".",
"items",
"(",
")",
")",
"]",
")",
"raise",
"UploadException",
"(",
"\"AJAX request not valid: form invalid '%s'\"",
"%",
"(",
"form_errors",
",",
")",
")",
"except",
"UploadException",
"as",
"e",
":",
"return",
"HttpResponse",
"(",
"json",
".",
"dumps",
"(",
"{",
"'error'",
":",
"str",
"(",
"e",
")",
"}",
")",
",",
"*",
"*",
"response_params",
")"
] |
receives an upload from the uploader. Receives only one file at the time.
|
[
"receives",
"an",
"upload",
"from",
"the",
"uploader",
".",
"Receives",
"only",
"one",
"file",
"at",
"the",
"time",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/admin/clipboardadmin.py#L62-L135
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/management/commands/sync_page_themes.py
|
Command.set_options
|
def set_options(self, **options):
"""
Set instance variables based on an options dict
"""
self.interactive = False
self.verbosity = options['verbosity']
self.symlink = ""
self.clear = False
ignore_patterns = []
self.ignore_patterns = list(set(ignore_patterns))
self.page_themes_updated = 0
self.skins_updated = 0
|
python
|
def set_options(self, **options):
"""
Set instance variables based on an options dict
"""
self.interactive = False
self.verbosity = options['verbosity']
self.symlink = ""
self.clear = False
ignore_patterns = []
self.ignore_patterns = list(set(ignore_patterns))
self.page_themes_updated = 0
self.skins_updated = 0
|
[
"def",
"set_options",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"interactive",
"=",
"False",
"self",
".",
"verbosity",
"=",
"options",
"[",
"'verbosity'",
"]",
"self",
".",
"symlink",
"=",
"\"\"",
"self",
".",
"clear",
"=",
"False",
"ignore_patterns",
"=",
"[",
"]",
"self",
".",
"ignore_patterns",
"=",
"list",
"(",
"set",
"(",
"ignore_patterns",
")",
")",
"self",
".",
"page_themes_updated",
"=",
"0",
"self",
".",
"skins_updated",
"=",
"0"
] |
Set instance variables based on an options dict
|
[
"Set",
"instance",
"variables",
"based",
"on",
"an",
"options",
"dict"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/management/commands/sync_page_themes.py#L30-L41
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/management/commands/sync_page_themes.py
|
Command.collect
|
def collect(self):
"""
Load and save ``PageColorScheme`` for every ``PageTheme``
.. code-block:: bash
static/themes/bootswatch/united/variables.scss
static/themes/bootswatch/united/styles.scss
"""
self.ignore_patterns = [
'*.png', '*.jpg', '*.js', '*.gif', '*.ttf', '*.md', '*.rst',
'*.svg']
page_themes = PageTheme.objects.all()
for finder in get_finders():
for path, storage in finder.list(self.ignore_patterns):
for t in page_themes:
static_path = 'themes/{0}'.format(t.name.split('/')[-1])
if static_path in path:
try:
page_theme = PageTheme.objects.get(id=t.id)
except PageTheme.DoesNotExist:
raise Exception(
"Run sync_themes before this command")
except Exception as e:
self.stdout.write(
"Cannot load {} into database original error: {}".format(t, e))
# find and load skins
skins_path = os.path.join(
storage.path('/'.join(path.split('/')[0:-1])))
for dirpath, skins, filenames in os.walk(skins_path):
for skin in [s for s in skins if s not in ['fonts']]:
for skin_dirpath, skins, filenames in os.walk(os.path.join(dirpath, skin)):
skin, created = PageColorScheme.objects.get_or_create(
theme=page_theme, label=skin, name=skin.title())
for f in filenames:
if 'styles' in f:
with codecs.open(os.path.join(skin_dirpath, f)) as style_file:
skin.styles = style_file.read()
elif 'variables' in f:
with codecs.open(os.path.join(skin_dirpath, f)) as variables_file:
skin.variables = variables_file.read()
skin.save()
self.skins_updated += 1
self.page_themes_updated += len(page_themes)
|
python
|
def collect(self):
"""
Load and save ``PageColorScheme`` for every ``PageTheme``
.. code-block:: bash
static/themes/bootswatch/united/variables.scss
static/themes/bootswatch/united/styles.scss
"""
self.ignore_patterns = [
'*.png', '*.jpg', '*.js', '*.gif', '*.ttf', '*.md', '*.rst',
'*.svg']
page_themes = PageTheme.objects.all()
for finder in get_finders():
for path, storage in finder.list(self.ignore_patterns):
for t in page_themes:
static_path = 'themes/{0}'.format(t.name.split('/')[-1])
if static_path in path:
try:
page_theme = PageTheme.objects.get(id=t.id)
except PageTheme.DoesNotExist:
raise Exception(
"Run sync_themes before this command")
except Exception as e:
self.stdout.write(
"Cannot load {} into database original error: {}".format(t, e))
# find and load skins
skins_path = os.path.join(
storage.path('/'.join(path.split('/')[0:-1])))
for dirpath, skins, filenames in os.walk(skins_path):
for skin in [s for s in skins if s not in ['fonts']]:
for skin_dirpath, skins, filenames in os.walk(os.path.join(dirpath, skin)):
skin, created = PageColorScheme.objects.get_or_create(
theme=page_theme, label=skin, name=skin.title())
for f in filenames:
if 'styles' in f:
with codecs.open(os.path.join(skin_dirpath, f)) as style_file:
skin.styles = style_file.read()
elif 'variables' in f:
with codecs.open(os.path.join(skin_dirpath, f)) as variables_file:
skin.variables = variables_file.read()
skin.save()
self.skins_updated += 1
self.page_themes_updated += len(page_themes)
|
[
"def",
"collect",
"(",
"self",
")",
":",
"self",
".",
"ignore_patterns",
"=",
"[",
"'*.png'",
",",
"'*.jpg'",
",",
"'*.js'",
",",
"'*.gif'",
",",
"'*.ttf'",
",",
"'*.md'",
",",
"'*.rst'",
",",
"'*.svg'",
"]",
"page_themes",
"=",
"PageTheme",
".",
"objects",
".",
"all",
"(",
")",
"for",
"finder",
"in",
"get_finders",
"(",
")",
":",
"for",
"path",
",",
"storage",
"in",
"finder",
".",
"list",
"(",
"self",
".",
"ignore_patterns",
")",
":",
"for",
"t",
"in",
"page_themes",
":",
"static_path",
"=",
"'themes/{0}'",
".",
"format",
"(",
"t",
".",
"name",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
")",
"if",
"static_path",
"in",
"path",
":",
"try",
":",
"page_theme",
"=",
"PageTheme",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"t",
".",
"id",
")",
"except",
"PageTheme",
".",
"DoesNotExist",
":",
"raise",
"Exception",
"(",
"\"Run sync_themes before this command\"",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"\"Cannot load {} into database original error: {}\"",
".",
"format",
"(",
"t",
",",
"e",
")",
")",
"# find and load skins",
"skins_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"storage",
".",
"path",
"(",
"'/'",
".",
"join",
"(",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
":",
"-",
"1",
"]",
")",
")",
")",
"for",
"dirpath",
",",
"skins",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"skins_path",
")",
":",
"for",
"skin",
"in",
"[",
"s",
"for",
"s",
"in",
"skins",
"if",
"s",
"not",
"in",
"[",
"'fonts'",
"]",
"]",
":",
"for",
"skin_dirpath",
",",
"skins",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"skin",
")",
")",
":",
"skin",
",",
"created",
"=",
"PageColorScheme",
".",
"objects",
".",
"get_or_create",
"(",
"theme",
"=",
"page_theme",
",",
"label",
"=",
"skin",
",",
"name",
"=",
"skin",
".",
"title",
"(",
")",
")",
"for",
"f",
"in",
"filenames",
":",
"if",
"'styles'",
"in",
"f",
":",
"with",
"codecs",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"skin_dirpath",
",",
"f",
")",
")",
"as",
"style_file",
":",
"skin",
".",
"styles",
"=",
"style_file",
".",
"read",
"(",
")",
"elif",
"'variables'",
"in",
"f",
":",
"with",
"codecs",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"skin_dirpath",
",",
"f",
")",
")",
"as",
"variables_file",
":",
"skin",
".",
"variables",
"=",
"variables_file",
".",
"read",
"(",
")",
"skin",
".",
"save",
"(",
")",
"self",
".",
"skins_updated",
"+=",
"1",
"self",
".",
"page_themes_updated",
"+=",
"len",
"(",
"page_themes",
")"
] |
Load and save ``PageColorScheme`` for every ``PageTheme``
.. code-block:: bash
static/themes/bootswatch/united/variables.scss
static/themes/bootswatch/united/styles.scss
|
[
"Load",
"and",
"save",
"PageColorScheme",
"for",
"every",
"PageTheme"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/management/commands/sync_page_themes.py#L43-L91
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/media/models/abstract.py
|
BaseImage.has_generic_permission
|
def has_generic_permission(self, request, permission_type):
"""
Return true if the current user has permission on this
image. Return the string 'ALL' if the user has all rights.
"""
user = request.user
if not user.is_authenticated():
return False
elif user.is_superuser:
return True
elif user == self.owner:
return True
elif self.folder:
return self.folder.has_generic_permission(request, permission_type)
else:
return False
|
python
|
def has_generic_permission(self, request, permission_type):
"""
Return true if the current user has permission on this
image. Return the string 'ALL' if the user has all rights.
"""
user = request.user
if not user.is_authenticated():
return False
elif user.is_superuser:
return True
elif user == self.owner:
return True
elif self.folder:
return self.folder.has_generic_permission(request, permission_type)
else:
return False
|
[
"def",
"has_generic_permission",
"(",
"self",
",",
"request",
",",
"permission_type",
")",
":",
"user",
"=",
"request",
".",
"user",
"if",
"not",
"user",
".",
"is_authenticated",
"(",
")",
":",
"return",
"False",
"elif",
"user",
".",
"is_superuser",
":",
"return",
"True",
"elif",
"user",
"==",
"self",
".",
"owner",
":",
"return",
"True",
"elif",
"self",
".",
"folder",
":",
"return",
"self",
".",
"folder",
".",
"has_generic_permission",
"(",
"request",
",",
"permission_type",
")",
"else",
":",
"return",
"False"
] |
Return true if the current user has permission on this
image. Return the string 'ALL' if the user has all rights.
|
[
"Return",
"true",
"if",
"the",
"current",
"user",
"has",
"permission",
"on",
"this",
"image",
".",
"Return",
"the",
"string",
"ALL",
"if",
"the",
"user",
"has",
"all",
"rights",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/models/abstract.py#L101-L116
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/media/widget/mediagallery/models.py
|
MediaGalleryWidget.get_template_data
|
def get_template_data(self, request, *args, **kwargs):
'''Add image dimensions'''
# little tricky with vertical centering
dimension = int(self.get_size().split('x')[0])
data = {}
if dimension <= 356:
data['image_dimension'] = "row-md-13"
if self.get_template_name().name.split("/")[-1] == "directories.html":
data['directories'] = self.get_directories(request)
return data
|
python
|
def get_template_data(self, request, *args, **kwargs):
'''Add image dimensions'''
# little tricky with vertical centering
dimension = int(self.get_size().split('x')[0])
data = {}
if dimension <= 356:
data['image_dimension'] = "row-md-13"
if self.get_template_name().name.split("/")[-1] == "directories.html":
data['directories'] = self.get_directories(request)
return data
|
[
"def",
"get_template_data",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# little tricky with vertical centering",
"dimension",
"=",
"int",
"(",
"self",
".",
"get_size",
"(",
")",
".",
"split",
"(",
"'x'",
")",
"[",
"0",
"]",
")",
"data",
"=",
"{",
"}",
"if",
"dimension",
"<=",
"356",
":",
"data",
"[",
"'image_dimension'",
"]",
"=",
"\"row-md-13\"",
"if",
"self",
".",
"get_template_name",
"(",
")",
".",
"name",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"==",
"\"directories.html\"",
":",
"data",
"[",
"'directories'",
"]",
"=",
"self",
".",
"get_directories",
"(",
"request",
")",
"return",
"data"
] |
Add image dimensions
|
[
"Add",
"image",
"dimensions"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/widget/mediagallery/models.py#L81-L95
|
train
|
django-leonardo/django-leonardo
|
leonardo/decorators.py
|
_decorate_urlconf
|
def _decorate_urlconf(urlpatterns, decorator=require_auth, *args, **kwargs):
'''Decorate all urlpatterns by specified decorator'''
if isinstance(urlpatterns, (list, tuple)):
for pattern in urlpatterns:
if getattr(pattern, 'callback', None):
pattern._callback = decorator(
pattern.callback, *args, **kwargs)
if getattr(pattern, 'url_patterns', []):
_decorate_urlconf(
pattern.url_patterns, decorator, *args, **kwargs)
else:
if getattr(urlpatterns, 'callback', None):
urlpatterns._callback = decorator(
urlpatterns.callback, *args, **kwargs)
|
python
|
def _decorate_urlconf(urlpatterns, decorator=require_auth, *args, **kwargs):
'''Decorate all urlpatterns by specified decorator'''
if isinstance(urlpatterns, (list, tuple)):
for pattern in urlpatterns:
if getattr(pattern, 'callback', None):
pattern._callback = decorator(
pattern.callback, *args, **kwargs)
if getattr(pattern, 'url_patterns', []):
_decorate_urlconf(
pattern.url_patterns, decorator, *args, **kwargs)
else:
if getattr(urlpatterns, 'callback', None):
urlpatterns._callback = decorator(
urlpatterns.callback, *args, **kwargs)
|
[
"def",
"_decorate_urlconf",
"(",
"urlpatterns",
",",
"decorator",
"=",
"require_auth",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"urlpatterns",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"pattern",
"in",
"urlpatterns",
":",
"if",
"getattr",
"(",
"pattern",
",",
"'callback'",
",",
"None",
")",
":",
"pattern",
".",
"_callback",
"=",
"decorator",
"(",
"pattern",
".",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"getattr",
"(",
"pattern",
",",
"'url_patterns'",
",",
"[",
"]",
")",
":",
"_decorate_urlconf",
"(",
"pattern",
".",
"url_patterns",
",",
"decorator",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"if",
"getattr",
"(",
"urlpatterns",
",",
"'callback'",
",",
"None",
")",
":",
"urlpatterns",
".",
"_callback",
"=",
"decorator",
"(",
"urlpatterns",
".",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Decorate all urlpatterns by specified decorator
|
[
"Decorate",
"all",
"urlpatterns",
"by",
"specified",
"decorator"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/decorators.py#L53-L68
|
train
|
django-leonardo/django-leonardo
|
leonardo/decorators.py
|
catch_result
|
def catch_result(task_func):
"""Catch printed result from Celery Task and return it in task response
"""
@functools.wraps(task_func, assigned=available_attrs(task_func))
def dec(*args, **kwargs):
# inicialize
orig_stdout = sys.stdout
sys.stdout = content = StringIO()
task_response = task_func(*args, **kwargs)
# catch
sys.stdout = orig_stdout
content.seek(0)
# propagate to the response
task_response['stdout'] = content.read()
return task_response
return dec
|
python
|
def catch_result(task_func):
"""Catch printed result from Celery Task and return it in task response
"""
@functools.wraps(task_func, assigned=available_attrs(task_func))
def dec(*args, **kwargs):
# inicialize
orig_stdout = sys.stdout
sys.stdout = content = StringIO()
task_response = task_func(*args, **kwargs)
# catch
sys.stdout = orig_stdout
content.seek(0)
# propagate to the response
task_response['stdout'] = content.read()
return task_response
return dec
|
[
"def",
"catch_result",
"(",
"task_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"task_func",
",",
"assigned",
"=",
"available_attrs",
"(",
"task_func",
")",
")",
"def",
"dec",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# inicialize",
"orig_stdout",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdout",
"=",
"content",
"=",
"StringIO",
"(",
")",
"task_response",
"=",
"task_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# catch",
"sys",
".",
"stdout",
"=",
"orig_stdout",
"content",
".",
"seek",
"(",
"0",
")",
"# propagate to the response",
"task_response",
"[",
"'stdout'",
"]",
"=",
"content",
".",
"read",
"(",
")",
"return",
"task_response",
"return",
"dec"
] |
Catch printed result from Celery Task and return it in task response
|
[
"Catch",
"printed",
"result",
"from",
"Celery",
"Task",
"and",
"return",
"it",
"in",
"task",
"response"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/decorators.py#L74-L90
|
train
|
django-leonardo/django-leonardo
|
leonardo/utils/compress_patch.py
|
compress_monkey_patch
|
def compress_monkey_patch():
"""patch all compress
we need access to variables from widget scss
for example we have::
/themes/bootswatch/cyborg/_variables
but only if is cyborg active for this reasone we need
dynamically append import to every scss file
"""
from compressor.templatetags import compress as compress_tags
from compressor import base as compress_base
compress_base.Compressor.filter_input = filter_input
compress_base.Compressor.output = output
compress_base.Compressor.hunks = hunks
compress_base.Compressor.precompile = precompile
compress_tags.CompressorMixin.render_compressed = render_compressed
from django_pyscss import compressor as pyscss_compressor
pyscss_compressor.DjangoScssFilter.input = input
|
python
|
def compress_monkey_patch():
"""patch all compress
we need access to variables from widget scss
for example we have::
/themes/bootswatch/cyborg/_variables
but only if is cyborg active for this reasone we need
dynamically append import to every scss file
"""
from compressor.templatetags import compress as compress_tags
from compressor import base as compress_base
compress_base.Compressor.filter_input = filter_input
compress_base.Compressor.output = output
compress_base.Compressor.hunks = hunks
compress_base.Compressor.precompile = precompile
compress_tags.CompressorMixin.render_compressed = render_compressed
from django_pyscss import compressor as pyscss_compressor
pyscss_compressor.DjangoScssFilter.input = input
|
[
"def",
"compress_monkey_patch",
"(",
")",
":",
"from",
"compressor",
".",
"templatetags",
"import",
"compress",
"as",
"compress_tags",
"from",
"compressor",
"import",
"base",
"as",
"compress_base",
"compress_base",
".",
"Compressor",
".",
"filter_input",
"=",
"filter_input",
"compress_base",
".",
"Compressor",
".",
"output",
"=",
"output",
"compress_base",
".",
"Compressor",
".",
"hunks",
"=",
"hunks",
"compress_base",
".",
"Compressor",
".",
"precompile",
"=",
"precompile",
"compress_tags",
".",
"CompressorMixin",
".",
"render_compressed",
"=",
"render_compressed",
"from",
"django_pyscss",
"import",
"compressor",
"as",
"pyscss_compressor",
"pyscss_compressor",
".",
"DjangoScssFilter",
".",
"input",
"=",
"input"
] |
patch all compress
we need access to variables from widget scss
for example we have::
/themes/bootswatch/cyborg/_variables
but only if is cyborg active for this reasone we need
dynamically append import to every scss file
|
[
"patch",
"all",
"compress"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/compress_patch.py#L37-L62
|
train
|
django-leonardo/django-leonardo
|
leonardo/utils/compress_patch.py
|
output
|
def output(self, mode='file', forced=False, context=None):
"""
The general output method, override in subclass if you need to do
any custom modification. Calls other mode specific methods or simply
returns the content directly.
"""
output = '\n'.join(self.filter_input(forced, context=context))
if not output:
return ''
if settings.COMPRESS_ENABLED or forced:
filtered_output = self.filter_output(output)
return self.handle_output(mode, filtered_output, forced)
return output
|
python
|
def output(self, mode='file', forced=False, context=None):
"""
The general output method, override in subclass if you need to do
any custom modification. Calls other mode specific methods or simply
returns the content directly.
"""
output = '\n'.join(self.filter_input(forced, context=context))
if not output:
return ''
if settings.COMPRESS_ENABLED or forced:
filtered_output = self.filter_output(output)
return self.handle_output(mode, filtered_output, forced)
return output
|
[
"def",
"output",
"(",
"self",
",",
"mode",
"=",
"'file'",
",",
"forced",
"=",
"False",
",",
"context",
"=",
"None",
")",
":",
"output",
"=",
"'\\n'",
".",
"join",
"(",
"self",
".",
"filter_input",
"(",
"forced",
",",
"context",
"=",
"context",
")",
")",
"if",
"not",
"output",
":",
"return",
"''",
"if",
"settings",
".",
"COMPRESS_ENABLED",
"or",
"forced",
":",
"filtered_output",
"=",
"self",
".",
"filter_output",
"(",
"output",
")",
"return",
"self",
".",
"handle_output",
"(",
"mode",
",",
"filtered_output",
",",
"forced",
")",
"return",
"output"
] |
The general output method, override in subclass if you need to do
any custom modification. Calls other mode specific methods or simply
returns the content directly.
|
[
"The",
"general",
"output",
"method",
"override",
"in",
"subclass",
"if",
"you",
"need",
"to",
"do",
"any",
"custom",
"modification",
".",
"Calls",
"other",
"mode",
"specific",
"methods",
"or",
"simply",
"returns",
"the",
"content",
"directly",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/compress_patch.py#L165-L180
|
train
|
django-leonardo/django-leonardo
|
leonardo/utils/compress_patch.py
|
precompile
|
def precompile(self, content, kind=None, elem=None, filename=None,
charset=None, **kwargs):
"""
Processes file using a pre compiler.
This is the place where files like coffee script are processed.
"""
if not kind:
return False, content
attrs = self.parser.elem_attribs(elem)
mimetype = attrs.get("type", None)
if mimetype is None:
return False, content
filter_or_command = self.precompiler_mimetypes.get(mimetype)
if filter_or_command is None:
if mimetype in ("text/css", "text/javascript"):
return False, content
raise CompressorError("Couldn't find any precompiler in "
"COMPRESS_PRECOMPILERS setting for "
"mimetype '%s'." % mimetype)
mod_name, cls_name = get_mod_func(filter_or_command)
try:
mod = import_module(mod_name)
except (ImportError, TypeError):
filter = CachedCompilerFilter(
content=content, filter_type=self.type, filename=filename,
charset=charset, command=filter_or_command, mimetype=mimetype)
return True, filter.input(**kwargs)
try:
precompiler_class = getattr(mod, cls_name)
except AttributeError:
raise FilterDoesNotExist('Could not find "%s".' % filter_or_command)
filter = precompiler_class(
content, attrs=attrs, filter_type=self.type, charset=charset,
filename=filename, **kwargs)
return True, filter.input(**kwargs)
|
python
|
def precompile(self, content, kind=None, elem=None, filename=None,
charset=None, **kwargs):
"""
Processes file using a pre compiler.
This is the place where files like coffee script are processed.
"""
if not kind:
return False, content
attrs = self.parser.elem_attribs(elem)
mimetype = attrs.get("type", None)
if mimetype is None:
return False, content
filter_or_command = self.precompiler_mimetypes.get(mimetype)
if filter_or_command is None:
if mimetype in ("text/css", "text/javascript"):
return False, content
raise CompressorError("Couldn't find any precompiler in "
"COMPRESS_PRECOMPILERS setting for "
"mimetype '%s'." % mimetype)
mod_name, cls_name = get_mod_func(filter_or_command)
try:
mod = import_module(mod_name)
except (ImportError, TypeError):
filter = CachedCompilerFilter(
content=content, filter_type=self.type, filename=filename,
charset=charset, command=filter_or_command, mimetype=mimetype)
return True, filter.input(**kwargs)
try:
precompiler_class = getattr(mod, cls_name)
except AttributeError:
raise FilterDoesNotExist('Could not find "%s".' % filter_or_command)
filter = precompiler_class(
content, attrs=attrs, filter_type=self.type, charset=charset,
filename=filename, **kwargs)
return True, filter.input(**kwargs)
|
[
"def",
"precompile",
"(",
"self",
",",
"content",
",",
"kind",
"=",
"None",
",",
"elem",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"charset",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kind",
":",
"return",
"False",
",",
"content",
"attrs",
"=",
"self",
".",
"parser",
".",
"elem_attribs",
"(",
"elem",
")",
"mimetype",
"=",
"attrs",
".",
"get",
"(",
"\"type\"",
",",
"None",
")",
"if",
"mimetype",
"is",
"None",
":",
"return",
"False",
",",
"content",
"filter_or_command",
"=",
"self",
".",
"precompiler_mimetypes",
".",
"get",
"(",
"mimetype",
")",
"if",
"filter_or_command",
"is",
"None",
":",
"if",
"mimetype",
"in",
"(",
"\"text/css\"",
",",
"\"text/javascript\"",
")",
":",
"return",
"False",
",",
"content",
"raise",
"CompressorError",
"(",
"\"Couldn't find any precompiler in \"",
"\"COMPRESS_PRECOMPILERS setting for \"",
"\"mimetype '%s'.\"",
"%",
"mimetype",
")",
"mod_name",
",",
"cls_name",
"=",
"get_mod_func",
"(",
"filter_or_command",
")",
"try",
":",
"mod",
"=",
"import_module",
"(",
"mod_name",
")",
"except",
"(",
"ImportError",
",",
"TypeError",
")",
":",
"filter",
"=",
"CachedCompilerFilter",
"(",
"content",
"=",
"content",
",",
"filter_type",
"=",
"self",
".",
"type",
",",
"filename",
"=",
"filename",
",",
"charset",
"=",
"charset",
",",
"command",
"=",
"filter_or_command",
",",
"mimetype",
"=",
"mimetype",
")",
"return",
"True",
",",
"filter",
".",
"input",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"precompiler_class",
"=",
"getattr",
"(",
"mod",
",",
"cls_name",
")",
"except",
"AttributeError",
":",
"raise",
"FilterDoesNotExist",
"(",
"'Could not find \"%s\".'",
"%",
"filter_or_command",
")",
"filter",
"=",
"precompiler_class",
"(",
"content",
",",
"attrs",
"=",
"attrs",
",",
"filter_type",
"=",
"self",
".",
"type",
",",
"charset",
"=",
"charset",
",",
"filename",
"=",
"filename",
",",
"*",
"*",
"kwargs",
")",
"return",
"True",
",",
"filter",
".",
"input",
"(",
"*",
"*",
"kwargs",
")"
] |
Processes file using a pre compiler.
This is the place where files like coffee script are processed.
|
[
"Processes",
"file",
"using",
"a",
"pre",
"compiler",
".",
"This",
"is",
"the",
"place",
"where",
"files",
"like",
"coffee",
"script",
"are",
"processed",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/compress_patch.py#L194-L230
|
train
|
frawau/aioblescan
|
aioblescan/aioblescan.py
|
MACAddr.decode
|
def decode(self,data):
"""Decode the MAC address from a byte array.
This will take the first 6 bytes from data and transform them into a MAC address
string representation. This will be assigned to the attribute "val". It then returns
the data stream minus the bytes consumed
:param data: The data stream containing the value to decode at its head
:type data: bytes
:returns: The datastream minus the bytes consumed
:rtype: bytes
"""
self.val=':'.join("%02x" % x for x in reversed(data[:6]))
return data[6:]
|
python
|
def decode(self,data):
"""Decode the MAC address from a byte array.
This will take the first 6 bytes from data and transform them into a MAC address
string representation. This will be assigned to the attribute "val". It then returns
the data stream minus the bytes consumed
:param data: The data stream containing the value to decode at its head
:type data: bytes
:returns: The datastream minus the bytes consumed
:rtype: bytes
"""
self.val=':'.join("%02x" % x for x in reversed(data[:6]))
return data[6:]
|
[
"def",
"decode",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"val",
"=",
"':'",
".",
"join",
"(",
"\"%02x\"",
"%",
"x",
"for",
"x",
"in",
"reversed",
"(",
"data",
"[",
":",
"6",
"]",
")",
")",
"return",
"data",
"[",
"6",
":",
"]"
] |
Decode the MAC address from a byte array.
This will take the first 6 bytes from data and transform them into a MAC address
string representation. This will be assigned to the attribute "val". It then returns
the data stream minus the bytes consumed
:param data: The data stream containing the value to decode at its head
:type data: bytes
:returns: The datastream minus the bytes consumed
:rtype: bytes
|
[
"Decode",
"the",
"MAC",
"address",
"from",
"a",
"byte",
"array",
"."
] |
02d12e90db3ee6df7be6513fec171f20dc533de3
|
https://github.com/frawau/aioblescan/blob/02d12e90db3ee6df7be6513fec171f20dc533de3/aioblescan/aioblescan.py#L75-L88
|
train
|
django-leonardo/django-leonardo
|
leonardo/templatetags/thumbnail.py
|
thumbnail
|
def thumbnail(parser, token):
'''
This template tag supports both syntax for declare thumbanil in template
'''
thumb = None
if SORL:
try:
thumb = sorl_thumb(parser, token)
except Exception:
thumb = False
if EASY and not thumb:
thumb = easy_thumb(parser, token)
return thumb
|
python
|
def thumbnail(parser, token):
'''
This template tag supports both syntax for declare thumbanil in template
'''
thumb = None
if SORL:
try:
thumb = sorl_thumb(parser, token)
except Exception:
thumb = False
if EASY and not thumb:
thumb = easy_thumb(parser, token)
return thumb
|
[
"def",
"thumbnail",
"(",
"parser",
",",
"token",
")",
":",
"thumb",
"=",
"None",
"if",
"SORL",
":",
"try",
":",
"thumb",
"=",
"sorl_thumb",
"(",
"parser",
",",
"token",
")",
"except",
"Exception",
":",
"thumb",
"=",
"False",
"if",
"EASY",
"and",
"not",
"thumb",
":",
"thumb",
"=",
"easy_thumb",
"(",
"parser",
",",
"token",
")",
"return",
"thumb"
] |
This template tag supports both syntax for declare thumbanil in template
|
[
"This",
"template",
"tag",
"supports",
"both",
"syntax",
"for",
"declare",
"thumbanil",
"in",
"template"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/templatetags/thumbnail.py#L18-L34
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/media/utils.py
|
handle_uploaded_file
|
def handle_uploaded_file(file, folder=None, is_public=True):
'''handle uploaded file to folder
match first media type and create media object and returns it
file: File object
folder: str or Folder isinstance
is_public: boolean
'''
_folder = None
if folder and isinstance(folder, Folder):
_folder = folder
elif folder:
_folder, folder_created = Folder.objects.get_or_create(
name=folder)
for cls in MEDIA_MODELS:
if cls.matches_file_type(file.name):
obj, created = cls.objects.get_or_create(
original_filename=file.name,
file=file,
folder=_folder,
is_public=is_public)
if created:
return obj
return None
|
python
|
def handle_uploaded_file(file, folder=None, is_public=True):
'''handle uploaded file to folder
match first media type and create media object and returns it
file: File object
folder: str or Folder isinstance
is_public: boolean
'''
_folder = None
if folder and isinstance(folder, Folder):
_folder = folder
elif folder:
_folder, folder_created = Folder.objects.get_or_create(
name=folder)
for cls in MEDIA_MODELS:
if cls.matches_file_type(file.name):
obj, created = cls.objects.get_or_create(
original_filename=file.name,
file=file,
folder=_folder,
is_public=is_public)
if created:
return obj
return None
|
[
"def",
"handle_uploaded_file",
"(",
"file",
",",
"folder",
"=",
"None",
",",
"is_public",
"=",
"True",
")",
":",
"_folder",
"=",
"None",
"if",
"folder",
"and",
"isinstance",
"(",
"folder",
",",
"Folder",
")",
":",
"_folder",
"=",
"folder",
"elif",
"folder",
":",
"_folder",
",",
"folder_created",
"=",
"Folder",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"folder",
")",
"for",
"cls",
"in",
"MEDIA_MODELS",
":",
"if",
"cls",
".",
"matches_file_type",
"(",
"file",
".",
"name",
")",
":",
"obj",
",",
"created",
"=",
"cls",
".",
"objects",
".",
"get_or_create",
"(",
"original_filename",
"=",
"file",
".",
"name",
",",
"file",
"=",
"file",
",",
"folder",
"=",
"_folder",
",",
"is_public",
"=",
"is_public",
")",
"if",
"created",
":",
"return",
"obj",
"return",
"None"
] |
handle uploaded file to folder
match first media type and create media object and returns it
file: File object
folder: str or Folder isinstance
is_public: boolean
|
[
"handle",
"uploaded",
"file",
"to",
"folder",
"match",
"first",
"media",
"type",
"and",
"create",
"media",
"object",
"and",
"returns",
"it"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/utils.py#L5-L33
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/media/utils.py
|
handle_uploaded_files
|
def handle_uploaded_files(files, folder=None, is_public=True):
'''handle uploaded files to folder
files: array of File objects or single object
folder: str or Folder isinstance
is_public: boolean
'''
results = []
for f in files:
result = handle_uploaded_file(f, folder, is_public)
results.append(result)
return results
|
python
|
def handle_uploaded_files(files, folder=None, is_public=True):
'''handle uploaded files to folder
files: array of File objects or single object
folder: str or Folder isinstance
is_public: boolean
'''
results = []
for f in files:
result = handle_uploaded_file(f, folder, is_public)
results.append(result)
return results
|
[
"def",
"handle_uploaded_files",
"(",
"files",
",",
"folder",
"=",
"None",
",",
"is_public",
"=",
"True",
")",
":",
"results",
"=",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"result",
"=",
"handle_uploaded_file",
"(",
"f",
",",
"folder",
",",
"is_public",
")",
"results",
".",
"append",
"(",
"result",
")",
"return",
"results"
] |
handle uploaded files to folder
files: array of File objects or single object
folder: str or Folder isinstance
is_public: boolean
|
[
"handle",
"uploaded",
"files",
"to",
"folder"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/utils.py#L36-L48
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/media/server/views.py
|
serve_protected_file
|
def serve_protected_file(request, path):
"""
Serve protected files to authenticated users with read permissions.
"""
path = path.rstrip('/')
try:
file_obj = File.objects.get(file=path)
except File.DoesNotExist:
raise Http404('File not found %s' % path)
if not file_obj.has_read_permission(request):
if settings.DEBUG:
raise PermissionDenied
else:
raise Http404('File not found %s' % path)
return server.serve(request, file_obj=file_obj.file, save_as=False)
|
python
|
def serve_protected_file(request, path):
"""
Serve protected files to authenticated users with read permissions.
"""
path = path.rstrip('/')
try:
file_obj = File.objects.get(file=path)
except File.DoesNotExist:
raise Http404('File not found %s' % path)
if not file_obj.has_read_permission(request):
if settings.DEBUG:
raise PermissionDenied
else:
raise Http404('File not found %s' % path)
return server.serve(request, file_obj=file_obj.file, save_as=False)
|
[
"def",
"serve_protected_file",
"(",
"request",
",",
"path",
")",
":",
"path",
"=",
"path",
".",
"rstrip",
"(",
"'/'",
")",
"try",
":",
"file_obj",
"=",
"File",
".",
"objects",
".",
"get",
"(",
"file",
"=",
"path",
")",
"except",
"File",
".",
"DoesNotExist",
":",
"raise",
"Http404",
"(",
"'File not found %s'",
"%",
"path",
")",
"if",
"not",
"file_obj",
".",
"has_read_permission",
"(",
"request",
")",
":",
"if",
"settings",
".",
"DEBUG",
":",
"raise",
"PermissionDenied",
"else",
":",
"raise",
"Http404",
"(",
"'File not found %s'",
"%",
"path",
")",
"return",
"server",
".",
"serve",
"(",
"request",
",",
"file_obj",
"=",
"file_obj",
".",
"file",
",",
"save_as",
"=",
"False",
")"
] |
Serve protected files to authenticated users with read permissions.
|
[
"Serve",
"protected",
"files",
"to",
"authenticated",
"users",
"with",
"read",
"permissions",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/server/views.py#L14-L28
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/media/server/views.py
|
serve_protected_thumbnail
|
def serve_protected_thumbnail(request, path):
"""
Serve protected thumbnails to authenticated users.
If the user doesn't have read permissions, redirect to a static image.
"""
source_path = thumbnail_to_original_filename(path)
if not source_path:
raise Http404('File not found')
try:
file_obj = File.objects.get(file=source_path)
except File.DoesNotExist:
raise Http404('File not found %s' % path)
if not file_obj.has_read_permission(request):
if settings.DEBUG:
raise PermissionDenied
else:
raise Http404('File not found %s' % path)
try:
thumbnail = ThumbnailFile(name=path, storage=file_obj.file.thumbnail_storage)
return thumbnail_server.serve(request, thumbnail, save_as=False)
except Exception:
raise Http404('File not found %s' % path)
|
python
|
def serve_protected_thumbnail(request, path):
"""
Serve protected thumbnails to authenticated users.
If the user doesn't have read permissions, redirect to a static image.
"""
source_path = thumbnail_to_original_filename(path)
if not source_path:
raise Http404('File not found')
try:
file_obj = File.objects.get(file=source_path)
except File.DoesNotExist:
raise Http404('File not found %s' % path)
if not file_obj.has_read_permission(request):
if settings.DEBUG:
raise PermissionDenied
else:
raise Http404('File not found %s' % path)
try:
thumbnail = ThumbnailFile(name=path, storage=file_obj.file.thumbnail_storage)
return thumbnail_server.serve(request, thumbnail, save_as=False)
except Exception:
raise Http404('File not found %s' % path)
|
[
"def",
"serve_protected_thumbnail",
"(",
"request",
",",
"path",
")",
":",
"source_path",
"=",
"thumbnail_to_original_filename",
"(",
"path",
")",
"if",
"not",
"source_path",
":",
"raise",
"Http404",
"(",
"'File not found'",
")",
"try",
":",
"file_obj",
"=",
"File",
".",
"objects",
".",
"get",
"(",
"file",
"=",
"source_path",
")",
"except",
"File",
".",
"DoesNotExist",
":",
"raise",
"Http404",
"(",
"'File not found %s'",
"%",
"path",
")",
"if",
"not",
"file_obj",
".",
"has_read_permission",
"(",
"request",
")",
":",
"if",
"settings",
".",
"DEBUG",
":",
"raise",
"PermissionDenied",
"else",
":",
"raise",
"Http404",
"(",
"'File not found %s'",
"%",
"path",
")",
"try",
":",
"thumbnail",
"=",
"ThumbnailFile",
"(",
"name",
"=",
"path",
",",
"storage",
"=",
"file_obj",
".",
"file",
".",
"thumbnail_storage",
")",
"return",
"thumbnail_server",
".",
"serve",
"(",
"request",
",",
"thumbnail",
",",
"save_as",
"=",
"False",
")",
"except",
"Exception",
":",
"raise",
"Http404",
"(",
"'File not found %s'",
"%",
"path",
")"
] |
Serve protected thumbnails to authenticated users.
If the user doesn't have read permissions, redirect to a static image.
|
[
"Serve",
"protected",
"thumbnails",
"to",
"authenticated",
"users",
".",
"If",
"the",
"user",
"doesn",
"t",
"have",
"read",
"permissions",
"redirect",
"to",
"a",
"static",
"image",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/server/views.py#L31-L52
|
train
|
django-leonardo/django-leonardo
|
leonardo/base.py
|
Leonardo.get_app_modules
|
def get_app_modules(self, apps):
"""return array of imported leonardo modules for apps
"""
modules = getattr(self, "_modules", [])
if not modules:
from django.utils.module_loading import module_has_submodule
# Try importing a modules from the module package
package_string = '.'.join(['leonardo', 'module'])
for app in apps:
exc = '...'
try:
# check if is not full app
_app = import_module(app)
except Exception as e:
_app = False
exc = e
if module_has_submodule(
import_module(package_string), app) or _app:
if _app:
mod = _app
else:
mod = import_module('.{0}'.format(app), package_string)
if mod:
modules.append(mod)
continue
warnings.warn('%s was skipped because %s ' % (app, exc))
self._modules = modules
return self._modules
|
python
|
def get_app_modules(self, apps):
"""return array of imported leonardo modules for apps
"""
modules = getattr(self, "_modules", [])
if not modules:
from django.utils.module_loading import module_has_submodule
# Try importing a modules from the module package
package_string = '.'.join(['leonardo', 'module'])
for app in apps:
exc = '...'
try:
# check if is not full app
_app = import_module(app)
except Exception as e:
_app = False
exc = e
if module_has_submodule(
import_module(package_string), app) or _app:
if _app:
mod = _app
else:
mod = import_module('.{0}'.format(app), package_string)
if mod:
modules.append(mod)
continue
warnings.warn('%s was skipped because %s ' % (app, exc))
self._modules = modules
return self._modules
|
[
"def",
"get_app_modules",
"(",
"self",
",",
"apps",
")",
":",
"modules",
"=",
"getattr",
"(",
"self",
",",
"\"_modules\"",
",",
"[",
"]",
")",
"if",
"not",
"modules",
":",
"from",
"django",
".",
"utils",
".",
"module_loading",
"import",
"module_has_submodule",
"# Try importing a modules from the module package",
"package_string",
"=",
"'.'",
".",
"join",
"(",
"[",
"'leonardo'",
",",
"'module'",
"]",
")",
"for",
"app",
"in",
"apps",
":",
"exc",
"=",
"'...'",
"try",
":",
"# check if is not full app",
"_app",
"=",
"import_module",
"(",
"app",
")",
"except",
"Exception",
"as",
"e",
":",
"_app",
"=",
"False",
"exc",
"=",
"e",
"if",
"module_has_submodule",
"(",
"import_module",
"(",
"package_string",
")",
",",
"app",
")",
"or",
"_app",
":",
"if",
"_app",
":",
"mod",
"=",
"_app",
"else",
":",
"mod",
"=",
"import_module",
"(",
"'.{0}'",
".",
"format",
"(",
"app",
")",
",",
"package_string",
")",
"if",
"mod",
":",
"modules",
".",
"append",
"(",
"mod",
")",
"continue",
"warnings",
".",
"warn",
"(",
"'%s was skipped because %s '",
"%",
"(",
"app",
",",
"exc",
")",
")",
"self",
".",
"_modules",
"=",
"modules",
"return",
"self",
".",
"_modules"
] |
return array of imported leonardo modules for apps
|
[
"return",
"array",
"of",
"imported",
"leonardo",
"modules",
"for",
"apps"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/base.py#L47-L80
|
train
|
django-leonardo/django-leonardo
|
leonardo/base.py
|
Leonardo.urlpatterns
|
def urlpatterns(self):
'''load and decorate urls from all modules
then store it as cached property for less loading
'''
if not hasattr(self, '_urlspatterns'):
urlpatterns = []
# load all urls
# support .urls file and urls_conf = 'elephantblog.urls' on default module
# decorate all url patterns if is not explicitly excluded
for mod in leonardo.modules:
# TODO this not work
if is_leonardo_module(mod):
conf = get_conf_from_module(mod)
if module_has_submodule(mod, 'urls'):
urls_mod = import_module('.urls', mod.__name__)
if hasattr(urls_mod, 'urlpatterns'):
# if not public decorate all
if conf['public']:
urlpatterns += urls_mod.urlpatterns
else:
_decorate_urlconf(urls_mod.urlpatterns,
require_auth)
urlpatterns += urls_mod.urlpatterns
# avoid circural dependency
# TODO use our loaded modules instead this property
from django.conf import settings
for urls_conf, conf in six.iteritems(getattr(settings, 'MODULE_URLS', {})):
# is public ?
try:
if conf['is_public']:
urlpatterns += \
patterns('',
url(r'', include(urls_conf)),
)
else:
_decorate_urlconf(
url(r'', include(urls_conf)),
require_auth)
urlpatterns += patterns('',
url(r'', include(urls_conf)))
except Exception as e:
raise Exception('raised %s during loading %s' %
(str(e), urls_conf))
self._urlpatterns = urlpatterns
return self._urlpatterns
|
python
|
def urlpatterns(self):
'''load and decorate urls from all modules
then store it as cached property for less loading
'''
if not hasattr(self, '_urlspatterns'):
urlpatterns = []
# load all urls
# support .urls file and urls_conf = 'elephantblog.urls' on default module
# decorate all url patterns if is not explicitly excluded
for mod in leonardo.modules:
# TODO this not work
if is_leonardo_module(mod):
conf = get_conf_from_module(mod)
if module_has_submodule(mod, 'urls'):
urls_mod = import_module('.urls', mod.__name__)
if hasattr(urls_mod, 'urlpatterns'):
# if not public decorate all
if conf['public']:
urlpatterns += urls_mod.urlpatterns
else:
_decorate_urlconf(urls_mod.urlpatterns,
require_auth)
urlpatterns += urls_mod.urlpatterns
# avoid circural dependency
# TODO use our loaded modules instead this property
from django.conf import settings
for urls_conf, conf in six.iteritems(getattr(settings, 'MODULE_URLS', {})):
# is public ?
try:
if conf['is_public']:
urlpatterns += \
patterns('',
url(r'', include(urls_conf)),
)
else:
_decorate_urlconf(
url(r'', include(urls_conf)),
require_auth)
urlpatterns += patterns('',
url(r'', include(urls_conf)))
except Exception as e:
raise Exception('raised %s during loading %s' %
(str(e), urls_conf))
self._urlpatterns = urlpatterns
return self._urlpatterns
|
[
"def",
"urlpatterns",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_urlspatterns'",
")",
":",
"urlpatterns",
"=",
"[",
"]",
"# load all urls",
"# support .urls file and urls_conf = 'elephantblog.urls' on default module",
"# decorate all url patterns if is not explicitly excluded",
"for",
"mod",
"in",
"leonardo",
".",
"modules",
":",
"# TODO this not work",
"if",
"is_leonardo_module",
"(",
"mod",
")",
":",
"conf",
"=",
"get_conf_from_module",
"(",
"mod",
")",
"if",
"module_has_submodule",
"(",
"mod",
",",
"'urls'",
")",
":",
"urls_mod",
"=",
"import_module",
"(",
"'.urls'",
",",
"mod",
".",
"__name__",
")",
"if",
"hasattr",
"(",
"urls_mod",
",",
"'urlpatterns'",
")",
":",
"# if not public decorate all",
"if",
"conf",
"[",
"'public'",
"]",
":",
"urlpatterns",
"+=",
"urls_mod",
".",
"urlpatterns",
"else",
":",
"_decorate_urlconf",
"(",
"urls_mod",
".",
"urlpatterns",
",",
"require_auth",
")",
"urlpatterns",
"+=",
"urls_mod",
".",
"urlpatterns",
"# avoid circural dependency",
"# TODO use our loaded modules instead this property",
"from",
"django",
".",
"conf",
"import",
"settings",
"for",
"urls_conf",
",",
"conf",
"in",
"six",
".",
"iteritems",
"(",
"getattr",
"(",
"settings",
",",
"'MODULE_URLS'",
",",
"{",
"}",
")",
")",
":",
"# is public ?",
"try",
":",
"if",
"conf",
"[",
"'is_public'",
"]",
":",
"urlpatterns",
"+=",
"patterns",
"(",
"''",
",",
"url",
"(",
"r''",
",",
"include",
"(",
"urls_conf",
")",
")",
",",
")",
"else",
":",
"_decorate_urlconf",
"(",
"url",
"(",
"r''",
",",
"include",
"(",
"urls_conf",
")",
")",
",",
"require_auth",
")",
"urlpatterns",
"+=",
"patterns",
"(",
"''",
",",
"url",
"(",
"r''",
",",
"include",
"(",
"urls_conf",
")",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"Exception",
"(",
"'raised %s during loading %s'",
"%",
"(",
"str",
"(",
"e",
")",
",",
"urls_conf",
")",
")",
"self",
".",
"_urlpatterns",
"=",
"urlpatterns",
"return",
"self",
".",
"_urlpatterns"
] |
load and decorate urls from all modules
then store it as cached property for less loading
|
[
"load",
"and",
"decorate",
"urls",
"from",
"all",
"modules",
"then",
"store",
"it",
"as",
"cached",
"property",
"for",
"less",
"loading"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/base.py#L83-L132
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/widget/application/reverse.py
|
cycle_app_reverse_cache
|
def cycle_app_reverse_cache(*args, **kwargs):
"""Does not really empty the cache; instead it adds a random element to the
cache key generation which guarantees that the cache does not yet contain
values for all newly generated keys"""
value = '%07x' % (SystemRandom().randint(0, 0x10000000))
cache.set(APP_REVERSE_CACHE_GENERATION_KEY, value)
return value
|
python
|
def cycle_app_reverse_cache(*args, **kwargs):
"""Does not really empty the cache; instead it adds a random element to the
cache key generation which guarantees that the cache does not yet contain
values for all newly generated keys"""
value = '%07x' % (SystemRandom().randint(0, 0x10000000))
cache.set(APP_REVERSE_CACHE_GENERATION_KEY, value)
return value
|
[
"def",
"cycle_app_reverse_cache",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"value",
"=",
"'%07x'",
"%",
"(",
"SystemRandom",
"(",
")",
".",
"randint",
"(",
"0",
",",
"0x10000000",
")",
")",
"cache",
".",
"set",
"(",
"APP_REVERSE_CACHE_GENERATION_KEY",
",",
"value",
")",
"return",
"value"
] |
Does not really empty the cache; instead it adds a random element to the
cache key generation which guarantees that the cache does not yet contain
values for all newly generated keys
|
[
"Does",
"not",
"really",
"empty",
"the",
"cache",
";",
"instead",
"it",
"adds",
"a",
"random",
"element",
"to",
"the",
"cache",
"key",
"generation",
"which",
"guarantees",
"that",
"the",
"cache",
"does",
"not",
"yet",
"contain",
"values",
"for",
"all",
"newly",
"generated",
"keys"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widget/application/reverse.py#L31-L37
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/widget/application/reverse.py
|
reverse
|
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
"""monkey patched reverse
path supports easy patching 3rd party urls
if 3rd party app has namespace for example ``catalogue`` and
you create FeinCMS plugin with same name as this namespace reverse
returns url from ApplicationContent !
"""
if not urlconf:
urlconf = get_urlconf()
resolver = get_resolver(urlconf)
args = args or []
kwargs = kwargs or {}
prefix = get_script_prefix()
if not isinstance(viewname, six.string_types):
view = viewname
else:
parts = viewname.split(':')
parts.reverse()
view = parts[0]
path = parts[1:]
resolved_path = []
ns_pattern = ''
while path:
ns = path.pop()
# Lookup the name to see if it could be an app identifier
try:
app_list = resolver.app_dict[ns]
# Yes! Path part matches an app in the current Resolver
if current_app and current_app in app_list:
# If we are reversing for a particular app,
# use that namespace
ns = current_app
elif ns not in app_list:
# The name isn't shared by one of the instances
# (i.e., the default) so just pick the first instance
# as the default.
ns = app_list[0]
except KeyError:
pass
try:
extra, resolver = resolver.namespace_dict[ns]
resolved_path.append(ns)
ns_pattern = ns_pattern + extra
except KeyError as key:
for urlconf, config in six.iteritems(
ApplicationWidget._feincms_content_models[0].ALL_APPS_CONFIG):
partials = viewname.split(':')
app = partials[0]
partials = partials[1:]
# check if namespace is same as app name and try resolve
if urlconf.split(".")[-1] == app:
try:
return app_reverse(
':'.join(partials),
urlconf, args=args, kwargs=kwargs,
current_app=current_app)
except NoReverseMatch:
pass
if resolved_path:
raise NoReverseMatch(
"%s is not a registered namespace inside '%s'" %
(key, ':'.join(resolved_path)))
else:
raise NoReverseMatch("%s is not a registered namespace" %
key)
if ns_pattern:
resolver = get_ns_resolver(ns_pattern, resolver)
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
|
python
|
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
"""monkey patched reverse
path supports easy patching 3rd party urls
if 3rd party app has namespace for example ``catalogue`` and
you create FeinCMS plugin with same name as this namespace reverse
returns url from ApplicationContent !
"""
if not urlconf:
urlconf = get_urlconf()
resolver = get_resolver(urlconf)
args = args or []
kwargs = kwargs or {}
prefix = get_script_prefix()
if not isinstance(viewname, six.string_types):
view = viewname
else:
parts = viewname.split(':')
parts.reverse()
view = parts[0]
path = parts[1:]
resolved_path = []
ns_pattern = ''
while path:
ns = path.pop()
# Lookup the name to see if it could be an app identifier
try:
app_list = resolver.app_dict[ns]
# Yes! Path part matches an app in the current Resolver
if current_app and current_app in app_list:
# If we are reversing for a particular app,
# use that namespace
ns = current_app
elif ns not in app_list:
# The name isn't shared by one of the instances
# (i.e., the default) so just pick the first instance
# as the default.
ns = app_list[0]
except KeyError:
pass
try:
extra, resolver = resolver.namespace_dict[ns]
resolved_path.append(ns)
ns_pattern = ns_pattern + extra
except KeyError as key:
for urlconf, config in six.iteritems(
ApplicationWidget._feincms_content_models[0].ALL_APPS_CONFIG):
partials = viewname.split(':')
app = partials[0]
partials = partials[1:]
# check if namespace is same as app name and try resolve
if urlconf.split(".")[-1] == app:
try:
return app_reverse(
':'.join(partials),
urlconf, args=args, kwargs=kwargs,
current_app=current_app)
except NoReverseMatch:
pass
if resolved_path:
raise NoReverseMatch(
"%s is not a registered namespace inside '%s'" %
(key, ':'.join(resolved_path)))
else:
raise NoReverseMatch("%s is not a registered namespace" %
key)
if ns_pattern:
resolver = get_ns_resolver(ns_pattern, resolver)
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
|
[
"def",
"reverse",
"(",
"viewname",
",",
"urlconf",
"=",
"None",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"current_app",
"=",
"None",
")",
":",
"if",
"not",
"urlconf",
":",
"urlconf",
"=",
"get_urlconf",
"(",
")",
"resolver",
"=",
"get_resolver",
"(",
"urlconf",
")",
"args",
"=",
"args",
"or",
"[",
"]",
"kwargs",
"=",
"kwargs",
"or",
"{",
"}",
"prefix",
"=",
"get_script_prefix",
"(",
")",
"if",
"not",
"isinstance",
"(",
"viewname",
",",
"six",
".",
"string_types",
")",
":",
"view",
"=",
"viewname",
"else",
":",
"parts",
"=",
"viewname",
".",
"split",
"(",
"':'",
")",
"parts",
".",
"reverse",
"(",
")",
"view",
"=",
"parts",
"[",
"0",
"]",
"path",
"=",
"parts",
"[",
"1",
":",
"]",
"resolved_path",
"=",
"[",
"]",
"ns_pattern",
"=",
"''",
"while",
"path",
":",
"ns",
"=",
"path",
".",
"pop",
"(",
")",
"# Lookup the name to see if it could be an app identifier",
"try",
":",
"app_list",
"=",
"resolver",
".",
"app_dict",
"[",
"ns",
"]",
"# Yes! Path part matches an app in the current Resolver",
"if",
"current_app",
"and",
"current_app",
"in",
"app_list",
":",
"# If we are reversing for a particular app,",
"# use that namespace",
"ns",
"=",
"current_app",
"elif",
"ns",
"not",
"in",
"app_list",
":",
"# The name isn't shared by one of the instances",
"# (i.e., the default) so just pick the first instance",
"# as the default.",
"ns",
"=",
"app_list",
"[",
"0",
"]",
"except",
"KeyError",
":",
"pass",
"try",
":",
"extra",
",",
"resolver",
"=",
"resolver",
".",
"namespace_dict",
"[",
"ns",
"]",
"resolved_path",
".",
"append",
"(",
"ns",
")",
"ns_pattern",
"=",
"ns_pattern",
"+",
"extra",
"except",
"KeyError",
"as",
"key",
":",
"for",
"urlconf",
",",
"config",
"in",
"six",
".",
"iteritems",
"(",
"ApplicationWidget",
".",
"_feincms_content_models",
"[",
"0",
"]",
".",
"ALL_APPS_CONFIG",
")",
":",
"partials",
"=",
"viewname",
".",
"split",
"(",
"':'",
")",
"app",
"=",
"partials",
"[",
"0",
"]",
"partials",
"=",
"partials",
"[",
"1",
":",
"]",
"# check if namespace is same as app name and try resolve",
"if",
"urlconf",
".",
"split",
"(",
"\".\"",
")",
"[",
"-",
"1",
"]",
"==",
"app",
":",
"try",
":",
"return",
"app_reverse",
"(",
"':'",
".",
"join",
"(",
"partials",
")",
",",
"urlconf",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
",",
"current_app",
"=",
"current_app",
")",
"except",
"NoReverseMatch",
":",
"pass",
"if",
"resolved_path",
":",
"raise",
"NoReverseMatch",
"(",
"\"%s is not a registered namespace inside '%s'\"",
"%",
"(",
"key",
",",
"':'",
".",
"join",
"(",
"resolved_path",
")",
")",
")",
"else",
":",
"raise",
"NoReverseMatch",
"(",
"\"%s is not a registered namespace\"",
"%",
"key",
")",
"if",
"ns_pattern",
":",
"resolver",
"=",
"get_ns_resolver",
"(",
"ns_pattern",
",",
"resolver",
")",
"return",
"iri_to_uri",
"(",
"resolver",
".",
"_reverse_with_prefix",
"(",
"view",
",",
"prefix",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] |
monkey patched reverse
path supports easy patching 3rd party urls
if 3rd party app has namespace for example ``catalogue`` and
you create FeinCMS plugin with same name as this namespace reverse
returns url from ApplicationContent !
|
[
"monkey",
"patched",
"reverse"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widget/application/reverse.py#L128-L209
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/processors/page.py
|
add_page_if_missing
|
def add_page_if_missing(request):
"""
Returns ``feincms_page`` for request.
"""
try:
page = Page.objects.for_request(request, best_match=True)
return {
'leonardo_page': page,
# DEPRECATED
'feincms_page': page,
}
except Page.DoesNotExist:
return {}
|
python
|
def add_page_if_missing(request):
"""
Returns ``feincms_page`` for request.
"""
try:
page = Page.objects.for_request(request, best_match=True)
return {
'leonardo_page': page,
# DEPRECATED
'feincms_page': page,
}
except Page.DoesNotExist:
return {}
|
[
"def",
"add_page_if_missing",
"(",
"request",
")",
":",
"try",
":",
"page",
"=",
"Page",
".",
"objects",
".",
"for_request",
"(",
"request",
",",
"best_match",
"=",
"True",
")",
"return",
"{",
"'leonardo_page'",
":",
"page",
",",
"# DEPRECATED",
"'feincms_page'",
":",
"page",
",",
"}",
"except",
"Page",
".",
"DoesNotExist",
":",
"return",
"{",
"}"
] |
Returns ``feincms_page`` for request.
|
[
"Returns",
"feincms_page",
"for",
"request",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/processors/page.py#L5-L18
|
train
|
django-leonardo/django-leonardo
|
leonardo/views/defaults.py
|
render_in_page
|
def render_in_page(request, template):
"""return rendered template in standalone mode or ``False``
"""
from leonardo.module.web.models import Page
page = request.leonardo_page if hasattr(
request, 'leonardo_page') else Page.objects.filter(parent=None).first()
if page:
try:
slug = request.path_info.split("/")[-2:-1][0]
except KeyError:
slug = None
try:
body = render_to_string(template, RequestContext(request, {
'request_path': request.path,
'feincms_page': page,
'slug': slug,
'standalone': True}))
response = http.HttpResponseNotFound(
body, content_type=CONTENT_TYPE)
except TemplateDoesNotExist:
response = False
return response
return False
|
python
|
def render_in_page(request, template):
"""return rendered template in standalone mode or ``False``
"""
from leonardo.module.web.models import Page
page = request.leonardo_page if hasattr(
request, 'leonardo_page') else Page.objects.filter(parent=None).first()
if page:
try:
slug = request.path_info.split("/")[-2:-1][0]
except KeyError:
slug = None
try:
body = render_to_string(template, RequestContext(request, {
'request_path': request.path,
'feincms_page': page,
'slug': slug,
'standalone': True}))
response = http.HttpResponseNotFound(
body, content_type=CONTENT_TYPE)
except TemplateDoesNotExist:
response = False
return response
return False
|
[
"def",
"render_in_page",
"(",
"request",
",",
"template",
")",
":",
"from",
"leonardo",
".",
"module",
".",
"web",
".",
"models",
"import",
"Page",
"page",
"=",
"request",
".",
"leonardo_page",
"if",
"hasattr",
"(",
"request",
",",
"'leonardo_page'",
")",
"else",
"Page",
".",
"objects",
".",
"filter",
"(",
"parent",
"=",
"None",
")",
".",
"first",
"(",
")",
"if",
"page",
":",
"try",
":",
"slug",
"=",
"request",
".",
"path_info",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"2",
":",
"-",
"1",
"]",
"[",
"0",
"]",
"except",
"KeyError",
":",
"slug",
"=",
"None",
"try",
":",
"body",
"=",
"render_to_string",
"(",
"template",
",",
"RequestContext",
"(",
"request",
",",
"{",
"'request_path'",
":",
"request",
".",
"path",
",",
"'feincms_page'",
":",
"page",
",",
"'slug'",
":",
"slug",
",",
"'standalone'",
":",
"True",
"}",
")",
")",
"response",
"=",
"http",
".",
"HttpResponseNotFound",
"(",
"body",
",",
"content_type",
"=",
"CONTENT_TYPE",
")",
"except",
"TemplateDoesNotExist",
":",
"response",
"=",
"False",
"return",
"response",
"return",
"False"
] |
return rendered template in standalone mode or ``False``
|
[
"return",
"rendered",
"template",
"in",
"standalone",
"mode",
"or",
"False"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/defaults.py#L11-L38
|
train
|
django-leonardo/django-leonardo
|
leonardo/views/defaults.py
|
page_not_found
|
def page_not_found(request, template_name='404.html'):
"""
Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/')
"""
response = render_in_page(request, template_name)
if response:
return response
template = Template(
'<h1>Not Found</h1>'
'<p>The requested URL {{ request_path }} was not found on this server.</p>')
body = template.render(RequestContext(
request, {'request_path': request.path}))
return http.HttpResponseNotFound(body, content_type=CONTENT_TYPE)
|
python
|
def page_not_found(request, template_name='404.html'):
"""
Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/')
"""
response = render_in_page(request, template_name)
if response:
return response
template = Template(
'<h1>Not Found</h1>'
'<p>The requested URL {{ request_path }} was not found on this server.</p>')
body = template.render(RequestContext(
request, {'request_path': request.path}))
return http.HttpResponseNotFound(body, content_type=CONTENT_TYPE)
|
[
"def",
"page_not_found",
"(",
"request",
",",
"template_name",
"=",
"'404.html'",
")",
":",
"response",
"=",
"render_in_page",
"(",
"request",
",",
"template_name",
")",
"if",
"response",
":",
"return",
"response",
"template",
"=",
"Template",
"(",
"'<h1>Not Found</h1>'",
"'<p>The requested URL {{ request_path }} was not found on this server.</p>'",
")",
"body",
"=",
"template",
".",
"render",
"(",
"RequestContext",
"(",
"request",
",",
"{",
"'request_path'",
":",
"request",
".",
"path",
"}",
")",
")",
"return",
"http",
".",
"HttpResponseNotFound",
"(",
"body",
",",
"content_type",
"=",
"CONTENT_TYPE",
")"
] |
Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/')
|
[
"Default",
"404",
"handler",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/defaults.py#L45-L64
|
train
|
django-leonardo/django-leonardo
|
leonardo/views/defaults.py
|
bad_request
|
def bad_request(request, template_name='400.html'):
"""
400 error handler.
Templates: :template:`400.html`
Context: None
"""
response = render_in_page(request, template_name)
if response:
return response
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
return http.HttpResponseBadRequest(template.render(Context({})))
|
python
|
def bad_request(request, template_name='400.html'):
"""
400 error handler.
Templates: :template:`400.html`
Context: None
"""
response = render_in_page(request, template_name)
if response:
return response
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
return http.HttpResponseBadRequest(template.render(Context({})))
|
[
"def",
"bad_request",
"(",
"request",
",",
"template_name",
"=",
"'400.html'",
")",
":",
"response",
"=",
"render_in_page",
"(",
"request",
",",
"template_name",
")",
"if",
"response",
":",
"return",
"response",
"try",
":",
"template",
"=",
"loader",
".",
"get_template",
"(",
"template_name",
")",
"except",
"TemplateDoesNotExist",
":",
"return",
"http",
".",
"HttpResponseBadRequest",
"(",
"'<h1>Bad Request (400)</h1>'",
",",
"content_type",
"=",
"'text/html'",
")",
"return",
"http",
".",
"HttpResponseBadRequest",
"(",
"template",
".",
"render",
"(",
"Context",
"(",
"{",
"}",
")",
")",
")"
] |
400 error handler.
Templates: :template:`400.html`
Context: None
|
[
"400",
"error",
"handler",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/defaults.py#L89-L106
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/middlewares/horizon.py
|
HorizonMiddleware.process_response
|
def process_response(self, request, response):
"""Convert HttpResponseRedirect to HttpResponse if request is via ajax
to allow ajax request to redirect url
"""
if request.is_ajax() and hasattr(request, 'horizon'):
queued_msgs = request.horizon['async_messages']
if type(response) == http.HttpResponseRedirect:
# Drop our messages back into the session as per usual so they
# don't disappear during the redirect. Not that we explicitly
# use django's messages methods here.
for tag, message, extra_tags in queued_msgs:
getattr(django_messages, tag)(request, message, extra_tags)
# if response['location'].startswith(settings.LOGOUT_URL):
# redirect_response = http.HttpResponse(status=401)
# # This header is used for handling the logout in JS
# redirect_response['logout'] = True
# if self.logout_reason is not None:
# utils.add_logout_reason(
# request, redirect_response, self.logout_reason)
# else:
redirect_response = http.HttpResponse()
# Use a set while checking if we want a cookie's attributes
# copied
cookie_keys = set(('max_age', 'expires', 'path', 'domain',
'secure', 'httponly', 'logout_reason'))
# Copy cookies from HttpResponseRedirect towards HttpResponse
for cookie_name, cookie in six.iteritems(response.cookies):
cookie_kwargs = dict((
(key, value) for key, value in six.iteritems(cookie)
if key in cookie_keys and value
))
redirect_response.set_cookie(
cookie_name, cookie.value, **cookie_kwargs)
redirect_response['X-Horizon-Location'] = response['location']
upload_url_key = 'X-File-Upload-URL'
if upload_url_key in response:
self.copy_headers(response, redirect_response,
(upload_url_key, 'X-Auth-Token'))
return redirect_response
if queued_msgs:
# TODO(gabriel): When we have an async connection to the
# client (e.g. websockets) this should be pushed to the
# socket queue rather than being sent via a header.
# The header method has notable drawbacks (length limits,
# etc.) and is not meant as a long-term solution.
response['X-Horizon-Messages'] = json.dumps(queued_msgs)
return response
|
python
|
def process_response(self, request, response):
"""Convert HttpResponseRedirect to HttpResponse if request is via ajax
to allow ajax request to redirect url
"""
if request.is_ajax() and hasattr(request, 'horizon'):
queued_msgs = request.horizon['async_messages']
if type(response) == http.HttpResponseRedirect:
# Drop our messages back into the session as per usual so they
# don't disappear during the redirect. Not that we explicitly
# use django's messages methods here.
for tag, message, extra_tags in queued_msgs:
getattr(django_messages, tag)(request, message, extra_tags)
# if response['location'].startswith(settings.LOGOUT_URL):
# redirect_response = http.HttpResponse(status=401)
# # This header is used for handling the logout in JS
# redirect_response['logout'] = True
# if self.logout_reason is not None:
# utils.add_logout_reason(
# request, redirect_response, self.logout_reason)
# else:
redirect_response = http.HttpResponse()
# Use a set while checking if we want a cookie's attributes
# copied
cookie_keys = set(('max_age', 'expires', 'path', 'domain',
'secure', 'httponly', 'logout_reason'))
# Copy cookies from HttpResponseRedirect towards HttpResponse
for cookie_name, cookie in six.iteritems(response.cookies):
cookie_kwargs = dict((
(key, value) for key, value in six.iteritems(cookie)
if key in cookie_keys and value
))
redirect_response.set_cookie(
cookie_name, cookie.value, **cookie_kwargs)
redirect_response['X-Horizon-Location'] = response['location']
upload_url_key = 'X-File-Upload-URL'
if upload_url_key in response:
self.copy_headers(response, redirect_response,
(upload_url_key, 'X-Auth-Token'))
return redirect_response
if queued_msgs:
# TODO(gabriel): When we have an async connection to the
# client (e.g. websockets) this should be pushed to the
# socket queue rather than being sent via a header.
# The header method has notable drawbacks (length limits,
# etc.) and is not meant as a long-term solution.
response['X-Horizon-Messages'] = json.dumps(queued_msgs)
return response
|
[
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"if",
"request",
".",
"is_ajax",
"(",
")",
"and",
"hasattr",
"(",
"request",
",",
"'horizon'",
")",
":",
"queued_msgs",
"=",
"request",
".",
"horizon",
"[",
"'async_messages'",
"]",
"if",
"type",
"(",
"response",
")",
"==",
"http",
".",
"HttpResponseRedirect",
":",
"# Drop our messages back into the session as per usual so they",
"# don't disappear during the redirect. Not that we explicitly",
"# use django's messages methods here.",
"for",
"tag",
",",
"message",
",",
"extra_tags",
"in",
"queued_msgs",
":",
"getattr",
"(",
"django_messages",
",",
"tag",
")",
"(",
"request",
",",
"message",
",",
"extra_tags",
")",
"# if response['location'].startswith(settings.LOGOUT_URL):",
"# redirect_response = http.HttpResponse(status=401)",
"# # This header is used for handling the logout in JS",
"# redirect_response['logout'] = True",
"# if self.logout_reason is not None:",
"# utils.add_logout_reason(",
"# request, redirect_response, self.logout_reason)",
"# else:",
"redirect_response",
"=",
"http",
".",
"HttpResponse",
"(",
")",
"# Use a set while checking if we want a cookie's attributes",
"# copied",
"cookie_keys",
"=",
"set",
"(",
"(",
"'max_age'",
",",
"'expires'",
",",
"'path'",
",",
"'domain'",
",",
"'secure'",
",",
"'httponly'",
",",
"'logout_reason'",
")",
")",
"# Copy cookies from HttpResponseRedirect towards HttpResponse",
"for",
"cookie_name",
",",
"cookie",
"in",
"six",
".",
"iteritems",
"(",
"response",
".",
"cookies",
")",
":",
"cookie_kwargs",
"=",
"dict",
"(",
"(",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"cookie",
")",
"if",
"key",
"in",
"cookie_keys",
"and",
"value",
")",
")",
"redirect_response",
".",
"set_cookie",
"(",
"cookie_name",
",",
"cookie",
".",
"value",
",",
"*",
"*",
"cookie_kwargs",
")",
"redirect_response",
"[",
"'X-Horizon-Location'",
"]",
"=",
"response",
"[",
"'location'",
"]",
"upload_url_key",
"=",
"'X-File-Upload-URL'",
"if",
"upload_url_key",
"in",
"response",
":",
"self",
".",
"copy_headers",
"(",
"response",
",",
"redirect_response",
",",
"(",
"upload_url_key",
",",
"'X-Auth-Token'",
")",
")",
"return",
"redirect_response",
"if",
"queued_msgs",
":",
"# TODO(gabriel): When we have an async connection to the",
"# client (e.g. websockets) this should be pushed to the",
"# socket queue rather than being sent via a header.",
"# The header method has notable drawbacks (length limits,",
"# etc.) and is not meant as a long-term solution.",
"response",
"[",
"'X-Horizon-Messages'",
"]",
"=",
"json",
".",
"dumps",
"(",
"queued_msgs",
")",
"return",
"response"
] |
Convert HttpResponseRedirect to HttpResponse if request is via ajax
to allow ajax request to redirect url
|
[
"Convert",
"HttpResponseRedirect",
"to",
"HttpResponse",
"if",
"request",
"is",
"via",
"ajax",
"to",
"allow",
"ajax",
"request",
"to",
"redirect",
"url"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/middlewares/horizon.py#L96-L143
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/middlewares/horizon.py
|
HorizonMiddleware.process_exception
|
def process_exception(self, request, exception):
"""Catches internal Horizon exception classes such as NotAuthorized,
NotFound and Http302 and handles them gracefully.
"""
if isinstance(exception, (exceptions.NotAuthorized,
exceptions.NotAuthenticated)):
auth_url = settings.LOGIN_URL
next_url = None
# prevent submiting forms after login and
# use http referer
if request.method in ("POST", "PUT"):
referrer = request.META.get('HTTP_REFERER')
if referrer and is_safe_url(referrer, request.get_host()):
next_url = referrer
if not next_url:
next_url = iri_to_uri(request.get_full_path())
if next_url != auth_url:
field_name = REDIRECT_FIELD_NAME
else:
field_name = None
login_url = request.build_absolute_uri(auth_url)
response = redirect_to_login(next_url, login_url=login_url,
redirect_field_name=field_name)
if isinstance(exception, exceptions.NotAuthorized):
logout_reason = _("Unauthorized. Please try logging in again.")
utils.add_logout_reason(request, response, logout_reason)
# delete messages, created in get_data() method
# since we are going to redirect user to the login page
response.delete_cookie('messages')
if request.is_ajax():
response_401 = http.HttpResponse(status=401)
response_401['X-Horizon-Location'] = response['location']
return response_401
return response
# If an internal "NotFound" error gets this far, return a real 404.
if isinstance(exception, exceptions.NotFound):
raise http.Http404(exception)
if isinstance(exception, exceptions.Http302):
# TODO(gabriel): Find a way to display an appropriate message to
# the user *on* the login form...
return shortcuts.redirect(exception.location)
|
python
|
def process_exception(self, request, exception):
"""Catches internal Horizon exception classes such as NotAuthorized,
NotFound and Http302 and handles them gracefully.
"""
if isinstance(exception, (exceptions.NotAuthorized,
exceptions.NotAuthenticated)):
auth_url = settings.LOGIN_URL
next_url = None
# prevent submiting forms after login and
# use http referer
if request.method in ("POST", "PUT"):
referrer = request.META.get('HTTP_REFERER')
if referrer and is_safe_url(referrer, request.get_host()):
next_url = referrer
if not next_url:
next_url = iri_to_uri(request.get_full_path())
if next_url != auth_url:
field_name = REDIRECT_FIELD_NAME
else:
field_name = None
login_url = request.build_absolute_uri(auth_url)
response = redirect_to_login(next_url, login_url=login_url,
redirect_field_name=field_name)
if isinstance(exception, exceptions.NotAuthorized):
logout_reason = _("Unauthorized. Please try logging in again.")
utils.add_logout_reason(request, response, logout_reason)
# delete messages, created in get_data() method
# since we are going to redirect user to the login page
response.delete_cookie('messages')
if request.is_ajax():
response_401 = http.HttpResponse(status=401)
response_401['X-Horizon-Location'] = response['location']
return response_401
return response
# If an internal "NotFound" error gets this far, return a real 404.
if isinstance(exception, exceptions.NotFound):
raise http.Http404(exception)
if isinstance(exception, exceptions.Http302):
# TODO(gabriel): Find a way to display an appropriate message to
# the user *on* the login form...
return shortcuts.redirect(exception.location)
|
[
"def",
"process_exception",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"if",
"isinstance",
"(",
"exception",
",",
"(",
"exceptions",
".",
"NotAuthorized",
",",
"exceptions",
".",
"NotAuthenticated",
")",
")",
":",
"auth_url",
"=",
"settings",
".",
"LOGIN_URL",
"next_url",
"=",
"None",
"# prevent submiting forms after login and",
"# use http referer",
"if",
"request",
".",
"method",
"in",
"(",
"\"POST\"",
",",
"\"PUT\"",
")",
":",
"referrer",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_REFERER'",
")",
"if",
"referrer",
"and",
"is_safe_url",
"(",
"referrer",
",",
"request",
".",
"get_host",
"(",
")",
")",
":",
"next_url",
"=",
"referrer",
"if",
"not",
"next_url",
":",
"next_url",
"=",
"iri_to_uri",
"(",
"request",
".",
"get_full_path",
"(",
")",
")",
"if",
"next_url",
"!=",
"auth_url",
":",
"field_name",
"=",
"REDIRECT_FIELD_NAME",
"else",
":",
"field_name",
"=",
"None",
"login_url",
"=",
"request",
".",
"build_absolute_uri",
"(",
"auth_url",
")",
"response",
"=",
"redirect_to_login",
"(",
"next_url",
",",
"login_url",
"=",
"login_url",
",",
"redirect_field_name",
"=",
"field_name",
")",
"if",
"isinstance",
"(",
"exception",
",",
"exceptions",
".",
"NotAuthorized",
")",
":",
"logout_reason",
"=",
"_",
"(",
"\"Unauthorized. Please try logging in again.\"",
")",
"utils",
".",
"add_logout_reason",
"(",
"request",
",",
"response",
",",
"logout_reason",
")",
"# delete messages, created in get_data() method",
"# since we are going to redirect user to the login page",
"response",
".",
"delete_cookie",
"(",
"'messages'",
")",
"if",
"request",
".",
"is_ajax",
"(",
")",
":",
"response_401",
"=",
"http",
".",
"HttpResponse",
"(",
"status",
"=",
"401",
")",
"response_401",
"[",
"'X-Horizon-Location'",
"]",
"=",
"response",
"[",
"'location'",
"]",
"return",
"response_401",
"return",
"response",
"# If an internal \"NotFound\" error gets this far, return a real 404.",
"if",
"isinstance",
"(",
"exception",
",",
"exceptions",
".",
"NotFound",
")",
":",
"raise",
"http",
".",
"Http404",
"(",
"exception",
")",
"if",
"isinstance",
"(",
"exception",
",",
"exceptions",
".",
"Http302",
")",
":",
"# TODO(gabriel): Find a way to display an appropriate message to",
"# the user *on* the login form...",
"return",
"shortcuts",
".",
"redirect",
"(",
"exception",
".",
"location",
")"
] |
Catches internal Horizon exception classes such as NotAuthorized,
NotFound and Http302 and handles them gracefully.
|
[
"Catches",
"internal",
"Horizon",
"exception",
"classes",
"such",
"as",
"NotAuthorized",
"NotFound",
"and",
"Http302",
"and",
"handles",
"them",
"gracefully",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/middlewares/horizon.py#L145-L195
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/media/views.py
|
canonical
|
def canonical(request, uploaded_at, file_id):
"""
Redirect to the current url of a public file
"""
filer_file = get_object_or_404(File, pk=file_id, is_public=True)
if (uploaded_at != filer_file.uploaded_at.strftime('%s') or
not filer_file.file):
raise Http404('No %s matches the given query.' %
File._meta.object_name)
return redirect(filer_file.url)
|
python
|
def canonical(request, uploaded_at, file_id):
"""
Redirect to the current url of a public file
"""
filer_file = get_object_or_404(File, pk=file_id, is_public=True)
if (uploaded_at != filer_file.uploaded_at.strftime('%s') or
not filer_file.file):
raise Http404('No %s matches the given query.' %
File._meta.object_name)
return redirect(filer_file.url)
|
[
"def",
"canonical",
"(",
"request",
",",
"uploaded_at",
",",
"file_id",
")",
":",
"filer_file",
"=",
"get_object_or_404",
"(",
"File",
",",
"pk",
"=",
"file_id",
",",
"is_public",
"=",
"True",
")",
"if",
"(",
"uploaded_at",
"!=",
"filer_file",
".",
"uploaded_at",
".",
"strftime",
"(",
"'%s'",
")",
"or",
"not",
"filer_file",
".",
"file",
")",
":",
"raise",
"Http404",
"(",
"'No %s matches the given query.'",
"%",
"File",
".",
"_meta",
".",
"object_name",
")",
"return",
"redirect",
"(",
"filer_file",
".",
"url",
")"
] |
Redirect to the current url of a public file
|
[
"Redirect",
"to",
"the",
"current",
"url",
"of",
"a",
"public",
"file"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/views.py#L77-L86
|
train
|
django-leonardo/django-leonardo
|
leonardo/exceptions.py
|
check_message
|
def check_message(keywords, message):
"""Checks an exception for given keywords and raises a new ``ActionError``
with the desired message if the keywords are found. This allows selective
control over API error messages.
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
if set(str(exc_value).split(" ")).issuperset(set(keywords)):
exc_value.message = message
raise
|
python
|
def check_message(keywords, message):
"""Checks an exception for given keywords and raises a new ``ActionError``
with the desired message if the keywords are found. This allows selective
control over API error messages.
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
if set(str(exc_value).split(" ")).issuperset(set(keywords)):
exc_value.message = message
raise
|
[
"def",
"check_message",
"(",
"keywords",
",",
"message",
")",
":",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"set",
"(",
"str",
"(",
"exc_value",
")",
".",
"split",
"(",
"\" \"",
")",
")",
".",
"issuperset",
"(",
"set",
"(",
"keywords",
")",
")",
":",
"exc_value",
".",
"message",
"=",
"message",
"raise"
] |
Checks an exception for given keywords and raises a new ``ActionError``
with the desired message if the keywords are found. This allows selective
control over API error messages.
|
[
"Checks",
"an",
"exception",
"for",
"given",
"keywords",
"and",
"raises",
"a",
"new",
"ActionError",
"with",
"the",
"desired",
"message",
"if",
"the",
"keywords",
"are",
"found",
".",
"This",
"allows",
"selective",
"control",
"over",
"API",
"error",
"messages",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/exceptions.py#L142-L150
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/page/forms.py
|
SwitchableFormFieldMixin.get_switched_form_field_attrs
|
def get_switched_form_field_attrs(self, prefix, input_type, name):
"""Creates attribute dicts for the switchable theme form
"""
attributes = {'class': 'switched', 'data-switch-on': prefix + 'field'}
attributes['data-' + prefix + 'field-' + input_type] = name
return attributes
|
python
|
def get_switched_form_field_attrs(self, prefix, input_type, name):
"""Creates attribute dicts for the switchable theme form
"""
attributes = {'class': 'switched', 'data-switch-on': prefix + 'field'}
attributes['data-' + prefix + 'field-' + input_type] = name
return attributes
|
[
"def",
"get_switched_form_field_attrs",
"(",
"self",
",",
"prefix",
",",
"input_type",
",",
"name",
")",
":",
"attributes",
"=",
"{",
"'class'",
":",
"'switched'",
",",
"'data-switch-on'",
":",
"prefix",
"+",
"'field'",
"}",
"attributes",
"[",
"'data-'",
"+",
"prefix",
"+",
"'field-'",
"+",
"input_type",
"]",
"=",
"name",
"return",
"attributes"
] |
Creates attribute dicts for the switchable theme form
|
[
"Creates",
"attribute",
"dicts",
"for",
"the",
"switchable",
"theme",
"form"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/page/forms.py#L23-L28
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/page/forms.py
|
PageCreateForm.clean_slug
|
def clean_slug(self):
"""slug title if is not provided
"""
slug = self.cleaned_data.get('slug', None)
if slug is None or len(slug) == 0 and 'title' in self.cleaned_data:
slug = slugify(self.cleaned_data['title'])
return slug
|
python
|
def clean_slug(self):
"""slug title if is not provided
"""
slug = self.cleaned_data.get('slug', None)
if slug is None or len(slug) == 0 and 'title' in self.cleaned_data:
slug = slugify(self.cleaned_data['title'])
return slug
|
[
"def",
"clean_slug",
"(",
"self",
")",
":",
"slug",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'slug'",
",",
"None",
")",
"if",
"slug",
"is",
"None",
"or",
"len",
"(",
"slug",
")",
"==",
"0",
"and",
"'title'",
"in",
"self",
".",
"cleaned_data",
":",
"slug",
"=",
"slugify",
"(",
"self",
".",
"cleaned_data",
"[",
"'title'",
"]",
")",
"return",
"slug"
] |
slug title if is not provided
|
[
"slug",
"title",
"if",
"is",
"not",
"provided"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/page/forms.py#L90-L96
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/widgets/utils.py
|
get_widget_from_id
|
def get_widget_from_id(id):
"""returns widget object by id
example web-htmltextwidget-2-2
"""
res = id.split('-')
try:
model_cls = apps.get_model(res[0], res[1])
obj = model_cls.objects.get(parent=res[2], id=res[3])
except:
obj = None
return obj
|
python
|
def get_widget_from_id(id):
"""returns widget object by id
example web-htmltextwidget-2-2
"""
res = id.split('-')
try:
model_cls = apps.get_model(res[0], res[1])
obj = model_cls.objects.get(parent=res[2], id=res[3])
except:
obj = None
return obj
|
[
"def",
"get_widget_from_id",
"(",
"id",
")",
":",
"res",
"=",
"id",
".",
"split",
"(",
"'-'",
")",
"try",
":",
"model_cls",
"=",
"apps",
".",
"get_model",
"(",
"res",
"[",
"0",
"]",
",",
"res",
"[",
"1",
"]",
")",
"obj",
"=",
"model_cls",
".",
"objects",
".",
"get",
"(",
"parent",
"=",
"res",
"[",
"2",
"]",
",",
"id",
"=",
"res",
"[",
"3",
"]",
")",
"except",
":",
"obj",
"=",
"None",
"return",
"obj"
] |
returns widget object by id
example web-htmltextwidget-2-2
|
[
"returns",
"widget",
"object",
"by",
"id"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/utils.py#L4-L16
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/widgets/utils.py
|
get_widget_class_from_id
|
def get_widget_class_from_id(id):
"""returns widget class by id
example web-htmltextwidget-2-2
"""
res = id.split('-')
try:
model_cls = apps.get_model(res[1], res[2])
except:
model_cls = None
return model_cls
|
python
|
def get_widget_class_from_id(id):
"""returns widget class by id
example web-htmltextwidget-2-2
"""
res = id.split('-')
try:
model_cls = apps.get_model(res[1], res[2])
except:
model_cls = None
return model_cls
|
[
"def",
"get_widget_class_from_id",
"(",
"id",
")",
":",
"res",
"=",
"id",
".",
"split",
"(",
"'-'",
")",
"try",
":",
"model_cls",
"=",
"apps",
".",
"get_model",
"(",
"res",
"[",
"1",
"]",
",",
"res",
"[",
"2",
"]",
")",
"except",
":",
"model_cls",
"=",
"None",
"return",
"model_cls"
] |
returns widget class by id
example web-htmltextwidget-2-2
|
[
"returns",
"widget",
"class",
"by",
"id"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/utils.py#L19-L30
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/processors/edit.py
|
frontendediting_request_processor
|
def frontendediting_request_processor(page, request):
"""
Sets the frontend editing state in the cookie depending on the
``frontend_editing`` GET parameter and the user's permissions.
"""
if 'frontend_editing' not in request.GET:
return
response = HttpResponseRedirect(request.path)
if request.user.has_module_perms('page'):
if 'frontend_editing' in request.GET:
try:
enable_fe = int(request.GET['frontend_editing']) > 0
except ValueError:
enable_fe = False
if enable_fe:
response.set_cookie(str('frontend_editing'), enable_fe)
clear_cache()
else:
response.delete_cookie(str('frontend_editing'))
clear_cache()
else:
response.delete_cookie(str('frontend_editing'))
# Redirect to cleanup URLs
return response
|
python
|
def frontendediting_request_processor(page, request):
"""
Sets the frontend editing state in the cookie depending on the
``frontend_editing`` GET parameter and the user's permissions.
"""
if 'frontend_editing' not in request.GET:
return
response = HttpResponseRedirect(request.path)
if request.user.has_module_perms('page'):
if 'frontend_editing' in request.GET:
try:
enable_fe = int(request.GET['frontend_editing']) > 0
except ValueError:
enable_fe = False
if enable_fe:
response.set_cookie(str('frontend_editing'), enable_fe)
clear_cache()
else:
response.delete_cookie(str('frontend_editing'))
clear_cache()
else:
response.delete_cookie(str('frontend_editing'))
# Redirect to cleanup URLs
return response
|
[
"def",
"frontendediting_request_processor",
"(",
"page",
",",
"request",
")",
":",
"if",
"'frontend_editing'",
"not",
"in",
"request",
".",
"GET",
":",
"return",
"response",
"=",
"HttpResponseRedirect",
"(",
"request",
".",
"path",
")",
"if",
"request",
".",
"user",
".",
"has_module_perms",
"(",
"'page'",
")",
":",
"if",
"'frontend_editing'",
"in",
"request",
".",
"GET",
":",
"try",
":",
"enable_fe",
"=",
"int",
"(",
"request",
".",
"GET",
"[",
"'frontend_editing'",
"]",
")",
">",
"0",
"except",
"ValueError",
":",
"enable_fe",
"=",
"False",
"if",
"enable_fe",
":",
"response",
".",
"set_cookie",
"(",
"str",
"(",
"'frontend_editing'",
")",
",",
"enable_fe",
")",
"clear_cache",
"(",
")",
"else",
":",
"response",
".",
"delete_cookie",
"(",
"str",
"(",
"'frontend_editing'",
")",
")",
"clear_cache",
"(",
")",
"else",
":",
"response",
".",
"delete_cookie",
"(",
"str",
"(",
"'frontend_editing'",
")",
")",
"# Redirect to cleanup URLs",
"return",
"response"
] |
Sets the frontend editing state in the cookie depending on the
``frontend_editing`` GET parameter and the user's permissions.
|
[
"Sets",
"the",
"frontend",
"editing",
"state",
"in",
"the",
"cookie",
"depending",
"on",
"the",
"frontend_editing",
"GET",
"parameter",
"and",
"the",
"user",
"s",
"permissions",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/processors/edit.py#L11-L40
|
train
|
django-leonardo/django-leonardo
|
leonardo/module/web/__init__.py
|
Default.extra_context
|
def extra_context(self):
"""Add site_name to context
"""
from django.conf import settings
return {
"site_name": (lambda r: settings.LEONARDO_SITE_NAME
if getattr(settings, 'LEONARDO_SITE_NAME', '') != ''
else settings.SITE_NAME),
"debug": lambda r: settings.TEMPLATE_DEBUG
}
|
python
|
def extra_context(self):
"""Add site_name to context
"""
from django.conf import settings
return {
"site_name": (lambda r: settings.LEONARDO_SITE_NAME
if getattr(settings, 'LEONARDO_SITE_NAME', '') != ''
else settings.SITE_NAME),
"debug": lambda r: settings.TEMPLATE_DEBUG
}
|
[
"def",
"extra_context",
"(",
"self",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"return",
"{",
"\"site_name\"",
":",
"(",
"lambda",
"r",
":",
"settings",
".",
"LEONARDO_SITE_NAME",
"if",
"getattr",
"(",
"settings",
",",
"'LEONARDO_SITE_NAME'",
",",
"''",
")",
"!=",
"''",
"else",
"settings",
".",
"SITE_NAME",
")",
",",
"\"debug\"",
":",
"lambda",
"r",
":",
"settings",
".",
"TEMPLATE_DEBUG",
"}"
] |
Add site_name to context
|
[
"Add",
"site_name",
"to",
"context"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/__init__.py#L113-L123
|
train
|
django-leonardo/django-leonardo
|
leonardo/conf/base.py
|
ModuleConfig.get_property
|
def get_property(self, key):
"""Expect Django Conf property"""
_key = DJANGO_CONF[key]
return getattr(self, _key, CONF_SPEC[_key])
|
python
|
def get_property(self, key):
"""Expect Django Conf property"""
_key = DJANGO_CONF[key]
return getattr(self, _key, CONF_SPEC[_key])
|
[
"def",
"get_property",
"(",
"self",
",",
"key",
")",
":",
"_key",
"=",
"DJANGO_CONF",
"[",
"key",
"]",
"return",
"getattr",
"(",
"self",
",",
"_key",
",",
"CONF_SPEC",
"[",
"_key",
"]",
")"
] |
Expect Django Conf property
|
[
"Expect",
"Django",
"Conf",
"property"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/conf/base.py#L21-L24
|
train
|
django-leonardo/django-leonardo
|
leonardo/conf/base.py
|
ModuleConfig.needs_sync
|
def needs_sync(self):
"""Indicates whater module needs templates, static etc."""
affected_attributes = [
'css_files', 'js_files',
'scss_files', 'widgets']
for attr in affected_attributes:
if len(getattr(self, attr)) > 0:
return True
return False
|
python
|
def needs_sync(self):
"""Indicates whater module needs templates, static etc."""
affected_attributes = [
'css_files', 'js_files',
'scss_files', 'widgets']
for attr in affected_attributes:
if len(getattr(self, attr)) > 0:
return True
return False
|
[
"def",
"needs_sync",
"(",
"self",
")",
":",
"affected_attributes",
"=",
"[",
"'css_files'",
",",
"'js_files'",
",",
"'scss_files'",
",",
"'widgets'",
"]",
"for",
"attr",
"in",
"affected_attributes",
":",
"if",
"len",
"(",
"getattr",
"(",
"self",
",",
"attr",
")",
")",
">",
"0",
":",
"return",
"True",
"return",
"False"
] |
Indicates whater module needs templates, static etc.
|
[
"Indicates",
"whater",
"module",
"needs",
"templates",
"static",
"etc",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/conf/base.py#L60-L70
|
train
|
django-leonardo/django-leonardo
|
leonardo/conf/base.py
|
LeonardoConfig.get_attr
|
def get_attr(self, name, default=None, fail_silently=True):
"""try extra context
"""
try:
return getattr(self, name)
except KeyError:
extra_context = getattr(self, "extra_context")
if name in extra_context:
value = extra_context[name]
if callable(value):
return value(request=None)
return default
|
python
|
def get_attr(self, name, default=None, fail_silently=True):
"""try extra context
"""
try:
return getattr(self, name)
except KeyError:
extra_context = getattr(self, "extra_context")
if name in extra_context:
value = extra_context[name]
if callable(value):
return value(request=None)
return default
|
[
"def",
"get_attr",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"fail_silently",
"=",
"True",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"self",
",",
"name",
")",
"except",
"KeyError",
":",
"extra_context",
"=",
"getattr",
"(",
"self",
",",
"\"extra_context\"",
")",
"if",
"name",
"in",
"extra_context",
":",
"value",
"=",
"extra_context",
"[",
"name",
"]",
"if",
"callable",
"(",
"value",
")",
":",
"return",
"value",
"(",
"request",
"=",
"None",
")",
"return",
"default"
] |
try extra context
|
[
"try",
"extra",
"context"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/conf/base.py#L93-L107
|
train
|
django-leonardo/django-leonardo
|
leonardo/utils/templates.py
|
find_all_templates
|
def find_all_templates(pattern='*.html', ignore_private=True):
"""
Finds all Django templates matching given glob in all TEMPLATE_LOADERS
:param str pattern: `glob <http://docs.python.org/2/library/glob.html>`_
to match
.. important:: At the moment egg loader is not supported.
"""
templates = []
template_loaders = flatten_template_loaders(settings.TEMPLATE_LOADERS)
for loader_name in template_loaders:
module, klass = loader_name.rsplit('.', 1)
if loader_name in (
'django.template.loaders.app_directories.Loader',
'django.template.loaders.filesystem.Loader',
):
loader_class = getattr(import_module(module), klass)
if getattr(loader_class, '_accepts_engine_in_init', False):
loader = loader_class(Engine.get_default())
else:
loader = loader_class()
for dir in loader.get_template_sources(''):
for root, dirnames, filenames in os.walk(dir):
for basename in filenames:
if ignore_private and basename.startswith("_"):
continue
filename = os.path.join(root, basename)
rel_filename = filename[len(dir)+1:]
if fnmatch.fnmatch(filename, pattern) or \
fnmatch.fnmatch(basename, pattern) or \
fnmatch.fnmatch(rel_filename, pattern):
templates.append(rel_filename)
else:
LOGGER.debug('%s is not supported' % loader_name)
return sorted(set(templates))
|
python
|
def find_all_templates(pattern='*.html', ignore_private=True):
"""
Finds all Django templates matching given glob in all TEMPLATE_LOADERS
:param str pattern: `glob <http://docs.python.org/2/library/glob.html>`_
to match
.. important:: At the moment egg loader is not supported.
"""
templates = []
template_loaders = flatten_template_loaders(settings.TEMPLATE_LOADERS)
for loader_name in template_loaders:
module, klass = loader_name.rsplit('.', 1)
if loader_name in (
'django.template.loaders.app_directories.Loader',
'django.template.loaders.filesystem.Loader',
):
loader_class = getattr(import_module(module), klass)
if getattr(loader_class, '_accepts_engine_in_init', False):
loader = loader_class(Engine.get_default())
else:
loader = loader_class()
for dir in loader.get_template_sources(''):
for root, dirnames, filenames in os.walk(dir):
for basename in filenames:
if ignore_private and basename.startswith("_"):
continue
filename = os.path.join(root, basename)
rel_filename = filename[len(dir)+1:]
if fnmatch.fnmatch(filename, pattern) or \
fnmatch.fnmatch(basename, pattern) or \
fnmatch.fnmatch(rel_filename, pattern):
templates.append(rel_filename)
else:
LOGGER.debug('%s is not supported' % loader_name)
return sorted(set(templates))
|
[
"def",
"find_all_templates",
"(",
"pattern",
"=",
"'*.html'",
",",
"ignore_private",
"=",
"True",
")",
":",
"templates",
"=",
"[",
"]",
"template_loaders",
"=",
"flatten_template_loaders",
"(",
"settings",
".",
"TEMPLATE_LOADERS",
")",
"for",
"loader_name",
"in",
"template_loaders",
":",
"module",
",",
"klass",
"=",
"loader_name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"if",
"loader_name",
"in",
"(",
"'django.template.loaders.app_directories.Loader'",
",",
"'django.template.loaders.filesystem.Loader'",
",",
")",
":",
"loader_class",
"=",
"getattr",
"(",
"import_module",
"(",
"module",
")",
",",
"klass",
")",
"if",
"getattr",
"(",
"loader_class",
",",
"'_accepts_engine_in_init'",
",",
"False",
")",
":",
"loader",
"=",
"loader_class",
"(",
"Engine",
".",
"get_default",
"(",
")",
")",
"else",
":",
"loader",
"=",
"loader_class",
"(",
")",
"for",
"dir",
"in",
"loader",
".",
"get_template_sources",
"(",
"''",
")",
":",
"for",
"root",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"dir",
")",
":",
"for",
"basename",
"in",
"filenames",
":",
"if",
"ignore_private",
"and",
"basename",
".",
"startswith",
"(",
"\"_\"",
")",
":",
"continue",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"basename",
")",
"rel_filename",
"=",
"filename",
"[",
"len",
"(",
"dir",
")",
"+",
"1",
":",
"]",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"filename",
",",
"pattern",
")",
"or",
"fnmatch",
".",
"fnmatch",
"(",
"basename",
",",
"pattern",
")",
"or",
"fnmatch",
".",
"fnmatch",
"(",
"rel_filename",
",",
"pattern",
")",
":",
"templates",
".",
"append",
"(",
"rel_filename",
")",
"else",
":",
"LOGGER",
".",
"debug",
"(",
"'%s is not supported'",
"%",
"loader_name",
")",
"return",
"sorted",
"(",
"set",
"(",
"templates",
")",
")"
] |
Finds all Django templates matching given glob in all TEMPLATE_LOADERS
:param str pattern: `glob <http://docs.python.org/2/library/glob.html>`_
to match
.. important:: At the moment egg loader is not supported.
|
[
"Finds",
"all",
"Django",
"templates",
"matching",
"given",
"glob",
"in",
"all",
"TEMPLATE_LOADERS"
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/templates.py#L40-L75
|
train
|
django-leonardo/django-leonardo
|
leonardo/utils/templates.py
|
flatten_template_loaders
|
def flatten_template_loaders(templates):
"""
Given a collection of template loaders, unwrap them into one flat iterable.
:param templates: template loaders to unwrap
:return: template loaders as an iterable of strings.
:rtype: generator expression
"""
for loader in templates:
if not isinstance(loader, string_types):
for subloader in flatten_template_loaders(loader):
yield subloader
else:
yield loader
|
python
|
def flatten_template_loaders(templates):
"""
Given a collection of template loaders, unwrap them into one flat iterable.
:param templates: template loaders to unwrap
:return: template loaders as an iterable of strings.
:rtype: generator expression
"""
for loader in templates:
if not isinstance(loader, string_types):
for subloader in flatten_template_loaders(loader):
yield subloader
else:
yield loader
|
[
"def",
"flatten_template_loaders",
"(",
"templates",
")",
":",
"for",
"loader",
"in",
"templates",
":",
"if",
"not",
"isinstance",
"(",
"loader",
",",
"string_types",
")",
":",
"for",
"subloader",
"in",
"flatten_template_loaders",
"(",
"loader",
")",
":",
"yield",
"subloader",
"else",
":",
"yield",
"loader"
] |
Given a collection of template loaders, unwrap them into one flat iterable.
:param templates: template loaders to unwrap
:return: template loaders as an iterable of strings.
:rtype: generator expression
|
[
"Given",
"a",
"collection",
"of",
"template",
"loaders",
"unwrap",
"them",
"into",
"one",
"flat",
"iterable",
"."
] |
4b933e1792221a13b4028753d5f1d3499b0816d4
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/templates.py#L78-L91
|
train
|
dahlia/sqlalchemy-imageattach
|
sqlalchemy_imageattach/file.py
|
SeekableFileProxy.seek
|
def seek(self, offset, whence=os.SEEK_SET):
"""Sets the file's current position.
:param offset: the offset to set
:type offset: :class:`numbers.Integral`
:param whence: see the docs of :meth:`file.seek()`.
default is :const:`os.SEEK_SET`
"""
self.wrapped.seek(offset, whence)
|
python
|
def seek(self, offset, whence=os.SEEK_SET):
"""Sets the file's current position.
:param offset: the offset to set
:type offset: :class:`numbers.Integral`
:param whence: see the docs of :meth:`file.seek()`.
default is :const:`os.SEEK_SET`
"""
self.wrapped.seek(offset, whence)
|
[
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"os",
".",
"SEEK_SET",
")",
":",
"self",
".",
"wrapped",
".",
"seek",
"(",
"offset",
",",
"whence",
")"
] |
Sets the file's current position.
:param offset: the offset to set
:type offset: :class:`numbers.Integral`
:param whence: see the docs of :meth:`file.seek()`.
default is :const:`os.SEEK_SET`
|
[
"Sets",
"the",
"file",
"s",
"current",
"position",
"."
] |
b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8
|
https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/file.py#L138-L147
|
train
|
dahlia/sqlalchemy-imageattach
|
sqlalchemy_imageattach/store.py
|
Store.put_file
|
def put_file(self, file, object_type, object_id, width, height, mimetype,
reproducible):
"""Puts the ``file`` of the image.
:param file: the image file to put
:type file: file-like object, :class:`file`
:param object_type: the object type of the image to put
e.g. ``'comics.cover'``
:type object_type: :class:`str`
:param object_id: the object identifier number of the image to put
:type object_id: :class:`numbers.Integral`
:param width: the width of the image to put
:type width: :class:`numbers.Integral`
:param height: the height of the image to put
:type height: :class:`numbers.Integral`
:param mimetype: the mimetype of the image to put
e.g. ``'image/jpeg'``
:type mimetype: :class:`str`
:param reproducible: :const:`True` only if it's reproducible by
computing e.g. resized thumbnails.
:const:`False` if it cannot be reproduced
e.g. original images
:type reproducible: :class:`bool`
.. note::
This is an abstract method which has to be implemented
(overridden) by subclasses.
It's not for consumers but implementations, so consumers
should use :meth:`store()` method instead of this.
"""
raise NotImplementedError('put_file() has to be implemented')
|
python
|
def put_file(self, file, object_type, object_id, width, height, mimetype,
reproducible):
"""Puts the ``file`` of the image.
:param file: the image file to put
:type file: file-like object, :class:`file`
:param object_type: the object type of the image to put
e.g. ``'comics.cover'``
:type object_type: :class:`str`
:param object_id: the object identifier number of the image to put
:type object_id: :class:`numbers.Integral`
:param width: the width of the image to put
:type width: :class:`numbers.Integral`
:param height: the height of the image to put
:type height: :class:`numbers.Integral`
:param mimetype: the mimetype of the image to put
e.g. ``'image/jpeg'``
:type mimetype: :class:`str`
:param reproducible: :const:`True` only if it's reproducible by
computing e.g. resized thumbnails.
:const:`False` if it cannot be reproduced
e.g. original images
:type reproducible: :class:`bool`
.. note::
This is an abstract method which has to be implemented
(overridden) by subclasses.
It's not for consumers but implementations, so consumers
should use :meth:`store()` method instead of this.
"""
raise NotImplementedError('put_file() has to be implemented')
|
[
"def",
"put_file",
"(",
"self",
",",
"file",
",",
"object_type",
",",
"object_id",
",",
"width",
",",
"height",
",",
"mimetype",
",",
"reproducible",
")",
":",
"raise",
"NotImplementedError",
"(",
"'put_file() has to be implemented'",
")"
] |
Puts the ``file`` of the image.
:param file: the image file to put
:type file: file-like object, :class:`file`
:param object_type: the object type of the image to put
e.g. ``'comics.cover'``
:type object_type: :class:`str`
:param object_id: the object identifier number of the image to put
:type object_id: :class:`numbers.Integral`
:param width: the width of the image to put
:type width: :class:`numbers.Integral`
:param height: the height of the image to put
:type height: :class:`numbers.Integral`
:param mimetype: the mimetype of the image to put
e.g. ``'image/jpeg'``
:type mimetype: :class:`str`
:param reproducible: :const:`True` only if it's reproducible by
computing e.g. resized thumbnails.
:const:`False` if it cannot be reproduced
e.g. original images
:type reproducible: :class:`bool`
.. note::
This is an abstract method which has to be implemented
(overridden) by subclasses.
It's not for consumers but implementations, so consumers
should use :meth:`store()` method instead of this.
|
[
"Puts",
"the",
"file",
"of",
"the",
"image",
"."
] |
b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8
|
https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/store.py#L29-L62
|
train
|
dahlia/sqlalchemy-imageattach
|
sqlalchemy_imageattach/store.py
|
Store.delete
|
def delete(self, image):
"""Delete the file of the given ``image``.
:param image: the image to delete
:type image: :class:`sqlalchemy_imageattach.entity.Image`
"""
from .entity import Image
if not isinstance(image, Image):
raise TypeError('image must be a sqlalchemy_imageattach.entity.'
'Image instance, not ' + repr(image))
self.delete_file(image.object_type, image.object_id,
image.width, image.height, image.mimetype)
|
python
|
def delete(self, image):
"""Delete the file of the given ``image``.
:param image: the image to delete
:type image: :class:`sqlalchemy_imageattach.entity.Image`
"""
from .entity import Image
if not isinstance(image, Image):
raise TypeError('image must be a sqlalchemy_imageattach.entity.'
'Image instance, not ' + repr(image))
self.delete_file(image.object_type, image.object_id,
image.width, image.height, image.mimetype)
|
[
"def",
"delete",
"(",
"self",
",",
"image",
")",
":",
"from",
".",
"entity",
"import",
"Image",
"if",
"not",
"isinstance",
"(",
"image",
",",
"Image",
")",
":",
"raise",
"TypeError",
"(",
"'image must be a sqlalchemy_imageattach.entity.'",
"'Image instance, not '",
"+",
"repr",
"(",
"image",
")",
")",
"self",
".",
"delete_file",
"(",
"image",
".",
"object_type",
",",
"image",
".",
"object_id",
",",
"image",
".",
"width",
",",
"image",
".",
"height",
",",
"image",
".",
"mimetype",
")"
] |
Delete the file of the given ``image``.
:param image: the image to delete
:type image: :class:`sqlalchemy_imageattach.entity.Image`
|
[
"Delete",
"the",
"file",
"of",
"the",
"given",
"image",
"."
] |
b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8
|
https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/store.py#L167-L179
|
train
|
dahlia/sqlalchemy-imageattach
|
sqlalchemy_imageattach/store.py
|
Store.locate
|
def locate(self, image):
"""Gets the URL of the given ``image``.
:param image: the image to get its url
:type image: :class:`sqlalchemy_imageattach.entity.Image`
:returns: the url of the image
:rtype: :class:`str`
"""
from .entity import Image
if not isinstance(image, Image):
raise TypeError('image must be a sqlalchemy_imageattach.entity.'
'Image instance, not ' + repr(image))
url = self.get_url(image.object_type, image.object_id,
image.width, image.height, image.mimetype)
if '?' in url:
fmt = '{0}&_ts={1}'
else:
fmt = '{0}?_ts={1}'
return fmt.format(url, image.created_at.strftime('%Y%m%d%H%M%S%f'))
|
python
|
def locate(self, image):
"""Gets the URL of the given ``image``.
:param image: the image to get its url
:type image: :class:`sqlalchemy_imageattach.entity.Image`
:returns: the url of the image
:rtype: :class:`str`
"""
from .entity import Image
if not isinstance(image, Image):
raise TypeError('image must be a sqlalchemy_imageattach.entity.'
'Image instance, not ' + repr(image))
url = self.get_url(image.object_type, image.object_id,
image.width, image.height, image.mimetype)
if '?' in url:
fmt = '{0}&_ts={1}'
else:
fmt = '{0}?_ts={1}'
return fmt.format(url, image.created_at.strftime('%Y%m%d%H%M%S%f'))
|
[
"def",
"locate",
"(",
"self",
",",
"image",
")",
":",
"from",
".",
"entity",
"import",
"Image",
"if",
"not",
"isinstance",
"(",
"image",
",",
"Image",
")",
":",
"raise",
"TypeError",
"(",
"'image must be a sqlalchemy_imageattach.entity.'",
"'Image instance, not '",
"+",
"repr",
"(",
"image",
")",
")",
"url",
"=",
"self",
".",
"get_url",
"(",
"image",
".",
"object_type",
",",
"image",
".",
"object_id",
",",
"image",
".",
"width",
",",
"image",
".",
"height",
",",
"image",
".",
"mimetype",
")",
"if",
"'?'",
"in",
"url",
":",
"fmt",
"=",
"'{0}&_ts={1}'",
"else",
":",
"fmt",
"=",
"'{0}?_ts={1}'",
"return",
"fmt",
".",
"format",
"(",
"url",
",",
"image",
".",
"created_at",
".",
"strftime",
"(",
"'%Y%m%d%H%M%S%f'",
")",
")"
] |
Gets the URL of the given ``image``.
:param image: the image to get its url
:type image: :class:`sqlalchemy_imageattach.entity.Image`
:returns: the url of the image
:rtype: :class:`str`
|
[
"Gets",
"the",
"URL",
"of",
"the",
"given",
"image",
"."
] |
b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8
|
https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/store.py#L256-L275
|
train
|
dahlia/sqlalchemy-imageattach
|
sqlalchemy_imageattach/entity.py
|
Image.identity_attributes
|
def identity_attributes(cls):
"""A list of the names of primary key fields.
:returns: A list of the names of primary key fields
:rtype: :class:`typing.Sequence`\ [:class:`str`]
.. versionadded:: 1.0.0
"""
columns = inspect(cls).primary_key
names = [c.name for c in columns if c.name not in ('width', 'height')]
return names
|
python
|
def identity_attributes(cls):
"""A list of the names of primary key fields.
:returns: A list of the names of primary key fields
:rtype: :class:`typing.Sequence`\ [:class:`str`]
.. versionadded:: 1.0.0
"""
columns = inspect(cls).primary_key
names = [c.name for c in columns if c.name not in ('width', 'height')]
return names
|
[
"def",
"identity_attributes",
"(",
"cls",
")",
":",
"columns",
"=",
"inspect",
"(",
"cls",
")",
".",
"primary_key",
"names",
"=",
"[",
"c",
".",
"name",
"for",
"c",
"in",
"columns",
"if",
"c",
".",
"name",
"not",
"in",
"(",
"'width'",
",",
"'height'",
")",
"]",
"return",
"names"
] |
A list of the names of primary key fields.
:returns: A list of the names of primary key fields
:rtype: :class:`typing.Sequence`\ [:class:`str`]
.. versionadded:: 1.0.0
|
[
"A",
"list",
"of",
"the",
"names",
"of",
"primary",
"key",
"fields",
"."
] |
b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8
|
https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L215-L226
|
train
|
dahlia/sqlalchemy-imageattach
|
sqlalchemy_imageattach/entity.py
|
Image.make_blob
|
def make_blob(self, store=current_store):
"""Gets the byte string of the image from the ``store``.
:param store: the storage which contains the image.
:data:`~sqlalchemy_imageattach.context.current_store`
by default
:type store: :class:`~sqlalchemy_imageattach.store.Store`
:returns: the binary data of the image
:rtype: :class:`str`
"""
with self.open_file(store) as f:
return f.read()
|
python
|
def make_blob(self, store=current_store):
"""Gets the byte string of the image from the ``store``.
:param store: the storage which contains the image.
:data:`~sqlalchemy_imageattach.context.current_store`
by default
:type store: :class:`~sqlalchemy_imageattach.store.Store`
:returns: the binary data of the image
:rtype: :class:`str`
"""
with self.open_file(store) as f:
return f.read()
|
[
"def",
"make_blob",
"(",
"self",
",",
"store",
"=",
"current_store",
")",
":",
"with",
"self",
".",
"open_file",
"(",
"store",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")"
] |
Gets the byte string of the image from the ``store``.
:param store: the storage which contains the image.
:data:`~sqlalchemy_imageattach.context.current_store`
by default
:type store: :class:`~sqlalchemy_imageattach.store.Store`
:returns: the binary data of the image
:rtype: :class:`str`
|
[
"Gets",
"the",
"byte",
"string",
"of",
"the",
"image",
"from",
"the",
"store",
"."
] |
b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8
|
https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L275-L287
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.