_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q242800
find_quality
train
def find_quality(positions): """ Find a quality consists of positions :param list[int] positions: note positions :rtype: str|None """ for q, p in QUALITY_DICT.items(): if positions == list(p): return q return None
python
{ "resource": "" }
q242801
Convention.configure
train
def configure(self, ns, mappings=None, **kwargs): """ Apply mappings to a namespace. """ if mappings is None: mappings = dict() mappings.update(kwargs) for operation, definition in mappings.items(): try: configure_func = self._fin...
python
{ "resource": "" }
q242802
Convention._find_func
train
def _find_func(self, operation): """ Find the function to use to configure the given operation. The input might be an `Operation` enum or a string. """ if isinstance(operation, Operation): operation_name = operation.name.lower() else: operation_n...
python
{ "resource": "" }
q242803
Convention._make_definition
train
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 ...
python
{ "resource": "" }
q242804
iter_links
train
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
{ "resource": "" }
q242805
configure_discovery
train
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
{ "resource": "" }
q242806
DiscoveryConvention.configure_discover
train
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 ...
python
{ "resource": "" }
q242807
nested
train
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
{ "resource": "" }
q242808
temporary_upload
train
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 = j...
python
{ "resource": "" }
q242809
configure_upload
train
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
{ "resource": "" }
q242810
UploadConvention.configure_upload
train
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) ...
python
{ "resource": "" }
q242811
UploadConvention.configure_uploadfor
train
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, f...
python
{ "resource": "" }
q242812
BaseFormatter.build_etag
train
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...
python
{ "resource": "" }
q242813
EncryptableCRUDStoreAdapter.update_and_reencrypt
train
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__ ...
python
{ "resource": "" }
q242814
DAGSchema.unflatten
train
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
{ "resource": "" }
q242815
DAGCloningController.clone
train
def clone(self, substitutions, commit=True, **kwargs): """ Clone a DAG, optionally skipping the commit. """ return self.store.clone(substitutions, **kwargs)
python
{ "resource": "" }
q242816
RelationConvention.configure_createfor
train
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 ...
python
{ "resource": "" }
q242817
RelationConvention.configure_deletefor
train
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 endpoi...
python
{ "resource": "" }
q242818
RelationConvention.configure_replacefor
train
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 c...
python
{ "resource": "" }
q242819
Parameters.build
train
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] = [ ...
python
{ "resource": "" }
q242820
Parameters.builder_types
train
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
{ "resource": "" }
q242821
configure_crud
train
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 ...
python
{ "resource": "" }
q242822
CRUDConvention.configure_count
train
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 u...
python
{ "resource": "" }
q242823
CRUDConvention.configure_create
train
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 ...
python
{ "resource": "" }
q242824
CRUDConvention.configure_updatebatch
train
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: ...
python
{ "resource": "" }
q242825
CRUDConvention.configure_retrieve
train
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 def...
python
{ "resource": "" }
q242826
CRUDConvention.configure_delete
train
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 ...
python
{ "resource": "" }
q242827
CRUDConvention.configure_replace
train
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...
python
{ "resource": "" }
q242828
CRUDConvention.configure_update
train
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 en...
python
{ "resource": "" }
q242829
CRUDConvention.configure_createcollection
train
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, defi...
python
{ "resource": "" }
q242830
NestedParameterBuilder.parse_ref
train
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
{ "resource": "" }
q242831
configure_build_info
train
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
{ "resource": "" }
q242832
build_logger_tree
train
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 ...
python
{ "resource": "" }
q242833
ParameterBuilder.build
train
def build(self, field: Field) -> Mapping[str, Any]: """ Build a parameter. """ return dict(self.iter_parsed_values(field))
python
{ "resource": "" }
q242834
ParameterBuilder.iter_parsed_values
train
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, ...
python
{ "resource": "" }
q242835
Namespace.object_ns
train
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
{ "resource": "" }
q242836
Namespace.url_for
train
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. "...
python
{ "resource": "" }
q242837
Namespace.href_for
train
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(operat...
python
{ "resource": "" }
q242838
configure_swagger
train
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) conve...
python
{ "resource": "" }
q242839
SwaggerConvention.configure_discover
train
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)) ...
python
{ "resource": "" }
q242840
ListParameterBuilder.parse_items
train
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
{ "resource": "" }
q242841
Link.for_
train
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...
python
{ "resource": "" }
q242842
build_parameter
train
def build_parameter(field: Field) -> Mapping[str, Any]: """ Build JSON parameter from a marshmallow field. """ builder = Parameters() return builder.build(field)
python
{ "resource": "" }
q242843
SavedSearchConvention.configure_savedsearch
train
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 availa...
python
{ "resource": "" }
q242844
encode_basic_auth
train
def encode_basic_auth(username, password): """ Encode basic auth credentials. """ return "Basic {}".format( b64encode( "{}:{}".format( username, password, ).encode("utf-8") ).decode("utf-8") )
python
{ "resource": "" }
q242845
configure_basic_auth_decorator
train
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...
python
{ "resource": "" }
q242846
ConfigBasicAuth.check_credentials
train
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
{ "resource": "" }
q242847
ConfigBasicAuth.challenge
train
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
{ "resource": "" }
q242848
Schemas.iter_fields
train
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
{ "resource": "" }
q242849
PaginatedList.links
train
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
{ "resource": "" }
q242850
OffsetLimitPaginatedList.links
train
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, q...
python
{ "resource": "" }
q242851
Page.to_items
train
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 choic...
python
{ "resource": "" }
q242852
Page.to_paginated_list
train
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 = ...
python
{ "resource": "" }
q242853
Page.parse_result
train
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:...
python
{ "resource": "" }
q242854
Page.from_query_string
train
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
{ "resource": "" }
q242855
Page.make_paginated_list_schema_class
train
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), ...
python
{ "resource": "" }
q242856
OffsetLimitPage.parse_result
train
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: ...
python
{ "resource": "" }
q242857
name_for
train
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__) els...
python
{ "resource": "" }
q242858
instance_path_for
train
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
{ "resource": "" }
q242859
relation_path_for
train
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
{ "resource": "" }
q242860
configure_alias
train
def configure_alias(graph, ns, mappings): """ Register Alias endpoints for a resource object. """ convention = AliasConvention(graph) convention.configure(ns, mappings)
python
{ "resource": "" }
q242861
AliasConvention.configure_alias
train
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: - ac...
python
{ "resource": "" }
q242862
encode_id_header
train
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
{ "resource": "" }
q242863
load_request_data
train
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 41...
python
{ "resource": "" }
q242864
load_query_string_data
train
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(quer...
python
{ "resource": "" }
q242865
dump_response_data
train
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 sp...
python
{ "resource": "" }
q242866
merge_data
train
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
{ "resource": "" }
q242867
find_response_format
train
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 = [Resp...
python
{ "resource": "" }
q242868
build_swagger
train
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, ...
python
{ "resource": "" }
q242869
add_paths
train
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 versi...
python
{ "resource": "" }
q242870
add_definitions
train
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 ...
python
{ "resource": "" }
q242871
iter_definitions
train
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 sch...
python
{ "resource": "" }
q242872
build_path
train
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) fo...
python
{ "resource": "" }
q242873
header_param
train
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
{ "resource": "" }
q242874
query_param
train
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
{ "resource": "" }
q242875
path_param
train
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", "requ...
python
{ "resource": "" }
q242876
build_operation
train
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],...
python
{ "resource": "" }
q242877
add_responses
train
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...
python
{ "resource": "" }
q242878
build_response
train
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(resour...
python
{ "resource": "" }
q242879
iter_endpoints
train
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 grap...
python
{ "resource": "" }
q242880
get_converter
train
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 dynami...
python
{ "resource": "" }
q242881
request
train
def request(schema): """ Decorate a function with a request schema. """ def wrapper(func): setattr(func, REQUEST, schema) return func return wrapper
python
{ "resource": "" }
q242882
response
train
def response(schema): """ Decorate a function with a response schema. """ def wrapper(func): setattr(func, RESPONSE, schema) return func return wrapper
python
{ "resource": "" }
q242883
qs
train
def qs(schema): """ Decorate a function with a query string schema. """ def wrapper(func): setattr(func, QS, schema) return func return wrapper
python
{ "resource": "" }
q242884
should_skip_logging
train
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
{ "resource": "" }
q242885
logging_levels
train
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 = g...
python
{ "resource": "" }
q242886
audit
train
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_res...
python
{ "resource": "" }
q242887
_audit_request
train
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 t...
python
{ "resource": "" }
q242888
parse_response
train
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): ...
python
{ "resource": "" }
q242889
configure_audit_decorator
train
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_res...
python
{ "resource": "" }
q242890
configure_route_decorator
train
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....
python
{ "resource": "" }
q242891
extract_status_code
train
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: ...
python
{ "resource": "" }
q242892
extract_error_message
train
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....
python
{ "resource": "" }
q242893
make_json_error
train
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...
python
{ "resource": "" }
q242894
configure_error_handlers
train
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_h...
python
{ "resource": "" }
q242895
_BaseFrame.to_json_type
train
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
{ "resource": "" }
q242896
_BaseFrame._json_safe
train
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): ...
python
{ "resource": "" }
q242897
_BaseFrame._path_to_keys
train
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
{ "resource": "" }
q242898
_BaseFrame._path_to_value
train
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_...
python
{ "resource": "" }
q242899
_BaseFrame._remove_keys
train
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_t...
python
{ "resource": "" }