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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.field2choices | def field2choices(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for valid choices definition
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
comparable = [
validator.comparable
for validator in field.validators
if hasattr(validator, "comparable")
]
if comparable:
attributes["enum"] = comparable
else:
choices = [
OrderedSet(validator.choices)
for validator in field.validators
if hasattr(validator, "choices")
]
if choices:
attributes["enum"] = list(functools.reduce(operator.and_, choices))
return attributes | python | def field2choices(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for valid choices definition
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
comparable = [
validator.comparable
for validator in field.validators
if hasattr(validator, "comparable")
]
if comparable:
attributes["enum"] = comparable
else:
choices = [
OrderedSet(validator.choices)
for validator in field.validators
if hasattr(validator, "choices")
]
if choices:
attributes["enum"] = list(functools.reduce(operator.and_, choices))
return attributes | [
"def",
"field2choices",
"(",
"self",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"attributes",
"=",
"{",
"}",
"comparable",
"=",
"[",
"validator",
".",
"comparable",
"for",
"validator",
"in",
"field",
".",
"validators",
"if",
"hasattr",
"(",
"valida... | Return the dictionary of OpenAPI field attributes for valid choices definition
:param Field field: A marshmallow field.
:rtype: dict | [
"Return",
"the",
"dictionary",
"of",
"OpenAPI",
"field",
"attributes",
"for",
"valid",
"choices",
"definition"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L208-L232 | train | 224,500 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.field2read_only | def field2read_only(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a dump_only field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.dump_only:
attributes["readOnly"] = True
return attributes | python | def field2read_only(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a dump_only field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.dump_only:
attributes["readOnly"] = True
return attributes | [
"def",
"field2read_only",
"(",
"self",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"attributes",
"=",
"{",
"}",
"if",
"field",
".",
"dump_only",
":",
"attributes",
"[",
"\"readOnly\"",
"]",
"=",
"True",
"return",
"attributes"
] | Return the dictionary of OpenAPI field attributes for a dump_only field.
:param Field field: A marshmallow field.
:rtype: dict | [
"Return",
"the",
"dictionary",
"of",
"OpenAPI",
"field",
"attributes",
"for",
"a",
"dump_only",
"field",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L234-L243 | train | 224,501 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.field2write_only | def field2write_only(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a load_only field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.load_only and self.openapi_version.major >= 3:
attributes["writeOnly"] = True
return attributes | python | def field2write_only(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a load_only field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.load_only and self.openapi_version.major >= 3:
attributes["writeOnly"] = True
return attributes | [
"def",
"field2write_only",
"(",
"self",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"attributes",
"=",
"{",
"}",
"if",
"field",
".",
"load_only",
"and",
"self",
".",
"openapi_version",
".",
"major",
">=",
"3",
":",
"attributes",
"[",
"\"writeOnly\""... | Return the dictionary of OpenAPI field attributes for a load_only field.
:param Field field: A marshmallow field.
:rtype: dict | [
"Return",
"the",
"dictionary",
"of",
"OpenAPI",
"field",
"attributes",
"for",
"a",
"load_only",
"field",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L245-L254 | train | 224,502 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.field2nullable | def field2nullable(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a nullable field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.allow_none:
attributes[
"x-nullable" if self.openapi_version.major < 3 else "nullable"
] = True
return attributes | python | def field2nullable(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a nullable field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.allow_none:
attributes[
"x-nullable" if self.openapi_version.major < 3 else "nullable"
] = True
return attributes | [
"def",
"field2nullable",
"(",
"self",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"attributes",
"=",
"{",
"}",
"if",
"field",
".",
"allow_none",
":",
"attributes",
"[",
"\"x-nullable\"",
"if",
"self",
".",
"openapi_version",
".",
"major",
"<",
"3",
... | Return the dictionary of OpenAPI field attributes for a nullable field.
:param Field field: A marshmallow field.
:rtype: dict | [
"Return",
"the",
"dictionary",
"of",
"OpenAPI",
"field",
"attributes",
"for",
"a",
"nullable",
"field",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L256-L267 | train | 224,503 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.metadata2properties | def metadata2properties(self, field):
"""Return a dictionary of properties extracted from field Metadata
Will include field metadata that are valid properties of `OpenAPI schema
objects
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject>`_
(e.g. “description”, “enum”, “example”).
In addition, `specification extensions
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions>`_
are supported. Prefix `x_` to the desired extension when passing the
keyword argument to the field constructor. apispec will convert `x_` to
`x-` to comply with OpenAPI.
:param Field field: A marshmallow field.
:rtype: dict
"""
# Dasherize metadata that starts with x_
metadata = {
key.replace("_", "-") if key.startswith("x_") else key: value
for key, value in iteritems(field.metadata)
}
# Avoid validation error with "Additional properties not allowed"
ret = {
key: value
for key, value in metadata.items()
if key in _VALID_PROPERTIES or key.startswith(_VALID_PREFIX)
}
return ret | python | def metadata2properties(self, field):
"""Return a dictionary of properties extracted from field Metadata
Will include field metadata that are valid properties of `OpenAPI schema
objects
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject>`_
(e.g. “description”, “enum”, “example”).
In addition, `specification extensions
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions>`_
are supported. Prefix `x_` to the desired extension when passing the
keyword argument to the field constructor. apispec will convert `x_` to
`x-` to comply with OpenAPI.
:param Field field: A marshmallow field.
:rtype: dict
"""
# Dasherize metadata that starts with x_
metadata = {
key.replace("_", "-") if key.startswith("x_") else key: value
for key, value in iteritems(field.metadata)
}
# Avoid validation error with "Additional properties not allowed"
ret = {
key: value
for key, value in metadata.items()
if key in _VALID_PROPERTIES or key.startswith(_VALID_PREFIX)
}
return ret | [
"def",
"metadata2properties",
"(",
"self",
",",
"field",
")",
":",
"# Dasherize metadata that starts with x_",
"metadata",
"=",
"{",
"key",
".",
"replace",
"(",
"\"_\"",
",",
"\"-\"",
")",
"if",
"key",
".",
"startswith",
"(",
"\"x_\"",
")",
"else",
"key",
":... | Return a dictionary of properties extracted from field Metadata
Will include field metadata that are valid properties of `OpenAPI schema
objects
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject>`_
(e.g. “description”, “enum”, “example”).
In addition, `specification extensions
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions>`_
are supported. Prefix `x_` to the desired extension when passing the
keyword argument to the field constructor. apispec will convert `x_` to
`x-` to comply with OpenAPI.
:param Field field: A marshmallow field.
:rtype: dict | [
"Return",
"a",
"dictionary",
"of",
"properties",
"extracted",
"from",
"field",
"Metadata"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L367-L396 | train | 224,504 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.resolve_nested_schema | def resolve_nested_schema(self, schema):
"""Return the Open API representation of a marshmallow Schema.
Adds the schema to the spec if it isn't already present.
Typically will return a dictionary with the reference to the schema's
path in the spec unless the `schema_name_resolver` returns `None`, in
which case the returned dictoinary will contain a JSON Schema Object
representation of the schema.
:param schema: schema to add to the spec
"""
schema_instance = resolve_schema_instance(schema)
schema_key = make_schema_key(schema_instance)
if schema_key not in self.refs:
schema_cls = self.resolve_schema_class(schema)
name = self.schema_name_resolver(schema_cls)
if not name:
try:
json_schema = self.schema2jsonschema(schema)
except RuntimeError:
raise APISpecError(
"Name resolver returned None for schema {schema} which is "
"part of a chain of circular referencing schemas. Please"
" ensure that the schema_name_resolver passed to"
" MarshmallowPlugin returns a string for all circular"
" referencing schemas.".format(schema=schema)
)
if getattr(schema, "many", False):
return {"type": "array", "items": json_schema}
return json_schema
name = get_unique_schema_name(self.spec.components, name)
self.spec.components.schema(name, schema=schema)
return self.get_ref_dict(schema_instance) | python | def resolve_nested_schema(self, schema):
"""Return the Open API representation of a marshmallow Schema.
Adds the schema to the spec if it isn't already present.
Typically will return a dictionary with the reference to the schema's
path in the spec unless the `schema_name_resolver` returns `None`, in
which case the returned dictoinary will contain a JSON Schema Object
representation of the schema.
:param schema: schema to add to the spec
"""
schema_instance = resolve_schema_instance(schema)
schema_key = make_schema_key(schema_instance)
if schema_key not in self.refs:
schema_cls = self.resolve_schema_class(schema)
name = self.schema_name_resolver(schema_cls)
if not name:
try:
json_schema = self.schema2jsonschema(schema)
except RuntimeError:
raise APISpecError(
"Name resolver returned None for schema {schema} which is "
"part of a chain of circular referencing schemas. Please"
" ensure that the schema_name_resolver passed to"
" MarshmallowPlugin returns a string for all circular"
" referencing schemas.".format(schema=schema)
)
if getattr(schema, "many", False):
return {"type": "array", "items": json_schema}
return json_schema
name = get_unique_schema_name(self.spec.components, name)
self.spec.components.schema(name, schema=schema)
return self.get_ref_dict(schema_instance) | [
"def",
"resolve_nested_schema",
"(",
"self",
",",
"schema",
")",
":",
"schema_instance",
"=",
"resolve_schema_instance",
"(",
"schema",
")",
"schema_key",
"=",
"make_schema_key",
"(",
"schema_instance",
")",
"if",
"schema_key",
"not",
"in",
"self",
".",
"refs",
... | Return the Open API representation of a marshmallow Schema.
Adds the schema to the spec if it isn't already present.
Typically will return a dictionary with the reference to the schema's
path in the spec unless the `schema_name_resolver` returns `None`, in
which case the returned dictoinary will contain a JSON Schema Object
representation of the schema.
:param schema: schema to add to the spec | [
"Return",
"the",
"Open",
"API",
"representation",
"of",
"a",
"marshmallow",
"Schema",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L444-L477 | train | 224,505 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.property2parameter | def property2parameter(
self,
prop,
name="body",
required=False,
multiple=False,
location=None,
default_in="body",
):
"""Return the Parameter Object definition for a JSON Schema property.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject
:param dict prop: JSON Schema property
:param str name: Field name
:param bool required: Parameter is required
:param bool multiple: Parameter is repeated
:param str location: Location to look for ``name``
:param str default_in: Default location to look for ``name``
:raise: TranslationError if arg object cannot be translated to a Parameter Object schema.
:rtype: dict, a Parameter Object
"""
openapi_default_in = __location_map__.get(default_in, default_in)
openapi_location = __location_map__.get(location, openapi_default_in)
ret = {"in": openapi_location, "name": name}
if openapi_location == "body":
ret["required"] = False
ret["name"] = "body"
ret["schema"] = {
"type": "object",
"properties": {name: prop} if name else {},
}
if name and required:
ret["schema"]["required"] = [name]
else:
ret["required"] = required
if self.openapi_version.major < 3:
if multiple:
ret["collectionFormat"] = "multi"
ret.update(prop)
else:
if multiple:
ret["explode"] = True
ret["style"] = "form"
if prop.get("description", None):
ret["description"] = prop.pop("description")
ret["schema"] = prop
return ret | python | def property2parameter(
self,
prop,
name="body",
required=False,
multiple=False,
location=None,
default_in="body",
):
"""Return the Parameter Object definition for a JSON Schema property.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject
:param dict prop: JSON Schema property
:param str name: Field name
:param bool required: Parameter is required
:param bool multiple: Parameter is repeated
:param str location: Location to look for ``name``
:param str default_in: Default location to look for ``name``
:raise: TranslationError if arg object cannot be translated to a Parameter Object schema.
:rtype: dict, a Parameter Object
"""
openapi_default_in = __location_map__.get(default_in, default_in)
openapi_location = __location_map__.get(location, openapi_default_in)
ret = {"in": openapi_location, "name": name}
if openapi_location == "body":
ret["required"] = False
ret["name"] = "body"
ret["schema"] = {
"type": "object",
"properties": {name: prop} if name else {},
}
if name and required:
ret["schema"]["required"] = [name]
else:
ret["required"] = required
if self.openapi_version.major < 3:
if multiple:
ret["collectionFormat"] = "multi"
ret.update(prop)
else:
if multiple:
ret["explode"] = True
ret["style"] = "form"
if prop.get("description", None):
ret["description"] = prop.pop("description")
ret["schema"] = prop
return ret | [
"def",
"property2parameter",
"(",
"self",
",",
"prop",
",",
"name",
"=",
"\"body\"",
",",
"required",
"=",
"False",
",",
"multiple",
"=",
"False",
",",
"location",
"=",
"None",
",",
"default_in",
"=",
"\"body\"",
",",
")",
":",
"openapi_default_in",
"=",
... | Return the Parameter Object definition for a JSON Schema property.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject
:param dict prop: JSON Schema property
:param str name: Field name
:param bool required: Parameter is required
:param bool multiple: Parameter is repeated
:param str location: Location to look for ``name``
:param str default_in: Default location to look for ``name``
:raise: TranslationError if arg object cannot be translated to a Parameter Object schema.
:rtype: dict, a Parameter Object | [
"Return",
"the",
"Parameter",
"Object",
"definition",
"for",
"a",
"JSON",
"Schema",
"property",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L571-L619 | train | 224,506 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | OpenAPIConverter.get_ref_dict | def get_ref_dict(self, schema):
"""Method to create a dictionary containing a JSON reference to the
schema in the spec
"""
schema_key = make_schema_key(schema)
ref_schema = build_reference(
"schema", self.openapi_version.major, self.refs[schema_key]
)
if getattr(schema, "many", False):
return {"type": "array", "items": ref_schema}
return ref_schema | python | def get_ref_dict(self, schema):
"""Method to create a dictionary containing a JSON reference to the
schema in the spec
"""
schema_key = make_schema_key(schema)
ref_schema = build_reference(
"schema", self.openapi_version.major, self.refs[schema_key]
)
if getattr(schema, "many", False):
return {"type": "array", "items": ref_schema}
return ref_schema | [
"def",
"get_ref_dict",
"(",
"self",
",",
"schema",
")",
":",
"schema_key",
"=",
"make_schema_key",
"(",
"schema",
")",
"ref_schema",
"=",
"build_reference",
"(",
"\"schema\"",
",",
"self",
".",
"openapi_version",
".",
"major",
",",
"self",
".",
"refs",
"[",
... | Method to create a dictionary containing a JSON reference to the
schema in the spec | [
"Method",
"to",
"create",
"a",
"dictionary",
"containing",
"a",
"JSON",
"reference",
"to",
"the",
"schema",
"in",
"the",
"spec"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L696-L706 | train | 224,507 |
marshmallow-code/apispec | src/apispec/core.py | clean_operations | def clean_operations(operations, openapi_major_version):
"""Ensure that all parameters with "in" equal to "path" are also required
as required by the OpenAPI specification, as well as normalizing any
references to global parameters. Also checks for invalid HTTP methods.
See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject.
:param dict operations: Dict mapping status codes to operations
:param int openapi_major_version: The major version of the OpenAPI standard
to use. Supported values are 2 and 3.
"""
invalid = {
key
for key in set(iterkeys(operations)) - set(VALID_METHODS[openapi_major_version])
if not key.startswith("x-")
}
if invalid:
raise APISpecError(
"One or more HTTP methods are invalid: {}".format(", ".join(invalid))
)
def get_ref(obj_type, obj, openapi_major_version):
"""Return object or rererence
If obj is a dict, it is assumed to be a complete description and it is returned as is.
Otherwise, it is assumed to be a reference name as string and the corresponding $ref
string is returned.
:param str obj_type: "parameter" or "response"
:param dict|str obj: parameter or response in dict form or as ref_id string
:param int openapi_major_version: The major version of the OpenAPI standard
"""
if isinstance(obj, dict):
return obj
return build_reference(obj_type, openapi_major_version, obj)
for operation in (operations or {}).values():
if "parameters" in operation:
parameters = operation["parameters"]
for parameter in parameters:
if (
isinstance(parameter, dict)
and "in" in parameter
and parameter["in"] == "path"
):
parameter["required"] = True
operation["parameters"] = [
get_ref("parameter", p, openapi_major_version) for p in parameters
]
if "responses" in operation:
responses = OrderedDict()
for code, response in iteritems(operation["responses"]):
try:
code = int(code) # handles IntEnums like http.HTTPStatus
except (TypeError, ValueError):
if openapi_major_version < 3:
warnings.warn("Non-integer code not allowed in OpenAPI < 3")
responses[str(code)] = get_ref(
"response", response, openapi_major_version
)
operation["responses"] = responses | python | def clean_operations(operations, openapi_major_version):
"""Ensure that all parameters with "in" equal to "path" are also required
as required by the OpenAPI specification, as well as normalizing any
references to global parameters. Also checks for invalid HTTP methods.
See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject.
:param dict operations: Dict mapping status codes to operations
:param int openapi_major_version: The major version of the OpenAPI standard
to use. Supported values are 2 and 3.
"""
invalid = {
key
for key in set(iterkeys(operations)) - set(VALID_METHODS[openapi_major_version])
if not key.startswith("x-")
}
if invalid:
raise APISpecError(
"One or more HTTP methods are invalid: {}".format(", ".join(invalid))
)
def get_ref(obj_type, obj, openapi_major_version):
"""Return object or rererence
If obj is a dict, it is assumed to be a complete description and it is returned as is.
Otherwise, it is assumed to be a reference name as string and the corresponding $ref
string is returned.
:param str obj_type: "parameter" or "response"
:param dict|str obj: parameter or response in dict form or as ref_id string
:param int openapi_major_version: The major version of the OpenAPI standard
"""
if isinstance(obj, dict):
return obj
return build_reference(obj_type, openapi_major_version, obj)
for operation in (operations or {}).values():
if "parameters" in operation:
parameters = operation["parameters"]
for parameter in parameters:
if (
isinstance(parameter, dict)
and "in" in parameter
and parameter["in"] == "path"
):
parameter["required"] = True
operation["parameters"] = [
get_ref("parameter", p, openapi_major_version) for p in parameters
]
if "responses" in operation:
responses = OrderedDict()
for code, response in iteritems(operation["responses"]):
try:
code = int(code) # handles IntEnums like http.HTTPStatus
except (TypeError, ValueError):
if openapi_major_version < 3:
warnings.warn("Non-integer code not allowed in OpenAPI < 3")
responses[str(code)] = get_ref(
"response", response, openapi_major_version
)
operation["responses"] = responses | [
"def",
"clean_operations",
"(",
"operations",
",",
"openapi_major_version",
")",
":",
"invalid",
"=",
"{",
"key",
"for",
"key",
"in",
"set",
"(",
"iterkeys",
"(",
"operations",
")",
")",
"-",
"set",
"(",
"VALID_METHODS",
"[",
"openapi_major_version",
"]",
")... | Ensure that all parameters with "in" equal to "path" are also required
as required by the OpenAPI specification, as well as normalizing any
references to global parameters. Also checks for invalid HTTP methods.
See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject.
:param dict operations: Dict mapping status codes to operations
:param int openapi_major_version: The major version of the OpenAPI standard
to use. Supported values are 2 and 3. | [
"Ensure",
"that",
"all",
"parameters",
"with",
"in",
"equal",
"to",
"path",
"are",
"also",
"required",
"as",
"required",
"by",
"the",
"OpenAPI",
"specification",
"as",
"well",
"as",
"normalizing",
"any",
"references",
"to",
"global",
"parameters",
".",
"Also",... | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L21-L82 | train | 224,508 |
marshmallow-code/apispec | src/apispec/core.py | Components.schema | def schema(self, name, component=None, **kwargs):
"""Add a new schema to the spec.
:param str name: identifier by which schema may be referenced.
:param dict component: schema definition.
.. note::
If you are using `apispec.ext.marshmallow`, you can pass fields' metadata as
additional keyword arguments.
For example, to add ``enum`` and ``description`` to your field: ::
status = fields.String(
required=True,
enum=['open', 'closed'],
description='Status (open or closed)',
)
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject
"""
if name in self._schemas:
raise DuplicateComponentNameError(
'Another schema with name "{}" is already registered.'.format(name)
)
component = component or {}
ret = component.copy()
# Execute all helpers from plugins
for plugin in self._plugins:
try:
ret.update(plugin.schema_helper(name, component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
self._schemas[name] = ret
return self | python | def schema(self, name, component=None, **kwargs):
"""Add a new schema to the spec.
:param str name: identifier by which schema may be referenced.
:param dict component: schema definition.
.. note::
If you are using `apispec.ext.marshmallow`, you can pass fields' metadata as
additional keyword arguments.
For example, to add ``enum`` and ``description`` to your field: ::
status = fields.String(
required=True,
enum=['open', 'closed'],
description='Status (open or closed)',
)
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject
"""
if name in self._schemas:
raise DuplicateComponentNameError(
'Another schema with name "{}" is already registered.'.format(name)
)
component = component or {}
ret = component.copy()
# Execute all helpers from plugins
for plugin in self._plugins:
try:
ret.update(plugin.schema_helper(name, component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
self._schemas[name] = ret
return self | [
"def",
"schema",
"(",
"self",
",",
"name",
",",
"component",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"name",
"in",
"self",
".",
"_schemas",
":",
"raise",
"DuplicateComponentNameError",
"(",
"'Another schema with name \"{}\" is already registered.'",
... | Add a new schema to the spec.
:param str name: identifier by which schema may be referenced.
:param dict component: schema definition.
.. note::
If you are using `apispec.ext.marshmallow`, you can pass fields' metadata as
additional keyword arguments.
For example, to add ``enum`` and ``description`` to your field: ::
status = fields.String(
required=True,
enum=['open', 'closed'],
description='Status (open or closed)',
)
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject | [
"Add",
"a",
"new",
"schema",
"to",
"the",
"spec",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L113-L147 | train | 224,509 |
marshmallow-code/apispec | src/apispec/core.py | Components.parameter | def parameter(self, component_id, location, component=None, **kwargs):
""" Add a parameter which can be referenced.
:param str param_id: identifier by which parameter may be referenced.
:param str location: location of the parameter.
:param dict component: parameter fields.
:param dict kwargs: plugin-specific arguments
"""
if component_id in self._parameters:
raise DuplicateComponentNameError(
'Another parameter with name "{}" is already registered.'.format(
component_id
)
)
component = component or {}
ret = component.copy()
ret.setdefault("name", component_id)
ret["in"] = location
# Execute all helpers from plugins
for plugin in self._plugins:
try:
ret.update(plugin.parameter_helper(component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
self._parameters[component_id] = ret
return self | python | def parameter(self, component_id, location, component=None, **kwargs):
""" Add a parameter which can be referenced.
:param str param_id: identifier by which parameter may be referenced.
:param str location: location of the parameter.
:param dict component: parameter fields.
:param dict kwargs: plugin-specific arguments
"""
if component_id in self._parameters:
raise DuplicateComponentNameError(
'Another parameter with name "{}" is already registered.'.format(
component_id
)
)
component = component or {}
ret = component.copy()
ret.setdefault("name", component_id)
ret["in"] = location
# Execute all helpers from plugins
for plugin in self._plugins:
try:
ret.update(plugin.parameter_helper(component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
self._parameters[component_id] = ret
return self | [
"def",
"parameter",
"(",
"self",
",",
"component_id",
",",
"location",
",",
"component",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"component_id",
"in",
"self",
".",
"_parameters",
":",
"raise",
"DuplicateComponentNameError",
"(",
"'Another paramet... | Add a parameter which can be referenced.
:param str param_id: identifier by which parameter may be referenced.
:param str location: location of the parameter.
:param dict component: parameter fields.
:param dict kwargs: plugin-specific arguments | [
"Add",
"a",
"parameter",
"which",
"can",
"be",
"referenced",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L149-L174 | train | 224,510 |
marshmallow-code/apispec | src/apispec/core.py | Components.response | def response(self, component_id, component=None, **kwargs):
"""Add a response which can be referenced.
:param str component_id: ref_id to use as reference
:param dict component: response fields
:param dict kwargs: plugin-specific arguments
"""
if component_id in self._responses:
raise DuplicateComponentNameError(
'Another response with name "{}" is already registered.'.format(
component_id
)
)
component = component or {}
ret = component.copy()
# Execute all helpers from plugins
for plugin in self._plugins:
try:
ret.update(plugin.response_helper(component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
self._responses[component_id] = ret
return self | python | def response(self, component_id, component=None, **kwargs):
"""Add a response which can be referenced.
:param str component_id: ref_id to use as reference
:param dict component: response fields
:param dict kwargs: plugin-specific arguments
"""
if component_id in self._responses:
raise DuplicateComponentNameError(
'Another response with name "{}" is already registered.'.format(
component_id
)
)
component = component or {}
ret = component.copy()
# Execute all helpers from plugins
for plugin in self._plugins:
try:
ret.update(plugin.response_helper(component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
self._responses[component_id] = ret
return self | [
"def",
"response",
"(",
"self",
",",
"component_id",
",",
"component",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"component_id",
"in",
"self",
".",
"_responses",
":",
"raise",
"DuplicateComponentNameError",
"(",
"'Another response with name \"{}\" is a... | Add a response which can be referenced.
:param str component_id: ref_id to use as reference
:param dict component: response fields
:param dict kwargs: plugin-specific arguments | [
"Add",
"a",
"response",
"which",
"can",
"be",
"referenced",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L176-L198 | train | 224,511 |
marshmallow-code/apispec | src/apispec/core.py | Components.security_scheme | def security_scheme(self, component_id, component):
"""Add a security scheme which can be referenced.
:param str component_id: component_id to use as reference
:param dict kwargs: security scheme fields
"""
if component_id in self._security_schemes:
raise DuplicateComponentNameError(
'Another security scheme with name "{}" is already registered.'.format(
component_id
)
)
self._security_schemes[component_id] = component
return self | python | def security_scheme(self, component_id, component):
"""Add a security scheme which can be referenced.
:param str component_id: component_id to use as reference
:param dict kwargs: security scheme fields
"""
if component_id in self._security_schemes:
raise DuplicateComponentNameError(
'Another security scheme with name "{}" is already registered.'.format(
component_id
)
)
self._security_schemes[component_id] = component
return self | [
"def",
"security_scheme",
"(",
"self",
",",
"component_id",
",",
"component",
")",
":",
"if",
"component_id",
"in",
"self",
".",
"_security_schemes",
":",
"raise",
"DuplicateComponentNameError",
"(",
"'Another security scheme with name \"{}\" is already registered.'",
".",
... | Add a security scheme which can be referenced.
:param str component_id: component_id to use as reference
:param dict kwargs: security scheme fields | [
"Add",
"a",
"security",
"scheme",
"which",
"can",
"be",
"referenced",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L200-L213 | train | 224,512 |
marshmallow-code/apispec | src/apispec/core.py | APISpec.path | def path(
self, path=None, operations=None, summary=None, description=None, **kwargs
):
"""Add a new path object to the spec.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#path-item-object
:param str|None path: URL path component
:param dict|None operations: describes the http methods and options for `path`
:param str summary: short summary relevant to all operations in this path
:param str description: long description relevant to all operations in this path
:param dict kwargs: parameters used by any path helpers see :meth:`register_path_helper`
"""
operations = operations or OrderedDict()
# Execute path helpers
for plugin in self.plugins:
try:
ret = plugin.path_helper(path=path, operations=operations, **kwargs)
except PluginMethodNotImplementedError:
continue
if ret is not None:
path = ret
if not path:
raise APISpecError("Path template is not specified.")
# Execute operation helpers
for plugin in self.plugins:
try:
plugin.operation_helper(path=path, operations=operations, **kwargs)
except PluginMethodNotImplementedError:
continue
clean_operations(operations, self.openapi_version.major)
self._paths.setdefault(path, operations).update(operations)
if summary is not None:
self._paths[path]["summary"] = summary
if description is not None:
self._paths[path]["description"] = description
return self | python | def path(
self, path=None, operations=None, summary=None, description=None, **kwargs
):
"""Add a new path object to the spec.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#path-item-object
:param str|None path: URL path component
:param dict|None operations: describes the http methods and options for `path`
:param str summary: short summary relevant to all operations in this path
:param str description: long description relevant to all operations in this path
:param dict kwargs: parameters used by any path helpers see :meth:`register_path_helper`
"""
operations = operations or OrderedDict()
# Execute path helpers
for plugin in self.plugins:
try:
ret = plugin.path_helper(path=path, operations=operations, **kwargs)
except PluginMethodNotImplementedError:
continue
if ret is not None:
path = ret
if not path:
raise APISpecError("Path template is not specified.")
# Execute operation helpers
for plugin in self.plugins:
try:
plugin.operation_helper(path=path, operations=operations, **kwargs)
except PluginMethodNotImplementedError:
continue
clean_operations(operations, self.openapi_version.major)
self._paths.setdefault(path, operations).update(operations)
if summary is not None:
self._paths[path]["summary"] = summary
if description is not None:
self._paths[path]["description"] = description
return self | [
"def",
"path",
"(",
"self",
",",
"path",
"=",
"None",
",",
"operations",
"=",
"None",
",",
"summary",
"=",
"None",
",",
"description",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"operations",
"=",
"operations",
"or",
"OrderedDict",
"(",
")",
"# ... | Add a new path object to the spec.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#path-item-object
:param str|None path: URL path component
:param dict|None operations: describes the http methods and options for `path`
:param str summary: short summary relevant to all operations in this path
:param str description: long description relevant to all operations in this path
:param dict kwargs: parameters used by any path helpers see :meth:`register_path_helper` | [
"Add",
"a",
"new",
"path",
"object",
"to",
"the",
"spec",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L279-L319 | train | 224,513 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/__init__.py | resolver | def resolver(schema):
"""Default implementation of a schema name resolver function
"""
name = schema.__name__
if name.endswith("Schema"):
return name[:-6] or name
return name | python | def resolver(schema):
"""Default implementation of a schema name resolver function
"""
name = schema.__name__
if name.endswith("Schema"):
return name[:-6] or name
return name | [
"def",
"resolver",
"(",
"schema",
")",
":",
"name",
"=",
"schema",
".",
"__name__",
"if",
"name",
".",
"endswith",
"(",
"\"Schema\"",
")",
":",
"return",
"name",
"[",
":",
"-",
"6",
"]",
"or",
"name",
"return",
"name"
] | Default implementation of a schema name resolver function | [
"Default",
"implementation",
"of",
"a",
"schema",
"name",
"resolver",
"function"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/__init__.py#L43-L49 | train | 224,514 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/__init__.py | MarshmallowPlugin.resolve_schema_in_request_body | def resolve_schema_in_request_body(self, request_body):
"""Function to resolve a schema in a requestBody object - modifies then
response dict to convert Marshmallow Schema object or class into dict
"""
content = request_body["content"]
for content_type in content:
schema = content[content_type]["schema"]
content[content_type]["schema"] = self.openapi.resolve_schema_dict(schema) | python | def resolve_schema_in_request_body(self, request_body):
"""Function to resolve a schema in a requestBody object - modifies then
response dict to convert Marshmallow Schema object or class into dict
"""
content = request_body["content"]
for content_type in content:
schema = content[content_type]["schema"]
content[content_type]["schema"] = self.openapi.resolve_schema_dict(schema) | [
"def",
"resolve_schema_in_request_body",
"(",
"self",
",",
"request_body",
")",
":",
"content",
"=",
"request_body",
"[",
"\"content\"",
"]",
"for",
"content_type",
"in",
"content",
":",
"schema",
"=",
"content",
"[",
"content_type",
"]",
"[",
"\"schema\"",
"]",... | Function to resolve a schema in a requestBody object - modifies then
response dict to convert Marshmallow Schema object or class into dict | [
"Function",
"to",
"resolve",
"a",
"schema",
"in",
"a",
"requestBody",
"object",
"-",
"modifies",
"then",
"response",
"dict",
"to",
"convert",
"Marshmallow",
"Schema",
"object",
"or",
"class",
"into",
"dict"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/__init__.py#L100-L107 | train | 224,515 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/__init__.py | MarshmallowPlugin.resolve_schema | def resolve_schema(self, data):
"""Function to resolve a schema in a parameter or response - modifies the
corresponding dict to convert Marshmallow Schema object or class into dict
:param APISpec spec: `APISpec` containing refs.
:param dict|str data: either a parameter or response dictionary that may
contain a schema, or a reference provided as string
"""
if not isinstance(data, dict):
return
# OAS 2 component or OAS 3 header
if "schema" in data:
data["schema"] = self.openapi.resolve_schema_dict(data["schema"])
# OAS 3 component except header
if self.openapi_version.major >= 3:
if "content" in data:
for content_type in data["content"]:
schema = data["content"][content_type]["schema"]
data["content"][content_type][
"schema"
] = self.openapi.resolve_schema_dict(schema) | python | def resolve_schema(self, data):
"""Function to resolve a schema in a parameter or response - modifies the
corresponding dict to convert Marshmallow Schema object or class into dict
:param APISpec spec: `APISpec` containing refs.
:param dict|str data: either a parameter or response dictionary that may
contain a schema, or a reference provided as string
"""
if not isinstance(data, dict):
return
# OAS 2 component or OAS 3 header
if "schema" in data:
data["schema"] = self.openapi.resolve_schema_dict(data["schema"])
# OAS 3 component except header
if self.openapi_version.major >= 3:
if "content" in data:
for content_type in data["content"]:
schema = data["content"][content_type]["schema"]
data["content"][content_type][
"schema"
] = self.openapi.resolve_schema_dict(schema) | [
"def",
"resolve_schema",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"return",
"# OAS 2 component or OAS 3 header",
"if",
"\"schema\"",
"in",
"data",
":",
"data",
"[",
"\"schema\"",
"]",
"=",
"self",
"... | Function to resolve a schema in a parameter or response - modifies the
corresponding dict to convert Marshmallow Schema object or class into dict
:param APISpec spec: `APISpec` containing refs.
:param dict|str data: either a parameter or response dictionary that may
contain a schema, or a reference provided as string | [
"Function",
"to",
"resolve",
"a",
"schema",
"in",
"a",
"parameter",
"or",
"response",
"-",
"modifies",
"the",
"corresponding",
"dict",
"to",
"convert",
"Marshmallow",
"Schema",
"object",
"or",
"class",
"into",
"dict"
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/__init__.py#L109-L130 | train | 224,516 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/__init__.py | MarshmallowPlugin.warn_if_schema_already_in_spec | def warn_if_schema_already_in_spec(self, schema_key):
"""Method to warn the user if the schema has already been added to the
spec.
"""
if schema_key in self.openapi.refs:
warnings.warn(
"{} has already been added to the spec. Adding it twice may "
"cause references to not resolve properly.".format(schema_key[0]),
UserWarning,
) | python | def warn_if_schema_already_in_spec(self, schema_key):
"""Method to warn the user if the schema has already been added to the
spec.
"""
if schema_key in self.openapi.refs:
warnings.warn(
"{} has already been added to the spec. Adding it twice may "
"cause references to not resolve properly.".format(schema_key[0]),
UserWarning,
) | [
"def",
"warn_if_schema_already_in_spec",
"(",
"self",
",",
"schema_key",
")",
":",
"if",
"schema_key",
"in",
"self",
".",
"openapi",
".",
"refs",
":",
"warnings",
".",
"warn",
"(",
"\"{} has already been added to the spec. Adding it twice may \"",
"\"cause references to n... | Method to warn the user if the schema has already been added to the
spec. | [
"Method",
"to",
"warn",
"the",
"user",
"if",
"the",
"schema",
"has",
"already",
"been",
"added",
"to",
"the",
"spec",
"."
] | e92ceffd12b2e392b8d199ed314bd2a7e6512dff | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/__init__.py#L213-L222 | train | 224,517 |
flyingrub/scdl | scdl/utils.py | size_in_bytes | def size_in_bytes(insize):
"""
Returns the size in bytes from strings such as '5 mb' into 5242880.
>>> size_in_bytes('1m')
1048576
>>> size_in_bytes('1.5m')
1572864
>>> size_in_bytes('2g')
2147483648
>>> size_in_bytes(None)
Traceback (most recent call last):
raise ValueError('no string specified')
ValueError: no string specified
>>> size_in_bytes('')
Traceback (most recent call last):
raise ValueError('no string specified')
ValueError: no string specified
"""
if insize is None or insize.strip() == '':
raise ValueError('no string specified')
units = {
'k': 1024,
'm': 1024 ** 2,
'g': 1024 ** 3,
't': 1024 ** 4,
'p': 1024 ** 5,
}
match = re.search('^\s*([0-9\.]+)\s*([kmgtp])?', insize, re.I)
if match is None:
raise ValueError('match not found')
size, unit = match.groups()
if size:
size = float(size)
if unit:
size = size * units[unit.lower().strip()]
return int(size) | python | def size_in_bytes(insize):
"""
Returns the size in bytes from strings such as '5 mb' into 5242880.
>>> size_in_bytes('1m')
1048576
>>> size_in_bytes('1.5m')
1572864
>>> size_in_bytes('2g')
2147483648
>>> size_in_bytes(None)
Traceback (most recent call last):
raise ValueError('no string specified')
ValueError: no string specified
>>> size_in_bytes('')
Traceback (most recent call last):
raise ValueError('no string specified')
ValueError: no string specified
"""
if insize is None or insize.strip() == '':
raise ValueError('no string specified')
units = {
'k': 1024,
'm': 1024 ** 2,
'g': 1024 ** 3,
't': 1024 ** 4,
'p': 1024 ** 5,
}
match = re.search('^\s*([0-9\.]+)\s*([kmgtp])?', insize, re.I)
if match is None:
raise ValueError('match not found')
size, unit = match.groups()
if size:
size = float(size)
if unit:
size = size * units[unit.lower().strip()]
return int(size) | [
"def",
"size_in_bytes",
"(",
"insize",
")",
":",
"if",
"insize",
"is",
"None",
"or",
"insize",
".",
"strip",
"(",
")",
"==",
"''",
":",
"raise",
"ValueError",
"(",
"'no string specified'",
")",
"units",
"=",
"{",
"'k'",
":",
"1024",
",",
"'m'",
":",
... | Returns the size in bytes from strings such as '5 mb' into 5242880.
>>> size_in_bytes('1m')
1048576
>>> size_in_bytes('1.5m')
1572864
>>> size_in_bytes('2g')
2147483648
>>> size_in_bytes(None)
Traceback (most recent call last):
raise ValueError('no string specified')
ValueError: no string specified
>>> size_in_bytes('')
Traceback (most recent call last):
raise ValueError('no string specified')
ValueError: no string specified | [
"Returns",
"the",
"size",
"in",
"bytes",
"from",
"strings",
"such",
"as",
"5",
"mb",
"into",
"5242880",
"."
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/utils.py#L31-L73 | train | 224,518 |
flyingrub/scdl | scdl/scdl.py | main | def main():
"""
Main function, parses the URL from command line arguments
"""
signal.signal(signal.SIGINT, signal_handler)
global offset
global arguments
# Parse argument
arguments = docopt(__doc__, version=__version__)
if arguments['--debug']:
logger.level = logging.DEBUG
elif arguments['--error']:
logger.level = logging.ERROR
# import conf file
get_config()
logger.info('Soundcloud Downloader')
logger.debug(arguments)
if arguments['-o'] is not None:
try:
offset = int(arguments['-o'])
if offset < 0:
raise
except:
logger.error('Offset should be a positive integer...')
sys.exit()
logger.debug('offset: %d', offset)
if arguments['--min-size'] is not None:
try:
arguments['--min-size'] = utils.size_in_bytes(
arguments['--min-size']
)
except:
logger.exception(
'Min size should be an integer with a possible unit suffix'
)
sys.exit()
logger.debug('min-size: %d', arguments['--min-size'])
if arguments['--max-size'] is not None:
try:
arguments['--max-size'] = utils.size_in_bytes(
arguments['--max-size']
)
except:
logger.error(
'Max size should be an integer with a possible unit suffix'
)
sys.exit()
logger.debug('max-size: %d', arguments['--max-size'])
if arguments['--hidewarnings']:
warnings.filterwarnings('ignore')
if arguments['--path'] is not None:
if os.path.exists(arguments['--path']):
os.chdir(arguments['--path'])
else:
logger.error('Invalid path in arguments...')
sys.exit()
logger.debug('Downloading to '+os.getcwd()+'...')
if arguments['-l']:
parse_url(arguments['-l'])
elif arguments['me']:
if arguments['-f']:
download(who_am_i(), 'favorites', 'likes')
if arguments['-C']:
download(who_am_i(), 'commented', 'commented tracks')
elif arguments['-t']:
download(who_am_i(), 'tracks', 'uploaded tracks')
elif arguments['-a']:
download(who_am_i(), 'all', 'tracks and reposts')
elif arguments['-p']:
download(who_am_i(), 'playlists', 'playlists')
elif arguments['-m']:
download(who_am_i(), 'playlists-liked', 'my and liked playlists')
if arguments['--remove']:
remove_files() | python | def main():
"""
Main function, parses the URL from command line arguments
"""
signal.signal(signal.SIGINT, signal_handler)
global offset
global arguments
# Parse argument
arguments = docopt(__doc__, version=__version__)
if arguments['--debug']:
logger.level = logging.DEBUG
elif arguments['--error']:
logger.level = logging.ERROR
# import conf file
get_config()
logger.info('Soundcloud Downloader')
logger.debug(arguments)
if arguments['-o'] is not None:
try:
offset = int(arguments['-o'])
if offset < 0:
raise
except:
logger.error('Offset should be a positive integer...')
sys.exit()
logger.debug('offset: %d', offset)
if arguments['--min-size'] is not None:
try:
arguments['--min-size'] = utils.size_in_bytes(
arguments['--min-size']
)
except:
logger.exception(
'Min size should be an integer with a possible unit suffix'
)
sys.exit()
logger.debug('min-size: %d', arguments['--min-size'])
if arguments['--max-size'] is not None:
try:
arguments['--max-size'] = utils.size_in_bytes(
arguments['--max-size']
)
except:
logger.error(
'Max size should be an integer with a possible unit suffix'
)
sys.exit()
logger.debug('max-size: %d', arguments['--max-size'])
if arguments['--hidewarnings']:
warnings.filterwarnings('ignore')
if arguments['--path'] is not None:
if os.path.exists(arguments['--path']):
os.chdir(arguments['--path'])
else:
logger.error('Invalid path in arguments...')
sys.exit()
logger.debug('Downloading to '+os.getcwd()+'...')
if arguments['-l']:
parse_url(arguments['-l'])
elif arguments['me']:
if arguments['-f']:
download(who_am_i(), 'favorites', 'likes')
if arguments['-C']:
download(who_am_i(), 'commented', 'commented tracks')
elif arguments['-t']:
download(who_am_i(), 'tracks', 'uploaded tracks')
elif arguments['-a']:
download(who_am_i(), 'all', 'tracks and reposts')
elif arguments['-p']:
download(who_am_i(), 'playlists', 'playlists')
elif arguments['-m']:
download(who_am_i(), 'playlists-liked', 'my and liked playlists')
if arguments['--remove']:
remove_files() | [
"def",
"main",
"(",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal_handler",
")",
"global",
"offset",
"global",
"arguments",
"# Parse argument",
"arguments",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"__version__",
")... | Main function, parses the URL from command line arguments | [
"Main",
"function",
"parses",
"the",
"URL",
"from",
"command",
"line",
"arguments"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L111-L195 | train | 224,519 |
flyingrub/scdl | scdl/scdl.py | get_config | def get_config():
"""
Reads the music download filepath from scdl.cfg
"""
global token
config = configparser.ConfigParser()
config.read(os.path.join(os.path.expanduser('~'), '.config/scdl/scdl.cfg'))
try:
token = config['scdl']['auth_token']
path = config['scdl']['path']
except:
logger.error('Are you sure scdl.cfg is in $HOME/.config/scdl/ ?')
logger.error('Are both "auth_token" and "path" defined there?')
sys.exit()
if os.path.exists(path):
os.chdir(path)
else:
logger.error('Invalid path in scdl.cfg...')
sys.exit() | python | def get_config():
"""
Reads the music download filepath from scdl.cfg
"""
global token
config = configparser.ConfigParser()
config.read(os.path.join(os.path.expanduser('~'), '.config/scdl/scdl.cfg'))
try:
token = config['scdl']['auth_token']
path = config['scdl']['path']
except:
logger.error('Are you sure scdl.cfg is in $HOME/.config/scdl/ ?')
logger.error('Are both "auth_token" and "path" defined there?')
sys.exit()
if os.path.exists(path):
os.chdir(path)
else:
logger.error('Invalid path in scdl.cfg...')
sys.exit() | [
"def",
"get_config",
"(",
")",
":",
"global",
"token",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'.confi... | Reads the music download filepath from scdl.cfg | [
"Reads",
"the",
"music",
"download",
"filepath",
"from",
"scdl",
".",
"cfg"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L198-L216 | train | 224,520 |
flyingrub/scdl | scdl/scdl.py | get_item | def get_item(track_url, client_id=CLIENT_ID):
"""
Fetches metadata for a track or playlist
"""
try:
item_url = url['resolve'].format(track_url)
r = requests.get(item_url, params={'client_id': client_id})
logger.debug(r.url)
if r.status_code == 403:
return get_item(track_url, ALT_CLIENT_ID)
item = r.json()
no_tracks = item['kind'] == 'playlist' and not item['tracks']
if no_tracks and client_id != ALT_CLIENT_ID:
return get_item(track_url, ALT_CLIENT_ID)
except Exception:
if client_id == ALT_CLIENT_ID:
logger.error('Failed to get item...')
return
logger.error('Error resolving url, retrying...')
time.sleep(5)
try:
return get_item(track_url, ALT_CLIENT_ID)
except Exception as e:
logger.error('Could not resolve url {0}'.format(track_url))
logger.exception(e)
sys.exit(0)
return item | python | def get_item(track_url, client_id=CLIENT_ID):
"""
Fetches metadata for a track or playlist
"""
try:
item_url = url['resolve'].format(track_url)
r = requests.get(item_url, params={'client_id': client_id})
logger.debug(r.url)
if r.status_code == 403:
return get_item(track_url, ALT_CLIENT_ID)
item = r.json()
no_tracks = item['kind'] == 'playlist' and not item['tracks']
if no_tracks and client_id != ALT_CLIENT_ID:
return get_item(track_url, ALT_CLIENT_ID)
except Exception:
if client_id == ALT_CLIENT_ID:
logger.error('Failed to get item...')
return
logger.error('Error resolving url, retrying...')
time.sleep(5)
try:
return get_item(track_url, ALT_CLIENT_ID)
except Exception as e:
logger.error('Could not resolve url {0}'.format(track_url))
logger.exception(e)
sys.exit(0)
return item | [
"def",
"get_item",
"(",
"track_url",
",",
"client_id",
"=",
"CLIENT_ID",
")",
":",
"try",
":",
"item_url",
"=",
"url",
"[",
"'resolve'",
"]",
".",
"format",
"(",
"track_url",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"item_url",
",",
"params",
"=",
... | Fetches metadata for a track or playlist | [
"Fetches",
"metadata",
"for",
"a",
"track",
"or",
"playlist"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L219-L247 | train | 224,521 |
flyingrub/scdl | scdl/scdl.py | who_am_i | def who_am_i():
"""
Display username from current token and check for validity
"""
me = url['me'].format(token)
r = requests.get(me, params={'client_id': CLIENT_ID})
r.raise_for_status()
current_user = r.json()
logger.debug(me)
logger.info('Hello {0}!'.format(current_user['username']))
return current_user | python | def who_am_i():
"""
Display username from current token and check for validity
"""
me = url['me'].format(token)
r = requests.get(me, params={'client_id': CLIENT_ID})
r.raise_for_status()
current_user = r.json()
logger.debug(me)
logger.info('Hello {0}!'.format(current_user['username']))
return current_user | [
"def",
"who_am_i",
"(",
")",
":",
"me",
"=",
"url",
"[",
"'me'",
"]",
".",
"format",
"(",
"token",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"me",
",",
"params",
"=",
"{",
"'client_id'",
":",
"CLIENT_ID",
"}",
")",
"r",
".",
"raise_for_status",
... | Display username from current token and check for validity | [
"Display",
"username",
"from",
"current",
"token",
"and",
"check",
"for",
"validity"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L286-L297 | train | 224,522 |
flyingrub/scdl | scdl/scdl.py | remove_files | def remove_files():
"""
Removes any pre-existing tracks that were not just downloaded
"""
logger.info("Removing local track files that were not downloaded...")
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
if f not in fileToKeep:
os.remove(f) | python | def remove_files():
"""
Removes any pre-existing tracks that were not just downloaded
"""
logger.info("Removing local track files that were not downloaded...")
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
if f not in fileToKeep:
os.remove(f) | [
"def",
"remove_files",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"Removing local track files that were not downloaded...\"",
")",
"files",
"=",
"[",
"f",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"'.'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(... | Removes any pre-existing tracks that were not just downloaded | [
"Removes",
"any",
"pre",
"-",
"existing",
"tracks",
"that",
"were",
"not",
"just",
"downloaded"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L300-L308 | train | 224,523 |
flyingrub/scdl | scdl/scdl.py | get_track_info | def get_track_info(track_id):
"""
Fetches track info from Soundcloud, given a track_id
"""
logger.info('Retrieving more info on the track')
info_url = url["trackinfo"].format(track_id)
r = requests.get(info_url, params={'client_id': CLIENT_ID}, stream=True)
item = r.json()
logger.debug(item)
return item | python | def get_track_info(track_id):
"""
Fetches track info from Soundcloud, given a track_id
"""
logger.info('Retrieving more info on the track')
info_url = url["trackinfo"].format(track_id)
r = requests.get(info_url, params={'client_id': CLIENT_ID}, stream=True)
item = r.json()
logger.debug(item)
return item | [
"def",
"get_track_info",
"(",
"track_id",
")",
":",
"logger",
".",
"info",
"(",
"'Retrieving more info on the track'",
")",
"info_url",
"=",
"url",
"[",
"\"trackinfo\"",
"]",
".",
"format",
"(",
"track_id",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"info_u... | Fetches track info from Soundcloud, given a track_id | [
"Fetches",
"track",
"info",
"from",
"Soundcloud",
"given",
"a",
"track_id"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L311-L320 | train | 224,524 |
flyingrub/scdl | scdl/scdl.py | already_downloaded | def already_downloaded(track, title, filename):
"""
Returns True if the file has already been downloaded
"""
global arguments
already_downloaded = False
if os.path.isfile(filename):
already_downloaded = True
if arguments['--flac'] and can_convert(filename) \
and os.path.isfile(filename[:-4] + ".flac"):
already_downloaded = True
if arguments['--download-archive'] and in_download_archive(track):
already_downloaded = True
if arguments['--flac'] and can_convert(filename) and os.path.isfile(filename):
already_downloaded = False
if already_downloaded:
if arguments['-c'] or arguments['--remove']:
logger.info('Track "{0}" already downloaded.'.format(title))
return True
else:
logger.error('Track "{0}" already exists!'.format(title))
logger.error('Exiting... (run again with -c to continue)')
sys.exit(0)
return False | python | def already_downloaded(track, title, filename):
"""
Returns True if the file has already been downloaded
"""
global arguments
already_downloaded = False
if os.path.isfile(filename):
already_downloaded = True
if arguments['--flac'] and can_convert(filename) \
and os.path.isfile(filename[:-4] + ".flac"):
already_downloaded = True
if arguments['--download-archive'] and in_download_archive(track):
already_downloaded = True
if arguments['--flac'] and can_convert(filename) and os.path.isfile(filename):
already_downloaded = False
if already_downloaded:
if arguments['-c'] or arguments['--remove']:
logger.info('Track "{0}" already downloaded.'.format(title))
return True
else:
logger.error('Track "{0}" already exists!'.format(title))
logger.error('Exiting... (run again with -c to continue)')
sys.exit(0)
return False | [
"def",
"already_downloaded",
"(",
"track",
",",
"title",
",",
"filename",
")",
":",
"global",
"arguments",
"already_downloaded",
"=",
"False",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"already_downloaded",
"=",
"True",
"if",
"argume... | Returns True if the file has already been downloaded | [
"Returns",
"True",
"if",
"the",
"file",
"has",
"already",
"been",
"downloaded"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L562-L588 | train | 224,525 |
flyingrub/scdl | scdl/scdl.py | in_download_archive | def in_download_archive(track):
"""
Returns True if a track_id exists in the download archive
"""
global arguments
if not arguments['--download-archive']:
return
archive_filename = arguments.get('--download-archive')
try:
with open(archive_filename, 'a+', encoding='utf-8') as file:
logger.debug('Contents of {0}:'.format(archive_filename))
file.seek(0)
track_id = '{0}'.format(track['id'])
for line in file:
logger.debug('"'+line.strip()+'"')
if line.strip() == track_id:
return True
except IOError as ioe:
logger.error('Error trying to read download archive...')
logger.debug(ioe)
return False | python | def in_download_archive(track):
"""
Returns True if a track_id exists in the download archive
"""
global arguments
if not arguments['--download-archive']:
return
archive_filename = arguments.get('--download-archive')
try:
with open(archive_filename, 'a+', encoding='utf-8') as file:
logger.debug('Contents of {0}:'.format(archive_filename))
file.seek(0)
track_id = '{0}'.format(track['id'])
for line in file:
logger.debug('"'+line.strip()+'"')
if line.strip() == track_id:
return True
except IOError as ioe:
logger.error('Error trying to read download archive...')
logger.debug(ioe)
return False | [
"def",
"in_download_archive",
"(",
"track",
")",
":",
"global",
"arguments",
"if",
"not",
"arguments",
"[",
"'--download-archive'",
"]",
":",
"return",
"archive_filename",
"=",
"arguments",
".",
"get",
"(",
"'--download-archive'",
")",
"try",
":",
"with",
"open"... | Returns True if a track_id exists in the download archive | [
"Returns",
"True",
"if",
"a",
"track_id",
"exists",
"in",
"the",
"download",
"archive"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L591-L613 | train | 224,526 |
flyingrub/scdl | scdl/scdl.py | record_download_archive | def record_download_archive(track):
"""
Write the track_id in the download archive
"""
global arguments
if not arguments['--download-archive']:
return
archive_filename = arguments.get('--download-archive')
try:
with open(archive_filename, 'a', encoding='utf-8') as file:
file.write('{0}'.format(track['id'])+'\n')
except IOError as ioe:
logger.error('Error trying to write to download archive...')
logger.debug(ioe) | python | def record_download_archive(track):
"""
Write the track_id in the download archive
"""
global arguments
if not arguments['--download-archive']:
return
archive_filename = arguments.get('--download-archive')
try:
with open(archive_filename, 'a', encoding='utf-8') as file:
file.write('{0}'.format(track['id'])+'\n')
except IOError as ioe:
logger.error('Error trying to write to download archive...')
logger.debug(ioe) | [
"def",
"record_download_archive",
"(",
"track",
")",
":",
"global",
"arguments",
"if",
"not",
"arguments",
"[",
"'--download-archive'",
"]",
":",
"return",
"archive_filename",
"=",
"arguments",
".",
"get",
"(",
"'--download-archive'",
")",
"try",
":",
"with",
"o... | Write the track_id in the download archive | [
"Write",
"the",
"track_id",
"in",
"the",
"download",
"archive"
] | e833a22dd6676311b72fadd8a1c80f4a06acfad9 | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L616-L630 | train | 224,527 |
lins05/slackbot | slackbot/dispatcher.py | unicode_compact | def unicode_compact(func):
"""
Make sure the first parameter of the decorated method to be a unicode
object.
"""
@wraps(func)
def wrapped(self, text, *a, **kw):
if not isinstance(text, six.text_type):
text = text.decode('utf-8')
return func(self, text, *a, **kw)
return wrapped | python | def unicode_compact(func):
"""
Make sure the first parameter of the decorated method to be a unicode
object.
"""
@wraps(func)
def wrapped(self, text, *a, **kw):
if not isinstance(text, six.text_type):
text = text.decode('utf-8')
return func(self, text, *a, **kw)
return wrapped | [
"def",
"unicode_compact",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"self",
",",
"text",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"isinstance",
"(",
"text",
",",
"six",
".",
"text_type",
")",
... | Make sure the first parameter of the decorated method to be a unicode
object. | [
"Make",
"sure",
"the",
"first",
"parameter",
"of",
"the",
"decorated",
"method",
"to",
"be",
"a",
"unicode",
"object",
"."
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L173-L185 | train | 224,528 |
lins05/slackbot | slackbot/dispatcher.py | Message.reply_webapi | def reply_webapi(self, text, attachments=None, as_user=True, in_thread=None):
"""
Send a reply to the sender using Web API
(This function supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default.
"""
if in_thread is None:
in_thread = 'thread_ts' in self.body
if in_thread:
self.send_webapi(text, attachments=attachments, as_user=as_user, thread_ts=self.thread_ts)
else:
text = self.gen_reply(text)
self.send_webapi(text, attachments=attachments, as_user=as_user) | python | def reply_webapi(self, text, attachments=None, as_user=True, in_thread=None):
"""
Send a reply to the sender using Web API
(This function supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default.
"""
if in_thread is None:
in_thread = 'thread_ts' in self.body
if in_thread:
self.send_webapi(text, attachments=attachments, as_user=as_user, thread_ts=self.thread_ts)
else:
text = self.gen_reply(text)
self.send_webapi(text, attachments=attachments, as_user=as_user) | [
"def",
"reply_webapi",
"(",
"self",
",",
"text",
",",
"attachments",
"=",
"None",
",",
"as_user",
"=",
"True",
",",
"in_thread",
"=",
"None",
")",
":",
"if",
"in_thread",
"is",
"None",
":",
"in_thread",
"=",
"'thread_ts'",
"in",
"self",
".",
"body",
"i... | Send a reply to the sender using Web API
(This function supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default. | [
"Send",
"a",
"reply",
"to",
"the",
"sender",
"using",
"Web",
"API"
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L214-L230 | train | 224,529 |
lins05/slackbot | slackbot/dispatcher.py | Message.send_webapi | def send_webapi(self, text, attachments=None, as_user=True, thread_ts=None):
"""
Send a reply using Web API
(This function supports formatted message
when using a bot integration)
"""
self._client.send_message(
self._body['channel'],
text,
attachments=attachments,
as_user=as_user,
thread_ts=thread_ts) | python | def send_webapi(self, text, attachments=None, as_user=True, thread_ts=None):
"""
Send a reply using Web API
(This function supports formatted message
when using a bot integration)
"""
self._client.send_message(
self._body['channel'],
text,
attachments=attachments,
as_user=as_user,
thread_ts=thread_ts) | [
"def",
"send_webapi",
"(",
"self",
",",
"text",
",",
"attachments",
"=",
"None",
",",
"as_user",
"=",
"True",
",",
"thread_ts",
"=",
"None",
")",
":",
"self",
".",
"_client",
".",
"send_message",
"(",
"self",
".",
"_body",
"[",
"'channel'",
"]",
",",
... | Send a reply using Web API
(This function supports formatted message
when using a bot integration) | [
"Send",
"a",
"reply",
"using",
"Web",
"API"
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L233-L245 | train | 224,530 |
lins05/slackbot | slackbot/dispatcher.py | Message.reply | def reply(self, text, in_thread=None):
"""
Send a reply to the sender using RTM API
(This function doesn't supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default.
"""
if in_thread is None:
in_thread = 'thread_ts' in self.body
if in_thread:
self.send(text, thread_ts=self.thread_ts)
else:
text = self.gen_reply(text)
self.send(text) | python | def reply(self, text, in_thread=None):
"""
Send a reply to the sender using RTM API
(This function doesn't supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default.
"""
if in_thread is None:
in_thread = 'thread_ts' in self.body
if in_thread:
self.send(text, thread_ts=self.thread_ts)
else:
text = self.gen_reply(text)
self.send(text) | [
"def",
"reply",
"(",
"self",
",",
"text",
",",
"in_thread",
"=",
"None",
")",
":",
"if",
"in_thread",
"is",
"None",
":",
"in_thread",
"=",
"'thread_ts'",
"in",
"self",
".",
"body",
"if",
"in_thread",
":",
"self",
".",
"send",
"(",
"text",
",",
"threa... | Send a reply to the sender using RTM API
(This function doesn't supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default. | [
"Send",
"a",
"reply",
"to",
"the",
"sender",
"using",
"RTM",
"API"
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L248-L264 | train | 224,531 |
lins05/slackbot | slackbot/dispatcher.py | Message.direct_reply | def direct_reply(self, text):
"""
Send a reply via direct message using RTM API
"""
channel_id = self._client.open_dm_channel(self._get_user_id())
self._client.rtm_send_message(channel_id, text) | python | def direct_reply(self, text):
"""
Send a reply via direct message using RTM API
"""
channel_id = self._client.open_dm_channel(self._get_user_id())
self._client.rtm_send_message(channel_id, text) | [
"def",
"direct_reply",
"(",
"self",
",",
"text",
")",
":",
"channel_id",
"=",
"self",
".",
"_client",
".",
"open_dm_channel",
"(",
"self",
".",
"_get_user_id",
"(",
")",
")",
"self",
".",
"_client",
".",
"rtm_send_message",
"(",
"channel_id",
",",
"text",
... | Send a reply via direct message using RTM API | [
"Send",
"a",
"reply",
"via",
"direct",
"message",
"using",
"RTM",
"API"
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L267-L273 | train | 224,532 |
lins05/slackbot | slackbot/dispatcher.py | Message.send | def send(self, text, thread_ts=None):
"""
Send a reply using RTM API
(This function doesn't supports formatted message
when using a bot integration)
"""
self._client.rtm_send_message(self._body['channel'], text, thread_ts=thread_ts) | python | def send(self, text, thread_ts=None):
"""
Send a reply using RTM API
(This function doesn't supports formatted message
when using a bot integration)
"""
self._client.rtm_send_message(self._body['channel'], text, thread_ts=thread_ts) | [
"def",
"send",
"(",
"self",
",",
"text",
",",
"thread_ts",
"=",
"None",
")",
":",
"self",
".",
"_client",
".",
"rtm_send_message",
"(",
"self",
".",
"_body",
"[",
"'channel'",
"]",
",",
"text",
",",
"thread_ts",
"=",
"thread_ts",
")"
] | Send a reply using RTM API
(This function doesn't supports formatted message
when using a bot integration) | [
"Send",
"a",
"reply",
"using",
"RTM",
"API"
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L277-L284 | train | 224,533 |
lins05/slackbot | slackbot/dispatcher.py | Message.react | def react(self, emojiname):
"""
React to a message using the web api
"""
self._client.react_to_message(
emojiname=emojiname,
channel=self._body['channel'],
timestamp=self._body['ts']) | python | def react(self, emojiname):
"""
React to a message using the web api
"""
self._client.react_to_message(
emojiname=emojiname,
channel=self._body['channel'],
timestamp=self._body['ts']) | [
"def",
"react",
"(",
"self",
",",
"emojiname",
")",
":",
"self",
".",
"_client",
".",
"react_to_message",
"(",
"emojiname",
"=",
"emojiname",
",",
"channel",
"=",
"self",
".",
"_body",
"[",
"'channel'",
"]",
",",
"timestamp",
"=",
"self",
".",
"_body",
... | React to a message using the web api | [
"React",
"to",
"a",
"message",
"using",
"the",
"web",
"api"
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/dispatcher.py#L286-L293 | train | 224,534 |
lins05/slackbot | slackbot/bot.py | default_reply | def default_reply(*args, **kwargs):
"""
Decorator declaring the wrapped function to the default reply hanlder.
May be invoked as a simple, argument-less decorator (i.e. ``@default_reply``) or
with arguments customizing its behavior (e.g. ``@default_reply(matchstr='pattern')``).
"""
invoked = bool(not args or kwargs)
matchstr = kwargs.pop('matchstr', r'^.*$')
flags = kwargs.pop('flags', 0)
if not invoked:
func = args[0]
def wrapper(func):
PluginsManager.commands['default_reply'][
re.compile(matchstr, flags)] = func
logger.info('registered default_reply plugin "%s" to "%s"', func.__name__,
matchstr)
return func
return wrapper if invoked else wrapper(func) | python | def default_reply(*args, **kwargs):
"""
Decorator declaring the wrapped function to the default reply hanlder.
May be invoked as a simple, argument-less decorator (i.e. ``@default_reply``) or
with arguments customizing its behavior (e.g. ``@default_reply(matchstr='pattern')``).
"""
invoked = bool(not args or kwargs)
matchstr = kwargs.pop('matchstr', r'^.*$')
flags = kwargs.pop('flags', 0)
if not invoked:
func = args[0]
def wrapper(func):
PluginsManager.commands['default_reply'][
re.compile(matchstr, flags)] = func
logger.info('registered default_reply plugin "%s" to "%s"', func.__name__,
matchstr)
return func
return wrapper if invoked else wrapper(func) | [
"def",
"default_reply",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"invoked",
"=",
"bool",
"(",
"not",
"args",
"or",
"kwargs",
")",
"matchstr",
"=",
"kwargs",
".",
"pop",
"(",
"'matchstr'",
",",
"r'^.*$'",
")",
"flags",
"=",
"kwargs",
".",
... | Decorator declaring the wrapped function to the default reply hanlder.
May be invoked as a simple, argument-less decorator (i.e. ``@default_reply``) or
with arguments customizing its behavior (e.g. ``@default_reply(matchstr='pattern')``). | [
"Decorator",
"declaring",
"the",
"wrapped",
"function",
"to",
"the",
"default",
"reply",
"hanlder",
"."
] | 7195d46b9e1dc4ecfae0bdcaa91461202689bfe5 | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/bot.py#L73-L94 | train | 224,535 |
MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.get_previous_price | def get_previous_price(self, currency, date_obj):
"""
Get Price for one bit coin on given date
"""
start = date_obj.strftime('%Y-%m-%d')
end = date_obj.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi', {}).get(start, None)
if self._force_decimal:
return Decimal(price)
return price
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | python | def get_previous_price(self, currency, date_obj):
"""
Get Price for one bit coin on given date
"""
start = date_obj.strftime('%Y-%m-%d')
end = date_obj.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi', {}).get(start, None)
if self._force_decimal:
return Decimal(price)
return price
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | [
"def",
"get_previous_price",
"(",
"self",
",",
"currency",
",",
"date_obj",
")",
":",
"start",
"=",
"date_obj",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"end",
"=",
"date_obj",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"url",
"=",
"(",
"'https://api.coindesk.... | Get Price for one bit coin on given date | [
"Get",
"Price",
"for",
"one",
"bit",
"coin",
"on",
"given",
"date"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L35-L54 | train | 224,536 |
MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.get_previous_price_list | def get_previous_price_list(self, currency, start_date, end_date):
"""
Get List of prices between two dates
"""
start = start_date.strftime('%Y-%m-%d')
end = end_date.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = self._decode_rates(response)
price_dict = data.get('bpi', {})
return price_dict
return {} | python | def get_previous_price_list(self, currency, start_date, end_date):
"""
Get List of prices between two dates
"""
start = start_date.strftime('%Y-%m-%d')
end = end_date.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = self._decode_rates(response)
price_dict = data.get('bpi', {})
return price_dict
return {} | [
"def",
"get_previous_price_list",
"(",
"self",
",",
"currency",
",",
"start_date",
",",
"end_date",
")",
":",
"start",
"=",
"start_date",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"end",
"=",
"end_date",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"url",
"=",
... | Get List of prices between two dates | [
"Get",
"List",
"of",
"prices",
"between",
"two",
"dates"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L56-L73 | train | 224,537 |
MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.convert_to_btc | def convert_to_btc(self, amount, currency):
"""
Convert X amount to Bit Coins
"""
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | python | def convert_to_btc(self, amount, currency):
"""
Convert X amount to Bit Coins
"""
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | [
"def",
"convert_to_btc",
"(",
"self",
",",
"amount",
",",
"currency",
")",
":",
"if",
"isinstance",
"(",
"amount",
",",
"Decimal",
")",
":",
"use_decimal",
"=",
"True",
"else",
":",
"use_decimal",
"=",
"self",
".",
"_force_decimal",
"url",
"=",
"'https://a... | Convert X amount to Bit Coins | [
"Convert",
"X",
"amount",
"to",
"Bit",
"Coins"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L75-L97 | train | 224,538 |
MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.convert_btc_to_cur | def convert_btc_to_cur(self, coins, currency):
"""
Convert X bit coins to valid currency amount
"""
if isinstance(coins, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_amount = coins * price
return converted_amount
except TypeError:
raise DecimalFloatMismatchError("convert_btc_to_cur requires coins parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | python | def convert_btc_to_cur(self, coins, currency):
"""
Convert X bit coins to valid currency amount
"""
if isinstance(coins, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_amount = coins * price
return converted_amount
except TypeError:
raise DecimalFloatMismatchError("convert_btc_to_cur requires coins parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | [
"def",
"convert_btc_to_cur",
"(",
"self",
",",
"coins",
",",
"currency",
")",
":",
"if",
"isinstance",
"(",
"coins",
",",
"Decimal",
")",
":",
"use_decimal",
"=",
"True",
"else",
":",
"use_decimal",
"=",
"self",
".",
"_force_decimal",
"url",
"=",
"'https:/... | Convert X bit coins to valid currency amount | [
"Convert",
"X",
"bit",
"coins",
"to",
"valid",
"currency",
"amount"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L99-L121 | train | 224,539 |
MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.convert_to_btc_on | def convert_to_btc_on(self, amount, currency, date_obj):
"""
Convert X amount to BTC based on given date rate
"""
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
start = date_obj.strftime('%Y-%m-%d')
end = date_obj.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi', {}).get(start, None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc_on requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given Date") | python | def convert_to_btc_on(self, amount, currency, date_obj):
"""
Convert X amount to BTC based on given date rate
"""
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
start = date_obj.strftime('%Y-%m-%d')
end = date_obj.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi', {}).get(start, None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc_on requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given Date") | [
"def",
"convert_to_btc_on",
"(",
"self",
",",
"amount",
",",
"currency",
",",
"date_obj",
")",
":",
"if",
"isinstance",
"(",
"amount",
",",
"Decimal",
")",
":",
"use_decimal",
"=",
"True",
"else",
":",
"use_decimal",
"=",
"self",
".",
"_force_decimal",
"st... | Convert X amount to BTC based on given date rate | [
"Convert",
"X",
"amount",
"to",
"BTC",
"based",
"on",
"given",
"date",
"rate"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L123-L152 | train | 224,540 |
DocNow/twarc | twarc/decorators.py | rate_limit | def rate_limit(f):
"""
A decorator to handle rate limiting from the Twitter API. If
a rate limit error is encountered we will sleep until we can
issue the API call again.
"""
def new_f(*args, **kwargs):
errors = 0
while True:
resp = f(*args, **kwargs)
if resp.status_code == 200:
errors = 0
return resp
elif resp.status_code == 401:
# Hack to retain the original exception, but augment it with
# additional context for the user to interpret it. In a Python
# 3 only future we can raise a new exception of the same type
# with a new message from the old error.
try:
resp.raise_for_status()
except requests.HTTPError as e:
message = "\nThis is a protected or locked account, or" +\
" the credentials provided are no longer valid."
e.args = (e.args[0] + message,) + e.args[1:]
log.warning("401 Authentication required for %s", resp.url)
raise
elif resp.status_code == 429:
reset = int(resp.headers['x-rate-limit-reset'])
now = time.time()
seconds = reset - now + 10
if seconds < 1:
seconds = 10
log.warning("rate limit exceeded: sleeping %s secs", seconds)
time.sleep(seconds)
elif resp.status_code >= 500:
errors += 1
if errors > 30:
log.warning("too many errors from Twitter, giving up")
resp.raise_for_status()
seconds = 60 * errors
log.warning("%s from Twitter API, sleeping %s",
resp.status_code, seconds)
time.sleep(seconds)
else:
resp.raise_for_status()
return new_f | python | def rate_limit(f):
"""
A decorator to handle rate limiting from the Twitter API. If
a rate limit error is encountered we will sleep until we can
issue the API call again.
"""
def new_f(*args, **kwargs):
errors = 0
while True:
resp = f(*args, **kwargs)
if resp.status_code == 200:
errors = 0
return resp
elif resp.status_code == 401:
# Hack to retain the original exception, but augment it with
# additional context for the user to interpret it. In a Python
# 3 only future we can raise a new exception of the same type
# with a new message from the old error.
try:
resp.raise_for_status()
except requests.HTTPError as e:
message = "\nThis is a protected or locked account, or" +\
" the credentials provided are no longer valid."
e.args = (e.args[0] + message,) + e.args[1:]
log.warning("401 Authentication required for %s", resp.url)
raise
elif resp.status_code == 429:
reset = int(resp.headers['x-rate-limit-reset'])
now = time.time()
seconds = reset - now + 10
if seconds < 1:
seconds = 10
log.warning("rate limit exceeded: sleeping %s secs", seconds)
time.sleep(seconds)
elif resp.status_code >= 500:
errors += 1
if errors > 30:
log.warning("too many errors from Twitter, giving up")
resp.raise_for_status()
seconds = 60 * errors
log.warning("%s from Twitter API, sleeping %s",
resp.status_code, seconds)
time.sleep(seconds)
else:
resp.raise_for_status()
return new_f | [
"def",
"rate_limit",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"0",
"while",
"True",
":",
"resp",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"resp",
".",
"stat... | A decorator to handle rate limiting from the Twitter API. If
a rate limit error is encountered we will sleep until we can
issue the API call again. | [
"A",
"decorator",
"to",
"handle",
"rate",
"limiting",
"from",
"the",
"Twitter",
"API",
".",
"If",
"a",
"rate",
"limit",
"error",
"is",
"encountered",
"we",
"will",
"sleep",
"until",
"we",
"can",
"issue",
"the",
"API",
"call",
"again",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L8-L53 | train | 224,541 |
DocNow/twarc | twarc/decorators.py | catch_timeout | def catch_timeout(f):
"""
A decorator to handle read timeouts from Twitter.
"""
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except (requests.exceptions.ReadTimeout,
requests.packages.urllib3.exceptions.ReadTimeoutError) as e:
log.warning("caught read timeout: %s", e)
self.connect()
return f(self, *args, **kwargs)
return new_f | python | def catch_timeout(f):
"""
A decorator to handle read timeouts from Twitter.
"""
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except (requests.exceptions.ReadTimeout,
requests.packages.urllib3.exceptions.ReadTimeoutError) as e:
log.warning("caught read timeout: %s", e)
self.connect()
return f(self, *args, **kwargs)
return new_f | [
"def",
"catch_timeout",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"(",
"requests",
"."... | A decorator to handle read timeouts from Twitter. | [
"A",
"decorator",
"to",
"handle",
"read",
"timeouts",
"from",
"Twitter",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L81-L93 | train | 224,542 |
DocNow/twarc | twarc/decorators.py | catch_gzip_errors | def catch_gzip_errors(f):
"""
A decorator to handle gzip encoding errors which have been known to
happen during hydration.
"""
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except requests.exceptions.ContentDecodingError as e:
log.warning("caught gzip error: %s", e)
self.connect()
return f(self, *args, **kwargs)
return new_f | python | def catch_gzip_errors(f):
"""
A decorator to handle gzip encoding errors which have been known to
happen during hydration.
"""
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except requests.exceptions.ContentDecodingError as e:
log.warning("caught gzip error: %s", e)
self.connect()
return f(self, *args, **kwargs)
return new_f | [
"def",
"catch_gzip_errors",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"requests",
".",
... | A decorator to handle gzip encoding errors which have been known to
happen during hydration. | [
"A",
"decorator",
"to",
"handle",
"gzip",
"encoding",
"errors",
"which",
"have",
"been",
"known",
"to",
"happen",
"during",
"hydration",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L96-L108 | train | 224,543 |
DocNow/twarc | twarc/decorators.py | interruptible_sleep | def interruptible_sleep(t, event=None):
"""
Sleeps for a specified duration, optionally stopping early for event.
Returns True if interrupted
"""
log.info("sleeping %s", t)
if event is None:
time.sleep(t)
return False
else:
return not event.wait(t) | python | def interruptible_sleep(t, event=None):
"""
Sleeps for a specified duration, optionally stopping early for event.
Returns True if interrupted
"""
log.info("sleeping %s", t)
if event is None:
time.sleep(t)
return False
else:
return not event.wait(t) | [
"def",
"interruptible_sleep",
"(",
"t",
",",
"event",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"sleeping %s\"",
",",
"t",
")",
"if",
"event",
"is",
"None",
":",
"time",
".",
"sleep",
"(",
"t",
")",
"return",
"False",
"else",
":",
"return",
... | Sleeps for a specified duration, optionally stopping early for event.
Returns True if interrupted | [
"Sleeps",
"for",
"a",
"specified",
"duration",
"optionally",
"stopping",
"early",
"for",
"event",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L111-L123 | train | 224,544 |
DocNow/twarc | twarc/decorators.py | filter_protected | def filter_protected(f):
"""
filter_protected will filter out protected tweets and users unless
explicitly requested not to.
"""
def new_f(self, *args, **kwargs):
for obj in f(self, *args, **kwargs):
if self.protected == False:
if 'user' in obj and obj['user']['protected']:
continue
elif 'protected' in obj and obj['protected']:
continue
yield obj
return new_f | python | def filter_protected(f):
"""
filter_protected will filter out protected tweets and users unless
explicitly requested not to.
"""
def new_f(self, *args, **kwargs):
for obj in f(self, *args, **kwargs):
if self.protected == False:
if 'user' in obj and obj['user']['protected']:
continue
elif 'protected' in obj and obj['protected']:
continue
yield obj
return new_f | [
"def",
"filter_protected",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"obj",
"in",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"pr... | filter_protected will filter out protected tweets and users unless
explicitly requested not to. | [
"filter_protected",
"will",
"filter",
"out",
"protected",
"tweets",
"and",
"users",
"unless",
"explicitly",
"requested",
"not",
"to",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L125-L139 | train | 224,545 |
DocNow/twarc | utils/extractor.py | tweets_files | def tweets_files(string, path):
"""Iterates over json files in path."""
for filename in os.listdir(path):
if re.match(string, filename) and ".jsonl" in filename:
f = gzip.open if ".gz" in filename else open
yield path + filename, f
Ellipsis | python | def tweets_files(string, path):
"""Iterates over json files in path."""
for filename in os.listdir(path):
if re.match(string, filename) and ".jsonl" in filename:
f = gzip.open if ".gz" in filename else open
yield path + filename, f
Ellipsis | [
"def",
"tweets_files",
"(",
"string",
",",
"path",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"if",
"re",
".",
"match",
"(",
"string",
",",
"filename",
")",
"and",
"\".jsonl\"",
"in",
"filename",
":",
"f",
"=",
... | Iterates over json files in path. | [
"Iterates",
"over",
"json",
"files",
"in",
"path",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/utils/extractor.py#L38-L45 | train | 224,546 |
DocNow/twarc | utils/extractor.py | extract | def extract(json_object, args, csv_writer):
"""Extract and write found attributes."""
found = [[]]
for attribute in args.attributes:
item = attribute.getElement(json_object)
if len(item) == 0:
for row in found:
row.append("NA")
else:
found1 = []
for value in item:
if value is None:
value = "NA"
new = copy.deepcopy(found)
for row in new:
row.append(value)
found1.extend(new)
found = found1
for row in found:
csv_writer.writerow(row)
return len(found) | python | def extract(json_object, args, csv_writer):
"""Extract and write found attributes."""
found = [[]]
for attribute in args.attributes:
item = attribute.getElement(json_object)
if len(item) == 0:
for row in found:
row.append("NA")
else:
found1 = []
for value in item:
if value is None:
value = "NA"
new = copy.deepcopy(found)
for row in new:
row.append(value)
found1.extend(new)
found = found1
for row in found:
csv_writer.writerow(row)
return len(found) | [
"def",
"extract",
"(",
"json_object",
",",
"args",
",",
"csv_writer",
")",
":",
"found",
"=",
"[",
"[",
"]",
"]",
"for",
"attribute",
"in",
"args",
".",
"attributes",
":",
"item",
"=",
"attribute",
".",
"getElement",
"(",
"json_object",
")",
"if",
"len... | Extract and write found attributes. | [
"Extract",
"and",
"write",
"found",
"attributes",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/utils/extractor.py#L91-L113 | train | 224,547 |
DocNow/twarc | utils/network.py | add | def add(from_user, from_id, to_user, to_id, type):
"adds a relation to the graph"
if options.users and to_user:
G.add_node(from_user, screen_name=from_user)
G.add_node(to_user, screen_name=to_user)
if G.has_edge(from_user, to_user):
weight = G[from_user][to_user]['weight'] + 1
else:
weight = 1
G.add_edge(from_user, to_user, type=type, weight=weight)
elif not options.users and to_id:
G.add_node(from_id, screen_name=from_user, type=type)
if to_user:
G.add_node(to_id, screen_name=to_user)
else:
G.add_node(to_id)
G.add_edge(from_id, to_id, type=type) | python | def add(from_user, from_id, to_user, to_id, type):
"adds a relation to the graph"
if options.users and to_user:
G.add_node(from_user, screen_name=from_user)
G.add_node(to_user, screen_name=to_user)
if G.has_edge(from_user, to_user):
weight = G[from_user][to_user]['weight'] + 1
else:
weight = 1
G.add_edge(from_user, to_user, type=type, weight=weight)
elif not options.users and to_id:
G.add_node(from_id, screen_name=from_user, type=type)
if to_user:
G.add_node(to_id, screen_name=to_user)
else:
G.add_node(to_id)
G.add_edge(from_id, to_id, type=type) | [
"def",
"add",
"(",
"from_user",
",",
"from_id",
",",
"to_user",
",",
"to_id",
",",
"type",
")",
":",
"if",
"options",
".",
"users",
"and",
"to_user",
":",
"G",
".",
"add_node",
"(",
"from_user",
",",
"screen_name",
"=",
"from_user",
")",
"G",
".",
"a... | adds a relation to the graph | [
"adds",
"a",
"relation",
"to",
"the",
"graph"
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/utils/network.py#L72-L91 | train | 224,548 |
DocNow/twarc | twarc/client.py | Twarc.timeline | def timeline(self, user_id=None, screen_name=None, max_id=None,
since_id=None, max_pages=None):
"""
Returns a collection of the most recent tweets posted
by the user indicated by the user_id or screen_name parameter.
Provide a user_id or screen_name.
"""
if user_id and screen_name:
raise ValueError('only user_id or screen_name may be passed')
# Strip if screen_name is prefixed with '@'
if screen_name:
screen_name = screen_name.lstrip('@')
id = screen_name or str(user_id)
id_type = "screen_name" if screen_name else "user_id"
log.info("starting user timeline for user %s", id)
if screen_name or user_id:
url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
else:
url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
params = {"count": 200, id_type: id, "include_ext_alt_text": "true"}
retrieved_pages = 0
reached_end = False
while True:
if since_id:
# Make the since_id inclusive, so we can avoid retrieving
# an empty page of results in some cases
params['since_id'] = str(int(since_id) - 1)
if max_id:
params['max_id'] = max_id
try:
resp = self.get(url, params=params, allow_404=True)
retrieved_pages += 1
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.warn("no timeline available for %s", id)
break
elif e.response.status_code == 401:
log.warn("protected account %s", id)
break
raise e
statuses = resp.json()
if len(statuses) == 0:
log.info("no new tweets matching %s", params)
break
for status in statuses:
# We've certainly reached the end of new results
if since_id is not None and status['id_str'] == str(since_id):
reached_end = True
break
# If you request an invalid user_id, you may still get
# results so need to check.
if not user_id or id == status.get("user",
{}).get("id_str"):
yield status
if reached_end:
log.info("no new tweets matching %s", params)
break
if max_pages is not None and retrieved_pages == max_pages:
log.info("reached max page limit for %s", params)
break
max_id = str(int(status["id_str"]) - 1) | python | def timeline(self, user_id=None, screen_name=None, max_id=None,
since_id=None, max_pages=None):
"""
Returns a collection of the most recent tweets posted
by the user indicated by the user_id or screen_name parameter.
Provide a user_id or screen_name.
"""
if user_id and screen_name:
raise ValueError('only user_id or screen_name may be passed')
# Strip if screen_name is prefixed with '@'
if screen_name:
screen_name = screen_name.lstrip('@')
id = screen_name or str(user_id)
id_type = "screen_name" if screen_name else "user_id"
log.info("starting user timeline for user %s", id)
if screen_name or user_id:
url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
else:
url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
params = {"count": 200, id_type: id, "include_ext_alt_text": "true"}
retrieved_pages = 0
reached_end = False
while True:
if since_id:
# Make the since_id inclusive, so we can avoid retrieving
# an empty page of results in some cases
params['since_id'] = str(int(since_id) - 1)
if max_id:
params['max_id'] = max_id
try:
resp = self.get(url, params=params, allow_404=True)
retrieved_pages += 1
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.warn("no timeline available for %s", id)
break
elif e.response.status_code == 401:
log.warn("protected account %s", id)
break
raise e
statuses = resp.json()
if len(statuses) == 0:
log.info("no new tweets matching %s", params)
break
for status in statuses:
# We've certainly reached the end of new results
if since_id is not None and status['id_str'] == str(since_id):
reached_end = True
break
# If you request an invalid user_id, you may still get
# results so need to check.
if not user_id or id == status.get("user",
{}).get("id_str"):
yield status
if reached_end:
log.info("no new tweets matching %s", params)
break
if max_pages is not None and retrieved_pages == max_pages:
log.info("reached max page limit for %s", params)
break
max_id = str(int(status["id_str"]) - 1) | [
"def",
"timeline",
"(",
"self",
",",
"user_id",
"=",
"None",
",",
"screen_name",
"=",
"None",
",",
"max_id",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"max_pages",
"=",
"None",
")",
":",
"if",
"user_id",
"and",
"screen_name",
":",
"raise",
"Value... | Returns a collection of the most recent tweets posted
by the user indicated by the user_id or screen_name parameter.
Provide a user_id or screen_name. | [
"Returns",
"a",
"collection",
"of",
"the",
"most",
"recent",
"tweets",
"posted",
"by",
"the",
"user",
"indicated",
"by",
"the",
"user_id",
"or",
"screen_name",
"parameter",
".",
"Provide",
"a",
"user_id",
"or",
"screen_name",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L138-L211 | train | 224,549 |
DocNow/twarc | twarc/client.py | Twarc.follower_ids | def follower_ids(self, user):
"""
Returns Twitter user id lists for the specified user's followers.
A user can be a specific using their screen_name or user_id
"""
user = str(user)
user = user.lstrip('@')
url = 'https://api.twitter.com/1.1/followers/ids.json'
if re.match(r'^\d+$', user):
params = {'user_id': user, 'cursor': -1}
else:
params = {'screen_name': user, 'cursor': -1}
while params['cursor'] != 0:
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.info("no users matching %s", screen_name)
raise e
user_ids = resp.json()
for user_id in user_ids['ids']:
yield str_type(user_id)
params['cursor'] = user_ids['next_cursor'] | python | def follower_ids(self, user):
"""
Returns Twitter user id lists for the specified user's followers.
A user can be a specific using their screen_name or user_id
"""
user = str(user)
user = user.lstrip('@')
url = 'https://api.twitter.com/1.1/followers/ids.json'
if re.match(r'^\d+$', user):
params = {'user_id': user, 'cursor': -1}
else:
params = {'screen_name': user, 'cursor': -1}
while params['cursor'] != 0:
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.info("no users matching %s", screen_name)
raise e
user_ids = resp.json()
for user_id in user_ids['ids']:
yield str_type(user_id)
params['cursor'] = user_ids['next_cursor'] | [
"def",
"follower_ids",
"(",
"self",
",",
"user",
")",
":",
"user",
"=",
"str",
"(",
"user",
")",
"user",
"=",
"user",
".",
"lstrip",
"(",
"'@'",
")",
"url",
"=",
"'https://api.twitter.com/1.1/followers/ids.json'",
"if",
"re",
".",
"match",
"(",
"r'^\\d+$'"... | Returns Twitter user id lists for the specified user's followers.
A user can be a specific using their screen_name or user_id | [
"Returns",
"Twitter",
"user",
"id",
"lists",
"for",
"the",
"specified",
"user",
"s",
"followers",
".",
"A",
"user",
"can",
"be",
"a",
"specific",
"using",
"their",
"screen_name",
"or",
"user_id"
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L254-L278 | train | 224,550 |
DocNow/twarc | twarc/client.py | Twarc.filter | def filter(self, track=None, follow=None, locations=None, event=None,
record_keepalive=False):
"""
Returns an iterator for tweets that match a given filter track from
the livestream of tweets happening right now.
If a threading.Event is provided for event and the event is set,
the filter will be interrupted.
"""
if locations is not None:
if type(locations) == list:
locations = ','.join(locations)
locations = locations.replace('\\', '')
url = 'https://stream.twitter.com/1.1/statuses/filter.json'
params = {
"stall_warning": True,
"include_ext_alt_text": True
}
if track:
params["track"] = track
if follow:
params["follow"] = follow
if locations:
params["locations"] = locations
headers = {'accept-encoding': 'deflate, gzip'}
errors = 0
while True:
try:
log.info("connecting to filter stream for %s", params)
resp = self.post(url, params, headers=headers, stream=True)
errors = 0
for line in resp.iter_lines(chunk_size=1024):
if event and event.is_set():
log.info("stopping filter")
# Explicitly close response
resp.close()
return
if not line:
log.info("keep-alive")
if record_keepalive:
yield "keep-alive"
continue
try:
yield json.loads(line.decode())
except Exception as e:
log.error("json parse error: %s - %s", e, line)
except requests.exceptions.HTTPError as e:
errors += 1
log.error("caught http error %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if e.response.status_code == 420:
if interruptible_sleep(errors * 60, event):
log.info("stopping filter")
return
else:
if interruptible_sleep(errors * 5, event):
log.info("stopping filter")
return
except Exception as e:
errors += 1
log.error("caught exception %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many exceptions")
raise e
log.error(e)
if interruptible_sleep(errors, event):
log.info("stopping filter")
return | python | def filter(self, track=None, follow=None, locations=None, event=None,
record_keepalive=False):
"""
Returns an iterator for tweets that match a given filter track from
the livestream of tweets happening right now.
If a threading.Event is provided for event and the event is set,
the filter will be interrupted.
"""
if locations is not None:
if type(locations) == list:
locations = ','.join(locations)
locations = locations.replace('\\', '')
url = 'https://stream.twitter.com/1.1/statuses/filter.json'
params = {
"stall_warning": True,
"include_ext_alt_text": True
}
if track:
params["track"] = track
if follow:
params["follow"] = follow
if locations:
params["locations"] = locations
headers = {'accept-encoding': 'deflate, gzip'}
errors = 0
while True:
try:
log.info("connecting to filter stream for %s", params)
resp = self.post(url, params, headers=headers, stream=True)
errors = 0
for line in resp.iter_lines(chunk_size=1024):
if event and event.is_set():
log.info("stopping filter")
# Explicitly close response
resp.close()
return
if not line:
log.info("keep-alive")
if record_keepalive:
yield "keep-alive"
continue
try:
yield json.loads(line.decode())
except Exception as e:
log.error("json parse error: %s - %s", e, line)
except requests.exceptions.HTTPError as e:
errors += 1
log.error("caught http error %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if e.response.status_code == 420:
if interruptible_sleep(errors * 60, event):
log.info("stopping filter")
return
else:
if interruptible_sleep(errors * 5, event):
log.info("stopping filter")
return
except Exception as e:
errors += 1
log.error("caught exception %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many exceptions")
raise e
log.error(e)
if interruptible_sleep(errors, event):
log.info("stopping filter")
return | [
"def",
"filter",
"(",
"self",
",",
"track",
"=",
"None",
",",
"follow",
"=",
"None",
",",
"locations",
"=",
"None",
",",
"event",
"=",
"None",
",",
"record_keepalive",
"=",
"False",
")",
":",
"if",
"locations",
"is",
"not",
"None",
":",
"if",
"type",... | Returns an iterator for tweets that match a given filter track from
the livestream of tweets happening right now.
If a threading.Event is provided for event and the event is set,
the filter will be interrupted. | [
"Returns",
"an",
"iterator",
"for",
"tweets",
"that",
"match",
"a",
"given",
"filter",
"track",
"from",
"the",
"livestream",
"of",
"tweets",
"happening",
"right",
"now",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L308-L378 | train | 224,551 |
DocNow/twarc | twarc/client.py | Twarc.sample | def sample(self, event=None, record_keepalive=False):
"""
Returns a small random sample of all public statuses. The Tweets
returned by the default access level are the same, so if two different
clients connect to this endpoint, they will see the same Tweets.
If a threading.Event is provided for event and the event is set,
the sample will be interrupted.
"""
url = 'https://stream.twitter.com/1.1/statuses/sample.json'
params = {"stall_warning": True}
headers = {'accept-encoding': 'deflate, gzip'}
errors = 0
while True:
try:
log.info("connecting to sample stream")
resp = self.post(url, params, headers=headers, stream=True)
errors = 0
for line in resp.iter_lines(chunk_size=512):
if event and event.is_set():
log.info("stopping sample")
# Explicitly close response
resp.close()
return
if line == "":
log.info("keep-alive")
if record_keepalive:
yield "keep-alive"
continue
try:
yield json.loads(line.decode())
except Exception as e:
log.error("json parse error: %s - %s", e, line)
except requests.exceptions.HTTPError as e:
errors += 1
log.error("caught http error %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if e.response.status_code == 420:
if interruptible_sleep(errors * 60, event):
log.info("stopping filter")
return
else:
if interruptible_sleep(errors * 5, event):
log.info("stopping filter")
return
except Exception as e:
errors += 1
log.error("caught exception %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if interruptible_sleep(errors, event):
log.info("stopping filter")
return | python | def sample(self, event=None, record_keepalive=False):
"""
Returns a small random sample of all public statuses. The Tweets
returned by the default access level are the same, so if two different
clients connect to this endpoint, they will see the same Tweets.
If a threading.Event is provided for event and the event is set,
the sample will be interrupted.
"""
url = 'https://stream.twitter.com/1.1/statuses/sample.json'
params = {"stall_warning": True}
headers = {'accept-encoding': 'deflate, gzip'}
errors = 0
while True:
try:
log.info("connecting to sample stream")
resp = self.post(url, params, headers=headers, stream=True)
errors = 0
for line in resp.iter_lines(chunk_size=512):
if event and event.is_set():
log.info("stopping sample")
# Explicitly close response
resp.close()
return
if line == "":
log.info("keep-alive")
if record_keepalive:
yield "keep-alive"
continue
try:
yield json.loads(line.decode())
except Exception as e:
log.error("json parse error: %s - %s", e, line)
except requests.exceptions.HTTPError as e:
errors += 1
log.error("caught http error %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if e.response.status_code == 420:
if interruptible_sleep(errors * 60, event):
log.info("stopping filter")
return
else:
if interruptible_sleep(errors * 5, event):
log.info("stopping filter")
return
except Exception as e:
errors += 1
log.error("caught exception %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if interruptible_sleep(errors, event):
log.info("stopping filter")
return | [
"def",
"sample",
"(",
"self",
",",
"event",
"=",
"None",
",",
"record_keepalive",
"=",
"False",
")",
":",
"url",
"=",
"'https://stream.twitter.com/1.1/statuses/sample.json'",
"params",
"=",
"{",
"\"stall_warning\"",
":",
"True",
"}",
"headers",
"=",
"{",
"'accep... | Returns a small random sample of all public statuses. The Tweets
returned by the default access level are the same, so if two different
clients connect to this endpoint, they will see the same Tweets.
If a threading.Event is provided for event and the event is set,
the sample will be interrupted. | [
"Returns",
"a",
"small",
"random",
"sample",
"of",
"all",
"public",
"statuses",
".",
"The",
"Tweets",
"returned",
"by",
"the",
"default",
"access",
"level",
"are",
"the",
"same",
"so",
"if",
"two",
"different",
"clients",
"connect",
"to",
"this",
"endpoint",... | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L380-L436 | train | 224,552 |
DocNow/twarc | twarc/client.py | Twarc.dehydrate | def dehydrate(self, iterator):
"""
Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet.
"""
for line in iterator:
try:
yield json.loads(line)['id_str']
except Exception as e:
log.error("uhoh: %s\n" % e) | python | def dehydrate(self, iterator):
"""
Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet.
"""
for line in iterator:
try:
yield json.loads(line)['id_str']
except Exception as e:
log.error("uhoh: %s\n" % e) | [
"def",
"dehydrate",
"(",
"self",
",",
"iterator",
")",
":",
"for",
"line",
"in",
"iterator",
":",
"try",
":",
"yield",
"json",
".",
"loads",
"(",
"line",
")",
"[",
"'id_str'",
"]",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"error",
"(",
"\... | Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet. | [
"Pass",
"in",
"an",
"iterator",
"of",
"tweets",
"JSON",
"and",
"get",
"back",
"an",
"iterator",
"of",
"the",
"IDs",
"of",
"each",
"tweet",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L438-L447 | train | 224,553 |
DocNow/twarc | twarc/client.py | Twarc.hydrate | def hydrate(self, iterator):
"""
Pass in an iterator of tweet ids and get back an iterator for the
decoded JSON for each corresponding tweet.
"""
ids = []
url = "https://api.twitter.com/1.1/statuses/lookup.json"
# lookup 100 tweets at a time
for tweet_id in iterator:
tweet_id = str(tweet_id)
tweet_id = tweet_id.strip() # remove new line if present
ids.append(tweet_id)
if len(ids) == 100:
log.info("hydrating %s ids", len(ids))
resp = self.post(url, data={
"id": ','.join(ids),
"include_ext_alt_text": 'true'
})
tweets = resp.json()
tweets.sort(key=lambda t: t['id_str'])
for tweet in tweets:
yield tweet
ids = []
# hydrate any remaining ones
if len(ids) > 0:
log.info("hydrating %s", ids)
resp = self.post(url, data={
"id": ','.join(ids),
"include_ext_alt_text": 'true'
})
for tweet in resp.json():
yield tweet | python | def hydrate(self, iterator):
"""
Pass in an iterator of tweet ids and get back an iterator for the
decoded JSON for each corresponding tweet.
"""
ids = []
url = "https://api.twitter.com/1.1/statuses/lookup.json"
# lookup 100 tweets at a time
for tweet_id in iterator:
tweet_id = str(tweet_id)
tweet_id = tweet_id.strip() # remove new line if present
ids.append(tweet_id)
if len(ids) == 100:
log.info("hydrating %s ids", len(ids))
resp = self.post(url, data={
"id": ','.join(ids),
"include_ext_alt_text": 'true'
})
tweets = resp.json()
tweets.sort(key=lambda t: t['id_str'])
for tweet in tweets:
yield tweet
ids = []
# hydrate any remaining ones
if len(ids) > 0:
log.info("hydrating %s", ids)
resp = self.post(url, data={
"id": ','.join(ids),
"include_ext_alt_text": 'true'
})
for tweet in resp.json():
yield tweet | [
"def",
"hydrate",
"(",
"self",
",",
"iterator",
")",
":",
"ids",
"=",
"[",
"]",
"url",
"=",
"\"https://api.twitter.com/1.1/statuses/lookup.json\"",
"# lookup 100 tweets at a time",
"for",
"tweet_id",
"in",
"iterator",
":",
"tweet_id",
"=",
"str",
"(",
"tweet_id",
... | Pass in an iterator of tweet ids and get back an iterator for the
decoded JSON for each corresponding tweet. | [
"Pass",
"in",
"an",
"iterator",
"of",
"tweet",
"ids",
"and",
"get",
"back",
"an",
"iterator",
"for",
"the",
"decoded",
"JSON",
"for",
"each",
"corresponding",
"tweet",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L449-L482 | train | 224,554 |
DocNow/twarc | twarc/client.py | Twarc.retweets | def retweets(self, tweet_id):
"""
Retrieves up to the last 100 retweets for the provided
tweet.
"""
log.info("retrieving retweets of %s", tweet_id)
url = "https://api.twitter.com/1.1/statuses/retweets/""{}.json".format(
tweet_id)
resp = self.get(url, params={"count": 100})
for tweet in resp.json():
yield tweet | python | def retweets(self, tweet_id):
"""
Retrieves up to the last 100 retweets for the provided
tweet.
"""
log.info("retrieving retweets of %s", tweet_id)
url = "https://api.twitter.com/1.1/statuses/retweets/""{}.json".format(
tweet_id)
resp = self.get(url, params={"count": 100})
for tweet in resp.json():
yield tweet | [
"def",
"retweets",
"(",
"self",
",",
"tweet_id",
")",
":",
"log",
".",
"info",
"(",
"\"retrieving retweets of %s\"",
",",
"tweet_id",
")",
"url",
"=",
"\"https://api.twitter.com/1.1/statuses/retweets/\"",
"\"{}.json\"",
".",
"format",
"(",
"tweet_id",
")",
"resp",
... | Retrieves up to the last 100 retweets for the provided
tweet. | [
"Retrieves",
"up",
"to",
"the",
"last",
"100",
"retweets",
"for",
"the",
"provided",
"tweet",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L490-L501 | train | 224,555 |
DocNow/twarc | twarc/client.py | Twarc.trends_available | def trends_available(self):
"""
Returns a list of regions for which Twitter tracks trends.
"""
url = 'https://api.twitter.com/1.1/trends/available.json'
try:
resp = self.get(url)
except requests.exceptions.HTTPError as e:
raise e
return resp.json() | python | def trends_available(self):
"""
Returns a list of regions for which Twitter tracks trends.
"""
url = 'https://api.twitter.com/1.1/trends/available.json'
try:
resp = self.get(url)
except requests.exceptions.HTTPError as e:
raise e
return resp.json() | [
"def",
"trends_available",
"(",
"self",
")",
":",
"url",
"=",
"'https://api.twitter.com/1.1/trends/available.json'",
"try",
":",
"resp",
"=",
"self",
".",
"get",
"(",
"url",
")",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
"as",
"e",
":",
"raise... | Returns a list of regions for which Twitter tracks trends. | [
"Returns",
"a",
"list",
"of",
"regions",
"for",
"which",
"Twitter",
"tracks",
"trends",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L503-L512 | train | 224,556 |
DocNow/twarc | twarc/client.py | Twarc.trends_place | def trends_place(self, woeid, exclude=None):
"""
Returns recent Twitter trends for the specified WOEID. If
exclude == 'hashtags', Twitter will remove hashtag trends from the
response.
"""
url = 'https://api.twitter.com/1.1/trends/place.json'
params = {'id': woeid}
if exclude:
params['exclude'] = exclude
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.info("no region matching WOEID %s", woeid)
raise e
return resp.json() | python | def trends_place(self, woeid, exclude=None):
"""
Returns recent Twitter trends for the specified WOEID. If
exclude == 'hashtags', Twitter will remove hashtag trends from the
response.
"""
url = 'https://api.twitter.com/1.1/trends/place.json'
params = {'id': woeid}
if exclude:
params['exclude'] = exclude
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.info("no region matching WOEID %s", woeid)
raise e
return resp.json() | [
"def",
"trends_place",
"(",
"self",
",",
"woeid",
",",
"exclude",
"=",
"None",
")",
":",
"url",
"=",
"'https://api.twitter.com/1.1/trends/place.json'",
"params",
"=",
"{",
"'id'",
":",
"woeid",
"}",
"if",
"exclude",
":",
"params",
"[",
"'exclude'",
"]",
"=",... | Returns recent Twitter trends for the specified WOEID. If
exclude == 'hashtags', Twitter will remove hashtag trends from the
response. | [
"Returns",
"recent",
"Twitter",
"trends",
"for",
"the",
"specified",
"WOEID",
".",
"If",
"exclude",
"==",
"hashtags",
"Twitter",
"will",
"remove",
"hashtag",
"trends",
"from",
"the",
"response",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L514-L530 | train | 224,557 |
DocNow/twarc | twarc/client.py | Twarc.replies | def replies(self, tweet, recursive=False, prune=()):
"""
replies returns a generator of tweets that are replies for a given
tweet. It includes the original tweet. If you would like to fetch the
replies to the replies use recursive=True which will do a depth-first
recursive walk of the replies. It also walk up the reply chain if you
supply a tweet that is itself a reply to another tweet. You can
optionally supply a tuple of tweet ids to ignore during this traversal
using the prune parameter.
"""
yield tweet
# get replies to the tweet
screen_name = tweet['user']['screen_name']
tweet_id = tweet['id_str']
log.info("looking for replies to: %s", tweet_id)
for reply in self.search("to:%s" % screen_name, since_id=tweet_id):
if reply['in_reply_to_status_id_str'] != tweet_id:
continue
if reply['id_str'] in prune:
log.info("ignoring pruned tweet id %s", reply['id_str'])
continue
log.info("found reply: %s", reply["id_str"])
if recursive:
if reply['id_str'] not in prune:
prune = prune + (tweet_id,)
for r in self.replies(reply, recursive, prune):
yield r
else:
yield reply
# if this tweet is itself a reply to another tweet get it and
# get other potential replies to it
reply_to_id = tweet.get('in_reply_to_status_id_str')
log.info("prune=%s", prune)
if recursive and reply_to_id and reply_to_id not in prune:
t = self.tweet(reply_to_id)
if t:
log.info("found reply-to: %s", t['id_str'])
prune = prune + (tweet['id_str'],)
for r in self.replies(t, recursive=True, prune=prune):
yield r
# if this tweet is a quote go get that too whatever tweets it
# may be in reply to
quote_id = tweet.get('quotes_status_id_str')
if recursive and quote_id and quote_id not in prune:
t = self.tweet(quote_id)
if t:
log.info("found quote: %s", t['id_str'])
prune = prune + (tweet['id_str'],)
for r in self.replies(t, recursive=True, prune=prune):
yield r | python | def replies(self, tweet, recursive=False, prune=()):
"""
replies returns a generator of tweets that are replies for a given
tweet. It includes the original tweet. If you would like to fetch the
replies to the replies use recursive=True which will do a depth-first
recursive walk of the replies. It also walk up the reply chain if you
supply a tweet that is itself a reply to another tweet. You can
optionally supply a tuple of tweet ids to ignore during this traversal
using the prune parameter.
"""
yield tweet
# get replies to the tweet
screen_name = tweet['user']['screen_name']
tweet_id = tweet['id_str']
log.info("looking for replies to: %s", tweet_id)
for reply in self.search("to:%s" % screen_name, since_id=tweet_id):
if reply['in_reply_to_status_id_str'] != tweet_id:
continue
if reply['id_str'] in prune:
log.info("ignoring pruned tweet id %s", reply['id_str'])
continue
log.info("found reply: %s", reply["id_str"])
if recursive:
if reply['id_str'] not in prune:
prune = prune + (tweet_id,)
for r in self.replies(reply, recursive, prune):
yield r
else:
yield reply
# if this tweet is itself a reply to another tweet get it and
# get other potential replies to it
reply_to_id = tweet.get('in_reply_to_status_id_str')
log.info("prune=%s", prune)
if recursive and reply_to_id and reply_to_id not in prune:
t = self.tweet(reply_to_id)
if t:
log.info("found reply-to: %s", t['id_str'])
prune = prune + (tweet['id_str'],)
for r in self.replies(t, recursive=True, prune=prune):
yield r
# if this tweet is a quote go get that too whatever tweets it
# may be in reply to
quote_id = tweet.get('quotes_status_id_str')
if recursive and quote_id and quote_id not in prune:
t = self.tweet(quote_id)
if t:
log.info("found quote: %s", t['id_str'])
prune = prune + (tweet['id_str'],)
for r in self.replies(t, recursive=True, prune=prune):
yield r | [
"def",
"replies",
"(",
"self",
",",
"tweet",
",",
"recursive",
"=",
"False",
",",
"prune",
"=",
"(",
")",
")",
":",
"yield",
"tweet",
"# get replies to the tweet",
"screen_name",
"=",
"tweet",
"[",
"'user'",
"]",
"[",
"'screen_name'",
"]",
"tweet_id",
"=",... | replies returns a generator of tweets that are replies for a given
tweet. It includes the original tweet. If you would like to fetch the
replies to the replies use recursive=True which will do a depth-first
recursive walk of the replies. It also walk up the reply chain if you
supply a tweet that is itself a reply to another tweet. You can
optionally supply a tuple of tweet ids to ignore during this traversal
using the prune parameter. | [
"replies",
"returns",
"a",
"generator",
"of",
"tweets",
"that",
"are",
"replies",
"for",
"a",
"given",
"tweet",
".",
"It",
"includes",
"the",
"original",
"tweet",
".",
"If",
"you",
"would",
"like",
"to",
"fetch",
"the",
"replies",
"to",
"the",
"replies",
... | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L544-L603 | train | 224,558 |
DocNow/twarc | twarc/client.py | Twarc.list_members | def list_members(self, list_id=None, slug=None, owner_screen_name=None, owner_id=None):
"""
Returns the members of a list.
List id or (slug and (owner_screen_name or owner_id)) are required
"""
assert list_id or (slug and (owner_screen_name or owner_id))
url = 'https://api.twitter.com/1.1/lists/members.json'
params = {'cursor': -1}
if list_id:
params['list_id'] = list_id
else:
params['slug'] = slug
if owner_screen_name:
params['owner_screen_name'] = owner_screen_name
else:
params['owner_id'] = owner_id
while params['cursor'] != 0:
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.error("no matching list")
raise e
users = resp.json()
for user in users['users']:
yield user
params['cursor'] = users['next_cursor'] | python | def list_members(self, list_id=None, slug=None, owner_screen_name=None, owner_id=None):
"""
Returns the members of a list.
List id or (slug and (owner_screen_name or owner_id)) are required
"""
assert list_id or (slug and (owner_screen_name or owner_id))
url = 'https://api.twitter.com/1.1/lists/members.json'
params = {'cursor': -1}
if list_id:
params['list_id'] = list_id
else:
params['slug'] = slug
if owner_screen_name:
params['owner_screen_name'] = owner_screen_name
else:
params['owner_id'] = owner_id
while params['cursor'] != 0:
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.error("no matching list")
raise e
users = resp.json()
for user in users['users']:
yield user
params['cursor'] = users['next_cursor'] | [
"def",
"list_members",
"(",
"self",
",",
"list_id",
"=",
"None",
",",
"slug",
"=",
"None",
",",
"owner_screen_name",
"=",
"None",
",",
"owner_id",
"=",
"None",
")",
":",
"assert",
"list_id",
"or",
"(",
"slug",
"and",
"(",
"owner_screen_name",
"or",
"owne... | Returns the members of a list.
List id or (slug and (owner_screen_name or owner_id)) are required | [
"Returns",
"the",
"members",
"of",
"a",
"list",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L605-L634 | train | 224,559 |
DocNow/twarc | twarc/client.py | Twarc.connect | def connect(self):
"""
Sets up the HTTP session to talk to Twitter. If one is active it is
closed and another one is opened.
"""
if not (self.consumer_key and self.consumer_secret and self.access_token
and self.access_token_secret):
raise RuntimeError("MissingKeys")
if self.client:
log.info("closing existing http session")
self.client.close()
if self.last_response:
log.info("closing last response")
self.last_response.close()
log.info("creating http session")
self.client = OAuth1Session(
client_key=self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.access_token,
resource_owner_secret=self.access_token_secret
) | python | def connect(self):
"""
Sets up the HTTP session to talk to Twitter. If one is active it is
closed and another one is opened.
"""
if not (self.consumer_key and self.consumer_secret and self.access_token
and self.access_token_secret):
raise RuntimeError("MissingKeys")
if self.client:
log.info("closing existing http session")
self.client.close()
if self.last_response:
log.info("closing last response")
self.last_response.close()
log.info("creating http session")
self.client = OAuth1Session(
client_key=self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.access_token,
resource_owner_secret=self.access_token_secret
) | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"consumer_key",
"and",
"self",
".",
"consumer_secret",
"and",
"self",
".",
"access_token",
"and",
"self",
".",
"access_token_secret",
")",
":",
"raise",
"RuntimeError",
"(",
"\"MissingKe... | Sets up the HTTP session to talk to Twitter. If one is active it is
closed and another one is opened. | [
"Sets",
"up",
"the",
"HTTP",
"session",
"to",
"talk",
"to",
"Twitter",
".",
"If",
"one",
"is",
"active",
"it",
"is",
"closed",
"and",
"another",
"one",
"is",
"opened",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L707-L729 | train | 224,560 |
DocNow/twarc | twarc/client.py | Twarc.get_keys | def get_keys(self):
"""
Get the Twitter API keys. Order of precedence is command line,
environment, config file. Return True if all the keys were found
and False if not.
"""
env = os.environ.get
if not self.consumer_key:
self.consumer_key = env('CONSUMER_KEY')
if not self.consumer_secret:
self.consumer_secret = env('CONSUMER_SECRET')
if not self.access_token:
self.access_token = env('ACCESS_TOKEN')
if not self.access_token_secret:
self.access_token_secret = env('ACCESS_TOKEN_SECRET')
if self.config and not (self.consumer_key and
self.consumer_secret and
self.access_token and
self.access_token_secret):
self.load_config() | python | def get_keys(self):
"""
Get the Twitter API keys. Order of precedence is command line,
environment, config file. Return True if all the keys were found
and False if not.
"""
env = os.environ.get
if not self.consumer_key:
self.consumer_key = env('CONSUMER_KEY')
if not self.consumer_secret:
self.consumer_secret = env('CONSUMER_SECRET')
if not self.access_token:
self.access_token = env('ACCESS_TOKEN')
if not self.access_token_secret:
self.access_token_secret = env('ACCESS_TOKEN_SECRET')
if self.config and not (self.consumer_key and
self.consumer_secret and
self.access_token and
self.access_token_secret):
self.load_config() | [
"def",
"get_keys",
"(",
"self",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"get",
"if",
"not",
"self",
".",
"consumer_key",
":",
"self",
".",
"consumer_key",
"=",
"env",
"(",
"'CONSUMER_KEY'",
")",
"if",
"not",
"self",
".",
"consumer_secret",
":"... | Get the Twitter API keys. Order of precedence is command line,
environment, config file. Return True if all the keys were found
and False if not. | [
"Get",
"the",
"Twitter",
"API",
"keys",
".",
"Order",
"of",
"precedence",
"is",
"command",
"line",
"environment",
"config",
"file",
".",
"Return",
"True",
"if",
"all",
"the",
"keys",
"were",
"found",
"and",
"False",
"if",
"not",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L731-L751 | train | 224,561 |
DocNow/twarc | twarc/client.py | Twarc.validate_keys | def validate_keys(self):
"""
Validate the keys provided are authentic credentials.
"""
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
keys_present = self.consumer_key and self.consumer_secret and \
self.access_token and self.access_token_secret
if keys_present:
try:
# Need to explicitly reconnect to confirm the current creds
# are used in the session object.
self.connect()
self.get(url)
except requests.HTTPError as e:
if e.response.status_code == 401:
raise RuntimeError('Invalid credentials provided.')
else:
raise e
else:
raise RuntimeError('Incomplete credentials provided.') | python | def validate_keys(self):
"""
Validate the keys provided are authentic credentials.
"""
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
keys_present = self.consumer_key and self.consumer_secret and \
self.access_token and self.access_token_secret
if keys_present:
try:
# Need to explicitly reconnect to confirm the current creds
# are used in the session object.
self.connect()
self.get(url)
except requests.HTTPError as e:
if e.response.status_code == 401:
raise RuntimeError('Invalid credentials provided.')
else:
raise e
else:
raise RuntimeError('Incomplete credentials provided.') | [
"def",
"validate_keys",
"(",
"self",
")",
":",
"url",
"=",
"'https://api.twitter.com/1.1/account/verify_credentials.json'",
"keys_present",
"=",
"self",
".",
"consumer_key",
"and",
"self",
".",
"consumer_secret",
"and",
"self",
".",
"access_token",
"and",
"self",
".",... | Validate the keys provided are authentic credentials. | [
"Validate",
"the",
"keys",
"provided",
"are",
"authentic",
"credentials",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L753-L774 | train | 224,562 |
rochacbruno/dynaconf | dynaconf/contrib/flask_dynaconf.py | FlaskDynaconf.init_app | def init_app(self, app, **kwargs):
"""kwargs holds initial dynaconf configuration"""
self.kwargs.update(kwargs)
self.settings = self.dynaconf_instance or LazySettings(**self.kwargs)
app.config = self.make_config(app)
app.dynaconf = self.settings | python | def init_app(self, app, **kwargs):
"""kwargs holds initial dynaconf configuration"""
self.kwargs.update(kwargs)
self.settings = self.dynaconf_instance or LazySettings(**self.kwargs)
app.config = self.make_config(app)
app.dynaconf = self.settings | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"kwargs",
".",
"update",
"(",
"kwargs",
")",
"self",
".",
"settings",
"=",
"self",
".",
"dynaconf_instance",
"or",
"LazySettings",
"(",
"*",
"*",
"self",
".",... | kwargs holds initial dynaconf configuration | [
"kwargs",
"holds",
"initial",
"dynaconf",
"configuration"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/contrib/flask_dynaconf.py#L102-L107 | train | 224,563 |
rochacbruno/dynaconf | dynaconf/contrib/flask_dynaconf.py | DynaconfConfig.get | def get(self, key, default=None):
"""Gets config from dynaconf variables
if variables does not exists in dynaconf try getting from
`app.config` to support runtime settings."""
return self._settings.get(key, Config.get(self, key, default)) | python | def get(self, key, default=None):
"""Gets config from dynaconf variables
if variables does not exists in dynaconf try getting from
`app.config` to support runtime settings."""
return self._settings.get(key, Config.get(self, key, default)) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"_settings",
".",
"get",
"(",
"key",
",",
"Config",
".",
"get",
"(",
"self",
",",
"key",
",",
"default",
")",
")"
] | Gets config from dynaconf variables
if variables does not exists in dynaconf try getting from
`app.config` to support runtime settings. | [
"Gets",
"config",
"from",
"dynaconf",
"variables",
"if",
"variables",
"does",
"not",
"exists",
"in",
"dynaconf",
"try",
"getting",
"from",
"app",
".",
"config",
"to",
"support",
"runtime",
"settings",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/contrib/flask_dynaconf.py#L130-L134 | train | 224,564 |
rochacbruno/dynaconf | dynaconf/utils/__init__.py | object_merge | def object_merge(old, new, unique=False):
"""
Recursively merge two data structures.
:param unique: When set to True existing list items are not set.
"""
if isinstance(old, list) and isinstance(new, list):
if old == new:
return
for item in old[::-1]:
if unique and item in new:
continue
new.insert(0, item)
if isinstance(old, dict) and isinstance(new, dict):
for key, value in old.items():
if key not in new:
new[key] = value
else:
object_merge(value, new[key]) | python | def object_merge(old, new, unique=False):
"""
Recursively merge two data structures.
:param unique: When set to True existing list items are not set.
"""
if isinstance(old, list) and isinstance(new, list):
if old == new:
return
for item in old[::-1]:
if unique and item in new:
continue
new.insert(0, item)
if isinstance(old, dict) and isinstance(new, dict):
for key, value in old.items():
if key not in new:
new[key] = value
else:
object_merge(value, new[key]) | [
"def",
"object_merge",
"(",
"old",
",",
"new",
",",
"unique",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"old",
",",
"list",
")",
"and",
"isinstance",
"(",
"new",
",",
"list",
")",
":",
"if",
"old",
"==",
"new",
":",
"return",
"for",
"item",
... | Recursively merge two data structures.
:param unique: When set to True existing list items are not set. | [
"Recursively",
"merge",
"two",
"data",
"structures",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/__init__.py#L20-L38 | train | 224,565 |
rochacbruno/dynaconf | dynaconf/utils/__init__.py | compat_kwargs | def compat_kwargs(kwargs):
"""To keep backwards compat change the kwargs to new names"""
warn_deprecations(kwargs)
for old, new in RENAMED_VARS.items():
if old in kwargs:
kwargs[new] = kwargs[old]
# update cross references
for c_old, c_new in RENAMED_VARS.items():
if c_new == new:
kwargs[c_old] = kwargs[new] | python | def compat_kwargs(kwargs):
"""To keep backwards compat change the kwargs to new names"""
warn_deprecations(kwargs)
for old, new in RENAMED_VARS.items():
if old in kwargs:
kwargs[new] = kwargs[old]
# update cross references
for c_old, c_new in RENAMED_VARS.items():
if c_new == new:
kwargs[c_old] = kwargs[new] | [
"def",
"compat_kwargs",
"(",
"kwargs",
")",
":",
"warn_deprecations",
"(",
"kwargs",
")",
"for",
"old",
",",
"new",
"in",
"RENAMED_VARS",
".",
"items",
"(",
")",
":",
"if",
"old",
"in",
"kwargs",
":",
"kwargs",
"[",
"new",
"]",
"=",
"kwargs",
"[",
"o... | To keep backwards compat change the kwargs to new names | [
"To",
"keep",
"backwards",
"compat",
"change",
"the",
"kwargs",
"to",
"new",
"names"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/__init__.py#L107-L116 | train | 224,566 |
rochacbruno/dynaconf | dynaconf/utils/__init__.py | deduplicate | def deduplicate(list_object):
"""Rebuild `list_object` removing duplicated and keeping order"""
new = []
for item in list_object:
if item not in new:
new.append(item)
return new | python | def deduplicate(list_object):
"""Rebuild `list_object` removing duplicated and keeping order"""
new = []
for item in list_object:
if item not in new:
new.append(item)
return new | [
"def",
"deduplicate",
"(",
"list_object",
")",
":",
"new",
"=",
"[",
"]",
"for",
"item",
"in",
"list_object",
":",
"if",
"item",
"not",
"in",
"new",
":",
"new",
".",
"append",
"(",
"item",
")",
"return",
"new"
] | Rebuild `list_object` removing duplicated and keeping order | [
"Rebuild",
"list_object",
"removing",
"duplicated",
"and",
"keeping",
"order"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/__init__.py#L148-L154 | train | 224,567 |
rochacbruno/dynaconf | dynaconf/utils/__init__.py | trimmed_split | def trimmed_split(s, seps=(";", ",")):
"""Given a string s, split is by one of one of the seps."""
for sep in seps:
if sep not in s:
continue
data = [item.strip() for item in s.strip().split(sep)]
return data
return [s] | python | def trimmed_split(s, seps=(";", ",")):
"""Given a string s, split is by one of one of the seps."""
for sep in seps:
if sep not in s:
continue
data = [item.strip() for item in s.strip().split(sep)]
return data
return [s] | [
"def",
"trimmed_split",
"(",
"s",
",",
"seps",
"=",
"(",
"\";\"",
",",
"\",\"",
")",
")",
":",
"for",
"sep",
"in",
"seps",
":",
"if",
"sep",
"not",
"in",
"s",
":",
"continue",
"data",
"=",
"[",
"item",
".",
"strip",
"(",
")",
"for",
"item",
"in... | Given a string s, split is by one of one of the seps. | [
"Given",
"a",
"string",
"s",
"split",
"is",
"by",
"one",
"of",
"one",
"of",
"the",
"seps",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/__init__.py#L175-L182 | train | 224,568 |
rochacbruno/dynaconf | dynaconf/utils/__init__.py | ensure_a_list | def ensure_a_list(data):
"""Ensure data is a list or wrap it in a list"""
if not data:
return []
if isinstance(data, (list, tuple, set)):
return list(data)
if isinstance(data, str):
data = trimmed_split(data) # settings.toml,other.yaml
return data
return [data] | python | def ensure_a_list(data):
"""Ensure data is a list or wrap it in a list"""
if not data:
return []
if isinstance(data, (list, tuple, set)):
return list(data)
if isinstance(data, str):
data = trimmed_split(data) # settings.toml,other.yaml
return data
return [data] | [
"def",
"ensure_a_list",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"[",
"]",
"if",
"isinstance",
"(",
"data",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
":",
"return",
"list",
"(",
"data",
")",
"if",
"isinstance",
"(",
... | Ensure data is a list or wrap it in a list | [
"Ensure",
"data",
"is",
"a",
"list",
"or",
"wrap",
"it",
"in",
"a",
"list"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/__init__.py#L185-L194 | train | 224,569 |
rochacbruno/dynaconf | dynaconf/loaders/redis_loader.py | load | def load(obj, env=None, silent=True, key=None):
"""Reads and loads in to "settings" a single key or all keys from redis
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:param silent: if errors should raise
:param key: if defined load a single key, else load all in env
:return: None
"""
redis = StrictRedis(**obj.get("REDIS_FOR_DYNACONF"))
holder = obj.get("ENVVAR_PREFIX_FOR_DYNACONF")
try:
if key:
value = redis.hget(holder.upper(), key)
if value:
obj.logger.debug(
"redis_loader: loading by key: %s:%s (%s:%s)",
key,
value,
IDENTIFIER,
holder,
)
if value:
parsed_value = parse_conf_data(value, tomlfy=True)
if parsed_value:
obj.set(key, parsed_value)
else:
data = {
key: parse_conf_data(value, tomlfy=True)
for key, value in redis.hgetall(holder.upper()).items()
}
if data:
obj.logger.debug(
"redis_loader: loading: %s (%s:%s)",
data,
IDENTIFIER,
holder,
)
obj.update(data, loader_identifier=IDENTIFIER)
except Exception as e:
if silent:
if hasattr(obj, "logger"):
obj.logger.error(str(e))
return False
raise | python | def load(obj, env=None, silent=True, key=None):
"""Reads and loads in to "settings" a single key or all keys from redis
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:param silent: if errors should raise
:param key: if defined load a single key, else load all in env
:return: None
"""
redis = StrictRedis(**obj.get("REDIS_FOR_DYNACONF"))
holder = obj.get("ENVVAR_PREFIX_FOR_DYNACONF")
try:
if key:
value = redis.hget(holder.upper(), key)
if value:
obj.logger.debug(
"redis_loader: loading by key: %s:%s (%s:%s)",
key,
value,
IDENTIFIER,
holder,
)
if value:
parsed_value = parse_conf_data(value, tomlfy=True)
if parsed_value:
obj.set(key, parsed_value)
else:
data = {
key: parse_conf_data(value, tomlfy=True)
for key, value in redis.hgetall(holder.upper()).items()
}
if data:
obj.logger.debug(
"redis_loader: loading: %s (%s:%s)",
data,
IDENTIFIER,
holder,
)
obj.update(data, loader_identifier=IDENTIFIER)
except Exception as e:
if silent:
if hasattr(obj, "logger"):
obj.logger.error(str(e))
return False
raise | [
"def",
"load",
"(",
"obj",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"redis",
"=",
"StrictRedis",
"(",
"*",
"*",
"obj",
".",
"get",
"(",
"\"REDIS_FOR_DYNACONF\"",
")",
")",
"holder",
"=",
"obj",
".",
... | Reads and loads in to "settings" a single key or all keys from redis
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:param silent: if errors should raise
:param key: if defined load a single key, else load all in env
:return: None | [
"Reads",
"and",
"loads",
"in",
"to",
"settings",
"a",
"single",
"key",
"or",
"all",
"keys",
"from",
"redis"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/redis_loader.py#L16-L60 | train | 224,570 |
rochacbruno/dynaconf | dynaconf/loaders/py_loader.py | load | def load(obj, settings_module, identifier="py", silent=False, key=None):
"""Tries to import a python module"""
mod, loaded_from = get_module(obj, settings_module, silent)
if mod and loaded_from:
obj.logger.debug("py_loader: {}".format(mod))
else:
obj.logger.debug(
"py_loader: %s (Ignoring, Not Found)", settings_module
)
return
for setting in dir(mod):
if setting.isupper():
if key is None or key == setting:
setting_value = getattr(mod, setting)
obj.logger.debug(
"py_loader: loading %s: %s (%s)",
setting,
"*****" if "secret" in settings_module else setting_value,
identifier,
)
obj.set(setting, setting_value, loader_identifier=identifier)
obj._loaded_files.append(mod.__file__) | python | def load(obj, settings_module, identifier="py", silent=False, key=None):
"""Tries to import a python module"""
mod, loaded_from = get_module(obj, settings_module, silent)
if mod and loaded_from:
obj.logger.debug("py_loader: {}".format(mod))
else:
obj.logger.debug(
"py_loader: %s (Ignoring, Not Found)", settings_module
)
return
for setting in dir(mod):
if setting.isupper():
if key is None or key == setting:
setting_value = getattr(mod, setting)
obj.logger.debug(
"py_loader: loading %s: %s (%s)",
setting,
"*****" if "secret" in settings_module else setting_value,
identifier,
)
obj.set(setting, setting_value, loader_identifier=identifier)
obj._loaded_files.append(mod.__file__) | [
"def",
"load",
"(",
"obj",
",",
"settings_module",
",",
"identifier",
"=",
"\"py\"",
",",
"silent",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"mod",
",",
"loaded_from",
"=",
"get_module",
"(",
"obj",
",",
"settings_module",
",",
"silent",
")",
"... | Tries to import a python module | [
"Tries",
"to",
"import",
"a",
"python",
"module"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/py_loader.py#L15-L39 | train | 224,571 |
rochacbruno/dynaconf | dynaconf/loaders/py_loader.py | import_from_filename | def import_from_filename(obj, filename, silent=False): # pragma: no cover
"""If settings_module is a filename path import it."""
if filename in [item.filename for item in inspect.stack()]:
raise ImportError(
"Looks like you are loading dynaconf "
"from inside the {} file and then it is trying "
"to load itself entering in a circular reference "
"problem. To solve it you have to "
"invoke your program from another root folder "
"or rename your program file.".format(filename)
)
_find_file = getattr(obj, "find_file", find_file)
if not filename.endswith(".py"):
filename = "{0}.py".format(filename)
if filename in default_settings.SETTINGS_FILE_FOR_DYNACONF:
silent = True
mod = types.ModuleType(filename.rstrip(".py"))
mod.__file__ = filename
mod._is_error = False
try:
with io.open(
_find_file(filename),
encoding=default_settings.ENCODING_FOR_DYNACONF,
) as config_file:
exec(compile(config_file.read(), filename, "exec"), mod.__dict__)
except IOError as e:
e.strerror = ("py_loader: error loading file (%s %s)\n") % (
e.strerror,
filename,
)
if silent and e.errno in (errno.ENOENT, errno.EISDIR):
return
raw_logger().debug(e.strerror)
mod._is_error = True
return mod | python | def import_from_filename(obj, filename, silent=False): # pragma: no cover
"""If settings_module is a filename path import it."""
if filename in [item.filename for item in inspect.stack()]:
raise ImportError(
"Looks like you are loading dynaconf "
"from inside the {} file and then it is trying "
"to load itself entering in a circular reference "
"problem. To solve it you have to "
"invoke your program from another root folder "
"or rename your program file.".format(filename)
)
_find_file = getattr(obj, "find_file", find_file)
if not filename.endswith(".py"):
filename = "{0}.py".format(filename)
if filename in default_settings.SETTINGS_FILE_FOR_DYNACONF:
silent = True
mod = types.ModuleType(filename.rstrip(".py"))
mod.__file__ = filename
mod._is_error = False
try:
with io.open(
_find_file(filename),
encoding=default_settings.ENCODING_FOR_DYNACONF,
) as config_file:
exec(compile(config_file.read(), filename, "exec"), mod.__dict__)
except IOError as e:
e.strerror = ("py_loader: error loading file (%s %s)\n") % (
e.strerror,
filename,
)
if silent and e.errno in (errno.ENOENT, errno.EISDIR):
return
raw_logger().debug(e.strerror)
mod._is_error = True
return mod | [
"def",
"import_from_filename",
"(",
"obj",
",",
"filename",
",",
"silent",
"=",
"False",
")",
":",
"# pragma: no cover",
"if",
"filename",
"in",
"[",
"item",
".",
"filename",
"for",
"item",
"in",
"inspect",
".",
"stack",
"(",
")",
"]",
":",
"raise",
"Imp... | If settings_module is a filename path import it. | [
"If",
"settings_module",
"is",
"a",
"filename",
"path",
"import",
"it",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/py_loader.py#L58-L94 | train | 224,572 |
rochacbruno/dynaconf | dynaconf/loaders/vault_loader.py | _get_env_list | def _get_env_list(obj, env):
"""Creates the list of environments to read
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:return: a list of working environments
"""
# add the [default] env
env_list = [obj.get("DEFAULT_ENV_FOR_DYNACONF")]
# compatibility with older versions that still uses [dynaconf] as
# [default] env
global_env = obj.get("ENVVAR_PREFIX_FOR_DYNACONF") or "DYNACONF"
if global_env not in env_list:
env_list.append(global_env)
# add the current env
if obj.current_env and obj.current_env not in env_list:
env_list.append(obj.current_env)
# add a manually set env
if env and env not in env_list:
env_list.append(env)
# add the [global] env
env_list.append("GLOBAL")
return [env.lower() for env in env_list] | python | def _get_env_list(obj, env):
"""Creates the list of environments to read
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:return: a list of working environments
"""
# add the [default] env
env_list = [obj.get("DEFAULT_ENV_FOR_DYNACONF")]
# compatibility with older versions that still uses [dynaconf] as
# [default] env
global_env = obj.get("ENVVAR_PREFIX_FOR_DYNACONF") or "DYNACONF"
if global_env not in env_list:
env_list.append(global_env)
# add the current env
if obj.current_env and obj.current_env not in env_list:
env_list.append(obj.current_env)
# add a manually set env
if env and env not in env_list:
env_list.append(env)
# add the [global] env
env_list.append("GLOBAL")
return [env.lower() for env in env_list] | [
"def",
"_get_env_list",
"(",
"obj",
",",
"env",
")",
":",
"# add the [default] env",
"env_list",
"=",
"[",
"obj",
".",
"get",
"(",
"\"DEFAULT_ENV_FOR_DYNACONF\"",
")",
"]",
"# compatibility with older versions that still uses [dynaconf] as",
"# [default] env",
"global_env",... | Creates the list of environments to read
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:return: a list of working environments | [
"Creates",
"the",
"list",
"of",
"environments",
"to",
"read"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/vault_loader.py#L18-L40 | train | 224,573 |
rochacbruno/dynaconf | dynaconf/loaders/vault_loader.py | load | def load(obj, env=None, silent=None, key=None):
"""Reads and loads in to "settings" a single key or all keys from vault
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:param silent: if errors should raise
:param key: if defined load a single key, else load all in env
:return: None
"""
client = get_client(obj)
env_list = _get_env_list(obj, env)
for env in env_list:
path = "/".join([obj.VAULT_PATH_FOR_DYNACONF, env]).replace("//", "/")
data = client.read(path)
if data:
# There seems to be a data dict within a data dict,
# extract the inner data
data = data.get("data", {}).get("data", {})
try:
if data and key:
value = parse_conf_data(data.get(key), tomlfy=True)
if value:
obj.logger.debug(
"vault_loader: loading by key: %s:%s (%s:%s)",
key,
"****",
IDENTIFIER,
path,
)
obj.set(key, value)
elif data:
obj.logger.debug(
"vault_loader: loading: %s (%s:%s)",
list(data.keys()),
IDENTIFIER,
path,
)
obj.update(data, loader_identifier=IDENTIFIER, tomlfy=True)
except Exception as e:
if silent:
if hasattr(obj, "logger"):
obj.logger.error(str(e))
return False
raise | python | def load(obj, env=None, silent=None, key=None):
"""Reads and loads in to "settings" a single key or all keys from vault
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:param silent: if errors should raise
:param key: if defined load a single key, else load all in env
:return: None
"""
client = get_client(obj)
env_list = _get_env_list(obj, env)
for env in env_list:
path = "/".join([obj.VAULT_PATH_FOR_DYNACONF, env]).replace("//", "/")
data = client.read(path)
if data:
# There seems to be a data dict within a data dict,
# extract the inner data
data = data.get("data", {}).get("data", {})
try:
if data and key:
value = parse_conf_data(data.get(key), tomlfy=True)
if value:
obj.logger.debug(
"vault_loader: loading by key: %s:%s (%s:%s)",
key,
"****",
IDENTIFIER,
path,
)
obj.set(key, value)
elif data:
obj.logger.debug(
"vault_loader: loading: %s (%s:%s)",
list(data.keys()),
IDENTIFIER,
path,
)
obj.update(data, loader_identifier=IDENTIFIER, tomlfy=True)
except Exception as e:
if silent:
if hasattr(obj, "logger"):
obj.logger.error(str(e))
return False
raise | [
"def",
"load",
"(",
"obj",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"client",
"=",
"get_client",
"(",
"obj",
")",
"env_list",
"=",
"_get_env_list",
"(",
"obj",
",",
"env",
")",
"for",
"env",
"in",
"e... | Reads and loads in to "settings" a single key or all keys from vault
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:param silent: if errors should raise
:param key: if defined load a single key, else load all in env
:return: None | [
"Reads",
"and",
"loads",
"in",
"to",
"settings",
"a",
"single",
"key",
"or",
"all",
"keys",
"from",
"vault"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/vault_loader.py#L53-L97 | train | 224,574 |
rochacbruno/dynaconf | dynaconf/cli.py | set_settings | def set_settings(instance=None):
"""Pick correct settings instance and set it to a global variable."""
global settings
settings = None
if instance:
settings = import_settings(instance)
elif "INSTANCE_FOR_DYNACONF" in os.environ:
settings = import_settings(os.environ["INSTANCE_FOR_DYNACONF"])
elif "FLASK_APP" in os.environ: # pragma: no cover
with suppress(ImportError, click.UsageError):
from flask.cli import ScriptInfo
flask_app = ScriptInfo().load_app()
settings = flask_app.config
click.echo(
click.style(
"Flask app detected", fg="white", bg="bright_black"
)
)
elif "DJANGO_SETTINGS_MODULE" in os.environ: # pragma: no cover
sys.path.insert(0, os.path.abspath(os.getcwd()))
try:
# Django extension v2
from django.conf import settings
settings.DYNACONF.configure()
except (ImportError, AttributeError):
# Backwards compatible with old django extension (pre 2.0.0)
import dynaconf.contrib.django_dynaconf # noqa
from django.conf import settings as django_settings
django_settings.configure()
settings = django_settings
if settings is not None:
click.echo(
click.style(
"Django app detected", fg="white", bg="bright_black"
)
)
if settings is None:
settings = LazySettings() | python | def set_settings(instance=None):
"""Pick correct settings instance and set it to a global variable."""
global settings
settings = None
if instance:
settings = import_settings(instance)
elif "INSTANCE_FOR_DYNACONF" in os.environ:
settings = import_settings(os.environ["INSTANCE_FOR_DYNACONF"])
elif "FLASK_APP" in os.environ: # pragma: no cover
with suppress(ImportError, click.UsageError):
from flask.cli import ScriptInfo
flask_app = ScriptInfo().load_app()
settings = flask_app.config
click.echo(
click.style(
"Flask app detected", fg="white", bg="bright_black"
)
)
elif "DJANGO_SETTINGS_MODULE" in os.environ: # pragma: no cover
sys.path.insert(0, os.path.abspath(os.getcwd()))
try:
# Django extension v2
from django.conf import settings
settings.DYNACONF.configure()
except (ImportError, AttributeError):
# Backwards compatible with old django extension (pre 2.0.0)
import dynaconf.contrib.django_dynaconf # noqa
from django.conf import settings as django_settings
django_settings.configure()
settings = django_settings
if settings is not None:
click.echo(
click.style(
"Django app detected", fg="white", bg="bright_black"
)
)
if settings is None:
settings = LazySettings() | [
"def",
"set_settings",
"(",
"instance",
"=",
"None",
")",
":",
"global",
"settings",
"settings",
"=",
"None",
"if",
"instance",
":",
"settings",
"=",
"import_settings",
"(",
"instance",
")",
"elif",
"\"INSTANCE_FOR_DYNACONF\"",
"in",
"os",
".",
"environ",
":",... | Pick correct settings instance and set it to a global variable. | [
"Pick",
"correct",
"settings",
"instance",
"and",
"set",
"it",
"to",
"a",
"global",
"variable",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/cli.py#L33-L81 | train | 224,575 |
rochacbruno/dynaconf | dynaconf/cli.py | import_settings | def import_settings(dotted_path):
"""Import settings instance from python dotted path.
Last item in dotted path must be settings instace.
Example: import_settings('path.to.settings')
"""
if "." in dotted_path:
module, name = dotted_path.rsplit(".", 1)
else:
raise click.UsageError(
"invalid path to settings instance: {}".format(dotted_path)
)
try:
module = importlib.import_module(module)
except ImportError as e:
raise click.UsageError(e)
try:
return getattr(module, name)
except AttributeError as e:
raise click.UsageError(e) | python | def import_settings(dotted_path):
"""Import settings instance from python dotted path.
Last item in dotted path must be settings instace.
Example: import_settings('path.to.settings')
"""
if "." in dotted_path:
module, name = dotted_path.rsplit(".", 1)
else:
raise click.UsageError(
"invalid path to settings instance: {}".format(dotted_path)
)
try:
module = importlib.import_module(module)
except ImportError as e:
raise click.UsageError(e)
try:
return getattr(module, name)
except AttributeError as e:
raise click.UsageError(e) | [
"def",
"import_settings",
"(",
"dotted_path",
")",
":",
"if",
"\".\"",
"in",
"dotted_path",
":",
"module",
",",
"name",
"=",
"dotted_path",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"else",
":",
"raise",
"click",
".",
"UsageError",
"(",
"\"invalid path t... | Import settings instance from python dotted path.
Last item in dotted path must be settings instace.
Example: import_settings('path.to.settings') | [
"Import",
"settings",
"instance",
"from",
"python",
"dotted",
"path",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/cli.py#L84-L104 | train | 224,576 |
rochacbruno/dynaconf | dynaconf/cli.py | read_file_in_root_directory | def read_file_in_root_directory(*names, **kwargs):
"""Read a file on root dir."""
return read_file(
os.path.join(os.path.dirname(__file__), *names),
encoding=kwargs.get("encoding", "utf-8"),
) | python | def read_file_in_root_directory(*names, **kwargs):
"""Read a file on root dir."""
return read_file(
os.path.join(os.path.dirname(__file__), *names),
encoding=kwargs.get("encoding", "utf-8"),
) | [
"def",
"read_file_in_root_directory",
"(",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"read_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"*",
"names",
")",
",",
"encodi... | Read a file on root dir. | [
"Read",
"a",
"file",
"on",
"root",
"dir",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/cli.py#L119-L124 | train | 224,577 |
rochacbruno/dynaconf | dynaconf/cli.py | show_banner | def show_banner(ctx, param, value):
"""Shows dynaconf awesome banner"""
if not value or ctx.resilient_parsing:
return
set_settings()
click.echo(settings.dynaconf_banner)
click.echo("Learn more at: http://github.com/rochacbruno/dynaconf")
ctx.exit() | python | def show_banner(ctx, param, value):
"""Shows dynaconf awesome banner"""
if not value or ctx.resilient_parsing:
return
set_settings()
click.echo(settings.dynaconf_banner)
click.echo("Learn more at: http://github.com/rochacbruno/dynaconf")
ctx.exit() | [
"def",
"show_banner",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"not",
"value",
"or",
"ctx",
".",
"resilient_parsing",
":",
"return",
"set_settings",
"(",
")",
"click",
".",
"echo",
"(",
"settings",
".",
"dynaconf_banner",
")",
"click",
"."... | Shows dynaconf awesome banner | [
"Shows",
"dynaconf",
"awesome",
"banner"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/cli.py#L143-L150 | train | 224,578 |
rochacbruno/dynaconf | dynaconf/cli.py | write | def write(to, _vars, _secrets, path, env, y):
"""Writes data to specific source"""
_vars = split_vars(_vars)
_secrets = split_vars(_secrets)
loader = importlib.import_module("dynaconf.loaders.{}_loader".format(to))
if to in EXTS:
# Lets write to a file
path = Path(path)
if str(path).endswith(constants.ALL_EXTENSIONS + ("py",)):
settings_path = path
secrets_path = path.parent / ".secrets.{}".format(to)
else:
if to == "env":
if str(path) in (".env", "./.env"): # pragma: no cover
settings_path = path
elif str(path).endswith("/.env"):
settings_path = path
elif str(path).endswith(".env"):
settings_path = path.parent / ".env"
else:
settings_path = path / ".env"
Path.touch(settings_path)
secrets_path = None
_vars.update(_secrets)
else:
settings_path = path / "settings.{}".format(to)
secrets_path = path / ".secrets.{}".format(to)
if (
_vars and not y and settings_path and settings_path.exists()
): # pragma: no cover # noqa
click.confirm(
"{} exists do you want to overwrite it?".format(settings_path),
abort=True,
)
if (
_secrets and not y and secrets_path and secrets_path.exists()
): # pragma: no cover # noqa
click.confirm(
"{} exists do you want to overwrite it?".format(secrets_path),
abort=True,
)
if to not in ["py", "env"]:
if _vars:
_vars = {env: _vars}
if _secrets:
_secrets = {env: _secrets}
if _vars and settings_path:
loader.write(settings_path, _vars, merge=True)
click.echo("Data successful written to {}".format(settings_path))
if _secrets and secrets_path:
loader.write(secrets_path, _secrets, merge=True)
click.echo("Data successful written to {}".format(secrets_path))
else: # pragma: no cover
# lets write to external source
with settings.using_env(env):
# make sure we're in the correct environment
loader.write(settings, _vars, **_secrets)
click.echo("Data successful written to {}".format(to)) | python | def write(to, _vars, _secrets, path, env, y):
"""Writes data to specific source"""
_vars = split_vars(_vars)
_secrets = split_vars(_secrets)
loader = importlib.import_module("dynaconf.loaders.{}_loader".format(to))
if to in EXTS:
# Lets write to a file
path = Path(path)
if str(path).endswith(constants.ALL_EXTENSIONS + ("py",)):
settings_path = path
secrets_path = path.parent / ".secrets.{}".format(to)
else:
if to == "env":
if str(path) in (".env", "./.env"): # pragma: no cover
settings_path = path
elif str(path).endswith("/.env"):
settings_path = path
elif str(path).endswith(".env"):
settings_path = path.parent / ".env"
else:
settings_path = path / ".env"
Path.touch(settings_path)
secrets_path = None
_vars.update(_secrets)
else:
settings_path = path / "settings.{}".format(to)
secrets_path = path / ".secrets.{}".format(to)
if (
_vars and not y and settings_path and settings_path.exists()
): # pragma: no cover # noqa
click.confirm(
"{} exists do you want to overwrite it?".format(settings_path),
abort=True,
)
if (
_secrets and not y and secrets_path and secrets_path.exists()
): # pragma: no cover # noqa
click.confirm(
"{} exists do you want to overwrite it?".format(secrets_path),
abort=True,
)
if to not in ["py", "env"]:
if _vars:
_vars = {env: _vars}
if _secrets:
_secrets = {env: _secrets}
if _vars and settings_path:
loader.write(settings_path, _vars, merge=True)
click.echo("Data successful written to {}".format(settings_path))
if _secrets and secrets_path:
loader.write(secrets_path, _secrets, merge=True)
click.echo("Data successful written to {}".format(secrets_path))
else: # pragma: no cover
# lets write to external source
with settings.using_env(env):
# make sure we're in the correct environment
loader.write(settings, _vars, **_secrets)
click.echo("Data successful written to {}".format(to)) | [
"def",
"write",
"(",
"to",
",",
"_vars",
",",
"_secrets",
",",
"path",
",",
"env",
",",
"y",
")",
":",
"_vars",
"=",
"split_vars",
"(",
"_vars",
")",
"_secrets",
"=",
"split_vars",
"(",
"_secrets",
")",
"loader",
"=",
"importlib",
".",
"import_module",... | Writes data to specific source | [
"Writes",
"data",
"to",
"specific",
"source"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/cli.py#L496-L562 | train | 224,579 |
rochacbruno/dynaconf | dynaconf/cli.py | validate | def validate(path): # pragma: no cover
"""Validates Dynaconf settings based on rules defined in
dynaconf_validators.toml"""
# reads the 'dynaconf_validators.toml' from path
# for each section register the validator for specific env
# call validate
path = Path(path)
if not str(path).endswith(".toml"):
path = path / "dynaconf_validators.toml"
if not path.exists(): # pragma: no cover # noqa
click.echo(
click.style("{} not found".format(path), fg="white", bg="red")
)
sys.exit(1)
validation_data = toml.load(open(str(path)))
success = True
for env, name_data in validation_data.items():
for name, data in name_data.items():
if not isinstance(data, dict): # pragma: no cover
click.echo(
click.style(
"Invalid rule for parameter '{}'".format(name),
fg="white",
bg="yellow",
)
)
else:
data.setdefault("env", env)
click.echo(
click.style(
"Validating '{}' with '{}'".format(name, data),
fg="white",
bg="blue",
)
)
try:
Validator(name, **data).validate(settings)
except ValidationError as e:
click.echo(
click.style(
"Error: {}".format(e), fg="white", bg="red"
)
)
success = False
if success:
click.echo(click.style("Validation success!", fg="white", bg="green")) | python | def validate(path): # pragma: no cover
"""Validates Dynaconf settings based on rules defined in
dynaconf_validators.toml"""
# reads the 'dynaconf_validators.toml' from path
# for each section register the validator for specific env
# call validate
path = Path(path)
if not str(path).endswith(".toml"):
path = path / "dynaconf_validators.toml"
if not path.exists(): # pragma: no cover # noqa
click.echo(
click.style("{} not found".format(path), fg="white", bg="red")
)
sys.exit(1)
validation_data = toml.load(open(str(path)))
success = True
for env, name_data in validation_data.items():
for name, data in name_data.items():
if not isinstance(data, dict): # pragma: no cover
click.echo(
click.style(
"Invalid rule for parameter '{}'".format(name),
fg="white",
bg="yellow",
)
)
else:
data.setdefault("env", env)
click.echo(
click.style(
"Validating '{}' with '{}'".format(name, data),
fg="white",
bg="blue",
)
)
try:
Validator(name, **data).validate(settings)
except ValidationError as e:
click.echo(
click.style(
"Error: {}".format(e), fg="white", bg="red"
)
)
success = False
if success:
click.echo(click.style("Validation success!", fg="white", bg="green")) | [
"def",
"validate",
"(",
"path",
")",
":",
"# pragma: no cover",
"# reads the 'dynaconf_validators.toml' from path",
"# for each section register the validator for specific env",
"# call validate",
"path",
"=",
"Path",
"(",
"path",
")",
"if",
"not",
"str",
"(",
"path",
")",
... | Validates Dynaconf settings based on rules defined in
dynaconf_validators.toml | [
"Validates",
"Dynaconf",
"settings",
"based",
"on",
"rules",
"defined",
"in",
"dynaconf_validators",
".",
"toml"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/cli.py#L569-L620 | train | 224,580 |
rochacbruno/dynaconf | example/common/program.py | connect | def connect(server, port, username, password):
"""This function might be something coming from your ORM"""
print("-" * 79)
print("Connecting to: {}".format(server))
print("At port: {}".format(port))
print("Using username: {}".format(username))
print("Using password: {}".format(password))
print("-" * 79) | python | def connect(server, port, username, password):
"""This function might be something coming from your ORM"""
print("-" * 79)
print("Connecting to: {}".format(server))
print("At port: {}".format(port))
print("Using username: {}".format(username))
print("Using password: {}".format(password))
print("-" * 79) | [
"def",
"connect",
"(",
"server",
",",
"port",
",",
"username",
",",
"password",
")",
":",
"print",
"(",
"\"-\"",
"*",
"79",
")",
"print",
"(",
"\"Connecting to: {}\"",
".",
"format",
"(",
"server",
")",
")",
"print",
"(",
"\"At port: {}\"",
".",
"format"... | This function might be something coming from your ORM | [
"This",
"function",
"might",
"be",
"something",
"coming",
"from",
"your",
"ORM"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/example/common/program.py#L4-L11 | train | 224,581 |
rochacbruno/dynaconf | dynaconf/loaders/env_loader.py | write | def write(settings_path, settings_data, **kwargs):
"""Write data to .env file"""
for key, value in settings_data.items():
dotenv_cli.set_key(str(settings_path), key.upper(), str(value)) | python | def write(settings_path, settings_data, **kwargs):
"""Write data to .env file"""
for key, value in settings_data.items():
dotenv_cli.set_key(str(settings_path), key.upper(), str(value)) | [
"def",
"write",
"(",
"settings_path",
",",
"settings_data",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
",",
"value",
"in",
"settings_data",
".",
"items",
"(",
")",
":",
"dotenv_cli",
".",
"set_key",
"(",
"str",
"(",
"settings_path",
")",
",",
"ke... | Write data to .env file | [
"Write",
"data",
"to",
".",
"env",
"file"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/env_loader.py#L60-L63 | train | 224,582 |
rochacbruno/dynaconf | dynaconf/utils/parse_conf.py | parse_with_toml | def parse_with_toml(data):
"""Uses TOML syntax to parse data"""
try:
return toml.loads("key={}".format(data), DynaBox).key
except toml.TomlDecodeError:
return data | python | def parse_with_toml(data):
"""Uses TOML syntax to parse data"""
try:
return toml.loads("key={}".format(data), DynaBox).key
except toml.TomlDecodeError:
return data | [
"def",
"parse_with_toml",
"(",
"data",
")",
":",
"try",
":",
"return",
"toml",
".",
"loads",
"(",
"\"key={}\"",
".",
"format",
"(",
"data",
")",
",",
"DynaBox",
")",
".",
"key",
"except",
"toml",
".",
"TomlDecodeError",
":",
"return",
"data"
] | Uses TOML syntax to parse data | [
"Uses",
"TOML",
"syntax",
"to",
"parse",
"data"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/parse_conf.py#L28-L33 | train | 224,583 |
rochacbruno/dynaconf | dynaconf/loaders/base.py | BaseLoader.load | def load(self, filename=None, key=None, silent=True):
"""
Reads and loads in to `self.obj` a single key or all keys from source
:param filename: Optional filename to load
:param key: if provided load a single key
:param silent: if load erros should be silenced
"""
filename = filename or self.obj.get(self.identifier.upper())
if not filename:
return
if not isinstance(filename, (list, tuple)):
split_files = ensure_a_list(filename)
if all([f.endswith(self.extensions) for f in split_files]): # noqa
files = split_files # it is a ['file.ext', ...]
else: # it is a single config as string
files = [filename]
else: # it is already a list/tuple
files = filename
self.obj._loaded_files.extend(files)
# add the [default] env
env_list = [self.obj.get("DEFAULT_ENV_FOR_DYNACONF")]
# compatibility with older versions that still uses [dynaconf] as
# [default] env
global_env = self.obj.get("ENVVAR_PREFIX_FOR_DYNACONF") or "DYNACONF"
if global_env not in env_list:
env_list.append(global_env)
# add the current [env]
if self.env not in env_list:
env_list.append(self.env)
# add the [global] env
env_list.append("GLOBAL")
# load all envs
self._read(files, env_list, silent, key) | python | def load(self, filename=None, key=None, silent=True):
"""
Reads and loads in to `self.obj` a single key or all keys from source
:param filename: Optional filename to load
:param key: if provided load a single key
:param silent: if load erros should be silenced
"""
filename = filename or self.obj.get(self.identifier.upper())
if not filename:
return
if not isinstance(filename, (list, tuple)):
split_files = ensure_a_list(filename)
if all([f.endswith(self.extensions) for f in split_files]): # noqa
files = split_files # it is a ['file.ext', ...]
else: # it is a single config as string
files = [filename]
else: # it is already a list/tuple
files = filename
self.obj._loaded_files.extend(files)
# add the [default] env
env_list = [self.obj.get("DEFAULT_ENV_FOR_DYNACONF")]
# compatibility with older versions that still uses [dynaconf] as
# [default] env
global_env = self.obj.get("ENVVAR_PREFIX_FOR_DYNACONF") or "DYNACONF"
if global_env not in env_list:
env_list.append(global_env)
# add the current [env]
if self.env not in env_list:
env_list.append(self.env)
# add the [global] env
env_list.append("GLOBAL")
# load all envs
self._read(files, env_list, silent, key) | [
"def",
"load",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"key",
"=",
"None",
",",
"silent",
"=",
"True",
")",
":",
"filename",
"=",
"filename",
"or",
"self",
".",
"obj",
".",
"get",
"(",
"self",
".",
"identifier",
".",
"upper",
"(",
")",
")... | Reads and loads in to `self.obj` a single key or all keys from source
:param filename: Optional filename to load
:param key: if provided load a single key
:param silent: if load erros should be silenced | [
"Reads",
"and",
"loads",
"in",
"to",
"self",
".",
"obj",
"a",
"single",
"key",
"or",
"all",
"keys",
"from",
"source"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/base.py#L44-L84 | train | 224,584 |
rochacbruno/dynaconf | dynaconf/base.py | LazySettings._setup | def _setup(self):
"""Initial setup, run once."""
default_settings.reload()
environment_variable = self._kwargs.get(
"ENVVAR_FOR_DYNACONF", default_settings.ENVVAR_FOR_DYNACONF
)
settings_module = os.environ.get(environment_variable)
self._wrapped = Settings(
settings_module=settings_module, **self._kwargs
)
self.logger.debug("Lazy Settings _setup ...") | python | def _setup(self):
"""Initial setup, run once."""
default_settings.reload()
environment_variable = self._kwargs.get(
"ENVVAR_FOR_DYNACONF", default_settings.ENVVAR_FOR_DYNACONF
)
settings_module = os.environ.get(environment_variable)
self._wrapped = Settings(
settings_module=settings_module, **self._kwargs
)
self.logger.debug("Lazy Settings _setup ...") | [
"def",
"_setup",
"(",
"self",
")",
":",
"default_settings",
".",
"reload",
"(",
")",
"environment_variable",
"=",
"self",
".",
"_kwargs",
".",
"get",
"(",
"\"ENVVAR_FOR_DYNACONF\"",
",",
"default_settings",
".",
"ENVVAR_FOR_DYNACONF",
")",
"settings_module",
"=",
... | Initial setup, run once. | [
"Initial",
"setup",
"run",
"once",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L115-L125 | train | 224,585 |
rochacbruno/dynaconf | dynaconf/base.py | LazySettings.configure | def configure(self, settings_module=None, **kwargs):
"""
Allows user to reconfigure settings object passing a new settings
module or separated kwargs
:param settings_module: defines the setttings file
:param kwargs: override default settings
"""
default_settings.reload()
environment_var = self._kwargs.get(
"ENVVAR_FOR_DYNACONF", default_settings.ENVVAR_FOR_DYNACONF
)
settings_module = settings_module or os.environ.get(environment_var)
compat_kwargs(kwargs)
kwargs.update(self._kwargs)
self._wrapped = Settings(settings_module=settings_module, **kwargs)
self.logger.debug("Lazy Settings configured ...") | python | def configure(self, settings_module=None, **kwargs):
"""
Allows user to reconfigure settings object passing a new settings
module or separated kwargs
:param settings_module: defines the setttings file
:param kwargs: override default settings
"""
default_settings.reload()
environment_var = self._kwargs.get(
"ENVVAR_FOR_DYNACONF", default_settings.ENVVAR_FOR_DYNACONF
)
settings_module = settings_module or os.environ.get(environment_var)
compat_kwargs(kwargs)
kwargs.update(self._kwargs)
self._wrapped = Settings(settings_module=settings_module, **kwargs)
self.logger.debug("Lazy Settings configured ...") | [
"def",
"configure",
"(",
"self",
",",
"settings_module",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"default_settings",
".",
"reload",
"(",
")",
"environment_var",
"=",
"self",
".",
"_kwargs",
".",
"get",
"(",
"\"ENVVAR_FOR_DYNACONF\"",
",",
"default_se... | Allows user to reconfigure settings object passing a new settings
module or separated kwargs
:param settings_module: defines the setttings file
:param kwargs: override default settings | [
"Allows",
"user",
"to",
"reconfigure",
"settings",
"object",
"passing",
"a",
"new",
"settings",
"module",
"or",
"separated",
"kwargs"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L127-L143 | train | 224,586 |
rochacbruno/dynaconf | dynaconf/base.py | Settings.as_dict | def as_dict(self, env=None, internal=False):
"""Returns a dictionary with set key and values.
:param env: Str env name, default self.current_env `DEVELOPMENT`
:param internal: bool - should include dynaconf internal vars?
"""
ctx_mgr = suppress() if env is None else self.using_env(env)
with ctx_mgr:
data = self.store.copy()
# if not internal remove internal settings
if not internal:
for name in dir(default_settings):
data.pop(name, None)
return data | python | def as_dict(self, env=None, internal=False):
"""Returns a dictionary with set key and values.
:param env: Str env name, default self.current_env `DEVELOPMENT`
:param internal: bool - should include dynaconf internal vars?
"""
ctx_mgr = suppress() if env is None else self.using_env(env)
with ctx_mgr:
data = self.store.copy()
# if not internal remove internal settings
if not internal:
for name in dir(default_settings):
data.pop(name, None)
return data | [
"def",
"as_dict",
"(",
"self",
",",
"env",
"=",
"None",
",",
"internal",
"=",
"False",
")",
":",
"ctx_mgr",
"=",
"suppress",
"(",
")",
"if",
"env",
"is",
"None",
"else",
"self",
".",
"using_env",
"(",
"env",
")",
"with",
"ctx_mgr",
":",
"data",
"="... | Returns a dictionary with set key and values.
:param env: Str env name, default self.current_env `DEVELOPMENT`
:param internal: bool - should include dynaconf internal vars? | [
"Returns",
"a",
"dictionary",
"with",
"set",
"key",
"and",
"values",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L237-L250 | train | 224,587 |
rochacbruno/dynaconf | dynaconf/base.py | Settings._dotted_get | def _dotted_get(self, dotted_key, default=None, **kwargs):
"""
Perform dotted key lookups and keep track of where we are.
"""
split_key = dotted_key.split(".")
name, keys = split_key[0], split_key[1:]
result = self.get(name, default=default, **kwargs)
self._memoized = result
# If we've reached the end, then return result and clear the
# memoized data.
if not keys or result is default:
self._memoized = None
return result
# If we've still got key elements to traverse, let's do that.
return self._dotted_get(".".join(keys), default=default, **kwargs) | python | def _dotted_get(self, dotted_key, default=None, **kwargs):
"""
Perform dotted key lookups and keep track of where we are.
"""
split_key = dotted_key.split(".")
name, keys = split_key[0], split_key[1:]
result = self.get(name, default=default, **kwargs)
self._memoized = result
# If we've reached the end, then return result and clear the
# memoized data.
if not keys or result is default:
self._memoized = None
return result
# If we've still got key elements to traverse, let's do that.
return self._dotted_get(".".join(keys), default=default, **kwargs) | [
"def",
"_dotted_get",
"(",
"self",
",",
"dotted_key",
",",
"default",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"split_key",
"=",
"dotted_key",
".",
"split",
"(",
"\".\"",
")",
"name",
",",
"keys",
"=",
"split_key",
"[",
"0",
"]",
",",
"split_k... | Perform dotted key lookups and keep track of where we are. | [
"Perform",
"dotted",
"key",
"lookups",
"and",
"keep",
"track",
"of",
"where",
"we",
"are",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L252-L268 | train | 224,588 |
rochacbruno/dynaconf | dynaconf/base.py | Settings.exists | def exists(self, key, fresh=False):
"""Check if key exists
:param key: the name of setting variable
:param fresh: if key should be taken from source direclty
:return: Boolean
"""
key = key.upper()
if key in self._deleted:
return False
return self.get(key, fresh=fresh, default=missing) is not missing | python | def exists(self, key, fresh=False):
"""Check if key exists
:param key: the name of setting variable
:param fresh: if key should be taken from source direclty
:return: Boolean
"""
key = key.upper()
if key in self._deleted:
return False
return self.get(key, fresh=fresh, default=missing) is not missing | [
"def",
"exists",
"(",
"self",
",",
"key",
",",
"fresh",
"=",
"False",
")",
":",
"key",
"=",
"key",
".",
"upper",
"(",
")",
"if",
"key",
"in",
"self",
".",
"_deleted",
":",
"return",
"False",
"return",
"self",
".",
"get",
"(",
"key",
",",
"fresh",... | Check if key exists
:param key: the name of setting variable
:param fresh: if key should be taken from source direclty
:return: Boolean | [
"Check",
"if",
"key",
"exists"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L310-L320 | train | 224,589 |
rochacbruno/dynaconf | dynaconf/base.py | Settings.get_environ | def get_environ(self, key, default=None, cast=None):
"""Get value from environment variable using os.environ.get
:param key: The name of the setting value, will always be upper case
:param default: In case of not found it will be returned
:param cast: Should cast in to @int, @float, @bool or @json ?
or cast must be true to use cast inference
:return: The value if found, default or None
"""
key = key.upper()
data = self.environ.get(key, default)
if data:
if cast in converters:
data = converters.get(cast)(data)
if cast is True:
data = parse_conf_data(data, tomlfy=True)
return data | python | def get_environ(self, key, default=None, cast=None):
"""Get value from environment variable using os.environ.get
:param key: The name of the setting value, will always be upper case
:param default: In case of not found it will be returned
:param cast: Should cast in to @int, @float, @bool or @json ?
or cast must be true to use cast inference
:return: The value if found, default or None
"""
key = key.upper()
data = self.environ.get(key, default)
if data:
if cast in converters:
data = converters.get(cast)(data)
if cast is True:
data = parse_conf_data(data, tomlfy=True)
return data | [
"def",
"get_environ",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"cast",
"=",
"None",
")",
":",
"key",
"=",
"key",
".",
"upper",
"(",
")",
"data",
"=",
"self",
".",
"environ",
".",
"get",
"(",
"key",
",",
"default",
")",
"if",
"... | Get value from environment variable using os.environ.get
:param key: The name of the setting value, will always be upper case
:param default: In case of not found it will be returned
:param cast: Should cast in to @int, @float, @bool or @json ?
or cast must be true to use cast inference
:return: The value if found, default or None | [
"Get",
"value",
"from",
"environment",
"variable",
"using",
"os",
".",
"environ",
".",
"get"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L333-L349 | train | 224,590 |
rochacbruno/dynaconf | dynaconf/base.py | Settings.settings_module | def settings_module(self):
"""Gets SETTINGS_MODULE variable"""
settings_module = parse_conf_data(
os.environ.get(
self.ENVVAR_FOR_DYNACONF, self.SETTINGS_FILE_FOR_DYNACONF
),
tomlfy=True,
)
if settings_module != getattr(self, "SETTINGS_MODULE", None):
self.set("SETTINGS_MODULE", settings_module)
return self.SETTINGS_MODULE | python | def settings_module(self):
"""Gets SETTINGS_MODULE variable"""
settings_module = parse_conf_data(
os.environ.get(
self.ENVVAR_FOR_DYNACONF, self.SETTINGS_FILE_FOR_DYNACONF
),
tomlfy=True,
)
if settings_module != getattr(self, "SETTINGS_MODULE", None):
self.set("SETTINGS_MODULE", settings_module)
return self.SETTINGS_MODULE | [
"def",
"settings_module",
"(",
"self",
")",
":",
"settings_module",
"=",
"parse_conf_data",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"self",
".",
"ENVVAR_FOR_DYNACONF",
",",
"self",
".",
"SETTINGS_FILE_FOR_DYNACONF",
")",
",",
"tomlfy",
"=",
"True",
",",
... | Gets SETTINGS_MODULE variable | [
"Gets",
"SETTINGS_MODULE",
"variable"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L472-L482 | train | 224,591 |
rochacbruno/dynaconf | dynaconf/base.py | Settings.clean | def clean(self, *args, **kwargs):
"""Clean all loaded values to reload when switching envs"""
for key in list(self.store.keys()):
self.unset(key) | python | def clean(self, *args, **kwargs):
"""Clean all loaded values to reload when switching envs"""
for key in list(self.store.keys()):
self.unset(key) | [
"def",
"clean",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
"in",
"list",
"(",
"self",
".",
"store",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"unset",
"(",
"key",
")"
] | Clean all loaded values to reload when switching envs | [
"Clean",
"all",
"loaded",
"values",
"to",
"reload",
"when",
"switching",
"envs"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L534-L537 | train | 224,592 |
rochacbruno/dynaconf | dynaconf/base.py | Settings.unset | def unset(self, key):
"""Unset on all references
:param key: The key to be unset
"""
key = key.strip().upper()
if key not in dir(default_settings) and key not in self._defaults:
self.logger.debug("Unset %s", key)
delattr(self, key)
self.store.pop(key, None) | python | def unset(self, key):
"""Unset on all references
:param key: The key to be unset
"""
key = key.strip().upper()
if key not in dir(default_settings) and key not in self._defaults:
self.logger.debug("Unset %s", key)
delattr(self, key)
self.store.pop(key, None) | [
"def",
"unset",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"key",
".",
"strip",
"(",
")",
".",
"upper",
"(",
")",
"if",
"key",
"not",
"in",
"dir",
"(",
"default_settings",
")",
"and",
"key",
"not",
"in",
"self",
".",
"_defaults",
":",
"self",... | Unset on all references
:param key: The key to be unset | [
"Unset",
"on",
"all",
"references"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L539-L548 | train | 224,593 |
rochacbruno/dynaconf | dynaconf/base.py | Settings.set | def set(
self,
key,
value,
loader_identifier=None,
tomlfy=False,
dotted_lookup=True,
is_secret=False,
):
"""Set a value storing references for the loader
:param key: The key to store
:param value: The value to store
:param loader_identifier: Optional loader name e.g: toml, yaml etc.
:param tomlfy: Bool define if value is parsed by toml (defaults False)
:param is_secret: Bool define if secret values is hidden on logs.
"""
if "." in key and dotted_lookup is True:
return self._dotted_set(
key, value, loader_identifier=loader_identifier, tomlfy=tomlfy
)
value = parse_conf_data(value, tomlfy=tomlfy)
key = key.strip().upper()
existing = getattr(self, key, None)
if existing is not None and existing != value:
value = self._merge_before_set(key, existing, value, is_secret)
if isinstance(value, dict):
value = DynaBox(value, box_it_up=True)
setattr(self, key, value)
self.store[key] = value
self._deleted.discard(key)
# set loader identifiers so cleaners know which keys to clean
if loader_identifier and loader_identifier in self.loaded_by_loaders:
self.loaded_by_loaders[loader_identifier][key] = value
elif loader_identifier:
self.loaded_by_loaders[loader_identifier] = {key: value}
elif loader_identifier is None:
# if .set is called without loader identifier it becomes
# a default value and goes away only when explicitly unset
self._defaults[key] = value | python | def set(
self,
key,
value,
loader_identifier=None,
tomlfy=False,
dotted_lookup=True,
is_secret=False,
):
"""Set a value storing references for the loader
:param key: The key to store
:param value: The value to store
:param loader_identifier: Optional loader name e.g: toml, yaml etc.
:param tomlfy: Bool define if value is parsed by toml (defaults False)
:param is_secret: Bool define if secret values is hidden on logs.
"""
if "." in key and dotted_lookup is True:
return self._dotted_set(
key, value, loader_identifier=loader_identifier, tomlfy=tomlfy
)
value = parse_conf_data(value, tomlfy=tomlfy)
key = key.strip().upper()
existing = getattr(self, key, None)
if existing is not None and existing != value:
value = self._merge_before_set(key, existing, value, is_secret)
if isinstance(value, dict):
value = DynaBox(value, box_it_up=True)
setattr(self, key, value)
self.store[key] = value
self._deleted.discard(key)
# set loader identifiers so cleaners know which keys to clean
if loader_identifier and loader_identifier in self.loaded_by_loaders:
self.loaded_by_loaders[loader_identifier][key] = value
elif loader_identifier:
self.loaded_by_loaders[loader_identifier] = {key: value}
elif loader_identifier is None:
# if .set is called without loader identifier it becomes
# a default value and goes away only when explicitly unset
self._defaults[key] = value | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"loader_identifier",
"=",
"None",
",",
"tomlfy",
"=",
"False",
",",
"dotted_lookup",
"=",
"True",
",",
"is_secret",
"=",
"False",
",",
")",
":",
"if",
"\".\"",
"in",
"key",
"and",
"dotted_lookup... | Set a value storing references for the loader
:param key: The key to store
:param value: The value to store
:param loader_identifier: Optional loader name e.g: toml, yaml etc.
:param tomlfy: Bool define if value is parsed by toml (defaults False)
:param is_secret: Bool define if secret values is hidden on logs. | [
"Set",
"a",
"value",
"storing",
"references",
"for",
"the",
"loader"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L572-L616 | train | 224,594 |
rochacbruno/dynaconf | dynaconf/base.py | Settings._merge_before_set | def _merge_before_set(self, key, existing, value, is_secret):
"""Merge the new value being set with the existing value before set"""
def _log_before_merging(_value):
self.logger.debug(
"Merging existing %s: %s with new: %s", key, existing, _value
)
def _log_after_merge(_value):
self.logger.debug("%s merged to %s", key, _value)
global_merge = getattr(self, "MERGE_ENABLED_FOR_DYNACONF", False)
if isinstance(value, dict):
local_merge = value.pop(
"dynaconf_merge", value.pop("dynaconf_merge_unique", None)
)
if global_merge or local_merge:
safe_value = {k: "***" for k in value} if is_secret else value
_log_before_merging(safe_value)
object_merge(existing, value)
safe_value = (
{
k: ("***" if k in safe_value else v)
for k, v in value.items()
}
if is_secret
else value
)
_log_after_merge(safe_value)
if isinstance(value, (list, tuple)):
local_merge = (
"dynaconf_merge" in value or "dynaconf_merge_unique" in value
)
if global_merge or local_merge:
value = list(value)
unique = False
if local_merge:
try:
value.remove("dynaconf_merge")
except ValueError: # EAFP
value.remove("dynaconf_merge_unique")
unique = True
original = set(value)
_log_before_merging(
["***" for item in value] if is_secret else value
)
object_merge(existing, value, unique=unique)
safe_value = (
["***" if item in original else item for item in value]
if is_secret
else value
)
_log_after_merge(safe_value)
return value | python | def _merge_before_set(self, key, existing, value, is_secret):
"""Merge the new value being set with the existing value before set"""
def _log_before_merging(_value):
self.logger.debug(
"Merging existing %s: %s with new: %s", key, existing, _value
)
def _log_after_merge(_value):
self.logger.debug("%s merged to %s", key, _value)
global_merge = getattr(self, "MERGE_ENABLED_FOR_DYNACONF", False)
if isinstance(value, dict):
local_merge = value.pop(
"dynaconf_merge", value.pop("dynaconf_merge_unique", None)
)
if global_merge or local_merge:
safe_value = {k: "***" for k in value} if is_secret else value
_log_before_merging(safe_value)
object_merge(existing, value)
safe_value = (
{
k: ("***" if k in safe_value else v)
for k, v in value.items()
}
if is_secret
else value
)
_log_after_merge(safe_value)
if isinstance(value, (list, tuple)):
local_merge = (
"dynaconf_merge" in value or "dynaconf_merge_unique" in value
)
if global_merge or local_merge:
value = list(value)
unique = False
if local_merge:
try:
value.remove("dynaconf_merge")
except ValueError: # EAFP
value.remove("dynaconf_merge_unique")
unique = True
original = set(value)
_log_before_merging(
["***" for item in value] if is_secret else value
)
object_merge(existing, value, unique=unique)
safe_value = (
["***" if item in original else item for item in value]
if is_secret
else value
)
_log_after_merge(safe_value)
return value | [
"def",
"_merge_before_set",
"(",
"self",
",",
"key",
",",
"existing",
",",
"value",
",",
"is_secret",
")",
":",
"def",
"_log_before_merging",
"(",
"_value",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Merging existing %s: %s with new: %s\"",
",",
"k... | Merge the new value being set with the existing value before set | [
"Merge",
"the",
"new",
"value",
"being",
"set",
"with",
"the",
"existing",
"value",
"before",
"set"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L655-L713 | train | 224,595 |
rochacbruno/dynaconf | dynaconf/base.py | Settings.loaders | def loaders(self): # pragma: no cover
"""Return available loaders"""
if self.LOADERS_FOR_DYNACONF in (None, 0, "0", "false", False):
self.logger.info("No loader defined")
return []
if not self._loaders:
for loader_module_name in self.LOADERS_FOR_DYNACONF:
loader = importlib.import_module(loader_module_name)
self._loaders.append(loader)
return self._loaders | python | def loaders(self): # pragma: no cover
"""Return available loaders"""
if self.LOADERS_FOR_DYNACONF in (None, 0, "0", "false", False):
self.logger.info("No loader defined")
return []
if not self._loaders:
for loader_module_name in self.LOADERS_FOR_DYNACONF:
loader = importlib.import_module(loader_module_name)
self._loaders.append(loader)
return self._loaders | [
"def",
"loaders",
"(",
"self",
")",
":",
"# pragma: no cover",
"if",
"self",
".",
"LOADERS_FOR_DYNACONF",
"in",
"(",
"None",
",",
"0",
",",
"\"0\"",
",",
"\"false\"",
",",
"False",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"No loader defined\"",... | Return available loaders | [
"Return",
"available",
"loaders"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L716-L727 | train | 224,596 |
rochacbruno/dynaconf | dynaconf/base.py | Settings.reload | def reload(self, env=None, silent=None): # pragma: no cover
"""Clean end Execute all loaders"""
self.clean()
self.execute_loaders(env, silent) | python | def reload(self, env=None, silent=None): # pragma: no cover
"""Clean end Execute all loaders"""
self.clean()
self.execute_loaders(env, silent) | [
"def",
"reload",
"(",
"self",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"None",
")",
":",
"# pragma: no cover",
"self",
".",
"clean",
"(",
")",
"self",
".",
"execute_loaders",
"(",
"env",
",",
"silent",
")"
] | Clean end Execute all loaders | [
"Clean",
"end",
"Execute",
"all",
"loaders"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L729-L732 | train | 224,597 |
rochacbruno/dynaconf | dynaconf/base.py | Settings.execute_loaders | def execute_loaders(self, env=None, silent=None, key=None, filename=None):
"""Execute all internal and registered loaders
:param env: The environment to load
:param silent: If loading erros is silenced
:param key: if provided load a single key
:param filename: optional custom filename to load
"""
if key is None:
default_loader(self, self._defaults)
env = (env or self.current_env).upper()
silent = silent or self.SILENT_ERRORS_FOR_DYNACONF
settings_loader(
self, env=env, silent=silent, key=key, filename=filename
)
self.load_extra_yaml(env, silent, key) # DEPRECATED
enable_external_loaders(self)
for loader in self.loaders:
self.logger.debug("Dynaconf executing: %s", loader.__name__)
loader.load(self, env, silent=silent, key=key)
self.load_includes(env, silent=silent, key=key)
self.logger.debug("Loaded Files: %s", deduplicate(self._loaded_files)) | python | def execute_loaders(self, env=None, silent=None, key=None, filename=None):
"""Execute all internal and registered loaders
:param env: The environment to load
:param silent: If loading erros is silenced
:param key: if provided load a single key
:param filename: optional custom filename to load
"""
if key is None:
default_loader(self, self._defaults)
env = (env or self.current_env).upper()
silent = silent or self.SILENT_ERRORS_FOR_DYNACONF
settings_loader(
self, env=env, silent=silent, key=key, filename=filename
)
self.load_extra_yaml(env, silent, key) # DEPRECATED
enable_external_loaders(self)
for loader in self.loaders:
self.logger.debug("Dynaconf executing: %s", loader.__name__)
loader.load(self, env, silent=silent, key=key)
self.load_includes(env, silent=silent, key=key)
self.logger.debug("Loaded Files: %s", deduplicate(self._loaded_files)) | [
"def",
"execute_loaders",
"(",
"self",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"None",
",",
"key",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"default_loader",
"(",
"self",
",",
"self",
".",
"_defaults",... | Execute all internal and registered loaders
:param env: The environment to load
:param silent: If loading erros is silenced
:param key: if provided load a single key
:param filename: optional custom filename to load | [
"Execute",
"all",
"internal",
"and",
"registered",
"loaders"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L734-L755 | train | 224,598 |
rochacbruno/dynaconf | dynaconf/base.py | Settings.load_includes | def load_includes(self, env, silent, key):
"""Do we have any nested includes we need to process?"""
includes = self.get("DYNACONF_INCLUDE", [])
includes.extend(ensure_a_list(self.get("INCLUDES_FOR_DYNACONF")))
if includes:
self.logger.debug("Processing includes %s", includes)
self.load_file(path=includes, env=env, silent=silent, key=key) | python | def load_includes(self, env, silent, key):
"""Do we have any nested includes we need to process?"""
includes = self.get("DYNACONF_INCLUDE", [])
includes.extend(ensure_a_list(self.get("INCLUDES_FOR_DYNACONF")))
if includes:
self.logger.debug("Processing includes %s", includes)
self.load_file(path=includes, env=env, silent=silent, key=key) | [
"def",
"load_includes",
"(",
"self",
",",
"env",
",",
"silent",
",",
"key",
")",
":",
"includes",
"=",
"self",
".",
"get",
"(",
"\"DYNACONF_INCLUDE\"",
",",
"[",
"]",
")",
"includes",
".",
"extend",
"(",
"ensure_a_list",
"(",
"self",
".",
"get",
"(",
... | Do we have any nested includes we need to process? | [
"Do",
"we",
"have",
"any",
"nested",
"includes",
"we",
"need",
"to",
"process?"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L757-L763 | train | 224,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.