id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27,700 | globality-corp/microcosm-flask | microcosm_flask/conventions/base.py | Convention._make_definition | def _make_definition(self, definition):
"""
Generate a definition.
The input might already be a `EndpointDefinition` or it might be a tuple.
"""
if not definition:
return EndpointDefinition()
if isinstance(definition, EndpointDefinition):
return definition
elif len(definition) == 1:
return EndpointDefinition(
func=definition[0],
)
elif len(definition) == 2:
return EndpointDefinition(
func=definition[0],
response_schema=definition[1],
)
elif len(definition) == 3:
return EndpointDefinition(
func=definition[0],
request_schema=definition[1],
response_schema=definition[2],
)
elif len(definition) == 4:
return EndpointDefinition(
func=definition[0],
request_schema=definition[1],
response_schema=definition[2],
header_func=definition[3],
) | python | def _make_definition(self, definition):
if not definition:
return EndpointDefinition()
if isinstance(definition, EndpointDefinition):
return definition
elif len(definition) == 1:
return EndpointDefinition(
func=definition[0],
)
elif len(definition) == 2:
return EndpointDefinition(
func=definition[0],
response_schema=definition[1],
)
elif len(definition) == 3:
return EndpointDefinition(
func=definition[0],
request_schema=definition[1],
response_schema=definition[2],
)
elif len(definition) == 4:
return EndpointDefinition(
func=definition[0],
request_schema=definition[1],
response_schema=definition[2],
header_func=definition[3],
) | [
"def",
"_make_definition",
"(",
"self",
",",
"definition",
")",
":",
"if",
"not",
"definition",
":",
"return",
"EndpointDefinition",
"(",
")",
"if",
"isinstance",
"(",
"definition",
",",
"EndpointDefinition",
")",
":",
"return",
"definition",
"elif",
"len",
"(... | Generate a definition.
The input might already be a `EndpointDefinition` or it might be a tuple. | [
"Generate",
"a",
"definition",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/base.py#L127-L159 |
27,701 | globality-corp/microcosm-flask | microcosm_flask/conventions/discovery.py | iter_links | def iter_links(operations, page):
"""
Generate links for an iterable of operations on a starting page.
"""
for operation, ns, rule, func in operations:
yield Link.for_(
operation=operation,
ns=ns,
type=ns.subject_name,
qs=page.to_items(),
) | python | def iter_links(operations, page):
for operation, ns, rule, func in operations:
yield Link.for_(
operation=operation,
ns=ns,
type=ns.subject_name,
qs=page.to_items(),
) | [
"def",
"iter_links",
"(",
"operations",
",",
"page",
")",
":",
"for",
"operation",
",",
"ns",
",",
"rule",
",",
"func",
"in",
"operations",
":",
"yield",
"Link",
".",
"for_",
"(",
"operation",
"=",
"operation",
",",
"ns",
"=",
"ns",
",",
"type",
"=",... | Generate links for an iterable of operations on a starting page. | [
"Generate",
"links",
"for",
"an",
"iterable",
"of",
"operations",
"on",
"a",
"starting",
"page",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/discovery.py#L16-L27 |
27,702 | globality-corp/microcosm-flask | microcosm_flask/conventions/discovery.py | configure_discovery | def configure_discovery(graph):
"""
Build a singleton endpoint that provides a link to all search endpoints.
"""
ns = Namespace(
subject=graph.config.discovery_convention.name,
)
convention = DiscoveryConvention(graph)
convention.configure(ns, discover=tuple())
return ns.subject | python | def configure_discovery(graph):
ns = Namespace(
subject=graph.config.discovery_convention.name,
)
convention = DiscoveryConvention(graph)
convention.configure(ns, discover=tuple())
return ns.subject | [
"def",
"configure_discovery",
"(",
"graph",
")",
":",
"ns",
"=",
"Namespace",
"(",
"subject",
"=",
"graph",
".",
"config",
".",
"discovery_convention",
".",
"name",
",",
")",
"convention",
"=",
"DiscoveryConvention",
"(",
"graph",
")",
"convention",
".",
"co... | Build a singleton endpoint that provides a link to all search endpoints. | [
"Build",
"a",
"singleton",
"endpoint",
"that",
"provides",
"a",
"link",
"to",
"all",
"search",
"endpoints",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/discovery.py#L81-L91 |
27,703 | globality-corp/microcosm-flask | microcosm_flask/conventions/discovery.py | DiscoveryConvention.configure_discover | def configure_discover(self, ns, definition):
"""
Register a discovery endpoint for a set of operations.
"""
page_schema = OffsetLimitPageSchema()
@self.add_route("/", Operation.Discover, ns)
def discover():
# accept pagination limit from request
page = OffsetLimitPage.from_query_string(page_schema)
page.offset = 0
response_data = dict(
_links=Links({
"self": Link.for_(Operation.Discover, ns, qs=page.to_items()),
"search": [
link for link in iter_links(self.find_matching_endpoints(ns), page)
],
}).to_dict()
)
return make_response(response_data) | python | def configure_discover(self, ns, definition):
page_schema = OffsetLimitPageSchema()
@self.add_route("/", Operation.Discover, ns)
def discover():
# accept pagination limit from request
page = OffsetLimitPage.from_query_string(page_schema)
page.offset = 0
response_data = dict(
_links=Links({
"self": Link.for_(Operation.Discover, ns, qs=page.to_items()),
"search": [
link for link in iter_links(self.find_matching_endpoints(ns), page)
],
}).to_dict()
)
return make_response(response_data) | [
"def",
"configure_discover",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"page_schema",
"=",
"OffsetLimitPageSchema",
"(",
")",
"@",
"self",
".",
"add_route",
"(",
"\"/\"",
",",
"Operation",
".",
"Discover",
",",
"ns",
")",
"def",
"discover",
"(",... | Register a discovery endpoint for a set of operations. | [
"Register",
"a",
"discovery",
"endpoint",
"for",
"a",
"set",
"of",
"operations",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/discovery.py#L51-L72 |
27,704 | globality-corp/microcosm-flask | microcosm_flask/conventions/upload.py | nested | def nested(*contexts):
"""
Reimplementation of nested in python 3.
"""
with ExitStack() as stack:
results = [
stack.enter_context(context)
for context in contexts
]
yield results | python | def nested(*contexts):
with ExitStack() as stack:
results = [
stack.enter_context(context)
for context in contexts
]
yield results | [
"def",
"nested",
"(",
"*",
"contexts",
")",
":",
"with",
"ExitStack",
"(",
")",
"as",
"stack",
":",
"results",
"=",
"[",
"stack",
".",
"enter_context",
"(",
"context",
")",
"for",
"context",
"in",
"contexts",
"]",
"yield",
"results"
] | Reimplementation of nested in python 3. | [
"Reimplementation",
"of",
"nested",
"in",
"python",
"3",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/upload.py#L27-L36 |
27,705 | globality-corp/microcosm-flask | microcosm_flask/conventions/upload.py | temporary_upload | def temporary_upload(name, fileobj):
"""
Upload a file to a temporary location.
Flask will not load sufficiently large files into memory, so it
makes sense to always load files into a temporary directory.
"""
tempdir = mkdtemp()
filename = secure_filename(fileobj.filename)
filepath = join(tempdir, filename)
fileobj.save(filepath)
try:
yield name, filepath, fileobj.filename
finally:
rmtree(tempdir) | python | def temporary_upload(name, fileobj):
tempdir = mkdtemp()
filename = secure_filename(fileobj.filename)
filepath = join(tempdir, filename)
fileobj.save(filepath)
try:
yield name, filepath, fileobj.filename
finally:
rmtree(tempdir) | [
"def",
"temporary_upload",
"(",
"name",
",",
"fileobj",
")",
":",
"tempdir",
"=",
"mkdtemp",
"(",
")",
"filename",
"=",
"secure_filename",
"(",
"fileobj",
".",
"filename",
")",
"filepath",
"=",
"join",
"(",
"tempdir",
",",
"filename",
")",
"fileobj",
".",
... | Upload a file to a temporary location.
Flask will not load sufficiently large files into memory, so it
makes sense to always load files into a temporary directory. | [
"Upload",
"a",
"file",
"to",
"a",
"temporary",
"location",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/upload.py#L40-L55 |
27,706 | globality-corp/microcosm-flask | microcosm_flask/conventions/upload.py | configure_upload | def configure_upload(graph, ns, mappings, exclude_func=None):
"""
Register Upload endpoints for a resource object.
"""
convention = UploadConvention(graph, exclude_func)
convention.configure(ns, mappings) | python | def configure_upload(graph, ns, mappings, exclude_func=None):
convention = UploadConvention(graph, exclude_func)
convention.configure(ns, mappings) | [
"def",
"configure_upload",
"(",
"graph",
",",
"ns",
",",
"mappings",
",",
"exclude_func",
"=",
"None",
")",
":",
"convention",
"=",
"UploadConvention",
"(",
"graph",
",",
"exclude_func",
")",
"convention",
".",
"configure",
"(",
"ns",
",",
"mappings",
")"
] | Register Upload endpoints for a resource object. | [
"Register",
"Upload",
"endpoints",
"for",
"a",
"resource",
"object",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/upload.py#L130-L136 |
27,707 | globality-corp/microcosm-flask | microcosm_flask/conventions/upload.py | UploadConvention.configure_upload | def configure_upload(self, ns, definition):
"""
Register an upload endpoint.
The definition's func should be an upload function, which must:
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form (formname, tempfilepath, filename)
- optionally return a resource
:param ns: the namespace
:param definition: the endpoint definition
"""
upload = self.create_upload_func(ns, definition, ns.collection_path, Operation.Upload)
upload.__doc__ = "Upload a {}".format(ns.subject_name) | python | def configure_upload(self, ns, definition):
upload = self.create_upload_func(ns, definition, ns.collection_path, Operation.Upload)
upload.__doc__ = "Upload a {}".format(ns.subject_name) | [
"def",
"configure_upload",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"upload",
"=",
"self",
".",
"create_upload_func",
"(",
"ns",
",",
"definition",
",",
"ns",
".",
"collection_path",
",",
"Operation",
".",
"Upload",
")",
"upload",
".",
"__doc__... | Register an upload endpoint.
The definition's func should be an upload function, which must:
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form (formname, tempfilepath, filename)
- optionally return a resource
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"an",
"upload",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/upload.py#L97-L111 |
27,708 | globality-corp/microcosm-flask | microcosm_flask/conventions/upload.py | UploadConvention.configure_uploadfor | def configure_uploadfor(self, ns, definition):
"""
Register an upload-for relation endpoint.
The definition's func should be an upload function, which must:
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form (formname, tempfilepath, filename)
- optionall return a resource
:param ns: the namespace
:param definition: the endpoint definition
"""
upload_for = self.create_upload_func(ns, definition, ns.relation_path, Operation.UploadFor)
upload_for.__doc__ = "Upload a {} for a {}".format(ns.subject_name, ns.object_name) | python | def configure_uploadfor(self, ns, definition):
upload_for = self.create_upload_func(ns, definition, ns.relation_path, Operation.UploadFor)
upload_for.__doc__ = "Upload a {} for a {}".format(ns.subject_name, ns.object_name) | [
"def",
"configure_uploadfor",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"upload_for",
"=",
"self",
".",
"create_upload_func",
"(",
"ns",
",",
"definition",
",",
"ns",
".",
"relation_path",
",",
"Operation",
".",
"UploadFor",
")",
"upload_for",
"."... | Register an upload-for relation endpoint.
The definition's func should be an upload function, which must:
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form (formname, tempfilepath, filename)
- optionall return a resource
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"an",
"upload",
"-",
"for",
"relation",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/upload.py#L113-L127 |
27,709 | globality-corp/microcosm-flask | microcosm_flask/formatting/base.py | BaseFormatter.build_etag | def build_etag(self, response, include_etag=True, **kwargs):
"""
Add an etag to the response body.
Uses spooky where possible because it is empirically fast and well-regarded.
See: http://blog.reverberate.org/2012/01/state-of-hash-functions-2012.html
"""
if not include_etag:
return
if not spooky:
# use built-in md5
response.add_etag()
return
# use spooky
response.headers["ETag"] = quote_etag(
hexlify(
spooky.hash128(
response.get_data(),
).to_bytes(16, "little"),
).decode("utf-8"),
) | python | def build_etag(self, response, include_etag=True, **kwargs):
if not include_etag:
return
if not spooky:
# use built-in md5
response.add_etag()
return
# use spooky
response.headers["ETag"] = quote_etag(
hexlify(
spooky.hash128(
response.get_data(),
).to_bytes(16, "little"),
).decode("utf-8"),
) | [
"def",
"build_etag",
"(",
"self",
",",
"response",
",",
"include_etag",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"include_etag",
":",
"return",
"if",
"not",
"spooky",
":",
"# use built-in md5",
"response",
".",
"add_etag",
"(",
")",
"... | Add an etag to the response body.
Uses spooky where possible because it is empirically fast and well-regarded.
See: http://blog.reverberate.org/2012/01/state-of-hash-functions-2012.html | [
"Add",
"an",
"etag",
"to",
"the",
"response",
"body",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/formatting/base.py#L50-L74 |
27,710 | globality-corp/microcosm-flask | microcosm_flask/encryption/conventions/crud_adapter.py | EncryptableCRUDStoreAdapter.update_and_reencrypt | def update_and_reencrypt(self, **kwargs):
"""
Support re-encryption by enforcing that every update triggers a
new encryption call, even if the the original call does not update
the encrypted field.
"""
encrypted_field_name = self.store.model_class.__plaintext__
id_ = kwargs[self.identifier_key]
current_model = self.store.retrieve(id_)
current_value = current_model.plaintext
null_update = (
# Check if the update is for the encrypted field, and if it's explicitly set to null
encrypted_field_name in kwargs
and kwargs.get(encrypted_field_name) is None
)
new_value = kwargs.pop(self.store.model_class.__plaintext__, None)
use_new_value = new_value is not None or null_update
updated_value = new_value if use_new_value else current_value
model_kwargs = {
self.identifier_key: id_,
encrypted_field_name: updated_value,
**kwargs,
}
return super().update(
**model_kwargs,
) | python | def update_and_reencrypt(self, **kwargs):
encrypted_field_name = self.store.model_class.__plaintext__
id_ = kwargs[self.identifier_key]
current_model = self.store.retrieve(id_)
current_value = current_model.plaintext
null_update = (
# Check if the update is for the encrypted field, and if it's explicitly set to null
encrypted_field_name in kwargs
and kwargs.get(encrypted_field_name) is None
)
new_value = kwargs.pop(self.store.model_class.__plaintext__, None)
use_new_value = new_value is not None or null_update
updated_value = new_value if use_new_value else current_value
model_kwargs = {
self.identifier_key: id_,
encrypted_field_name: updated_value,
**kwargs,
}
return super().update(
**model_kwargs,
) | [
"def",
"update_and_reencrypt",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"encrypted_field_name",
"=",
"self",
".",
"store",
".",
"model_class",
".",
"__plaintext__",
"id_",
"=",
"kwargs",
"[",
"self",
".",
"identifier_key",
"]",
"current_model",
"=",
"... | Support re-encryption by enforcing that every update triggers a
new encryption call, even if the the original call does not update
the encrypted field. | [
"Support",
"re",
"-",
"encryption",
"by",
"enforcing",
"that",
"every",
"update",
"triggers",
"a",
"new",
"encryption",
"call",
"even",
"if",
"the",
"the",
"original",
"call",
"does",
"not",
"update",
"the",
"encrypted",
"field",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/encryption/conventions/crud_adapter.py#L10-L41 |
27,711 | globality-corp/microcosm-flask | microcosm_flask/cloning.py | DAGSchema.unflatten | def unflatten(self, obj):
"""
Translate substitutions dictionary into objects.
"""
obj.substitutions = [
dict(from_id=key, to_id=value)
for key, value in getattr(obj, "substitutions", {}).items()
] | python | def unflatten(self, obj):
obj.substitutions = [
dict(from_id=key, to_id=value)
for key, value in getattr(obj, "substitutions", {}).items()
] | [
"def",
"unflatten",
"(",
"self",
",",
"obj",
")",
":",
"obj",
".",
"substitutions",
"=",
"[",
"dict",
"(",
"from_id",
"=",
"key",
",",
"to_id",
"=",
"value",
")",
"for",
"key",
",",
"value",
"in",
"getattr",
"(",
"obj",
",",
"\"substitutions\"",
",",... | Translate substitutions dictionary into objects. | [
"Translate",
"substitutions",
"dictionary",
"into",
"objects",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/cloning.py#L69-L77 |
27,712 | globality-corp/microcosm-flask | microcosm_flask/cloning.py | DAGCloningController.clone | def clone(self, substitutions, commit=True, **kwargs):
"""
Clone a DAG, optionally skipping the commit.
"""
return self.store.clone(substitutions, **kwargs) | python | def clone(self, substitutions, commit=True, **kwargs):
return self.store.clone(substitutions, **kwargs) | [
"def",
"clone",
"(",
"self",
",",
"substitutions",
",",
"commit",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"store",
".",
"clone",
"(",
"substitutions",
",",
"*",
"*",
"kwargs",
")"
] | Clone a DAG, optionally skipping the commit. | [
"Clone",
"a",
"DAG",
"optionally",
"skipping",
"the",
"commit",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/cloning.py#L115-L120 |
27,713 | globality-corp/microcosm-flask | microcosm_flask/conventions/relation.py | RelationConvention.configure_createfor | def configure_createfor(self, ns, definition):
"""
Register a create-for relation endpoint.
The definition's func should be a create function, which must:
- accept kwargs for the new instance creation parameters
- return the created instance
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.relation_path, Operation.CreateFor, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def create(**path_data):
request_data = load_request_data(definition.request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
headers = encode_id_header(response_data)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
Operation.CreateFor.value.default_code,
headers=headers,
response_format=response_format,
)
create.__doc__ = "Create a new {} relative to a {}".format(pluralize(ns.object_name), ns.subject_name) | python | def configure_createfor(self, ns, definition):
@self.add_route(ns.relation_path, Operation.CreateFor, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def create(**path_data):
request_data = load_request_data(definition.request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
headers = encode_id_header(response_data)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
Operation.CreateFor.value.default_code,
headers=headers,
response_format=response_format,
)
create.__doc__ = "Create a new {} relative to a {}".format(pluralize(ns.object_name), ns.subject_name) | [
"def",
"configure_createfor",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"relation_path",
",",
"Operation",
".",
"CreateFor",
",",
"ns",
")",
"@",
"request",
"(",
"definition",
".",
"request_schema",... | Register a create-for relation endpoint.
The definition's func should be a create function, which must:
- accept kwargs for the new instance creation parameters
- return the created instance
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"create",
"-",
"for",
"relation",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/relation.py#L36-L66 |
27,714 | globality-corp/microcosm-flask | microcosm_flask/conventions/relation.py | RelationConvention.configure_deletefor | def configure_deletefor(self, ns, definition):
"""
Register a delete-for relation endpoint.
The definition's func should be a delete function, which must:
- accept kwargs for path data
- return truthy/falsey
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.relation_path, Operation.DeleteFor, ns)
@wraps(definition.func)
def delete(**path_data):
headers = dict()
response_data = dict()
require_response_data(definition.func(**path_data))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
"",
None,
status_code=Operation.DeleteFor.value.default_code,
headers=headers,
response_format=response_format,
)
delete.__doc__ = "Delete a {} relative to a {}".format(pluralize(ns.object_name), ns.subject_name) | python | def configure_deletefor(self, ns, definition):
@self.add_route(ns.relation_path, Operation.DeleteFor, ns)
@wraps(definition.func)
def delete(**path_data):
headers = dict()
response_data = dict()
require_response_data(definition.func(**path_data))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
"",
None,
status_code=Operation.DeleteFor.value.default_code,
headers=headers,
response_format=response_format,
)
delete.__doc__ = "Delete a {} relative to a {}".format(pluralize(ns.object_name), ns.subject_name) | [
"def",
"configure_deletefor",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"relation_path",
",",
"Operation",
".",
"DeleteFor",
",",
"ns",
")",
"@",
"wraps",
"(",
"definition",
".",
"func",
")",
"d... | Register a delete-for relation endpoint.
The definition's func should be a delete function, which must:
- accept kwargs for path data
- return truthy/falsey
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"delete",
"-",
"for",
"relation",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/relation.py#L68-L96 |
27,715 | globality-corp/microcosm-flask | microcosm_flask/conventions/relation.py | RelationConvention.configure_replacefor | def configure_replacefor(self, ns, definition):
"""
Register a replace-for relation endpoint.
For typical usage, this relation is not strictly required; once an object exists and has its own ID,
it is better to operate on it directly via dedicated CRUD routes.
However, in some cases, the composite key of (subject_id, object_id) is required to look up the object.
This happens, for example, when using DynamoDB where an object which maintains both a hash key and a range key
requires specifying them both for access.
The definition's func should be a replace function, which must:
- accept kwargs for the new instance replacement parameters
- return the instance
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.relation_path, Operation.ReplaceFor, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def replace(**path_data):
headers = dict()
request_data = load_request_data(definition.request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
status_code=Operation.ReplaceFor.value.default_code,
headers=headers,
response_format=response_format,
)
replace.__doc__ = "Replace a {} relative to a {}".format(pluralize(ns.object_name), ns.subject_name) | python | def configure_replacefor(self, ns, definition):
@self.add_route(ns.relation_path, Operation.ReplaceFor, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def replace(**path_data):
headers = dict()
request_data = load_request_data(definition.request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
status_code=Operation.ReplaceFor.value.default_code,
headers=headers,
response_format=response_format,
)
replace.__doc__ = "Replace a {} relative to a {}".format(pluralize(ns.object_name), ns.subject_name) | [
"def",
"configure_replacefor",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"relation_path",
",",
"Operation",
".",
"ReplaceFor",
",",
"ns",
")",
"@",
"request",
"(",
"definition",
".",
"request_schema... | Register a replace-for relation endpoint.
For typical usage, this relation is not strictly required; once an object exists and has its own ID,
it is better to operate on it directly via dedicated CRUD routes.
However, in some cases, the composite key of (subject_id, object_id) is required to look up the object.
This happens, for example, when using DynamoDB where an object which maintains both a hash key and a range key
requires specifying them both for access.
The definition's func should be a replace function, which must:
- accept kwargs for the new instance replacement parameters
- return the instance
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"replace",
"-",
"for",
"relation",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/relation.py#L98-L135 |
27,716 | globality-corp/microcosm-flask | microcosm_flask/swagger/parameters/__init__.py | Parameters.build | def build(self, field: Field) -> Mapping[str, Any]:
"""
Build a swagger parameter from a marshmallow field.
"""
builder_types = self.builder_types() + [
# put default last
self.default_builder_type()
]
builders: List[ParameterBuilder] = [
builder_type(
build_parameter=self.build,
)
for builder_type in builder_types
]
builder = next(
builder
for builder in builders
if builder.supports_field(field)
)
return builder.build(field) | python | def build(self, field: Field) -> Mapping[str, Any]:
builder_types = self.builder_types() + [
# put default last
self.default_builder_type()
]
builders: List[ParameterBuilder] = [
builder_type(
build_parameter=self.build,
)
for builder_type in builder_types
]
builder = next(
builder
for builder in builders
if builder.supports_field(field)
)
return builder.build(field) | [
"def",
"build",
"(",
"self",
",",
"field",
":",
"Field",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"builder_types",
"=",
"self",
".",
"builder_types",
"(",
")",
"+",
"[",
"# put default last",
"self",
".",
"default_builder_type",
"(",
")",
... | Build a swagger parameter from a marshmallow field. | [
"Build",
"a",
"swagger",
"parameter",
"from",
"a",
"marshmallow",
"field",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/__init__.py#L27-L50 |
27,717 | globality-corp/microcosm-flask | microcosm_flask/swagger/parameters/__init__.py | Parameters.builder_types | def builder_types(cls) -> List[Type[ParameterBuilder]]:
"""
Define the available builder types.
"""
return [
entry_point.load()
for entry_point in iter_entry_points(ENTRY_POINT)
] | python | def builder_types(cls) -> List[Type[ParameterBuilder]]:
return [
entry_point.load()
for entry_point in iter_entry_points(ENTRY_POINT)
] | [
"def",
"builder_types",
"(",
"cls",
")",
"->",
"List",
"[",
"Type",
"[",
"ParameterBuilder",
"]",
"]",
":",
"return",
"[",
"entry_point",
".",
"load",
"(",
")",
"for",
"entry_point",
"in",
"iter_entry_points",
"(",
"ENTRY_POINT",
")",
"]"
] | Define the available builder types. | [
"Define",
"the",
"available",
"builder",
"types",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/__init__.py#L55-L63 |
27,718 | globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | configure_crud | def configure_crud(graph, ns, mappings):
"""
Register CRUD endpoints for a resource object.
:param mappings: a dictionary from operations to tuple, where each tuple contains
the target function and zero or more marshmallow schemas according
to the signature of the "register_<foo>_endpoint" functions
Example mapping:
{
Operation.Create: (create_foo, NewFooSchema(), FooSchema()),
Operation.Delete: (delete_foo,),
Operation.Retrieve: (retrieve_foo, FooSchema()),
Operation.Search: (search_foo, SearchFooSchema(), FooSchema(), [ResponseFormats.CSV]),
}
"""
convention = CRUDConvention(graph)
convention.configure(ns, mappings) | python | def configure_crud(graph, ns, mappings):
convention = CRUDConvention(graph)
convention.configure(ns, mappings) | [
"def",
"configure_crud",
"(",
"graph",
",",
"ns",
",",
"mappings",
")",
":",
"convention",
"=",
"CRUDConvention",
"(",
"graph",
")",
"convention",
".",
"configure",
"(",
"ns",
",",
"mappings",
")"
] | Register CRUD endpoints for a resource object.
:param mappings: a dictionary from operations to tuple, where each tuple contains
the target function and zero or more marshmallow schemas according
to the signature of the "register_<foo>_endpoint" functions
Example mapping:
{
Operation.Create: (create_foo, NewFooSchema(), FooSchema()),
Operation.Delete: (delete_foo,),
Operation.Retrieve: (retrieve_foo, FooSchema()),
Operation.Search: (search_foo, SearchFooSchema(), FooSchema(), [ResponseFormats.CSV]),
} | [
"Register",
"CRUD",
"endpoints",
"for",
"a",
"resource",
"object",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L348-L367 |
27,719 | globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_count | def configure_count(self, ns, definition):
"""
Register a count endpoint.
The definition's func should be a count function, which must:
- accept kwargs for the query string
- return a count is the total number of items available
The definition's request_schema will be used to process query string arguments.
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.collection_path, Operation.Count, ns)
@qs(definition.request_schema)
@wraps(definition.func)
def count(**path_data):
request_data = load_query_string_data(definition.request_schema)
response_data = dict()
count = definition.func(**merge_data(path_data, request_data))
headers = encode_count_header(count)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
None,
None,
headers=headers,
response_format=response_format,
)
count.__doc__ = "Count the size of the collection of all {}".format(pluralize(ns.subject_name)) | python | def configure_count(self, ns, definition):
@self.add_route(ns.collection_path, Operation.Count, ns)
@qs(definition.request_schema)
@wraps(definition.func)
def count(**path_data):
request_data = load_query_string_data(definition.request_schema)
response_data = dict()
count = definition.func(**merge_data(path_data, request_data))
headers = encode_count_header(count)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
None,
None,
headers=headers,
response_format=response_format,
)
count.__doc__ = "Count the size of the collection of all {}".format(pluralize(ns.subject_name)) | [
"def",
"configure_count",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"collection_path",
",",
"Operation",
".",
"Count",
",",
"ns",
")",
"@",
"qs",
"(",
"definition",
".",
"request_schema",
")",
"... | Register a count endpoint.
The definition's func should be a count function, which must:
- accept kwargs for the query string
- return a count is the total number of items available
The definition's request_schema will be used to process query string arguments.
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"count",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L74-L105 |
27,720 | globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_create | def configure_create(self, ns, definition):
"""
Register a create endpoint.
The definition's func should be a create function, which must:
- accept kwargs for the request and path data
- return a new item
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.collection_path, Operation.Create, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def create(**path_data):
request_data = load_request_data(definition.request_schema)
response_data = definition.func(**merge_data(path_data, request_data))
headers = encode_id_header(response_data)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
status_code=Operation.Create.value.default_code,
headers=headers,
response_format=response_format,
)
create.__doc__ = "Create a new {}".format(ns.subject_name) | python | def configure_create(self, ns, definition):
@self.add_route(ns.collection_path, Operation.Create, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def create(**path_data):
request_data = load_request_data(definition.request_schema)
response_data = definition.func(**merge_data(path_data, request_data))
headers = encode_id_header(response_data)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
status_code=Operation.Create.value.default_code,
headers=headers,
response_format=response_format,
)
create.__doc__ = "Create a new {}".format(ns.subject_name) | [
"def",
"configure_create",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"collection_path",
",",
"Operation",
".",
"Create",
",",
"ns",
")",
"@",
"request",
"(",
"definition",
".",
"request_schema",
"... | Register a create endpoint.
The definition's func should be a create function, which must:
- accept kwargs for the request and path data
- return a new item
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"create",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L107-L137 |
27,721 | globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_updatebatch | def configure_updatebatch(self, ns, definition):
"""
Register an update batch endpoint.
The definition's func should be an update function, which must:
- accept kwargs for the request and path data
- return a new item
:param ns: the namespace
:param definition: the endpoint definition
"""
operation = Operation.UpdateBatch
@self.add_route(ns.collection_path, operation, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def update_batch(**path_data):
headers = dict()
request_data = load_request_data(definition.request_schema)
response_data = definition.func(**merge_data(path_data, request_data))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
status_code=operation.value.default_code,
headers=headers,
response_format=response_format,
)
update_batch.__doc__ = "Update a batch of {}".format(ns.subject_name) | python | def configure_updatebatch(self, ns, definition):
operation = Operation.UpdateBatch
@self.add_route(ns.collection_path, operation, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def update_batch(**path_data):
headers = dict()
request_data = load_request_data(definition.request_schema)
response_data = definition.func(**merge_data(path_data, request_data))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
status_code=operation.value.default_code,
headers=headers,
response_format=response_format,
)
update_batch.__doc__ = "Update a batch of {}".format(ns.subject_name) | [
"def",
"configure_updatebatch",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"operation",
"=",
"Operation",
".",
"UpdateBatch",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"collection_path",
",",
"operation",
",",
"ns",
")",
"@",
"request",
"(",... | Register an update batch endpoint.
The definition's func should be an update function, which must:
- accept kwargs for the request and path data
- return a new item
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"an",
"update",
"batch",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L139-L171 |
27,722 | globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_retrieve | def configure_retrieve(self, ns, definition):
"""
Register a retrieve endpoint.
The definition's func should be a retrieve function, which must:
- accept kwargs for path data
- return an item or falsey
:param ns: the namespace
:param definition: the endpoint definition
"""
request_schema = definition.request_schema or Schema()
@self.add_route(ns.instance_path, Operation.Retrieve, ns)
@qs(request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def retrieve(**path_data):
headers = dict()
request_data = load_query_string_data(request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
headers=headers,
response_format=response_format,
)
retrieve.__doc__ = "Retrieve a {} by id".format(ns.subject_name) | python | def configure_retrieve(self, ns, definition):
request_schema = definition.request_schema or Schema()
@self.add_route(ns.instance_path, Operation.Retrieve, ns)
@qs(request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def retrieve(**path_data):
headers = dict()
request_data = load_query_string_data(request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
headers=headers,
response_format=response_format,
)
retrieve.__doc__ = "Retrieve a {} by id".format(ns.subject_name) | [
"def",
"configure_retrieve",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"request_schema",
"=",
"definition",
".",
"request_schema",
"or",
"Schema",
"(",
")",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"instance_path",
",",
"Operation",
".",
"... | Register a retrieve endpoint.
The definition's func should be a retrieve function, which must:
- accept kwargs for path data
- return an item or falsey
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"retrieve",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L173-L204 |
27,723 | globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_delete | def configure_delete(self, ns, definition):
"""
Register a delete endpoint.
The definition's func should be a delete function, which must:
- accept kwargs for path data
- return truthy/falsey
:param ns: the namespace
:param definition: the endpoint definition
"""
request_schema = definition.request_schema or Schema()
@self.add_route(ns.instance_path, Operation.Delete, ns)
@qs(request_schema)
@wraps(definition.func)
def delete(**path_data):
headers = dict()
request_data = load_query_string_data(request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
"",
None,
status_code=Operation.Delete.value.default_code,
headers=headers,
response_format=response_format,
)
delete.__doc__ = "Delete a {} by id".format(ns.subject_name) | python | def configure_delete(self, ns, definition):
request_schema = definition.request_schema or Schema()
@self.add_route(ns.instance_path, Operation.Delete, ns)
@qs(request_schema)
@wraps(definition.func)
def delete(**path_data):
headers = dict()
request_data = load_query_string_data(request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
"",
None,
status_code=Operation.Delete.value.default_code,
headers=headers,
response_format=response_format,
)
delete.__doc__ = "Delete a {} by id".format(ns.subject_name) | [
"def",
"configure_delete",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"request_schema",
"=",
"definition",
".",
"request_schema",
"or",
"Schema",
"(",
")",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"instance_path",
",",
"Operation",
".",
"De... | Register a delete endpoint.
The definition's func should be a delete function, which must:
- accept kwargs for path data
- return truthy/falsey
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"delete",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L206-L237 |
27,724 | globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_replace | def configure_replace(self, ns, definition):
"""
Register a replace endpoint.
The definition's func should be a replace function, which must:
- accept kwargs for the request and path data
- return the replaced item
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.instance_path, Operation.Replace, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def replace(**path_data):
headers = dict()
request_data = load_request_data(definition.request_schema)
# Replace/put should create a resource if not already present, but we do not
# enforce these semantics at the HTTP layer. If `func` returns falsey, we
# will raise a 404.
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
headers=headers,
response_format=response_format,
)
replace.__doc__ = "Create or update a {} by id".format(ns.subject_name) | python | def configure_replace(self, ns, definition):
@self.add_route(ns.instance_path, Operation.Replace, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def replace(**path_data):
headers = dict()
request_data = load_request_data(definition.request_schema)
# Replace/put should create a resource if not already present, but we do not
# enforce these semantics at the HTTP layer. If `func` returns falsey, we
# will raise a 404.
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
headers=headers,
response_format=response_format,
)
replace.__doc__ = "Create or update a {} by id".format(ns.subject_name) | [
"def",
"configure_replace",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"instance_path",
",",
"Operation",
".",
"Replace",
",",
"ns",
")",
"@",
"request",
"(",
"definition",
".",
"request_schema",
"... | Register a replace endpoint.
The definition's func should be a replace function, which must:
- accept kwargs for the request and path data
- return the replaced item
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"replace",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L239-L271 |
27,725 | globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_update | def configure_update(self, ns, definition):
"""
Register an update endpoint.
The definition's func should be an update function, which must:
- accept kwargs for the request and path data
- return an updated item
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.instance_path, Operation.Update, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def update(**path_data):
headers = dict()
# NB: using partial here means that marshmallow will not validate required fields
request_data = load_request_data(definition.request_schema, partial=True)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
headers=headers,
response_format=response_format,
)
update.__doc__ = "Update some or all of a {} by id".format(ns.subject_name) | python | def configure_update(self, ns, definition):
@self.add_route(ns.instance_path, Operation.Update, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def update(**path_data):
headers = dict()
# NB: using partial here means that marshmallow will not validate required fields
request_data = load_request_data(definition.request_schema, partial=True)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
headers=headers,
response_format=response_format,
)
update.__doc__ = "Update some or all of a {} by id".format(ns.subject_name) | [
"def",
"configure_update",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"instance_path",
",",
"Operation",
".",
"Update",
",",
"ns",
")",
"@",
"request",
"(",
"definition",
".",
"request_schema",
")"... | Register an update endpoint.
The definition's func should be an update function, which must:
- accept kwargs for the request and path data
- return an updated item
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"an",
"update",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L273-L303 |
27,726 | globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_createcollection | def configure_createcollection(self, ns, definition):
"""
Register create collection endpoint.
:param ns: the namespace
:param definition: the endpoint definition
"""
paginated_list_schema = self.page_cls.make_paginated_list_schema_class(
ns,
definition.response_schema,
)()
@self.add_route(ns.collection_path, Operation.CreateCollection, ns)
@request(definition.request_schema)
@response(paginated_list_schema)
@wraps(definition.func)
def create_collection(**path_data):
request_data = load_request_data(definition.request_schema)
# NB: if we don't filter the request body through an explicit page schema,
# we will leak other request arguments into the pagination query strings
page = self.page_cls.from_query_string(self.page_schema(), request_data)
result = definition.func(**merge_data(
path_data,
merge_data(
request_data,
page.to_dict(func=identity),
),
))
response_data, headers = page.to_paginated_list(result, ns, Operation.CreateCollection)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
paginated_list_schema,
response_data,
headers=headers,
response_format=response_format,
)
create_collection.__doc__ = "Create the collection of {}".format(pluralize(ns.subject_name)) | python | def configure_createcollection(self, ns, definition):
paginated_list_schema = self.page_cls.make_paginated_list_schema_class(
ns,
definition.response_schema,
)()
@self.add_route(ns.collection_path, Operation.CreateCollection, ns)
@request(definition.request_schema)
@response(paginated_list_schema)
@wraps(definition.func)
def create_collection(**path_data):
request_data = load_request_data(definition.request_schema)
# NB: if we don't filter the request body through an explicit page schema,
# we will leak other request arguments into the pagination query strings
page = self.page_cls.from_query_string(self.page_schema(), request_data)
result = definition.func(**merge_data(
path_data,
merge_data(
request_data,
page.to_dict(func=identity),
),
))
response_data, headers = page.to_paginated_list(result, ns, Operation.CreateCollection)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
paginated_list_schema,
response_data,
headers=headers,
response_format=response_format,
)
create_collection.__doc__ = "Create the collection of {}".format(pluralize(ns.subject_name)) | [
"def",
"configure_createcollection",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"paginated_list_schema",
"=",
"self",
".",
"page_cls",
".",
"make_paginated_list_schema_class",
"(",
"ns",
",",
"definition",
".",
"response_schema",
",",
")",
"(",
")",
"@... | Register create collection endpoint.
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"create",
"collection",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L305-L345 |
27,727 | globality-corp/microcosm-flask | microcosm_flask/swagger/parameters/nested.py | NestedParameterBuilder.parse_ref | def parse_ref(self, field: Field) -> str:
"""
Parse the reference type for nested fields, if any.
"""
ref_name = type_name(name_for(field.schema))
return f"#/definitions/{ref_name}" | python | def parse_ref(self, field: Field) -> str:
ref_name = type_name(name_for(field.schema))
return f"#/definitions/{ref_name}" | [
"def",
"parse_ref",
"(",
"self",
",",
"field",
":",
"Field",
")",
"->",
"str",
":",
"ref_name",
"=",
"type_name",
"(",
"name_for",
"(",
"field",
".",
"schema",
")",
")",
"return",
"f\"#/definitions/{ref_name}\""
] | Parse the reference type for nested fields, if any. | [
"Parse",
"the",
"reference",
"type",
"for",
"nested",
"fields",
"if",
"any",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/nested.py#L16-L22 |
27,728 | globality-corp/microcosm-flask | microcosm_flask/conventions/build_info.py | configure_build_info | def configure_build_info(graph):
"""
Configure the build info endpoint.
"""
ns = Namespace(
subject=BuildInfo,
)
convention = BuildInfoConvention(graph)
convention.configure(ns, retrieve=tuple())
return convention.build_info | python | def configure_build_info(graph):
ns = Namespace(
subject=BuildInfo,
)
convention = BuildInfoConvention(graph)
convention.configure(ns, retrieve=tuple())
return convention.build_info | [
"def",
"configure_build_info",
"(",
"graph",
")",
":",
"ns",
"=",
"Namespace",
"(",
"subject",
"=",
"BuildInfo",
",",
")",
"convention",
"=",
"BuildInfoConvention",
"(",
"graph",
")",
"convention",
".",
"configure",
"(",
"ns",
",",
"retrieve",
"=",
"tuple",
... | Configure the build info endpoint. | [
"Configure",
"the",
"build",
"info",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/build_info.py#L63-L74 |
27,729 | globality-corp/microcosm-flask | microcosm_flask/conventions/logging_level.py | build_logger_tree | def build_logger_tree():
"""
Build a DFS tree representing the logger layout.
Adapted with much appreciation from: https://github.com/brandon-rhodes/logging_tree
"""
cache = {}
tree = make_logger_node("", root)
for name, logger in sorted(root.manager.loggerDict.items()):
if "." in name:
parent_name = ".".join(name.split(".")[:-1])
parent = cache[parent_name]
else:
parent = tree
cache[name] = make_logger_node(name, logger, parent)
return tree | python | def build_logger_tree():
cache = {}
tree = make_logger_node("", root)
for name, logger in sorted(root.manager.loggerDict.items()):
if "." in name:
parent_name = ".".join(name.split(".")[:-1])
parent = cache[parent_name]
else:
parent = tree
cache[name] = make_logger_node(name, logger, parent)
return tree | [
"def",
"build_logger_tree",
"(",
")",
":",
"cache",
"=",
"{",
"}",
"tree",
"=",
"make_logger_node",
"(",
"\"\"",
",",
"root",
")",
"for",
"name",
",",
"logger",
"in",
"sorted",
"(",
"root",
".",
"manager",
".",
"loggerDict",
".",
"items",
"(",
")",
"... | Build a DFS tree representing the logger layout.
Adapted with much appreciation from: https://github.com/brandon-rhodes/logging_tree | [
"Build",
"a",
"DFS",
"tree",
"representing",
"the",
"logger",
"layout",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/logging_level.py#L58-L75 |
27,730 | globality-corp/microcosm-flask | microcosm_flask/swagger/parameters/base.py | ParameterBuilder.build | def build(self, field: Field) -> Mapping[str, Any]:
"""
Build a parameter.
"""
return dict(self.iter_parsed_values(field)) | python | def build(self, field: Field) -> Mapping[str, Any]:
return dict(self.iter_parsed_values(field)) | [
"def",
"build",
"(",
"self",
",",
"field",
":",
"Field",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"dict",
"(",
"self",
".",
"iter_parsed_values",
"(",
"field",
")",
")"
] | Build a parameter. | [
"Build",
"a",
"parameter",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/base.py#L39-L44 |
27,731 | globality-corp/microcosm-flask | microcosm_flask/swagger/parameters/base.py | ParameterBuilder.iter_parsed_values | def iter_parsed_values(self, field: Field) -> Iterable[Tuple[str, Any]]:
"""
Walk the dictionary of parsers and emit all non-null values.
"""
for key, func in self.parsers.items():
value = func(field)
if not value:
continue
yield key, value | python | def iter_parsed_values(self, field: Field) -> Iterable[Tuple[str, Any]]:
for key, func in self.parsers.items():
value = func(field)
if not value:
continue
yield key, value | [
"def",
"iter_parsed_values",
"(",
"self",
",",
"field",
":",
"Field",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"for",
"key",
",",
"func",
"in",
"self",
".",
"parsers",
".",
"items",
"(",
")",
":",
"value",
"=",
... | Walk the dictionary of parsers and emit all non-null values. | [
"Walk",
"the",
"dictionary",
"of",
"parsers",
"and",
"emit",
"all",
"non",
"-",
"null",
"values",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/base.py#L53-L62 |
27,732 | globality-corp/microcosm-flask | microcosm_flask/namespaces.py | Namespace.object_ns | def object_ns(self):
"""
Create a new namespace for the current namespace's object value.
"""
return Namespace(
subject=self.object_,
object_=None,
prefix=self.prefix,
qualifier=self.qualifier,
version=self.version,
) | python | def object_ns(self):
return Namespace(
subject=self.object_,
object_=None,
prefix=self.prefix,
qualifier=self.qualifier,
version=self.version,
) | [
"def",
"object_ns",
"(",
"self",
")",
":",
"return",
"Namespace",
"(",
"subject",
"=",
"self",
".",
"object_",
",",
"object_",
"=",
"None",
",",
"prefix",
"=",
"self",
".",
"prefix",
",",
"qualifier",
"=",
"self",
".",
"qualifier",
",",
"version",
"=",... | Create a new namespace for the current namespace's object value. | [
"Create",
"a",
"new",
"namespace",
"for",
"the",
"current",
"namespace",
"s",
"object",
"value",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/namespaces.py#L81-L92 |
27,733 | globality-corp/microcosm-flask | microcosm_flask/namespaces.py | Namespace.url_for | def url_for(self, operation, _external=True, **kwargs):
"""
Construct a URL for an operation against a resource.
:param kwargs: additional arguments for URL path expansion,
which are passed to flask.url_for.
In particular, _external=True produces absolute url.
"""
return url_for(self.endpoint_for(operation), _external=_external, **kwargs) | python | def url_for(self, operation, _external=True, **kwargs):
return url_for(self.endpoint_for(operation), _external=_external, **kwargs) | [
"def",
"url_for",
"(",
"self",
",",
"operation",
",",
"_external",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"url_for",
"(",
"self",
".",
"endpoint_for",
"(",
"operation",
")",
",",
"_external",
"=",
"_external",
",",
"*",
"*",
"kwargs"... | Construct a URL for an operation against a resource.
:param kwargs: additional arguments for URL path expansion,
which are passed to flask.url_for.
In particular, _external=True produces absolute url. | [
"Construct",
"a",
"URL",
"for",
"an",
"operation",
"against",
"a",
"resource",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/namespaces.py#L159-L168 |
27,734 | globality-corp/microcosm-flask | microcosm_flask/namespaces.py | Namespace.href_for | def href_for(self, operation, qs=None, **kwargs):
"""
Construct an full href for an operation against a resource.
:parm qs: the query string dictionary, if any
:param kwargs: additional arguments for path expansion
"""
url = urljoin(request.url_root, self.url_for(operation, **kwargs))
qs_character = "?" if url.find("?") == -1 else "&"
return "{}{}".format(
url,
"{}{}".format(qs_character, urlencode(qs)) if qs else "",
) | python | def href_for(self, operation, qs=None, **kwargs):
url = urljoin(request.url_root, self.url_for(operation, **kwargs))
qs_character = "?" if url.find("?") == -1 else "&"
return "{}{}".format(
url,
"{}{}".format(qs_character, urlencode(qs)) if qs else "",
) | [
"def",
"href_for",
"(",
"self",
",",
"operation",
",",
"qs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"urljoin",
"(",
"request",
".",
"url_root",
",",
"self",
".",
"url_for",
"(",
"operation",
",",
"*",
"*",
"kwargs",
")",
")",
... | Construct an full href for an operation against a resource.
:parm qs: the query string dictionary, if any
:param kwargs: additional arguments for path expansion | [
"Construct",
"an",
"full",
"href",
"for",
"an",
"operation",
"against",
"a",
"resource",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/namespaces.py#L170-L184 |
27,735 | globality-corp/microcosm-flask | microcosm_flask/conventions/swagger.py | configure_swagger | def configure_swagger(graph):
"""
Build a singleton endpoint that provides swagger definitions for all operations.
"""
ns = Namespace(
subject=graph.config.swagger_convention.name,
version=graph.config.swagger_convention.version,
)
convention = SwaggerConvention(graph)
convention.configure(ns, discover=tuple())
return ns.subject | python | def configure_swagger(graph):
ns = Namespace(
subject=graph.config.swagger_convention.name,
version=graph.config.swagger_convention.version,
)
convention = SwaggerConvention(graph)
convention.configure(ns, discover=tuple())
return ns.subject | [
"def",
"configure_swagger",
"(",
"graph",
")",
":",
"ns",
"=",
"Namespace",
"(",
"subject",
"=",
"graph",
".",
"config",
".",
"swagger_convention",
".",
"name",
",",
"version",
"=",
"graph",
".",
"config",
".",
"swagger_convention",
".",
"version",
",",
")... | Build a singleton endpoint that provides swagger definitions for all operations. | [
"Build",
"a",
"singleton",
"endpoint",
"that",
"provides",
"swagger",
"definitions",
"for",
"all",
"operations",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/swagger.py#L76-L87 |
27,736 | globality-corp/microcosm-flask | microcosm_flask/conventions/swagger.py | SwaggerConvention.configure_discover | def configure_discover(self, ns, definition):
"""
Register a swagger endpoint for a set of operations.
"""
@self.add_route(ns.singleton_path, Operation.Discover, ns)
def discover():
swagger = build_swagger(self.graph, ns, self.find_matching_endpoints(ns))
g.hide_body = True
return make_response(swagger) | python | def configure_discover(self, ns, definition):
@self.add_route(ns.singleton_path, Operation.Discover, ns)
def discover():
swagger = build_swagger(self.graph, ns, self.find_matching_endpoints(ns))
g.hide_body = True
return make_response(swagger) | [
"def",
"configure_discover",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"singleton_path",
",",
"Operation",
".",
"Discover",
",",
"ns",
")",
"def",
"discover",
"(",
")",
":",
"swagger",
"=",
"bui... | Register a swagger endpoint for a set of operations. | [
"Register",
"a",
"swagger",
"endpoint",
"for",
"a",
"set",
"of",
"operations",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/swagger.py#L43-L52 |
27,737 | globality-corp/microcosm-flask | microcosm_flask/swagger/parameters/list.py | ListParameterBuilder.parse_items | def parse_items(self, field: Field) -> Mapping[str, Any]:
"""
Parse the child item type for list fields, if any.
"""
return self.build_parameter(field.container) | python | def parse_items(self, field: Field) -> Mapping[str, Any]:
return self.build_parameter(field.container) | [
"def",
"parse_items",
"(",
"self",
",",
"field",
":",
"Field",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"self",
".",
"build_parameter",
"(",
"field",
".",
"container",
")"
] | Parse the child item type for list fields, if any. | [
"Parse",
"the",
"child",
"item",
"type",
"for",
"list",
"fields",
"if",
"any",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/list.py#L16-L21 |
27,738 | globality-corp/microcosm-flask | microcosm_flask/linking.py | Link.for_ | def for_(cls, operation, ns, qs=None, type=None, allow_templates=False, **kwargs):
"""
Create a link to an operation on a resource object.
Supports link templating if enabled by making a best guess as to the URI
template construction.
See also [RFC 6570]( https://tools.ietf.org/html/rfc6570).
:param operation: the operation
:param ns: the namespace
:param qs: an optional query string (e.g. for paging)
:param type: an optional link type
:param allow_templates: whether generated links are allowed to contain templates
:param kwargs: optional endpoint expansion arguments (e.g. for URI parameters)
:raises BuildError: if link templating is needed and disallowed
"""
assert isinstance(ns, Namespace)
try:
href, templated = ns.href_for(operation, qs=qs, **kwargs), False
except BuildError as error:
if not allow_templates:
raise
uri_templates = {
argument: "{{{}}}".format(argument)
for argument in error.suggested.arguments
}
kwargs.update(uri_templates)
href, templated = ns.href_for(operation, qs=qs, **kwargs), True
return cls(
href=href,
type=type,
templated=templated,
) | python | def for_(cls, operation, ns, qs=None, type=None, allow_templates=False, **kwargs):
assert isinstance(ns, Namespace)
try:
href, templated = ns.href_for(operation, qs=qs, **kwargs), False
except BuildError as error:
if not allow_templates:
raise
uri_templates = {
argument: "{{{}}}".format(argument)
for argument in error.suggested.arguments
}
kwargs.update(uri_templates)
href, templated = ns.href_for(operation, qs=qs, **kwargs), True
return cls(
href=href,
type=type,
templated=templated,
) | [
"def",
"for_",
"(",
"cls",
",",
"operation",
",",
"ns",
",",
"qs",
"=",
"None",
",",
"type",
"=",
"None",
",",
"allow_templates",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"ns",
",",
"Namespace",
")",
"try",
":",... | Create a link to an operation on a resource object.
Supports link templating if enabled by making a best guess as to the URI
template construction.
See also [RFC 6570]( https://tools.ietf.org/html/rfc6570).
:param operation: the operation
:param ns: the namespace
:param qs: an optional query string (e.g. for paging)
:param type: an optional link type
:param allow_templates: whether generated links are allowed to contain templates
:param kwargs: optional endpoint expansion arguments (e.g. for URI parameters)
:raises BuildError: if link templating is needed and disallowed | [
"Create",
"a",
"link",
"to",
"an",
"operation",
"on",
"a",
"resource",
"object",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/linking.py#L74-L108 |
27,739 | globality-corp/microcosm-flask | microcosm_flask/swagger/api.py | build_parameter | def build_parameter(field: Field) -> Mapping[str, Any]:
"""
Build JSON parameter from a marshmallow field.
"""
builder = Parameters()
return builder.build(field) | python | def build_parameter(field: Field) -> Mapping[str, Any]:
builder = Parameters()
return builder.build(field) | [
"def",
"build_parameter",
"(",
"field",
":",
"Field",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"builder",
"=",
"Parameters",
"(",
")",
"return",
"builder",
".",
"build",
"(",
"field",
")"
] | Build JSON parameter from a marshmallow field. | [
"Build",
"JSON",
"parameter",
"from",
"a",
"marshmallow",
"field",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/api.py#L39-L45 |
27,740 | globality-corp/microcosm-flask | microcosm_flask/conventions/saved_search.py | SavedSearchConvention.configure_savedsearch | def configure_savedsearch(self, ns, definition):
"""
Register a saved search endpoint.
The definition's func should be a search function, which must:
- accept kwargs for the request data
- return a tuple of (items, count) where count is the total number of items
available (in the case of pagination)
The definition's request_schema will be used to process query string arguments.
:param ns: the namespace
:param definition: the endpoint definition
"""
paginated_list_schema = self.page_cls.make_paginated_list_schema_class(
ns,
definition.response_schema,
)()
@self.add_route(ns.collection_path, Operation.SavedSearch, ns)
@request(definition.request_schema)
@response(paginated_list_schema)
@wraps(definition.func)
def saved_search(**path_data):
request_data = load_request_data(definition.request_schema)
page = self.page_cls.from_dict(request_data)
request_data.update(page.to_dict(func=identity))
result = definition.func(**merge_data(path_data, request_data))
response_data, headers = page.to_paginated_list(result, ns, Operation.SavedSearch)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
paginated_list_schema,
response_data,
headers=headers,
response_format=response_format,
)
saved_search.__doc__ = "Persist and return the search results of {}".format(pluralize(ns.subject_name)) | python | def configure_savedsearch(self, ns, definition):
paginated_list_schema = self.page_cls.make_paginated_list_schema_class(
ns,
definition.response_schema,
)()
@self.add_route(ns.collection_path, Operation.SavedSearch, ns)
@request(definition.request_schema)
@response(paginated_list_schema)
@wraps(definition.func)
def saved_search(**path_data):
request_data = load_request_data(definition.request_schema)
page = self.page_cls.from_dict(request_data)
request_data.update(page.to_dict(func=identity))
result = definition.func(**merge_data(path_data, request_data))
response_data, headers = page.to_paginated_list(result, ns, Operation.SavedSearch)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
paginated_list_schema,
response_data,
headers=headers,
response_format=response_format,
)
saved_search.__doc__ = "Persist and return the search results of {}".format(pluralize(ns.subject_name)) | [
"def",
"configure_savedsearch",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"paginated_list_schema",
"=",
"self",
".",
"page_cls",
".",
"make_paginated_list_schema_class",
"(",
"ns",
",",
"definition",
".",
"response_schema",
",",
")",
"(",
")",
"@",
... | Register a saved search endpoint.
The definition's func should be a search function, which must:
- accept kwargs for the request data
- return a tuple of (items, count) where count is the total number of items
available (in the case of pagination)
The definition's request_schema will be used to process query string arguments.
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"saved",
"search",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/saved_search.py#L22-L61 |
27,741 | globality-corp/microcosm-flask | microcosm_flask/basic_auth.py | encode_basic_auth | def encode_basic_auth(username, password):
"""
Encode basic auth credentials.
"""
return "Basic {}".format(
b64encode(
"{}:{}".format(
username,
password,
).encode("utf-8")
).decode("utf-8")
) | python | def encode_basic_auth(username, password):
return "Basic {}".format(
b64encode(
"{}:{}".format(
username,
password,
).encode("utf-8")
).decode("utf-8")
) | [
"def",
"encode_basic_auth",
"(",
"username",
",",
"password",
")",
":",
"return",
"\"Basic {}\"",
".",
"format",
"(",
"b64encode",
"(",
"\"{}:{}\"",
".",
"format",
"(",
"username",
",",
"password",
",",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
... | Encode basic auth credentials. | [
"Encode",
"basic",
"auth",
"credentials",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/basic_auth.py#L22-L34 |
27,742 | globality-corp/microcosm-flask | microcosm_flask/basic_auth.py | configure_basic_auth_decorator | def configure_basic_auth_decorator(graph):
"""
Configure a basic auth decorator.
"""
# use the metadata name if no realm is defined
graph.config.setdefault("BASIC_AUTH_REALM", graph.metadata.name)
return ConfigBasicAuth(
app=graph.flask,
# wrap in dict to allow lists of items as well as dictionaries
credentials=dict(graph.config.basic_auth.credentials),
) | python | def configure_basic_auth_decorator(graph):
# use the metadata name if no realm is defined
graph.config.setdefault("BASIC_AUTH_REALM", graph.metadata.name)
return ConfigBasicAuth(
app=graph.flask,
# wrap in dict to allow lists of items as well as dictionaries
credentials=dict(graph.config.basic_auth.credentials),
) | [
"def",
"configure_basic_auth_decorator",
"(",
"graph",
")",
":",
"# use the metadata name if no realm is defined",
"graph",
".",
"config",
".",
"setdefault",
"(",
"\"BASIC_AUTH_REALM\"",
",",
"graph",
".",
"metadata",
".",
"name",
")",
"return",
"ConfigBasicAuth",
"(",
... | Configure a basic auth decorator. | [
"Configure",
"a",
"basic",
"auth",
"decorator",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/basic_auth.py#L73-L84 |
27,743 | globality-corp/microcosm-flask | microcosm_flask/basic_auth.py | ConfigBasicAuth.check_credentials | def check_credentials(self, username, password):
"""
Override credential checking to use configured credentials.
"""
return password is not None and self.credentials.get(username, None) == password | python | def check_credentials(self, username, password):
return password is not None and self.credentials.get(username, None) == password | [
"def",
"check_credentials",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"return",
"password",
"is",
"not",
"None",
"and",
"self",
".",
"credentials",
".",
"get",
"(",
"username",
",",
"None",
")",
"==",
"password"
] | Override credential checking to use configured credentials. | [
"Override",
"credential",
"checking",
"to",
"use",
"configured",
"credentials",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/basic_auth.py#L50-L55 |
27,744 | globality-corp/microcosm-flask | microcosm_flask/basic_auth.py | ConfigBasicAuth.challenge | def challenge(self):
"""
Override challenge to raise an exception that will trigger regular error handling.
"""
response = super(ConfigBasicAuth, self).challenge()
raise with_headers(Unauthorized(), response.headers) | python | def challenge(self):
response = super(ConfigBasicAuth, self).challenge()
raise with_headers(Unauthorized(), response.headers) | [
"def",
"challenge",
"(",
"self",
")",
":",
"response",
"=",
"super",
"(",
"ConfigBasicAuth",
",",
"self",
")",
".",
"challenge",
"(",
")",
"raise",
"with_headers",
"(",
"Unauthorized",
"(",
")",
",",
"response",
".",
"headers",
")"
] | Override challenge to raise an exception that will trigger regular error handling. | [
"Override",
"challenge",
"to",
"raise",
"an",
"exception",
"that",
"will",
"trigger",
"regular",
"error",
"handling",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/basic_auth.py#L57-L63 |
27,745 | globality-corp/microcosm-flask | microcosm_flask/swagger/schemas.py | Schemas.iter_fields | def iter_fields(self, schema: Schema) -> Iterable[Tuple[str, Field]]:
"""
Iterate through marshmallow schema fields.
Generates: name, field pairs
"""
for name in sorted(schema.fields.keys()):
field = schema.fields[name]
yield field.dump_to or name, field | python | def iter_fields(self, schema: Schema) -> Iterable[Tuple[str, Field]]:
for name in sorted(schema.fields.keys()):
field = schema.fields[name]
yield field.dump_to or name, field | [
"def",
"iter_fields",
"(",
"self",
",",
"schema",
":",
"Schema",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"Field",
"]",
"]",
":",
"for",
"name",
"in",
"sorted",
"(",
"schema",
".",
"fields",
".",
"keys",
"(",
")",
")",
":",
"field",
... | Iterate through marshmallow schema fields.
Generates: name, field pairs | [
"Iterate",
"through",
"marshmallow",
"schema",
"fields",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/schemas.py#L56-L65 |
27,746 | globality-corp/microcosm-flask | microcosm_flask/paging.py | PaginatedList.links | def links(self):
"""
Include a self link.
"""
links = Links()
links["self"] = Link.for_(
self._operation,
self._ns,
qs=self._page.to_items(),
**self._context
)
return links | python | def links(self):
links = Links()
links["self"] = Link.for_(
self._operation,
self._ns,
qs=self._page.to_items(),
**self._context
)
return links | [
"def",
"links",
"(",
"self",
")",
":",
"links",
"=",
"Links",
"(",
")",
"links",
"[",
"\"self\"",
"]",
"=",
"Link",
".",
"for_",
"(",
"self",
".",
"_operation",
",",
"self",
".",
"_ns",
",",
"qs",
"=",
"self",
".",
"_page",
".",
"to_items",
"(",
... | Include a self link. | [
"Include",
"a",
"self",
"link",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L85-L97 |
27,747 | globality-corp/microcosm-flask | microcosm_flask/paging.py | OffsetLimitPaginatedList.links | def links(self):
"""
Include previous and next links.
"""
links = super(OffsetLimitPaginatedList, self).links
if self._page.offset + self._page.limit < self.count:
links["next"] = Link.for_(
self._operation,
self._ns,
qs=self._page.next_page.to_items(),
**self._context
)
if self.offset > 0:
links["prev"] = Link.for_(
self._operation,
self._ns,
qs=self._page.prev_page.to_items(),
**self._context
)
return links | python | def links(self):
links = super(OffsetLimitPaginatedList, self).links
if self._page.offset + self._page.limit < self.count:
links["next"] = Link.for_(
self._operation,
self._ns,
qs=self._page.next_page.to_items(),
**self._context
)
if self.offset > 0:
links["prev"] = Link.for_(
self._operation,
self._ns,
qs=self._page.prev_page.to_items(),
**self._context
)
return links | [
"def",
"links",
"(",
"self",
")",
":",
"links",
"=",
"super",
"(",
"OffsetLimitPaginatedList",
",",
"self",
")",
".",
"links",
"if",
"self",
".",
"_page",
".",
"offset",
"+",
"self",
".",
"_page",
".",
"limit",
"<",
"self",
".",
"count",
":",
"links"... | Include previous and next links. | [
"Include",
"previous",
"and",
"next",
"links",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L124-L144 |
27,748 | globality-corp/microcosm-flask | microcosm_flask/paging.py | Page.to_items | def to_items(self, func=str):
"""
Contruct a list of dictionary items.
The items are normalized using:
- A sort function by key (for consistent results)
- A transformation function for values
The transformation function will default to `str`, which is a good choice when encoding values
as part of a response; this requires that complex types (UUID, Enum, etc.) have a valid string
encoding.
The transformation function should be set to `identity` in cases where raw values are desired;
this is normally necessary when passing page data to controller functions as kwargs.
"""
return [
(key, func(self.kwargs[key]))
for key in sorted(self.kwargs.keys())
] | python | def to_items(self, func=str):
return [
(key, func(self.kwargs[key]))
for key in sorted(self.kwargs.keys())
] | [
"def",
"to_items",
"(",
"self",
",",
"func",
"=",
"str",
")",
":",
"return",
"[",
"(",
"key",
",",
"func",
"(",
"self",
".",
"kwargs",
"[",
"key",
"]",
")",
")",
"for",
"key",
"in",
"sorted",
"(",
"self",
".",
"kwargs",
".",
"keys",
"(",
")",
... | Contruct a list of dictionary items.
The items are normalized using:
- A sort function by key (for consistent results)
- A transformation function for values
The transformation function will default to `str`, which is a good choice when encoding values
as part of a response; this requires that complex types (UUID, Enum, etc.) have a valid string
encoding.
The transformation function should be set to `identity` in cases where raw values are desired;
this is normally necessary when passing page data to controller functions as kwargs. | [
"Contruct",
"a",
"list",
"of",
"dictionary",
"items",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L155-L174 |
27,749 | globality-corp/microcosm-flask | microcosm_flask/paging.py | Page.to_paginated_list | def to_paginated_list(self, result, _ns, _operation, **kwargs):
"""
Convert a controller result to a paginated list.
The result format is assumed to meet the contract of this page class's `parse_result` function.
"""
items, context = self.parse_result(result)
headers = dict()
paginated_list = PaginatedList(
items=items,
_page=self,
_ns=_ns,
_operation=_operation,
_context=context,
)
return paginated_list, headers | python | def to_paginated_list(self, result, _ns, _operation, **kwargs):
items, context = self.parse_result(result)
headers = dict()
paginated_list = PaginatedList(
items=items,
_page=self,
_ns=_ns,
_operation=_operation,
_context=context,
)
return paginated_list, headers | [
"def",
"to_paginated_list",
"(",
"self",
",",
"result",
",",
"_ns",
",",
"_operation",
",",
"*",
"*",
"kwargs",
")",
":",
"items",
",",
"context",
"=",
"self",
".",
"parse_result",
"(",
"result",
")",
"headers",
"=",
"dict",
"(",
")",
"paginated_list",
... | Convert a controller result to a paginated list.
The result format is assumed to meet the contract of this page class's `parse_result` function. | [
"Convert",
"a",
"controller",
"result",
"to",
"a",
"paginated",
"list",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L179-L195 |
27,750 | globality-corp/microcosm-flask | microcosm_flask/paging.py | Page.parse_result | def parse_result(cls, result):
"""
Parse a simple items result.
May either be two item tuple containing items and a context dictionary (see: relation convention)
or a list of items.
"""
if isinstance(result, tuple) == 2:
items, context = result
else:
context = {}
items = result
return items, context | python | def parse_result(cls, result):
if isinstance(result, tuple) == 2:
items, context = result
else:
context = {}
items = result
return items, context | [
"def",
"parse_result",
"(",
"cls",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"tuple",
")",
"==",
"2",
":",
"items",
",",
"context",
"=",
"result",
"else",
":",
"context",
"=",
"{",
"}",
"items",
"=",
"result",
"return",
"items"... | Parse a simple items result.
May either be two item tuple containing items and a context dictionary (see: relation convention)
or a list of items. | [
"Parse",
"a",
"simple",
"items",
"result",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L198-L211 |
27,751 | globality-corp/microcosm-flask | microcosm_flask/paging.py | Page.from_query_string | def from_query_string(cls, schema, qs=None):
"""
Extract a page from the current query string.
:param qs: a query string dictionary (`request.args` will be used if omitted)
"""
dct = load_query_string_data(schema, qs)
return cls.from_dict(dct) | python | def from_query_string(cls, schema, qs=None):
dct = load_query_string_data(schema, qs)
return cls.from_dict(dct) | [
"def",
"from_query_string",
"(",
"cls",
",",
"schema",
",",
"qs",
"=",
"None",
")",
":",
"dct",
"=",
"load_query_string_data",
"(",
"schema",
",",
"qs",
")",
"return",
"cls",
".",
"from_dict",
"(",
"dct",
")"
] | Extract a page from the current query string.
:param qs: a query string dictionary (`request.args` will be used if omitted) | [
"Extract",
"a",
"page",
"from",
"the",
"current",
"query",
"string",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L214-L222 |
27,752 | globality-corp/microcosm-flask | microcosm_flask/paging.py | Page.make_paginated_list_schema_class | def make_paginated_list_schema_class(cls, ns, item_schema):
"""
Generate a schema class that represents a paginted list of items.
"""
class PaginatedListSchema(Schema):
__alias__ = "{}_list".format(ns.subject_name)
items = fields.List(fields.Nested(item_schema), required=True)
_links = fields.Raw()
return PaginatedListSchema | python | def make_paginated_list_schema_class(cls, ns, item_schema):
class PaginatedListSchema(Schema):
__alias__ = "{}_list".format(ns.subject_name)
items = fields.List(fields.Nested(item_schema), required=True)
_links = fields.Raw()
return PaginatedListSchema | [
"def",
"make_paginated_list_schema_class",
"(",
"cls",
",",
"ns",
",",
"item_schema",
")",
":",
"class",
"PaginatedListSchema",
"(",
"Schema",
")",
":",
"__alias__",
"=",
"\"{}_list\"",
".",
"format",
"(",
"ns",
".",
"subject_name",
")",
"items",
"=",
"fields"... | Generate a schema class that represents a paginted list of items. | [
"Generate",
"a",
"schema",
"class",
"that",
"represents",
"a",
"paginted",
"list",
"of",
"items",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L229-L239 |
27,753 | globality-corp/microcosm-flask | microcosm_flask/paging.py | OffsetLimitPage.parse_result | def parse_result(cls, result):
"""
Parse an items + count tuple result.
May either be three item tuple containing items, count, and a context dictionary (see: relation convention)
or a two item tuple containing only items and count.
"""
if len(result) == 3:
items, count, context = result
else:
context = {}
items, count = result
return items, count, context | python | def parse_result(cls, result):
if len(result) == 3:
items, count, context = result
else:
context = {}
items, count = result
return items, count, context | [
"def",
"parse_result",
"(",
"cls",
",",
"result",
")",
":",
"if",
"len",
"(",
"result",
")",
"==",
"3",
":",
"items",
",",
"count",
",",
"context",
"=",
"result",
"else",
":",
"context",
"=",
"{",
"}",
"items",
",",
"count",
"=",
"result",
"return"... | Parse an items + count tuple result.
May either be three item tuple containing items, count, and a context dictionary (see: relation convention)
or a two item tuple containing only items and count. | [
"Parse",
"an",
"items",
"+",
"count",
"tuple",
"result",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L299-L312 |
27,754 | globality-corp/microcosm-flask | microcosm_flask/naming.py | name_for | def name_for(obj):
"""
Get a name for something.
Allows overriding of default names using the `__alias__` attribute.
"""
if isinstance(obj, str):
return obj
cls = obj if isclass(obj) else obj.__class__
if hasattr(cls, "__alias__"):
return underscore(cls.__alias__)
else:
return underscore(cls.__name__) | python | def name_for(obj):
if isinstance(obj, str):
return obj
cls = obj if isclass(obj) else obj.__class__
if hasattr(cls, "__alias__"):
return underscore(cls.__alias__)
else:
return underscore(cls.__name__) | [
"def",
"name_for",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"return",
"obj",
"cls",
"=",
"obj",
"if",
"isclass",
"(",
"obj",
")",
"else",
"obj",
".",
"__class__",
"if",
"hasattr",
"(",
"cls",
",",
"\"__alias__\"",
... | Get a name for something.
Allows overriding of default names using the `__alias__` attribute. | [
"Get",
"a",
"name",
"for",
"something",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/naming.py#L10-L25 |
27,755 | globality-corp/microcosm-flask | microcosm_flask/naming.py | instance_path_for | def instance_path_for(name, identifier_type, identifier_key=None):
"""
Get a path for thing.
"""
return "/{}/<{}:{}>".format(
name_for(name),
identifier_type,
identifier_key or "{}_id".format(name_for(name)),
) | python | def instance_path_for(name, identifier_type, identifier_key=None):
return "/{}/<{}:{}>".format(
name_for(name),
identifier_type,
identifier_key or "{}_id".format(name_for(name)),
) | [
"def",
"instance_path_for",
"(",
"name",
",",
"identifier_type",
",",
"identifier_key",
"=",
"None",
")",
":",
"return",
"\"/{}/<{}:{}>\"",
".",
"format",
"(",
"name_for",
"(",
"name",
")",
",",
"identifier_type",
",",
"identifier_key",
"or",
"\"{}_id\"",
".",
... | Get a path for thing. | [
"Get",
"a",
"path",
"for",
"thing",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/naming.py#L48-L57 |
27,756 | globality-corp/microcosm-flask | microcosm_flask/naming.py | relation_path_for | def relation_path_for(from_name, to_name, identifier_type, identifier_key=None):
"""
Get a path relating a thing to another.
"""
return "/{}/<{}:{}>/{}".format(
name_for(from_name),
identifier_type,
identifier_key or "{}_id".format(name_for(from_name)),
name_for(to_name),
) | python | def relation_path_for(from_name, to_name, identifier_type, identifier_key=None):
return "/{}/<{}:{}>/{}".format(
name_for(from_name),
identifier_type,
identifier_key or "{}_id".format(name_for(from_name)),
name_for(to_name),
) | [
"def",
"relation_path_for",
"(",
"from_name",
",",
"to_name",
",",
"identifier_type",
",",
"identifier_key",
"=",
"None",
")",
":",
"return",
"\"/{}/<{}:{}>/{}\"",
".",
"format",
"(",
"name_for",
"(",
"from_name",
")",
",",
"identifier_type",
",",
"identifier_key"... | Get a path relating a thing to another. | [
"Get",
"a",
"path",
"relating",
"a",
"thing",
"to",
"another",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/naming.py#L71-L81 |
27,757 | globality-corp/microcosm-flask | microcosm_flask/conventions/alias.py | configure_alias | def configure_alias(graph, ns, mappings):
"""
Register Alias endpoints for a resource object.
"""
convention = AliasConvention(graph)
convention.configure(ns, mappings) | python | def configure_alias(graph, ns, mappings):
convention = AliasConvention(graph)
convention.configure(ns, mappings) | [
"def",
"configure_alias",
"(",
"graph",
",",
"ns",
",",
"mappings",
")",
":",
"convention",
"=",
"AliasConvention",
"(",
"graph",
")",
"convention",
".",
"configure",
"(",
"ns",
",",
"mappings",
")"
] | Register Alias endpoints for a resource object. | [
"Register",
"Alias",
"endpoints",
"for",
"a",
"resource",
"object",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/alias.py#L54-L60 |
27,758 | globality-corp/microcosm-flask | microcosm_flask/conventions/alias.py | AliasConvention.configure_alias | def configure_alias(self, ns, definition):
"""
Register an alias endpoint which will redirect to a resource's retrieve endpoint.
Note that the retrieve endpoint MUST be registered prior to the alias endpoint.
The definition's func should be a retrieve function, which must:
- accept kwargs for path data
- return a resource
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.alias_path, Operation.Alias, ns)
@qs(definition.request_schema)
@wraps(definition.func)
def retrieve(**path_data):
# request_schema is optional for Alias
request_data = (
load_query_string_data(definition.request_schema)
if definition.request_schema
else dict()
)
resource = definition.func(**merge_data(path_data, request_data))
kwargs = dict()
identifier = "{}_id".format(name_for(ns.subject))
kwargs[identifier] = resource.id
url = ns.url_for(Operation.Retrieve, **kwargs)
return redirect(url)
retrieve.__doc__ = "Alias a {} by name".format(ns.subject_name) | python | def configure_alias(self, ns, definition):
@self.add_route(ns.alias_path, Operation.Alias, ns)
@qs(definition.request_schema)
@wraps(definition.func)
def retrieve(**path_data):
# request_schema is optional for Alias
request_data = (
load_query_string_data(definition.request_schema)
if definition.request_schema
else dict()
)
resource = definition.func(**merge_data(path_data, request_data))
kwargs = dict()
identifier = "{}_id".format(name_for(ns.subject))
kwargs[identifier] = resource.id
url = ns.url_for(Operation.Retrieve, **kwargs)
return redirect(url)
retrieve.__doc__ = "Alias a {} by name".format(ns.subject_name) | [
"def",
"configure_alias",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"alias_path",
",",
"Operation",
".",
"Alias",
",",
"ns",
")",
"@",
"qs",
"(",
"definition",
".",
"request_schema",
")",
"@",
... | Register an alias endpoint which will redirect to a resource's retrieve endpoint.
Note that the retrieve endpoint MUST be registered prior to the alias endpoint.
The definition's func should be a retrieve function, which must:
- accept kwargs for path data
- return a resource
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"an",
"alias",
"endpoint",
"which",
"will",
"redirect",
"to",
"a",
"resource",
"s",
"retrieve",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/alias.py#L18-L51 |
27,759 | globality-corp/microcosm-flask | microcosm_flask/conventions/encoding.py | encode_id_header | def encode_id_header(resource):
"""
Generate a header for a newly created resource.
Assume `id` attribute convention.
"""
if not hasattr(resource, "id"):
return {}
return {
"X-{}-Id".format(
camelize(name_for(resource))
): str(resource.id),
} | python | def encode_id_header(resource):
if not hasattr(resource, "id"):
return {}
return {
"X-{}-Id".format(
camelize(name_for(resource))
): str(resource.id),
} | [
"def",
"encode_id_header",
"(",
"resource",
")",
":",
"if",
"not",
"hasattr",
"(",
"resource",
",",
"\"id\"",
")",
":",
"return",
"{",
"}",
"return",
"{",
"\"X-{}-Id\"",
".",
"format",
"(",
"camelize",
"(",
"name_for",
"(",
"resource",
")",
")",
")",
"... | Generate a header for a newly created resource.
Assume `id` attribute convention. | [
"Generate",
"a",
"header",
"for",
"a",
"newly",
"created",
"resource",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/encoding.py#L33-L47 |
27,760 | globality-corp/microcosm-flask | microcosm_flask/conventions/encoding.py | load_request_data | def load_request_data(request_schema, partial=False):
"""
Load request data as JSON using the given schema.
Forces JSON decoding even if the client not specify the `Content-Type` header properly.
This is friendlier to client and test software, even at the cost of not distinguishing
HTTP 400 and 415 errors.
"""
try:
json_data = request.get_json(force=True) or {}
except Exception:
# if `simplpejson` is installed, simplejson.scanner.JSONDecodeError will be raised
# on malformed JSON, where as built-in `json` returns None
json_data = {}
request_data = request_schema.load(json_data, partial=partial)
if request_data.errors:
# pass the validation errors back in the context
raise with_context(
UnprocessableEntity("Validation error"), [{
"message": "Could not validate field: {}".format(field),
"field": field,
"reasons": reasons
} for field, reasons in request_data.errors.items()],
)
return request_data.data | python | def load_request_data(request_schema, partial=False):
try:
json_data = request.get_json(force=True) or {}
except Exception:
# if `simplpejson` is installed, simplejson.scanner.JSONDecodeError will be raised
# on malformed JSON, where as built-in `json` returns None
json_data = {}
request_data = request_schema.load(json_data, partial=partial)
if request_data.errors:
# pass the validation errors back in the context
raise with_context(
UnprocessableEntity("Validation error"), [{
"message": "Could not validate field: {}".format(field),
"field": field,
"reasons": reasons
} for field, reasons in request_data.errors.items()],
)
return request_data.data | [
"def",
"load_request_data",
"(",
"request_schema",
",",
"partial",
"=",
"False",
")",
":",
"try",
":",
"json_data",
"=",
"request",
".",
"get_json",
"(",
"force",
"=",
"True",
")",
"or",
"{",
"}",
"except",
"Exception",
":",
"# if `simplpejson` is installed, s... | Load request data as JSON using the given schema.
Forces JSON decoding even if the client not specify the `Content-Type` header properly.
This is friendlier to client and test software, even at the cost of not distinguishing
HTTP 400 and 415 errors. | [
"Load",
"request",
"data",
"as",
"JSON",
"using",
"the",
"given",
"schema",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/encoding.py#L58-L84 |
27,761 | globality-corp/microcosm-flask | microcosm_flask/conventions/encoding.py | load_query_string_data | def load_query_string_data(request_schema, query_string_data=None):
"""
Load query string data using the given schema.
Schemas are assumed to be compatible with the `PageSchema`.
"""
if query_string_data is None:
query_string_data = request.args
request_data = request_schema.load(query_string_data)
if request_data.errors:
# pass the validation errors back in the context
raise with_context(UnprocessableEntity("Validation error"), dict(errors=request_data.errors))
return request_data.data | python | def load_query_string_data(request_schema, query_string_data=None):
if query_string_data is None:
query_string_data = request.args
request_data = request_schema.load(query_string_data)
if request_data.errors:
# pass the validation errors back in the context
raise with_context(UnprocessableEntity("Validation error"), dict(errors=request_data.errors))
return request_data.data | [
"def",
"load_query_string_data",
"(",
"request_schema",
",",
"query_string_data",
"=",
"None",
")",
":",
"if",
"query_string_data",
"is",
"None",
":",
"query_string_data",
"=",
"request",
".",
"args",
"request_data",
"=",
"request_schema",
".",
"load",
"(",
"query... | Load query string data using the given schema.
Schemas are assumed to be compatible with the `PageSchema`. | [
"Load",
"query",
"string",
"data",
"using",
"the",
"given",
"schema",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/encoding.py#L87-L101 |
27,762 | globality-corp/microcosm-flask | microcosm_flask/conventions/encoding.py | dump_response_data | def dump_response_data(response_schema,
response_data,
status_code=200,
headers=None,
response_format=None):
"""
Dumps response data as JSON using the given schema.
Forces JSON encoding even if the client did not specify the `Accept` header properly.
This is friendlier to client and test software, even at the cost of not distinguishing
HTTP 400 and 406 errors.
"""
if response_schema:
response_data = response_schema.dump(response_data).data
return make_response(response_data, response_schema, response_format, status_code, headers) | python | def dump_response_data(response_schema,
response_data,
status_code=200,
headers=None,
response_format=None):
if response_schema:
response_data = response_schema.dump(response_data).data
return make_response(response_data, response_schema, response_format, status_code, headers) | [
"def",
"dump_response_data",
"(",
"response_schema",
",",
"response_data",
",",
"status_code",
"=",
"200",
",",
"headers",
"=",
"None",
",",
"response_format",
"=",
"None",
")",
":",
"if",
"response_schema",
":",
"response_data",
"=",
"response_schema",
".",
"du... | Dumps response data as JSON using the given schema.
Forces JSON encoding even if the client did not specify the `Accept` header properly.
This is friendlier to client and test software, even at the cost of not distinguishing
HTTP 400 and 406 errors. | [
"Dumps",
"response",
"data",
"as",
"JSON",
"using",
"the",
"given",
"schema",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/encoding.py#L116-L133 |
27,763 | globality-corp/microcosm-flask | microcosm_flask/conventions/encoding.py | merge_data | def merge_data(path_data, request_data):
"""
Merge data from the URI path and the request.
Path data wins.
"""
merged = request_data.copy() if request_data else {}
merged.update(path_data or {})
return merged | python | def merge_data(path_data, request_data):
merged = request_data.copy() if request_data else {}
merged.update(path_data or {})
return merged | [
"def",
"merge_data",
"(",
"path_data",
",",
"request_data",
")",
":",
"merged",
"=",
"request_data",
".",
"copy",
"(",
")",
"if",
"request_data",
"else",
"{",
"}",
"merged",
".",
"update",
"(",
"path_data",
"or",
"{",
"}",
")",
"return",
"merged"
] | Merge data from the URI path and the request.
Path data wins. | [
"Merge",
"data",
"from",
"the",
"URI",
"path",
"and",
"the",
"request",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/encoding.py#L157-L166 |
27,764 | globality-corp/microcosm-flask | microcosm_flask/conventions/encoding.py | find_response_format | def find_response_format(allowed_response_formats):
"""
Basic content negotiation logic.
If the 'Accept' header doesn't exactly match a format we can handle, we return JSON
"""
# allowed formats default to [] before this
if not allowed_response_formats:
allowed_response_formats = [ResponseFormats.JSON]
content_type = request.headers.get("Accept")
if content_type is None:
# Nothing specified, default to endpoint definition
if allowed_response_formats:
return allowed_response_formats[0]
# Finally, default to JSON
return ResponseFormats.JSON
for response_format in ResponseFormats.prioritized():
if response_format not in allowed_response_formats:
continue
if response_format.matches(content_type):
return response_format
# fallback for previous behavior
return ResponseFormats.JSON | python | def find_response_format(allowed_response_formats):
# allowed formats default to [] before this
if not allowed_response_formats:
allowed_response_formats = [ResponseFormats.JSON]
content_type = request.headers.get("Accept")
if content_type is None:
# Nothing specified, default to endpoint definition
if allowed_response_formats:
return allowed_response_formats[0]
# Finally, default to JSON
return ResponseFormats.JSON
for response_format in ResponseFormats.prioritized():
if response_format not in allowed_response_formats:
continue
if response_format.matches(content_type):
return response_format
# fallback for previous behavior
return ResponseFormats.JSON | [
"def",
"find_response_format",
"(",
"allowed_response_formats",
")",
":",
"# allowed formats default to [] before this",
"if",
"not",
"allowed_response_formats",
":",
"allowed_response_formats",
"=",
"[",
"ResponseFormats",
".",
"JSON",
"]",
"content_type",
"=",
"request",
... | Basic content negotiation logic.
If the 'Accept' header doesn't exactly match a format we can handle, we return JSON | [
"Basic",
"content",
"negotiation",
"logic",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/encoding.py#L184-L210 |
27,765 | globality-corp/microcosm-flask | microcosm_flask/swagger/definitions.py | build_swagger | def build_swagger(graph, ns, operations):
"""
Build out the top-level swagger definition.
"""
base_path = graph.build_route_path(ns.path, ns.prefix)
schema = swagger.Swagger(
swagger="2.0",
info=swagger.Info(
title=graph.metadata.name,
version=ns.version,
),
consumes=swagger.MediaTypeList([
swagger.MimeType("application/json"),
]),
produces=swagger.MediaTypeList([
swagger.MimeType("application/json"),
]),
basePath=base_path,
paths=swagger.Paths(),
definitions=swagger.Definitions(),
)
add_paths(schema.paths, base_path, operations)
add_definitions(schema.definitions, operations)
try:
schema.validate()
except Exception:
logger.exception("Swagger definition did not validate against swagger schema")
raise
return schema | python | def build_swagger(graph, ns, operations):
base_path = graph.build_route_path(ns.path, ns.prefix)
schema = swagger.Swagger(
swagger="2.0",
info=swagger.Info(
title=graph.metadata.name,
version=ns.version,
),
consumes=swagger.MediaTypeList([
swagger.MimeType("application/json"),
]),
produces=swagger.MediaTypeList([
swagger.MimeType("application/json"),
]),
basePath=base_path,
paths=swagger.Paths(),
definitions=swagger.Definitions(),
)
add_paths(schema.paths, base_path, operations)
add_definitions(schema.definitions, operations)
try:
schema.validate()
except Exception:
logger.exception("Swagger definition did not validate against swagger schema")
raise
return schema | [
"def",
"build_swagger",
"(",
"graph",
",",
"ns",
",",
"operations",
")",
":",
"base_path",
"=",
"graph",
".",
"build_route_path",
"(",
"ns",
".",
"path",
",",
"ns",
".",
"prefix",
")",
"schema",
"=",
"swagger",
".",
"Swagger",
"(",
"swagger",
"=",
"\"2... | Build out the top-level swagger definition. | [
"Build",
"out",
"the",
"top",
"-",
"level",
"swagger",
"definition",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L40-L70 |
27,766 | globality-corp/microcosm-flask | microcosm_flask/swagger/definitions.py | add_paths | def add_paths(paths, base_path, operations):
"""
Add paths to swagger.
"""
for operation, ns, rule, func in operations:
path = build_path(operation, ns)
if not path.startswith(base_path):
continue
method = operation.value.method.lower()
# If there is no version number or prefix, we'd expect the base path to be ""
# However, OpenAPI requires the minimal base path to be "/"
# This means we need branching logic for that special case
suffix_start = 0 if len(base_path) == 1 else len(base_path)
paths.setdefault(
path[suffix_start:],
swagger.PathItem(),
)[method] = build_operation(operation, ns, rule, func) | python | def add_paths(paths, base_path, operations):
for operation, ns, rule, func in operations:
path = build_path(operation, ns)
if not path.startswith(base_path):
continue
method = operation.value.method.lower()
# If there is no version number or prefix, we'd expect the base path to be ""
# However, OpenAPI requires the minimal base path to be "/"
# This means we need branching logic for that special case
suffix_start = 0 if len(base_path) == 1 else len(base_path)
paths.setdefault(
path[suffix_start:],
swagger.PathItem(),
)[method] = build_operation(operation, ns, rule, func) | [
"def",
"add_paths",
"(",
"paths",
",",
"base_path",
",",
"operations",
")",
":",
"for",
"operation",
",",
"ns",
",",
"rule",
",",
"func",
"in",
"operations",
":",
"path",
"=",
"build_path",
"(",
"operation",
",",
"ns",
")",
"if",
"not",
"path",
".",
... | Add paths to swagger. | [
"Add",
"paths",
"to",
"swagger",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L73-L90 |
27,767 | globality-corp/microcosm-flask | microcosm_flask/swagger/definitions.py | add_definitions | def add_definitions(definitions, operations):
"""
Add definitions to swagger.
"""
for definition_schema in iter_definitions(definitions, operations):
if definition_schema is None:
continue
if isinstance(definition_schema, str):
continue
for name, schema in iter_schemas(definition_schema):
definitions.setdefault(name, swagger.Schema(schema)) | python | def add_definitions(definitions, operations):
for definition_schema in iter_definitions(definitions, operations):
if definition_schema is None:
continue
if isinstance(definition_schema, str):
continue
for name, schema in iter_schemas(definition_schema):
definitions.setdefault(name, swagger.Schema(schema)) | [
"def",
"add_definitions",
"(",
"definitions",
",",
"operations",
")",
":",
"for",
"definition_schema",
"in",
"iter_definitions",
"(",
"definitions",
",",
"operations",
")",
":",
"if",
"definition_schema",
"is",
"None",
":",
"continue",
"if",
"isinstance",
"(",
"... | Add definitions to swagger. | [
"Add",
"definitions",
"to",
"swagger",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L93-L105 |
27,768 | globality-corp/microcosm-flask | microcosm_flask/swagger/definitions.py | iter_definitions | def iter_definitions(definitions, operations):
"""
Generate definitions to be converted to swagger schema.
"""
# general error schema per errors.py
for error_schema_class in [ErrorSchema, ErrorContextSchema, SubErrorSchema]:
yield error_schema_class()
# add all request and response schemas
for operation, obj, rule, func in operations:
yield get_request_schema(func)
yield get_response_schema(func) | python | def iter_definitions(definitions, operations):
# general error schema per errors.py
for error_schema_class in [ErrorSchema, ErrorContextSchema, SubErrorSchema]:
yield error_schema_class()
# add all request and response schemas
for operation, obj, rule, func in operations:
yield get_request_schema(func)
yield get_response_schema(func) | [
"def",
"iter_definitions",
"(",
"definitions",
",",
"operations",
")",
":",
"# general error schema per errors.py",
"for",
"error_schema_class",
"in",
"[",
"ErrorSchema",
",",
"ErrorContextSchema",
",",
"SubErrorSchema",
"]",
":",
"yield",
"error_schema_class",
"(",
")"... | Generate definitions to be converted to swagger schema. | [
"Generate",
"definitions",
"to",
"be",
"converted",
"to",
"swagger",
"schema",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L108-L120 |
27,769 | globality-corp/microcosm-flask | microcosm_flask/swagger/definitions.py | build_path | def build_path(operation, ns):
"""
Build a path URI for an operation.
"""
try:
return ns.url_for(operation, _external=False)
except BuildError as error:
# we are missing some URI path parameters
uri_templates = {
argument: "{{{}}}".format(argument)
for argument in error.suggested.arguments
}
# flask will sometimes try to quote '{' and '}' characters
return unquote(ns.url_for(operation, _external=False, **uri_templates)) | python | def build_path(operation, ns):
try:
return ns.url_for(operation, _external=False)
except BuildError as error:
# we are missing some URI path parameters
uri_templates = {
argument: "{{{}}}".format(argument)
for argument in error.suggested.arguments
}
# flask will sometimes try to quote '{' and '}' characters
return unquote(ns.url_for(operation, _external=False, **uri_templates)) | [
"def",
"build_path",
"(",
"operation",
",",
"ns",
")",
":",
"try",
":",
"return",
"ns",
".",
"url_for",
"(",
"operation",
",",
"_external",
"=",
"False",
")",
"except",
"BuildError",
"as",
"error",
":",
"# we are missing some URI path parameters",
"uri_templates... | Build a path URI for an operation. | [
"Build",
"a",
"path",
"URI",
"for",
"an",
"operation",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L123-L137 |
27,770 | globality-corp/microcosm-flask | microcosm_flask/swagger/definitions.py | header_param | def header_param(name, required=False, param_type="string"):
"""
Build a header parameter definition.
"""
return swagger.HeaderParameterSubSchema(**{
"name": name,
"in": "header",
"required": required,
"type": param_type,
}) | python | def header_param(name, required=False, param_type="string"):
return swagger.HeaderParameterSubSchema(**{
"name": name,
"in": "header",
"required": required,
"type": param_type,
}) | [
"def",
"header_param",
"(",
"name",
",",
"required",
"=",
"False",
",",
"param_type",
"=",
"\"string\"",
")",
":",
"return",
"swagger",
".",
"HeaderParameterSubSchema",
"(",
"*",
"*",
"{",
"\"name\"",
":",
"name",
",",
"\"in\"",
":",
"\"header\"",
",",
"\"... | Build a header parameter definition. | [
"Build",
"a",
"header",
"parameter",
"definition",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L150-L160 |
27,771 | globality-corp/microcosm-flask | microcosm_flask/swagger/definitions.py | query_param | def query_param(name, field, required=False):
"""
Build a query parameter definition.
"""
parameter = build_parameter(field)
parameter["name"] = name
parameter["in"] = "query"
parameter["required"] = False
return swagger.QueryParameterSubSchema(**parameter) | python | def query_param(name, field, required=False):
parameter = build_parameter(field)
parameter["name"] = name
parameter["in"] = "query"
parameter["required"] = False
return swagger.QueryParameterSubSchema(**parameter) | [
"def",
"query_param",
"(",
"name",
",",
"field",
",",
"required",
"=",
"False",
")",
":",
"parameter",
"=",
"build_parameter",
"(",
"field",
")",
"parameter",
"[",
"\"name\"",
"]",
"=",
"name",
"parameter",
"[",
"\"in\"",
"]",
"=",
"\"query\"",
"parameter"... | Build a query parameter definition. | [
"Build",
"a",
"query",
"parameter",
"definition",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L163-L173 |
27,772 | globality-corp/microcosm-flask | microcosm_flask/swagger/definitions.py | path_param | def path_param(name, ns):
"""
Build a path parameter definition.
"""
if ns.identifier_type == "uuid":
param_type = "string"
param_format = "uuid"
else:
param_type = "string"
param_format = None
kwargs = {
"name": name,
"in": "path",
"required": True,
"type": param_type,
}
if param_format:
kwargs["format"] = param_format
return swagger.PathParameterSubSchema(**kwargs) | python | def path_param(name, ns):
if ns.identifier_type == "uuid":
param_type = "string"
param_format = "uuid"
else:
param_type = "string"
param_format = None
kwargs = {
"name": name,
"in": "path",
"required": True,
"type": param_type,
}
if param_format:
kwargs["format"] = param_format
return swagger.PathParameterSubSchema(**kwargs) | [
"def",
"path_param",
"(",
"name",
",",
"ns",
")",
":",
"if",
"ns",
".",
"identifier_type",
"==",
"\"uuid\"",
":",
"param_type",
"=",
"\"string\"",
"param_format",
"=",
"\"uuid\"",
"else",
":",
"param_type",
"=",
"\"string\"",
"param_format",
"=",
"None",
"kw... | Build a path parameter definition. | [
"Build",
"a",
"path",
"parameter",
"definition",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L176-L196 |
27,773 | globality-corp/microcosm-flask | microcosm_flask/swagger/definitions.py | build_operation | def build_operation(operation, ns, rule, func):
"""
Build an operation definition.
"""
swagger_operation = swagger.Operation(
operationId=operation_name(operation, ns),
parameters=swagger.ParametersList([
]),
responses=swagger.Responses(),
tags=[ns.subject_name],
)
# custom header parameter
swagger_operation.parameters.append(
header_param("X-Response-Skip-Null")
)
# path parameters
swagger_operation.parameters.extend([
path_param(argument, ns)
for argument in rule.arguments
])
# query string parameters
qs_schema = get_qs_schema(func)
if qs_schema:
swagger_operation.parameters.extend([
query_param(name, field)
for name, field in qs_schema.fields.items()
])
# body parameter
request_schema = get_request_schema(func)
if request_schema:
swagger_operation.parameters.append(
body_param(request_schema)
)
# sort parameters for predictable output
swagger_operation.parameters.sort(key=lambda parameter: parameter["name"])
add_responses(swagger_operation, operation, ns, func)
return swagger_operation | python | def build_operation(operation, ns, rule, func):
swagger_operation = swagger.Operation(
operationId=operation_name(operation, ns),
parameters=swagger.ParametersList([
]),
responses=swagger.Responses(),
tags=[ns.subject_name],
)
# custom header parameter
swagger_operation.parameters.append(
header_param("X-Response-Skip-Null")
)
# path parameters
swagger_operation.parameters.extend([
path_param(argument, ns)
for argument in rule.arguments
])
# query string parameters
qs_schema = get_qs_schema(func)
if qs_schema:
swagger_operation.parameters.extend([
query_param(name, field)
for name, field in qs_schema.fields.items()
])
# body parameter
request_schema = get_request_schema(func)
if request_schema:
swagger_operation.parameters.append(
body_param(request_schema)
)
# sort parameters for predictable output
swagger_operation.parameters.sort(key=lambda parameter: parameter["name"])
add_responses(swagger_operation, operation, ns, func)
return swagger_operation | [
"def",
"build_operation",
"(",
"operation",
",",
"ns",
",",
"rule",
",",
"func",
")",
":",
"swagger_operation",
"=",
"swagger",
".",
"Operation",
"(",
"operationId",
"=",
"operation_name",
"(",
"operation",
",",
"ns",
")",
",",
"parameters",
"=",
"swagger",
... | Build an operation definition. | [
"Build",
"an",
"operation",
"definition",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L199-L242 |
27,774 | globality-corp/microcosm-flask | microcosm_flask/swagger/definitions.py | add_responses | def add_responses(swagger_operation, operation, ns, func):
"""
Add responses to an operation.
"""
# default error
swagger_operation.responses["default"] = build_response(
description="An error occurred",
resource=type_name(name_for(ErrorSchema())),
)
if getattr(func, "__doc__", None):
description = func.__doc__.strip().splitlines()[0]
else:
description = "{} {}".format(operation.value.name, ns.subject_name)
if operation in (Operation.Upload, Operation.UploadFor):
swagger_operation.consumes = [
"multipart/form-data"
]
# resource request
request_resource = get_request_schema(func)
if isinstance(request_resource, str):
if not hasattr(swagger_operation, "consumes"):
swagger_operation.consumes = []
swagger_operation.consumes.append(request_resource)
# resources response
response_resource = get_response_schema(func)
if isinstance(response_resource, str):
if not hasattr(swagger_operation, "produces"):
swagger_operation.produces = []
swagger_operation.produces.append(response_resource)
elif not response_resource:
response_code = (
204
if operation.value.default_code == 200
else operation.value.default_code
)
swagger_operation.responses[str(response_code)] = build_response(
description=description,
)
else:
swagger_operation.responses[str(operation.value.default_code)] = build_response(
description=description,
resource=response_resource,
) | python | def add_responses(swagger_operation, operation, ns, func):
# default error
swagger_operation.responses["default"] = build_response(
description="An error occurred",
resource=type_name(name_for(ErrorSchema())),
)
if getattr(func, "__doc__", None):
description = func.__doc__.strip().splitlines()[0]
else:
description = "{} {}".format(operation.value.name, ns.subject_name)
if operation in (Operation.Upload, Operation.UploadFor):
swagger_operation.consumes = [
"multipart/form-data"
]
# resource request
request_resource = get_request_schema(func)
if isinstance(request_resource, str):
if not hasattr(swagger_operation, "consumes"):
swagger_operation.consumes = []
swagger_operation.consumes.append(request_resource)
# resources response
response_resource = get_response_schema(func)
if isinstance(response_resource, str):
if not hasattr(swagger_operation, "produces"):
swagger_operation.produces = []
swagger_operation.produces.append(response_resource)
elif not response_resource:
response_code = (
204
if operation.value.default_code == 200
else operation.value.default_code
)
swagger_operation.responses[str(response_code)] = build_response(
description=description,
)
else:
swagger_operation.responses[str(operation.value.default_code)] = build_response(
description=description,
resource=response_resource,
) | [
"def",
"add_responses",
"(",
"swagger_operation",
",",
"operation",
",",
"ns",
",",
"func",
")",
":",
"# default error",
"swagger_operation",
".",
"responses",
"[",
"\"default\"",
"]",
"=",
"build_response",
"(",
"description",
"=",
"\"An error occurred\"",
",",
"... | Add responses to an operation. | [
"Add",
"responses",
"to",
"an",
"operation",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L245-L292 |
27,775 | globality-corp/microcosm-flask | microcosm_flask/swagger/definitions.py | build_response | def build_response(description, resource=None):
"""
Build a response definition.
"""
response = swagger.Response(
description=description,
)
if resource is not None:
response.schema = swagger.JsonReference({
"$ref": "#/definitions/{}".format(type_name(name_for(resource))),
})
return response | python | def build_response(description, resource=None):
response = swagger.Response(
description=description,
)
if resource is not None:
response.schema = swagger.JsonReference({
"$ref": "#/definitions/{}".format(type_name(name_for(resource))),
})
return response | [
"def",
"build_response",
"(",
"description",
",",
"resource",
"=",
"None",
")",
":",
"response",
"=",
"swagger",
".",
"Response",
"(",
"description",
"=",
"description",
",",
")",
"if",
"resource",
"is",
"not",
"None",
":",
"response",
".",
"schema",
"=",
... | Build a response definition. | [
"Build",
"a",
"response",
"definition",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/definitions.py#L295-L307 |
27,776 | globality-corp/microcosm-flask | microcosm_flask/conventions/registry.py | iter_endpoints | def iter_endpoints(graph, match_func):
"""
Iterate through matching endpoints.
The `match_func` is expected to have a signature of:
def matches(operation, ns, rule):
return True
:returns: a generator over (`Operation`, `Namespace`, rule, func) tuples.
"""
for rule in graph.flask.url_map.iter_rules():
try:
operation, ns = Namespace.parse_endpoint(rule.endpoint, get_converter(rule))
except (IndexError, ValueError, InternalServerError):
# operation follows a different convention (e.g. "static")
continue
else:
# match_func gets access to rule to support path version filtering
if match_func(operation, ns, rule):
func = graph.flask.view_functions[rule.endpoint]
yield operation, ns, rule, func | python | def iter_endpoints(graph, match_func):
for rule in graph.flask.url_map.iter_rules():
try:
operation, ns = Namespace.parse_endpoint(rule.endpoint, get_converter(rule))
except (IndexError, ValueError, InternalServerError):
# operation follows a different convention (e.g. "static")
continue
else:
# match_func gets access to rule to support path version filtering
if match_func(operation, ns, rule):
func = graph.flask.view_functions[rule.endpoint]
yield operation, ns, rule, func | [
"def",
"iter_endpoints",
"(",
"graph",
",",
"match_func",
")",
":",
"for",
"rule",
"in",
"graph",
".",
"flask",
".",
"url_map",
".",
"iter_rules",
"(",
")",
":",
"try",
":",
"operation",
",",
"ns",
"=",
"Namespace",
".",
"parse_endpoint",
"(",
"rule",
... | Iterate through matching endpoints.
The `match_func` is expected to have a signature of:
def matches(operation, ns, rule):
return True
:returns: a generator over (`Operation`, `Namespace`, rule, func) tuples. | [
"Iterate",
"through",
"matching",
"endpoints",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/registry.py#L16-L38 |
27,777 | globality-corp/microcosm-flask | microcosm_flask/conventions/registry.py | get_converter | def get_converter(rule):
"""
Parse rule will extract the converter from the rule as a generator
We iterate through the parse_rule results to find the converter
parse_url returns the static rule part in the first iteration
parse_url returns the dynamic rule part in the second iteration if its dynamic
"""
for converter, _, _ in parse_rule(str(rule)):
if converter is not None:
return converter
return None | python | def get_converter(rule):
for converter, _, _ in parse_rule(str(rule)):
if converter is not None:
return converter
return None | [
"def",
"get_converter",
"(",
"rule",
")",
":",
"for",
"converter",
",",
"_",
",",
"_",
"in",
"parse_rule",
"(",
"str",
"(",
"rule",
")",
")",
":",
"if",
"converter",
"is",
"not",
"None",
":",
"return",
"converter",
"return",
"None"
] | Parse rule will extract the converter from the rule as a generator
We iterate through the parse_rule results to find the converter
parse_url returns the static rule part in the first iteration
parse_url returns the dynamic rule part in the second iteration if its dynamic | [
"Parse",
"rule",
"will",
"extract",
"the",
"converter",
"from",
"the",
"rule",
"as",
"a",
"generator"
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/registry.py#L41-L53 |
27,778 | globality-corp/microcosm-flask | microcosm_flask/conventions/registry.py | request | def request(schema):
"""
Decorate a function with a request schema.
"""
def wrapper(func):
setattr(func, REQUEST, schema)
return func
return wrapper | python | def request(schema):
def wrapper(func):
setattr(func, REQUEST, schema)
return func
return wrapper | [
"def",
"request",
"(",
"schema",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"setattr",
"(",
"func",
",",
"REQUEST",
",",
"schema",
")",
"return",
"func",
"return",
"wrapper"
] | Decorate a function with a request schema. | [
"Decorate",
"a",
"function",
"with",
"a",
"request",
"schema",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/registry.py#L56-L64 |
27,779 | globality-corp/microcosm-flask | microcosm_flask/conventions/registry.py | response | def response(schema):
"""
Decorate a function with a response schema.
"""
def wrapper(func):
setattr(func, RESPONSE, schema)
return func
return wrapper | python | def response(schema):
def wrapper(func):
setattr(func, RESPONSE, schema)
return func
return wrapper | [
"def",
"response",
"(",
"schema",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"setattr",
"(",
"func",
",",
"RESPONSE",
",",
"schema",
")",
"return",
"func",
"return",
"wrapper"
] | Decorate a function with a response schema. | [
"Decorate",
"a",
"function",
"with",
"a",
"response",
"schema",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/registry.py#L67-L75 |
27,780 | globality-corp/microcosm-flask | microcosm_flask/conventions/registry.py | qs | def qs(schema):
"""
Decorate a function with a query string schema.
"""
def wrapper(func):
setattr(func, QS, schema)
return func
return wrapper | python | def qs(schema):
def wrapper(func):
setattr(func, QS, schema)
return func
return wrapper | [
"def",
"qs",
"(",
"schema",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"setattr",
"(",
"func",
",",
"QS",
",",
"schema",
")",
"return",
"func",
"return",
"wrapper"
] | Decorate a function with a query string schema. | [
"Decorate",
"a",
"function",
"with",
"a",
"query",
"string",
"schema",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/registry.py#L78-L86 |
27,781 | globality-corp/microcosm-flask | microcosm_flask/audit.py | should_skip_logging | def should_skip_logging(func):
"""
Should we skip logging for this handler?
"""
disabled = strtobool(request.headers.get("x-request-nolog", "false"))
return disabled or getattr(func, SKIP_LOGGING, False) | python | def should_skip_logging(func):
disabled = strtobool(request.headers.get("x-request-nolog", "false"))
return disabled or getattr(func, SKIP_LOGGING, False) | [
"def",
"should_skip_logging",
"(",
"func",
")",
":",
"disabled",
"=",
"strtobool",
"(",
"request",
".",
"headers",
".",
"get",
"(",
"\"x-request-nolog\"",
",",
"\"false\"",
")",
")",
"return",
"disabled",
"or",
"getattr",
"(",
"func",
",",
"SKIP_LOGGING",
",... | Should we skip logging for this handler? | [
"Should",
"we",
"skip",
"logging",
"for",
"this",
"handler?"
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L59-L65 |
27,782 | globality-corp/microcosm-flask | microcosm_flask/audit.py | logging_levels | def logging_levels():
"""
Context manager to conditionally set logging levels.
Supports setting per-request debug logging using the `X-Request-Debug` header.
"""
enabled = strtobool(request.headers.get("x-request-debug", "false"))
level = None
try:
if enabled:
level = getLogger().getEffectiveLevel()
getLogger().setLevel(DEBUG)
yield
finally:
if enabled:
getLogger().setLevel(level) | python | def logging_levels():
enabled = strtobool(request.headers.get("x-request-debug", "false"))
level = None
try:
if enabled:
level = getLogger().getEffectiveLevel()
getLogger().setLevel(DEBUG)
yield
finally:
if enabled:
getLogger().setLevel(level) | [
"def",
"logging_levels",
"(",
")",
":",
"enabled",
"=",
"strtobool",
"(",
"request",
".",
"headers",
".",
"get",
"(",
"\"x-request-debug\"",
",",
"\"false\"",
")",
")",
"level",
"=",
"None",
"try",
":",
"if",
"enabled",
":",
"level",
"=",
"getLogger",
"(... | Context manager to conditionally set logging levels.
Supports setting per-request debug logging using the `X-Request-Debug` header. | [
"Context",
"manager",
"to",
"conditionally",
"set",
"logging",
"levels",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L69-L85 |
27,783 | globality-corp/microcosm-flask | microcosm_flask/audit.py | audit | def audit(func):
"""
Record a Flask route function in the audit log.
Generates a JSON record in the Flask log for every request.
"""
@wraps(func)
def wrapper(*args, **kwargs):
options = AuditOptions(
include_request_body=DEFAULT_INCLUDE_REQUEST_BODY,
include_response_body=DEFAULT_INCLUDE_RESPONSE_BODY,
include_path=True,
include_query_string=True,
)
with logging_levels():
return _audit_request(options, func, None, *args, **kwargs)
return wrapper | python | def audit(func):
@wraps(func)
def wrapper(*args, **kwargs):
options = AuditOptions(
include_request_body=DEFAULT_INCLUDE_REQUEST_BODY,
include_response_body=DEFAULT_INCLUDE_RESPONSE_BODY,
include_path=True,
include_query_string=True,
)
with logging_levels():
return _audit_request(options, func, None, *args, **kwargs)
return wrapper | [
"def",
"audit",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"AuditOptions",
"(",
"include_request_body",
"=",
"DEFAULT_INCLUDE_REQUEST_BODY",
",",
"include_re... | Record a Flask route function in the audit log.
Generates a JSON record in the Flask log for every request. | [
"Record",
"a",
"Flask",
"route",
"function",
"in",
"the",
"audit",
"log",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L88-L106 |
27,784 | globality-corp/microcosm-flask | microcosm_flask/audit.py | _audit_request | def _audit_request(options, func, request_context, *args, **kwargs): # noqa: C901
"""
Run a request function under audit.
"""
logger = getLogger("audit")
request_info = RequestInfo(options, func, request_context)
response = None
request_info.capture_request()
try:
# process the request
with elapsed_time(request_info.timing):
response = func(*args, **kwargs)
except Exception as error:
request_info.capture_error(error)
raise
else:
request_info.capture_response(response)
return response
finally:
if not should_skip_logging(func):
request_info.log(logger) | python | def _audit_request(options, func, request_context, *args, **kwargs): # noqa: C901
logger = getLogger("audit")
request_info = RequestInfo(options, func, request_context)
response = None
request_info.capture_request()
try:
# process the request
with elapsed_time(request_info.timing):
response = func(*args, **kwargs)
except Exception as error:
request_info.capture_error(error)
raise
else:
request_info.capture_response(response)
return response
finally:
if not should_skip_logging(func):
request_info.log(logger) | [
"def",
"_audit_request",
"(",
"options",
",",
"func",
",",
"request_context",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: C901",
"logger",
"=",
"getLogger",
"(",
"\"audit\"",
")",
"request_info",
"=",
"RequestInfo",
"(",
"options",
",",
"... | Run a request function under audit. | [
"Run",
"a",
"request",
"function",
"under",
"audit",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L309-L332 |
27,785 | globality-corp/microcosm-flask | microcosm_flask/audit.py | parse_response | def parse_response(response):
"""
Parse a Flask response into a body, a status code, and headers
The returned value from a Flask view could be:
* a tuple of (response, status) or (response, status, headers)
* a Response object
* a string
"""
if isinstance(response, tuple):
if len(response) > 2:
return response[0], response[1], response[2]
elif len(response) > 1:
return response[0], response[1], {}
try:
return response.data, response.status_code, response.headers
except AttributeError:
return response, 200, {} | python | def parse_response(response):
if isinstance(response, tuple):
if len(response) > 2:
return response[0], response[1], response[2]
elif len(response) > 1:
return response[0], response[1], {}
try:
return response.data, response.status_code, response.headers
except AttributeError:
return response, 200, {} | [
"def",
"parse_response",
"(",
"response",
")",
":",
"if",
"isinstance",
"(",
"response",
",",
"tuple",
")",
":",
"if",
"len",
"(",
"response",
")",
">",
"2",
":",
"return",
"response",
"[",
"0",
"]",
",",
"response",
"[",
"1",
"]",
",",
"response",
... | Parse a Flask response into a body, a status code, and headers
The returned value from a Flask view could be:
* a tuple of (response, status) or (response, status, headers)
* a Response object
* a string | [
"Parse",
"a",
"Flask",
"response",
"into",
"a",
"body",
"a",
"status",
"code",
"and",
"headers"
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L335-L352 |
27,786 | globality-corp/microcosm-flask | microcosm_flask/audit.py | configure_audit_decorator | def configure_audit_decorator(graph):
"""
Configure the audit decorator.
Example Usage:
@graph.audit
def login(username, password):
...
"""
include_request_body = int(graph.config.audit.include_request_body)
include_response_body = int(graph.config.audit.include_response_body)
include_path = strtobool(graph.config.audit.include_path)
include_query_string = strtobool(graph.config.audit.include_query_string)
def _audit(func):
@wraps(func)
def wrapper(*args, **kwargs):
options = AuditOptions(
include_request_body=include_request_body,
include_response_body=include_response_body,
include_path=include_path,
include_query_string=include_query_string,
)
return _audit_request(options, func, graph.request_context, *args, **kwargs)
return wrapper
return _audit | python | def configure_audit_decorator(graph):
include_request_body = int(graph.config.audit.include_request_body)
include_response_body = int(graph.config.audit.include_response_body)
include_path = strtobool(graph.config.audit.include_path)
include_query_string = strtobool(graph.config.audit.include_query_string)
def _audit(func):
@wraps(func)
def wrapper(*args, **kwargs):
options = AuditOptions(
include_request_body=include_request_body,
include_response_body=include_response_body,
include_path=include_path,
include_query_string=include_query_string,
)
return _audit_request(options, func, graph.request_context, *args, **kwargs)
return wrapper
return _audit | [
"def",
"configure_audit_decorator",
"(",
"graph",
")",
":",
"include_request_body",
"=",
"int",
"(",
"graph",
".",
"config",
".",
"audit",
".",
"include_request_body",
")",
"include_response_body",
"=",
"int",
"(",
"graph",
".",
"config",
".",
"audit",
".",
"i... | Configure the audit decorator.
Example Usage:
@graph.audit
def login(username, password):
... | [
"Configure",
"the",
"audit",
"decorator",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L361-L387 |
27,787 | globality-corp/microcosm-flask | microcosm_flask/routing.py | configure_route_decorator | def configure_route_decorator(graph):
"""
Configure a flask route decorator that operates on `Operation` and `Namespace` objects.
By default, enables CORS support, assuming that service APIs are not exposed
directly to browsers except when using API browsing tools.
Usage:
@graph.route(ns.collection_path, Operation.Search, ns)
def search_foo():
pass
"""
enable_audit = graph.config.route.enable_audit
enable_basic_auth = graph.config.route.enable_basic_auth
enable_context_logger = graph.config.route.enable_context_logger
enable_cors = graph.config.route.enable_cors
# routes depends on converters
graph.use(*graph.config.route.converters)
def route(path, operation, ns):
"""
:param path: a URI path, possibly derived from a property of the `ns`
:param operation: an `Operation` enum value
:param ns: a `Namespace` instance
"""
def decorator(func):
endpoint = ns.endpoint_for(operation)
endpoint_path = graph.build_route_path(path, ns.prefix)
if enable_cors:
func = cross_origin(supports_credentials=True)(func)
if enable_basic_auth or ns.enable_basic_auth:
func = graph.basic_auth.required(func)
if enable_context_logger and ns.controller is not None:
func = context_logger(
graph.request_context,
func,
parent=ns.controller,
)
# set the opaque component data_func to look at the flask request context
func = graph.opaque.initialize(graph.request_context)(func)
if graph.route_metrics.enabled:
func = graph.route_metrics(endpoint)(func)
# keep audit decoration last (before registering the route) so that
# errors raised by other decorators are captured in the audit trail
if enable_audit:
func = graph.audit(func)
graph.app.route(
endpoint_path,
endpoint=endpoint,
methods=[operation.value.method],
)(func)
return func
return decorator
return route | python | def configure_route_decorator(graph):
enable_audit = graph.config.route.enable_audit
enable_basic_auth = graph.config.route.enable_basic_auth
enable_context_logger = graph.config.route.enable_context_logger
enable_cors = graph.config.route.enable_cors
# routes depends on converters
graph.use(*graph.config.route.converters)
def route(path, operation, ns):
"""
:param path: a URI path, possibly derived from a property of the `ns`
:param operation: an `Operation` enum value
:param ns: a `Namespace` instance
"""
def decorator(func):
endpoint = ns.endpoint_for(operation)
endpoint_path = graph.build_route_path(path, ns.prefix)
if enable_cors:
func = cross_origin(supports_credentials=True)(func)
if enable_basic_auth or ns.enable_basic_auth:
func = graph.basic_auth.required(func)
if enable_context_logger and ns.controller is not None:
func = context_logger(
graph.request_context,
func,
parent=ns.controller,
)
# set the opaque component data_func to look at the flask request context
func = graph.opaque.initialize(graph.request_context)(func)
if graph.route_metrics.enabled:
func = graph.route_metrics(endpoint)(func)
# keep audit decoration last (before registering the route) so that
# errors raised by other decorators are captured in the audit trail
if enable_audit:
func = graph.audit(func)
graph.app.route(
endpoint_path,
endpoint=endpoint,
methods=[operation.value.method],
)(func)
return func
return decorator
return route | [
"def",
"configure_route_decorator",
"(",
"graph",
")",
":",
"enable_audit",
"=",
"graph",
".",
"config",
".",
"route",
".",
"enable_audit",
"enable_basic_auth",
"=",
"graph",
".",
"config",
".",
"route",
".",
"enable_basic_auth",
"enable_context_logger",
"=",
"gra... | Configure a flask route decorator that operates on `Operation` and `Namespace` objects.
By default, enables CORS support, assuming that service APIs are not exposed
directly to browsers except when using API browsing tools.
Usage:
@graph.route(ns.collection_path, Operation.Search, ns)
def search_foo():
pass | [
"Configure",
"a",
"flask",
"route",
"decorator",
"that",
"operates",
"on",
"Operation",
"and",
"Namespace",
"objects",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/routing.py#L22-L86 |
27,788 | globality-corp/microcosm-flask | microcosm_flask/errors.py | extract_status_code | def extract_status_code(error):
"""
Extract an error code from a message.
"""
try:
return int(error.code)
except (AttributeError, TypeError, ValueError):
try:
return int(error.status_code)
except (AttributeError, TypeError, ValueError):
try:
return int(error.errno)
except (AttributeError, TypeError, ValueError):
return 500 | python | def extract_status_code(error):
try:
return int(error.code)
except (AttributeError, TypeError, ValueError):
try:
return int(error.status_code)
except (AttributeError, TypeError, ValueError):
try:
return int(error.errno)
except (AttributeError, TypeError, ValueError):
return 500 | [
"def",
"extract_status_code",
"(",
"error",
")",
":",
"try",
":",
"return",
"int",
"(",
"error",
".",
"code",
")",
"except",
"(",
"AttributeError",
",",
"TypeError",
",",
"ValueError",
")",
":",
"try",
":",
"return",
"int",
"(",
"error",
".",
"status_cod... | Extract an error code from a message. | [
"Extract",
"an",
"error",
"code",
"from",
"a",
"message",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/errors.py#L42-L56 |
27,789 | globality-corp/microcosm-flask | microcosm_flask/errors.py | extract_error_message | def extract_error_message(error):
"""
Extract a useful message from an error.
Prefer the description attribute, then the message attribute, then
the errors string conversion. In each case, fall back to the error class's
name in the event that the attribute value was set to a uselessly empty string.
"""
try:
return error.description or error.__class__.__name__
except AttributeError:
try:
return str(error.message) or error.__class__.__name__
except AttributeError:
return str(error) or error.__class__.__name__ | python | def extract_error_message(error):
try:
return error.description or error.__class__.__name__
except AttributeError:
try:
return str(error.message) or error.__class__.__name__
except AttributeError:
return str(error) or error.__class__.__name__ | [
"def",
"extract_error_message",
"(",
"error",
")",
":",
"try",
":",
"return",
"error",
".",
"description",
"or",
"error",
".",
"__class__",
".",
"__name__",
"except",
"AttributeError",
":",
"try",
":",
"return",
"str",
"(",
"error",
".",
"message",
")",
"o... | Extract a useful message from an error.
Prefer the description attribute, then the message attribute, then
the errors string conversion. In each case, fall back to the error class's
name in the event that the attribute value was set to a uselessly empty string. | [
"Extract",
"a",
"useful",
"message",
"from",
"an",
"error",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/errors.py#L59-L74 |
27,790 | globality-corp/microcosm-flask | microcosm_flask/errors.py | make_json_error | def make_json_error(error):
"""
Handle errors by logging and
"""
message = extract_error_message(error)
status_code = extract_status_code(error)
context = extract_context(error)
retryable = extract_retryable(error)
headers = extract_headers(error)
# Flask will not log user exception (fortunately), but will log an error
# for exceptions that escape out of the application entirely (e.g. if the
# error handler raises an error)
error_logger.debug("Handling {} error: {}".format(
status_code,
message,
))
# Serialize into JSON response
response_data = {
"code": status_code,
"context": context,
"message": message,
"retryable": retryable,
}
# Don't pass in the error schema because it will suppress any extra fields
return dump_response_data(None, response_data, status_code, headers) | python | def make_json_error(error):
message = extract_error_message(error)
status_code = extract_status_code(error)
context = extract_context(error)
retryable = extract_retryable(error)
headers = extract_headers(error)
# Flask will not log user exception (fortunately), but will log an error
# for exceptions that escape out of the application entirely (e.g. if the
# error handler raises an error)
error_logger.debug("Handling {} error: {}".format(
status_code,
message,
))
# Serialize into JSON response
response_data = {
"code": status_code,
"context": context,
"message": message,
"retryable": retryable,
}
# Don't pass in the error schema because it will suppress any extra fields
return dump_response_data(None, response_data, status_code, headers) | [
"def",
"make_json_error",
"(",
"error",
")",
":",
"message",
"=",
"extract_error_message",
"(",
"error",
")",
"status_code",
"=",
"extract_status_code",
"(",
"error",
")",
"context",
"=",
"extract_context",
"(",
"error",
")",
"retryable",
"=",
"extract_retryable",... | Handle errors by logging and | [
"Handle",
"errors",
"by",
"logging",
"and"
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/errors.py#L121-L147 |
27,791 | globality-corp/microcosm-flask | microcosm_flask/errors.py | configure_error_handlers | def configure_error_handlers(graph):
"""
Register error handlers.
"""
# override all of the werkzeug HTTPExceptions
for code in default_exceptions.keys():
graph.flask.register_error_handler(code, make_json_error)
# register catch all for user exceptions
graph.flask.register_error_handler(Exception, make_json_error) | python | def configure_error_handlers(graph):
# override all of the werkzeug HTTPExceptions
for code in default_exceptions.keys():
graph.flask.register_error_handler(code, make_json_error)
# register catch all for user exceptions
graph.flask.register_error_handler(Exception, make_json_error) | [
"def",
"configure_error_handlers",
"(",
"graph",
")",
":",
"# override all of the werkzeug HTTPExceptions",
"for",
"code",
"in",
"default_exceptions",
".",
"keys",
"(",
")",
":",
"graph",
".",
"flask",
".",
"register_error_handler",
"(",
"code",
",",
"make_json_error"... | Register error handlers. | [
"Register",
"error",
"handlers",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/errors.py#L150-L160 |
27,792 | GetmeUK/MongoFrames | mongoframes/frames.py | _BaseFrame.to_json_type | def to_json_type(self):
"""
Return a dictionary for the document with values converted to JSON safe
types.
"""
document_dict = self._json_safe(self._document)
self._remove_keys(document_dict, self._private_fields)
return document_dict | python | def to_json_type(self):
document_dict = self._json_safe(self._document)
self._remove_keys(document_dict, self._private_fields)
return document_dict | [
"def",
"to_json_type",
"(",
"self",
")",
":",
"document_dict",
"=",
"self",
".",
"_json_safe",
"(",
"self",
".",
"_document",
")",
"self",
".",
"_remove_keys",
"(",
"document_dict",
",",
"self",
".",
"_private_fields",
")",
"return",
"document_dict"
] | Return a dictionary for the document with values converted to JSON safe
types. | [
"Return",
"a",
"dictionary",
"for",
"the",
"document",
"with",
"values",
"converted",
"to",
"JSON",
"safe",
"types",
"."
] | 7d2bd792235dfa77a9deecab5366f5f73480823d | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L56-L63 |
27,793 | GetmeUK/MongoFrames | mongoframes/frames.py | _BaseFrame._json_safe | def _json_safe(cls, value):
"""Return a JSON safe value"""
# Date
if type(value) == date:
return str(value)
# Datetime
elif type(value) == datetime:
return value.strftime('%Y-%m-%d %H:%M:%S')
# Object Id
elif isinstance(value, ObjectId):
return str(value)
# Frame
elif isinstance(value, _BaseFrame):
return value.to_json_type()
# Lists
elif isinstance(value, (list, tuple)):
return [cls._json_safe(v) for v in value]
# Dictionaries
elif isinstance(value, dict):
return {k:cls._json_safe(v) for k, v in value.items()}
return value | python | def _json_safe(cls, value):
# Date
if type(value) == date:
return str(value)
# Datetime
elif type(value) == datetime:
return value.strftime('%Y-%m-%d %H:%M:%S')
# Object Id
elif isinstance(value, ObjectId):
return str(value)
# Frame
elif isinstance(value, _BaseFrame):
return value.to_json_type()
# Lists
elif isinstance(value, (list, tuple)):
return [cls._json_safe(v) for v in value]
# Dictionaries
elif isinstance(value, dict):
return {k:cls._json_safe(v) for k, v in value.items()}
return value | [
"def",
"_json_safe",
"(",
"cls",
",",
"value",
")",
":",
"# Date",
"if",
"type",
"(",
"value",
")",
"==",
"date",
":",
"return",
"str",
"(",
"value",
")",
"# Datetime",
"elif",
"type",
"(",
"value",
")",
"==",
"datetime",
":",
"return",
"value",
".",... | Return a JSON safe value | [
"Return",
"a",
"JSON",
"safe",
"value"
] | 7d2bd792235dfa77a9deecab5366f5f73480823d | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L66-L92 |
27,794 | GetmeUK/MongoFrames | mongoframes/frames.py | _BaseFrame._path_to_keys | def _path_to_keys(cls, path):
"""Return a list of keys for a given path"""
# Paths are cached for performance
keys = _BaseFrame._path_to_keys_cache.get(path)
if keys is None:
keys = _BaseFrame._path_to_keys_cache[path] = path.split('.')
return keys | python | def _path_to_keys(cls, path):
# Paths are cached for performance
keys = _BaseFrame._path_to_keys_cache.get(path)
if keys is None:
keys = _BaseFrame._path_to_keys_cache[path] = path.split('.')
return keys | [
"def",
"_path_to_keys",
"(",
"cls",
",",
"path",
")",
":",
"# Paths are cached for performance",
"keys",
"=",
"_BaseFrame",
".",
"_path_to_keys_cache",
".",
"get",
"(",
"path",
")",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"_BaseFrame",
".",
"_path_to_key... | Return a list of keys for a given path | [
"Return",
"a",
"list",
"of",
"keys",
"for",
"a",
"given",
"path"
] | 7d2bd792235dfa77a9deecab5366f5f73480823d | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L95-L103 |
27,795 | GetmeUK/MongoFrames | mongoframes/frames.py | _BaseFrame._path_to_value | def _path_to_value(cls, path, parent_dict):
"""Return a value from a dictionary at the given path"""
keys = cls._path_to_keys(path)
# Traverse to the tip of the path
child_dict = parent_dict
for key in keys[:-1]:
child_dict = child_dict.get(key)
if child_dict is None:
return
return child_dict.get(keys[-1]) | python | def _path_to_value(cls, path, parent_dict):
keys = cls._path_to_keys(path)
# Traverse to the tip of the path
child_dict = parent_dict
for key in keys[:-1]:
child_dict = child_dict.get(key)
if child_dict is None:
return
return child_dict.get(keys[-1]) | [
"def",
"_path_to_value",
"(",
"cls",
",",
"path",
",",
"parent_dict",
")",
":",
"keys",
"=",
"cls",
".",
"_path_to_keys",
"(",
"path",
")",
"# Traverse to the tip of the path",
"child_dict",
"=",
"parent_dict",
"for",
"key",
"in",
"keys",
"[",
":",
"-",
"1",... | Return a value from a dictionary at the given path | [
"Return",
"a",
"value",
"from",
"a",
"dictionary",
"at",
"the",
"given",
"path"
] | 7d2bd792235dfa77a9deecab5366f5f73480823d | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L106-L117 |
27,796 | GetmeUK/MongoFrames | mongoframes/frames.py | _BaseFrame._remove_keys | def _remove_keys(cls, parent_dict, paths):
"""
Remove a list of keys from a dictionary.
Keys are specified as a series of `.` separated paths for keys in child
dictionaries, e.g 'parent_key.child_key.grandchild_key'.
"""
for path in paths:
keys = cls._path_to_keys(path)
# Traverse to the tip of the path
child_dict = parent_dict
for key in keys[:-1]:
child_dict = child_dict.get(key)
if child_dict is None:
break
if child_dict is None:
continue
# Remove the key
if keys[-1] in child_dict:
child_dict.pop(keys[-1]) | python | def _remove_keys(cls, parent_dict, paths):
for path in paths:
keys = cls._path_to_keys(path)
# Traverse to the tip of the path
child_dict = parent_dict
for key in keys[:-1]:
child_dict = child_dict.get(key)
if child_dict is None:
break
if child_dict is None:
continue
# Remove the key
if keys[-1] in child_dict:
child_dict.pop(keys[-1]) | [
"def",
"_remove_keys",
"(",
"cls",
",",
"parent_dict",
",",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"keys",
"=",
"cls",
".",
"_path_to_keys",
"(",
"path",
")",
"# Traverse to the tip of the path",
"child_dict",
"=",
"parent_dict",
"for",
"key",
... | Remove a list of keys from a dictionary.
Keys are specified as a series of `.` separated paths for keys in child
dictionaries, e.g 'parent_key.child_key.grandchild_key'. | [
"Remove",
"a",
"list",
"of",
"keys",
"from",
"a",
"dictionary",
"."
] | 7d2bd792235dfa77a9deecab5366f5f73480823d | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L120-L144 |
27,797 | GetmeUK/MongoFrames | mongoframes/frames.py | Frame.insert | def insert(self):
"""Insert this document"""
from mongoframes.queries import to_refs
# Send insert signal
signal('insert').send(self.__class__, frames=[self])
# Prepare the document to be inserted
document = to_refs(self._document)
# Insert the document and update the Id
self._id = self.get_collection().insert_one(document).inserted_id
# Send inserted signal
signal('inserted').send(self.__class__, frames=[self]) | python | def insert(self):
from mongoframes.queries import to_refs
# Send insert signal
signal('insert').send(self.__class__, frames=[self])
# Prepare the document to be inserted
document = to_refs(self._document)
# Insert the document and update the Id
self._id = self.get_collection().insert_one(document).inserted_id
# Send inserted signal
signal('inserted').send(self.__class__, frames=[self]) | [
"def",
"insert",
"(",
"self",
")",
":",
"from",
"mongoframes",
".",
"queries",
"import",
"to_refs",
"# Send insert signal",
"signal",
"(",
"'insert'",
")",
".",
"send",
"(",
"self",
".",
"__class__",
",",
"frames",
"=",
"[",
"self",
"]",
")",
"# Prepare th... | Insert this document | [
"Insert",
"this",
"document"
] | 7d2bd792235dfa77a9deecab5366f5f73480823d | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L218-L232 |
27,798 | GetmeUK/MongoFrames | mongoframes/frames.py | Frame.update | def update(self, *fields):
"""
Update this document. Optionally a specific list of fields to update can
be specified.
"""
from mongoframes.queries import to_refs
assert '_id' in self._document, "Can't update documents without `_id`"
# Send update signal
signal('update').send(self.__class__, frames=[self])
# Check for selective updates
if len(fields) > 0:
document = {}
for field in fields:
document[field] = self._path_to_value(field, self._document)
else:
document = self._document
# Prepare the document to be updated
document = to_refs(document)
document.pop('_id', None)
# Update the document
self.get_collection().update_one({'_id': self._id}, {'$set': document})
# Send updated signal
signal('updated').send(self.__class__, frames=[self]) | python | def update(self, *fields):
from mongoframes.queries import to_refs
assert '_id' in self._document, "Can't update documents without `_id`"
# Send update signal
signal('update').send(self.__class__, frames=[self])
# Check for selective updates
if len(fields) > 0:
document = {}
for field in fields:
document[field] = self._path_to_value(field, self._document)
else:
document = self._document
# Prepare the document to be updated
document = to_refs(document)
document.pop('_id', None)
# Update the document
self.get_collection().update_one({'_id': self._id}, {'$set': document})
# Send updated signal
signal('updated').send(self.__class__, frames=[self]) | [
"def",
"update",
"(",
"self",
",",
"*",
"fields",
")",
":",
"from",
"mongoframes",
".",
"queries",
"import",
"to_refs",
"assert",
"'_id'",
"in",
"self",
".",
"_document",
",",
"\"Can't update documents without `_id`\"",
"# Send update signal",
"signal",
"(",
"'upd... | Update this document. Optionally a specific list of fields to update can
be specified. | [
"Update",
"this",
"document",
".",
"Optionally",
"a",
"specific",
"list",
"of",
"fields",
"to",
"update",
"can",
"be",
"specified",
"."
] | 7d2bd792235dfa77a9deecab5366f5f73480823d | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L234-L262 |
27,799 | GetmeUK/MongoFrames | mongoframes/frames.py | Frame.upsert | def upsert(self, *fields):
"""
Update or Insert this document depending on whether it exists or not.
The presense of an `_id` value in the document is used to determine if
the document exists.
NOTE: This method is not the same as specifying the `upsert` flag when
calling MongoDB. When called for a document with an `_id` value, this
method will call the database to see if a record with that Id exists,
if not it will call `insert`, if so it will call `update`. This
operation is therefore not atomic and much slower than the equivalent
MongoDB operation (due to the extra call).
"""
# If no `_id` is provided then we insert the document
if not self._id:
return self.insert()
# If an `_id` is provided then we need to check if it exists before
# performing the `upsert`.
#
if self.count({'_id': self._id}) == 0:
self.insert()
else:
self.update(*fields) | python | def upsert(self, *fields):
# If no `_id` is provided then we insert the document
if not self._id:
return self.insert()
# If an `_id` is provided then we need to check if it exists before
# performing the `upsert`.
#
if self.count({'_id': self._id}) == 0:
self.insert()
else:
self.update(*fields) | [
"def",
"upsert",
"(",
"self",
",",
"*",
"fields",
")",
":",
"# If no `_id` is provided then we insert the document",
"if",
"not",
"self",
".",
"_id",
":",
"return",
"self",
".",
"insert",
"(",
")",
"# If an `_id` is provided then we need to check if it exists before",
"... | Update or Insert this document depending on whether it exists or not.
The presense of an `_id` value in the document is used to determine if
the document exists.
NOTE: This method is not the same as specifying the `upsert` flag when
calling MongoDB. When called for a document with an `_id` value, this
method will call the database to see if a record with that Id exists,
if not it will call `insert`, if so it will call `update`. This
operation is therefore not atomic and much slower than the equivalent
MongoDB operation (due to the extra call). | [
"Update",
"or",
"Insert",
"this",
"document",
"depending",
"on",
"whether",
"it",
"exists",
"or",
"not",
".",
"The",
"presense",
"of",
"an",
"_id",
"value",
"in",
"the",
"document",
"is",
"used",
"to",
"determine",
"if",
"the",
"document",
"exists",
"."
] | 7d2bd792235dfa77a9deecab5366f5f73480823d | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L264-L288 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.