def add_corona_log( infected: int, cured: int, tests: int, deaths: int = 0, log_date: typing.Optional[datetime.date] = None, median: int = 0, hospitalized: int = 0, confirmed_hospitalized: int = 0, confirmed_hospitalized_icu: int = 0, confirmed_hospitalized_ventilation: int = 0, ) -> int: if not log_date: log_date = datetime.date.today() values = dict( infected=infected, cured=cured, tests=tests, deaths=deaths, median=median, hospitalized=hospitalized, confirmed_hospitalized=confirmed_hospitalized, confirmed_hospitalized_icu=confirmed_hospitalized_icu, confirmed_hospitalized_ventilation=confirmed_hospitalized_ventilation, ) log, created = CoronaLog.get_or_create(date=log_date, defaults=values) if not created: update_model_from_dict(log, values) log.save() return log.id
async def update_shape_position(sid, data): sid_data = state.sid_map[sid] user = sid_data["user"] room = sid_data["room"] location = sid_data["location"] shape, layer = await _get_shape(data, location, user) if not await has_ownership(layer, room, data, user, shape): return # Overwrite the old data with the new data if not data["temporary"]: with db.atomic(): data["shape"]["layer"] = Layer.get(location=location, name=data["shape"]["layer"]) # Shape model = reduce_data_to_model(Shape, data["shape"]) update_model_from_dict(shape, model) shape.save() if shape.type_ == "polygon": # Subshape type_instance = shape.subtype # no backrefs on these tables type_instance.update_from_dict(data["shape"], ignore_unknown=True) type_instance.save() await sync_shape_update(layer, room, data, sid, shape)
async def update_shape_position(sid: str, data: Dict[str, Any]): pr: PlayerRoom = game_state.get(sid) if data["temporary"] and not has_ownership_temp(data["shape"], pr): logger.warning( f"User {pr.player.name} attempted to move a shape it does not own." ) return shape, layer = await _get_shape(data, pr) # Overwrite the old data with the new data if not data["temporary"]: if not has_ownership(shape, pr): logger.warning( f"User {pr.player.name} attempted to move a shape it does not own." ) return with db.atomic(): # Shape update_model_from_dict(shape, reduce_data_to_model(Shape, data["shape"])) shape.save() if shape.type_ == "polygon": # Subshape type_instance = shape.subtype # no backrefs on these tables type_instance.update_from_dict(data["shape"], ignore_unknown=True) type_instance.save() await sync_shape_update(layer, pr, data, sid, shape)
def create_pokemon(name, hp, special_attack, defense, attack, special_defense, speed): stats = {'hp': hp, 'special_attack': special_attack, 'defense': defense, 'attack': attack, 'special_defense': special_defense, 'speed': speed} try: pokemon = get_pokemon_by_name(name) update_model_from_dict(pokemon, stats) pokemon.save() except PokemonNotFoundError: pokemon = Pokemon.create(name=name, **stats) return pokemon
async def update_tracker(sid: str, data: TrackerDelta): pr: PlayerRoom = game_state.get(sid) shape = get_shape_or_none(pr, data["shape"], "Tracker.Update") if shape is None: return tracker = Tracker.get_by_id(data["uuid"]) changed_visible = tracker.visible != data.get("visible", tracker.visible) update_model_from_dict(tracker, data) tracker.save() owners = [*get_owner_sids(pr, shape, skip_sid=sid)] for psid in owners: await sio.emit( "Shape.Options.Tracker.Update", data, room=psid, namespace=GAME_NS, ) for psid in game_state.get_sids(active_location=pr.active_location, skip_sid=sid): if psid in owners: continue if changed_visible: if tracker.visible: await sio.emit( "Shape.Options.Tracker.Create", { "shape": shape.uuid, **tracker.as_dict() }, room=psid, namespace=GAME_NS, ) else: await sio.emit( "Shape.Options.Tracker.Remove", { "shape": shape.uuid, "value": tracker.uuid }, room=psid, namespace=GAME_NS, ) else: await sio.emit( "Shape.Options.Tracker.Update", data, room=psid, namespace=GAME_NS, )
async def update_aura(sid: str, data: AuraDelta): pr: PlayerRoom = game_state.get(sid) shape = get_shape_or_none(pr, data["shape"], "Aura.Update") if shape is None: return aura = Aura.get_by_id(data["uuid"]) changed_visible = aura.visible != data.get("visible", aura.visible) update_model_from_dict(aura, data) aura.save() owners = [*get_owner_sids(pr, shape, skip_sid=sid)] for psid in owners: await sio.emit( "Shape.Options.Aura.Update", data, room=psid, namespace=GAME_NS, ) for psid in game_state.get_sids(active_location=pr.active_location, skip_sid=sid): if psid in owners: continue if changed_visible: if aura.visible: await sio.emit( "Shape.Options.Aura.Create", { "shape": shape.uuid, **aura.as_dict() }, room=psid, namespace=GAME_NS, ) else: await sio.emit( "Shape.Options.Aura.Remove", { "shape": shape.uuid, "value": aura.uuid }, room=psid, namespace=GAME_NS, ) else: await sio.emit( "Shape.Options.Aura.Update", data, room=psid, namespace=GAME_NS, )
def moveGroup(self, group: Group, widget: GroupWidgetUi): """ Re-order the position of groups @param group: Group which is being drag to reorder @param widget: Current group """ group_to_be_moved: GroupWidgetUi = self.groups[group.id] update_model_from_dict(group_to_be_moved.group, model_to_dict(group)) group_to_be_moved.parentWidget().layout().removeWidget( group_to_be_moved) index = widget.parentWidget().layout().indexOf(widget) widget.parentWidget().layout().insertWidget(index + 1, group_to_be_moved)
def movie_update(id): """Updates a movie and returns it.""" input = request.json # don't update created/creator-fields input.pop("created", 0) input.pop("creator", 0) m = db.get_movie(id) update_model_from_dict(m, input) m.modified = util.utcnow() m.save() return jsonify(m), 200
def moveAppToGroup(self, container, widget: GroupWidgetUi): """ Move an app into a group @param container: Container of the app, which is being dragged @param widget: Group which is getting dropped """ widget_to_be_moved = self.apps[container.id] # Update the in-memory object of container update_model_from_dict(widget_to_be_moved.container, model_to_dict(container)) widget_to_be_moved.parentWidget().layout().removeWidget( widget_to_be_moved) widget.app_list_layout.addWidget(widget_to_be_moved)
def moveAppWidget(self, container, widget: AppWidgetUi): """ Reorder the position of App @param container: App is being dragged @param widget: App is getting dropped """ widget_to_be_moved = self.apps[container.id] # Update the in-memory object of container update_model_from_dict(widget_to_be_moved.container, model_to_dict(container)) widget_to_be_moved.parentWidget().layout().removeWidget( widget_to_be_moved) index = widget.parentWidget().layout().indexOf(widget) widget.parentWidget().layout().insertWidget(index + 1, widget_to_be_moved)
async def update(request: Request, uid: str): user = User.get_or_none(id=uid) if user is None: return json({'Erro': 'Usuário não encontrado'}, status=404) query = User.update(**request.json).where(User.id == user.id).execute() user = update_model_from_dict(user, request.json) return json(model_to_dict(user), dumps=dumps, cls=Serialize)
def update_from_dict(self, data, ignore_unknown=False, use_whitelist=False): """注意值是没有写入数据库的, 需要显式 save""" cls = type(self) clean_data = cls._filter_attrs(data) return shortcuts.update_model_from_dict(self, clean_data, ignore_unknown)
def importShortcuts(container: Container, shortcuts: List[dict]): for shortcut_dict in shortcuts: shortcut = PreferencesShortcut() update_model_from_dict(shortcut, shortcut_dict) shortcut.container = container if shortcut.pref_type in ['File', 'Folder']: if not os.path.exists(shortcut.default_value): shortcut.default_value = '' try: PreferencesShortcut.get( (PreferencesShortcut.container == container) & (PreferencesShortcut.shortcut == shortcut.shortcut) & (PreferencesShortcut.mapping_to == shortcut.mapping_to) & (PreferencesShortcut.pref_type == shortcut.pref_type)) logger.info("Ignoring shortcut label %s cuz it is already exists" % shortcut.label) except DoesNotExist: shortcut.save()
def create_pokemon(name, hp, special_attack, defense, attack, special_defense, speed): stats = { "hp": hp, "special_attack": special_attack, "defense": defense, "attack": attack, "special_defense": special_defense, "speed": speed, } try: pokemon = get_pokemon_by_name(name) update_model_from_dict(pokemon, stats) pokemon.save() except PokemonNotFoundError: pokemon = Pokemon.create(name=name, **stats) return pokemon
async def set_location_options(sid: str, data: LocationOptionsData): pr: PlayerRoom = game_state.get(sid) if pr.role != Role.DM: logger.warning(f"{pr.player.name} attempted to set a room option") return if data.get("location", None) is None: options = pr.room.default_options else: loc = Location.get_by_id(data["location"]) if loc.options is None: loc.options = LocationOptions.create( unit_size=None, unit_size_unit=None, grid_type=None, use_grid=None, full_fow=None, fow_opacity=None, fow_los=None, vision_mode=None, vision_min_range=None, vision_max_range=None, ) loc.save() options = loc.options update_model_from_dict(options, data["options"]) options.save() if data.get("location", None) is None: for sid in game_state.get_sids(skip_sid=sid, room=pr.room): await sio.emit("Location.Options.Set", data, room=sid, namespace=GAME_NS) else: await sio.emit( "Location.Options.Set", data, room=pr.active_location.get_path(), skip_sid=sid, namespace=GAME_NS, )
async def set_location_options(sid, data): sid_data = state.sid_map[sid] user = sid_data["user"] room = sid_data["room"] location = sid_data["location"] if room.creator != user: logger.warning(f"{user.name} attempted to set a room option") return update_model_from_dict(location, data) location.save() await sio.emit( "Location.Set", data, room=location.get_path(), skip_sid=sid, namespace="/planarally", )
def patch(self, metric_id): """ Update the values for a given metric. This cannot change the ``metric_id`` value. Accepts JSON data with the following format: .. code-block::json { "name": {string, optional}, "units": {string, optional}, "upper_limit": {float, optional}, "lower_limit": {float, optional} } Returns ------- 200 : Success. Returned JSON data has two keys: ``old_value`` and ``new_value``, each containing only the values of the :class:`orm.Metric` object *that were requested to be changed*. 404 : The requested metric is not found. 409 : The target metric name already exists. See Also -------- :func:`routes.get_metric_as_json` :func:`routes.post_metric` :func:`routes.delete_metric` :func:`routes.put_metric` """ # XXX: This is essentially the same code as `put`... Gotta refactor ASAP data = request.get_json() # First see if our item actually exists try: metric = db.Metric.get(db.Metric.metric_id == metric_id) old = model_to_dict(metric) except DoesNotExist: return ErrorResponse.metric_not_found(metric_id) metric = update_model_from_dict(metric, data) try: metric.save() except IntegrityError: # Failed the unique constraint on Metric.name return ErrorResponse.unique_metric_name_required( old['name'], metric.name) return 204
async def update_group(sid: str, group_info: ServerGroup): pr: PlayerRoom = game_state.get(sid) try: group = Group.get_by_id(group_info["uuid"]) except Group.DoesNotExist: logger.exception( f"Could not retrieve group information for {group_info['uuid']}") else: update_model_from_dict(group, group_info) group.save() for psid, _ in game_state.get_users(room=pr.room): await sio.emit( "Group.Update", group_info, room=psid, skip_sid=sid, namespace=GAME_NS, )
async def update_initiative_effect(sid: int, data: Dict[str, Any]): pr: PlayerRoom = game_state.get(sid) if not has_ownership(Shape.get_or_none(uuid=data["actor"]), pr): logger.warning( f"{pr.player.name} attempted to update an initiative effect") return with db.atomic(): effect = InitiativeEffect.get(uuid=data["effect"]["uuid"]) update_model_from_dict( effect, reduce_data_to_model(InitiativeEffect, data["effect"])) effect.save() await sio.emit( "Initiative.Effect.Update", data, room=pr.active_location.get_path(), skip_sid=sid, namespace=GAME_NS, )
def put_synth_button_setting( index: int, new_fields: Dict, audio_manager: AudioManager, ) -> Optional[SynthButtonSetting]: """ Updates a SynthButtonSetting. Checks that certain invariants hold on the updates being requested. Namely: - On mode change, ensure the following: - If mode -> tone: frequency and overtones must exist - If mode -> wav: wav_id must exist, and there must exist a real wav at that ID """ # TODO: Clean this whole thing up if (new_fields.get("mode") == SynthButtonMode.Tone.value and ("frequency" not in new_fields or "overtones" not in new_fields)) or ( new_fields.get("mode") == SynthButtonMode.Wav.value and ("wav_id" not in new_fields)): return None if (new_fields.get("mode") == SynthButtonMode.Wav.value and "wav_id" in new_fields and len(WavFile.select().where(WavFile.id == new_fields["wav_id"])) == 0): return None setting = get_synth_button_setting(index) if setting is None: return None update_model_from_dict(setting, new_fields) setting.save() audio_manager.set_driver( index, synth_button_setting_to_base_driver(config.SAMPLE_RATE, setting), ) return setting
def main(): foo = Foo.get(id=1) print(foo) print(model_to_dict(foo)) print(model_to_dict(foo, exclude=[Foo.type])) print(model_to_dict(foo, extra_attrs=['upper_name'])) d = { 'id': 1, 'name': 'n1', 'type': 1, } foo = dict_to_model(Foo, d) print(foo) d['type'] = 2 update_model_from_dict(foo, d) print(foo) d['id'] = 2 update_model_from_dict(foo, d) # id 同样会改掉 print(foo)
def load_pokemon_from_api(name): request = requests.get(f"https://pokeapi.co/api/v2/pokemon/{name}") pokemon_data = request.json() stats = {} for stat in pokemon_data["stats"]: stat_name = stat["stat"]["name"].replace("-", "_") stat_value = int(stat["base_stat"]) stats[stat_name] = stat_value sprite_front = pokemon_data["sprites"]["front_default"] sprite_back = pokemon_data["sprites"]["back_default"] pokemon = Pokemon.get_or_none(name=name) data = {"sprite_front": sprite_front, "sprite_back": sprite_back, **stats} if pokemon is None: pokemon = Pokemon.create(name=name, **data) else: update_model_from_dict(pokemon, data) pokemon.save() return pokemon
def load_pokemon_from_api(name): request = requests.get(f'https://pokeapi.co/api/v2/pokemon/{name}') pokemon_data = request.json() stats = {} for stat in pokemon_data['stats']: stat_name = stat['stat']['name'].replace('-', '_') stat_value = int(stat['base_stat']) stats[stat_name] = stat_value sprite_front = pokemon_data['sprites']['front_default'] sprite_back = pokemon_data['sprites']['back_default'] pokemon = Pokemon.get_or_none(name=name) data = {'sprite_front': sprite_front, 'sprite_back': sprite_back, **stats} if pokemon is None: pokemon = Pokemon.create(name=name, **data) else: update_model_from_dict(pokemon, data) pokemon.save() return pokemon
async def update_initiative_effect(sid, data): sid_data = state.sid_map[sid] user = sid_data["user"] room = sid_data["room"] location = sid_data["location"] if room.creator != user and not ShapeOwner.get_or_none(shape=shape, user=user): logger.warning(f"{user.name} attempted to update an initiative effect") return with db.atomic(): effect = InitiativeEffect.get(uuid=data["effect"]["uuid"]) update_model_from_dict( effect, reduce_data_to_model(InitiativeEffect, data["effect"])) effect.save() await sio.emit( "Initiative.Effect.Update", data, room=location.get_path(), skip_sid=sid, namespace="/planarally", )
async def set_location_options(sid: int, data: Dict[str, Any]): pr: PlayerRoom = game_state.get(sid) if pr.role != Role.DM: logger.warning(f"{pr.player.name} attempted to set a room option") return if data.get("location", None) is None: options = pr.room.default_options else: loc = Location[data["location"]] if loc.options is None: loc.options = LocationOptions.create( unit_size=None, unit_size_unit=None, use_grid=None, full_fow=None, fow_opacity=None, fow_los=None, vision_mode=None, grid_size=None, vision_min_range=None, vision_max_range=None, ) options = loc.options update_model_from_dict(options, data["options"]) options.save() await sio.emit( "Location.Options.Set", data, room=pr.active_location.get_path(), skip_sid=sid, namespace="/planarally", )
def createGroup(self, container, widget: AppWidgetUi): """ Create group when user drag two apps together @param container: Container is being dragged @param widget: Container is getting dropped """ widget_to_be_moved = self.apps[container.id] # Update the in-memory object of container update_model_from_dict(widget_to_be_moved.container, model_to_dict(container)) group = group_service.createGroup(self._tr('New Folder')) self.addGroupWidget(group) widget_to_be_moved.container.group = group widget_to_be_moved.container.save() widget.container.group = group widget.container.save() group_widget = self.groups[group.id] self.groups[group.id] = group_widget self.ui.app_list.layout().addWidget(group_widget) widget_to_be_moved.parentWidget().layout().removeWidget( widget_to_be_moved) group_widget.app_list_layout.addWidget(widget_to_be_moved) widget.parentWidget().layout().removeWidget(widget) group_widget.app_list_layout.addWidget(widget)
def update_from_dict(self, data, *args, **kwargs): data["vertices"] = json.dumps(data["vertices"]) return update_model_from_dict(self, data, *args, **kwargs)
def update_from_dict(self, data, *args, **kwargs): return update_model_from_dict(self, data, *args, **kwargs)
async def update_initiative(sid: int, data: Dict[str, Any]): pr: PlayerRoom = game_state.get(sid) shape = Shape.get_or_none(uuid=data["uuid"]) if not has_ownership(shape, pr): logger.warning( f"{pr.player.name} attempted to change initiative of an asset it does not own" ) return location_data = InitiativeLocationData.get_or_none( location=pr.active_location) if location_data is None: location_data = InitiativeLocationData.create( location=pr.active_location, turn=data["uuid"], round=1) initiatives = Initiative.select().where( Initiative.location_data == location_data) initiative = Initiative.get_or_none(uuid=data["uuid"]) # Create new initiative if initiative is None: with db.atomic(): # Update indices try: index = (initiatives.where( Initiative.initiative >= data["initiative"]).order_by( -Initiative.index)[0].index + 1) except IndexError: index = 0 else: Initiative.update( index=Initiative.index + 1).where((Initiative.location_data == location_data) & (Initiative.index >= index)) # Create model instance initiative = dict_to_model(Initiative, reduce_data_to_model(Initiative, data)) initiative.location_data = location_data initiative.index = index initiative.save(force_insert=True) # Update initiative else: with db.atomic(): if data["initiative"] != initiative.initiative: # Update indices old_index = initiative.index try: new_index = (initiatives.where( Initiative.initiative >= data["initiative"]).order_by( -Initiative.index)[0].index) except IndexError: new_index = 0 else: if new_index < old_index: new_index += 1 if old_index != new_index: # SIGN=1 IF old_index > new_index WHICH MEANS the initiative is increased # SIGN=-1 IF old_index < new_index WHICH MEANS the initiative is decreased sign = (old_index - new_index) // abs(old_index - new_index) indices = [0, old_index, new_index] update = Initiative.update( index=Initiative.index + sign).where((Initiative.location_data == location_data) & (Initiative.index <= indices[sign]) & (Initiative.index >= indices[-sign])) update.execute() data["index"] = new_index # Update model instance update_model_from_dict(initiative, reduce_data_to_model(Initiative, data)) initiative.save() data["index"] = initiative.index await send_client_initiatives(pr)
def update_element(user_id, document_id, element_id, data): element = select_element(user_id, document_id, element_id) update_model_from_dict(element, data) element.save() return model_to_dict(element, recurse=False)