async def patch(self, request: Request) -> JSONResponse: """Updates form by ID.""" try: data = await request.json() except json.decoder.JSONDecodeError: return JSONResponse("Expected a JSON body.", 400) form_id = request.path_params["form_id"].lower() await discord.verify_edit_access(form_id, request) if raw_form := await request.state.db.forms.find_one({"_id": form_id}): if "_id" in data or "id" in data: if (data.get("id") or data.get("_id")) != form_id: return JSONResponse({"error": "locked_field"}, status_code=400) # Build Data Merger merge_strategy = [(dict, ["merge"])] merger = deepmerge.Merger(merge_strategy, ["override"], ["override"]) # Merge Form Data updated_form = merger.merge(raw_form, data) try: form = Form(**updated_form) except ValidationError as e: return JSONResponse(e.errors(), status_code=422) await request.state.db.forms.replace_one({"_id": form_id}, form.dict()) return JSONResponse(form.dict())
def merge_dicts(da, db): ''' TODO ''' ## note: ansible does not like raw lib import errors, so move ## import here into function so caller can handle this more ## gracefully import deepmerge merger = deepmerge.Merger( # pass in a list of tuple, with the # strategies you are looking to apply # to each type. [ (list, ["append"]), ##(collections.abc.Mapping, ["merge"]) (dict, ["merge"]) ], # next, choose the fallback strategies, # applied to all other types: ["override"], # finally, choose the strategies in # the case where the types conflict: ["override"] ) ## important: this operation always changes first dict given as param, use copy if this is an issue return merger.merge(da, db)
def merge_defaults(a, b): merger = deepmerge.Merger( # pass in a list of tuple, with the # strategies you are looking to apply # to each type. [(list, ["append"]), (dict, ["merge"])], # next, choose the fallback strategies, # applied to all other types: ["override"], # finally, choose the strategies in # the case where the types conflict: ["override"]) merger.merge(a, b) return a
def find_reference(ref: oas.Reference, components: ResolvedTypesMap) -> oas.ObjectValue: key = camelized_python_name(ref.ref.name) if key not in components: raise NotImplementedError('Reference is not found in the registry') obj = components[key] assert isinstance( obj, oas.ObjectValue), "Referenced object is not of type ObjectValue" return obj merge_strategy = deepmerge.Merger([ (list, "append"), (dict, "merge"), (frozenset, add_to_set), ], ["override"], ["override"]) SCHEMA_PROCESSOR = { oas.StringValue: _process_string_or_enum, oas.IntegerValue: _process_integer, oas.FloatValue: _process_float, oas.BooleanValue: _process_bool, oas.ObjectValue: _process_object, oas.Reference: _process_reference, oas.ArrayValue: _process_array, oas.ObjectWithAdditionalProperties: _process_freeform_object, oas.ProductSchemaType: _process_product_schema_type, oas.UnionSchemaTypeAny: _process_unions, oas.UnionSchemaTypeOne: _process_unions,
def append_no_duplicate(config, path, base, nxt): """ a list strategy to append only the elements not yet in the list.""" for e in nxt: if e not in base: base.append(e) return base # merger object to merge dict with list in a recursive way # with a strategy for list to avoid duplicates m = deepmerge.Merger( # pass in a list of tuple, with the # strategies you are looking to apply # to each type. [(list, [append_no_duplicate]), (dict, ["merge"])], # next, choose the fallback strategies, # applied to all other types: ["override"], # finally, choose the strategies in # the case where the types conflict: ["override"], ) def generate_filter_conditions(conditions: List[FilterCondition], merge_matches=False, global_security=None): """Return a function: - taking an operation (as a dict) as well as three flags: - on_tags (default = True) - on_operations (default = True) - on_security_scopes (default = True)
import time import hmc5883l import mpu6050 import json import deepmerge import sys merge = deepmerge.Merger([(dict, ["merge"])], ["override"], ["override"]).merge default_config = { "accel": {"bus": 0, "address": 0x68}, "compass": {"gauss": 4.7, "declination": (-2,5), "port": 0}, "frequency": 100 } config = merge(default_config, json.loads(sys.argv[1])) accel = mpu6050.mpu6050(**config["accel"]) compass = hmc5883l.hmc5883l(**config["compass"]) while True: json.dump({ "accel": accel.get_accel_data(), "gyro": accel.get_gyro_data(), "temp": accel.get_temp(), "heading": compass.heading(), "time": time.time()}, sys.stdout) sys.stdout.write("\n") sys.stdout.flush() time.sleep(1./config["frequency"])
import deepmerge # type: ignore from .private.merger import option_check_key_exist, option_merge_fallback, option_type_conflict merger_nocreate = deepmerge.Merger( [ (list, "append"), (dict, [option_check_key_exist, "merge"]), ], ['override', option_merge_fallback], [option_type_conflict] ) """A dict/list merger that doesn't allow dict key creation, based on the :mod:`deepmerge` module.""" # A merger that allows key creation merger = deepmerge.Merger( [ (list, "append"), (dict, "merge"), ], ['override', option_merge_fallback], [option_type_conflict] ) """A dict/list merger, based on the :mod:`deepmerge` module."""
def config_merger(): return deepmerge.Merger(type_strategies=[(dict, ["merge"]), (list, ["override"])], fallback_strategies=['override'], type_conflict_strategies=['override'])
# for two most popular types: 'object' and 'array'. if "type" not in schema: if "properties" in schema: schema_type = "object" elif "items" in schema: schema_type = "array" else: schema_type = None else: schema_type = schema["type"] return schema_type _merge_mappings = deepmerge.Merger( [(collections.Mapping, deepmerge.strategy.dict.DictStrategies("merge"))], ["override"], ["override"], ).merge class HttpdomainRenderer(abc.RestructuredTextRenderer): """Render OpenAPI v3 using `sphinxcontrib-httpdomain` extension.""" _markup_converters = {"commonmark": m2r.convert, "restructuredtext": lambda x: x} _response_examples_for = {"200", "201", "202", "2XX"} _request_parameters_order = ["header", "path", "query", "cookie"] option_spec = { "markup": functools.partial(directives.choice, values=_markup_converters), "http-methods-order": lambda s: s.split(), "response-examples-for": None,
with open(template_config, 'r') as tc: config = yaml.load(tc) defaults = config["defaults"] # Work out which templates we are calculating if templates == "all": work = config["packages"] else: work = {} for t in templates: work[t] = config["packages"][t] # We need different actions for merging configs and contexts ContextMerger = deepmerge.Merger([(dict, ["merge"])], ["override"], ["override"]) for exporter_name, exporter_config in work.items(): merged_context = ContextMerger.merge( defaults["context"], exporter_config.get("context", {})) merged_config = { **defaults["config"], **exporter_config.get("config", {}) } logging.info("Building exporter {}".format(exporter_name)) # First we need to work out the context for this build real_context = merged_context["static"] # Add in the exporter name as a context variable