Python playhouse.shortcuts.model_to_dict() Examples
The following are 30
code examples of playhouse.shortcuts.model_to_dict().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
playhouse.shortcuts
, or try the search function
.
Example #1
Source File: collection_resource.py From sanic_crud with MIT License | 6 votes |
def post(self, request): valid_request = self.validate_request(request) if valid_request is not True: return valid_request try: result = self.model.create(**request.json) return self.response_json(data=model_to_dict(result), status_code=200, message=self.config.response_messages.SuccessRowCreated.format(result.id) ) except Exception as e: log.error(traceback.print_exc()) return self.response_json(message=str(e), status_code=500 )
Example #2
Source File: web.py From renrenBackup with MIT License | 6 votes |
def handle_session(): uid = 0 paths = request.path.split('/') if len(paths) > 1 and paths[1].isdigit(): uid = int(paths[1]) if 'user' in session and ((not uid) or (uid and session['user']['uid'] == uid)): g.user = session['user'] elif uid: user = FetchedUser.get_or_none(FetchedUser.uid == uid) if not user: abort(404, "no such user") session['user'] = model_to_dict(user) g.user = session['user'] else: g.user = None
Example #3
Source File: views.py From PyPlanet with GNU General Public License v3.0 | 6 votes |
def get_data(self): if self.cache and self.advanced == self.cache_advanced: return self.cache self.fields, self.map_list, self.folder_info, self.folder_instance = \ await self.folder_manager.get_folder_code_contents(self.folder_code) self.title = 'Folder: ' + self.folder_info['name'] karma = any(f['index'] == "karma" for f in self.fields) length = any(f['index'] == "local_record" for f in self.fields) items = [] for item in self.map_list: dict_item = model_to_dict(item) if length: dict_item['local_record'] = times.format_time((item.local['first_record'].score if hasattr(item, 'local') and item.local['first_record'] else 0)) if karma and 'karma' in self.app.instance.apps.apps: dict_item['karma'] = (await self.app.instance.apps.apps['karma'].get_map_karma(item))['map_karma'] items.append(dict_item) self.cache = items return self.cache
Example #4
Source File: planedb-serv.py From ADS-B-funhouse with MIT License | 6 votes |
def get_aircraft(icao24): icao24 = icao24.lower() try: obj = Plane.get(icao24 = icao24) except Plane.DoesNotExist: abort(404) o = model_to_dict(obj) # model_to_dict does not format dates try: o['added_on'] = str(obj.added_on.strftime('%Y-%m-%d %H:%M:%S')) except AttributeError: # String is not a date string o['added_on'] = None try: o['updated_on'] = str(obj.updated_on.strftime('%Y-%m-%d %H:%M:%S')) except AttributeError: o['updated_on'] = None return o
Example #5
Source File: data_record.py From slim with zlib License | 6 votes |
def _to_dict(self): data = {} fields = self.val._meta.fields for name, v in model_to_dict(self.val, recurse=False).items(): if isinstance(fields[name], peewee.ForeignKeyField): name = name + '_id' elif isinstance(fields[name], peewee.BlobField): v = get_bytes_from_blob(v) if self.selected != ALL_COLUMNS and (self.selected and (name not in self.selected)): continue data[name] = v if self.available_columns != ALL_COLUMNS: return dict_filter(data, self.available_columns) return data
Example #6
Source File: planedb-serv.py From ADS-B-funhouse with MIT License | 6 votes |
def get_airport(ica_or_iata): ica_or_iata = ica_or_iata.upper() try: obj = Airport.get(icao = ica_or_iata) except Airport.DoesNotExist: try: obj = Airport.get(iata = ica_or_iata) except Airport.DoesNotExist: abort(404) o = model_to_dict(obj) # model_to_dict does not format dates o['lat'] = "%f" % obj.lat o['lon'] = "%f" % obj.lon o['alt'] = "%d" % obj.alt o['added_on'] = str(obj.added_on.strftime('%Y-%m-%d %H:%M:%S')) o['updated_on'] = str(obj.updated_on.strftime('%Y-%m-%d %H:%M:%S')) return o
Example #7
Source File: planedb-serv.py From ADS-B-funhouse with MIT License | 6 votes |
def get_airline(icao): icao = icao.upper() try: obj = Airline.get(icao = icao) except Airline.DoesNotExist: abort(404) o = model_to_dict(obj) # model_to_dict does not format dates try: o['added_on'] = str(obj.added_on.strftime('%Y-%m-%d %H:%M:%S')) except AttributeError: # String is not a date string o['added_on'] = None try: o['updated_on'] = str(obj.updated_on.strftime('%Y-%m-%d %H:%M:%S')) except AttributeError: o['updated_on'] = None return o
Example #8
Source File: all.py From ray with MIT License | 6 votes |
def update(self, fields_to_update=None): if not fields_to_update: fields_to_update = model_to_dict(self, recurse=False) model_id = fields_to_update['id'] del fields_to_update['id'] model_class = self.__class__ query = super(PeeweeModel, self).update(**fields_to_update) query = query.where(model_class.id == model_id) query.execute() for field, value in fields_to_update.items(): setattr(self, field, value) return self
Example #9
Source File: planedb-serv.py From ADS-B-funhouse with MIT License | 6 votes |
def get_route(flight): flight = flight.upper() try: obj = Route.get(flight = flight) except Route.DoesNotExist: abort(404) o = model_to_dict(obj) # model_to_dict does not format dates try: o['added_on'] = str(obj.added_on.strftime('%Y-%m-%d %H:%M:%S')) except AttributeError: # String is not a date string o['added_on'] = None try: o['updated_on'] = str(obj.updated_on.strftime('%Y-%m-%d %H:%M:%S')) except AttributeError: o['updated_on'] = None return o
Example #10
Source File: collection_resource.py From sanic_crud with MIT License | 6 votes |
def get(self, request, **kwargs): try: response_messages = self.config.response_messages # Verify page is an int try: page = int(request.args.get('page', 1)) except ValueError: return self.response_json(status_code=400, message=response_messages.ErrorTypeInteger.format('page')) include_backrefs = False include_foreign_keys = False if 'backrefs' in request.args and request.args['backrefs'][0] == 'true': include_backrefs = True include_foreign_keys = True elif 'foreign_keys' in request.args and request.args['foreign_keys'][0] == 'true': include_foreign_keys = True results = [] data = kwargs.get('filtered_results') total_records = data.count() total_pages = ceil(total_records / self.config.COLLECTION_MAX_RESULTS_PER_PAGE) data = data.paginate(page, self.config.COLLECTION_MAX_RESULTS_PER_PAGE) for row in data: results.append(model_to_dict(row, recurse=include_foreign_keys, backrefs=include_backrefs)) return self.response_json(data=results, status_code=200, message=response_messages.SuccessOk, page=page, total_pages=total_pages) except Exception as e: log.error(traceback.print_exc()) return self.response_json(message=str(e), status_code=500 )
Example #11
Source File: single_resource.py From sanic_crud with MIT License | 5 votes |
def get(self, request, **kwargs): try: shortcuts = self.model.shortcuts response_messages = self.config.response_messages primary_key = kwargs.get(shortcuts.primary_key) include_backrefs = False include_foreign_keys = False if 'backrefs' in request.args and request.args['backrefs'][0] == 'true': include_backrefs = True include_foreign_keys = True elif 'foreign_keys' in request.args and request.args['foreign_keys'][0] == 'true': include_foreign_keys = True data = self.get_model(primary_key) if not data: return self.response_json( data=data, status_code=404, message=response_messages.ErrorDoesNotExist.format(primary_key) ) else: return self.response_json( data=model_to_dict(data, recurse=include_foreign_keys, backrefs=include_backrefs), status_code=200, message=response_messages.SuccessOk ) except Exception as e: log.error(traceback.print_exc()) return self.response_json( message=str(e), status_code=500 )
Example #12
Source File: planedb-serv.py From ADS-B-funhouse with MIT License | 5 votes |
def get_imagechecks(): from playhouse.shortcuts import model_to_dict, dict_to_model checks = [] try: for check in PlaneImageCheck().select(): plane = Plane.get(icao24 = check.icao24) checks.append(model_to_dict(plane)) except PlaneImageCheck.DoesNotExist: return None return checks
Example #13
Source File: single_resource.py From sanic_crud with MIT License | 5 votes |
def put(self, request, **kwargs): valid_request = self.validate_request(request) if valid_request is not True: return valid_request try: shortcuts = self.model.shortcuts response_messages = self.config.response_messages request_data = request.json.items() primary_key = kwargs.get(shortcuts.primary_key) resource = self.get_model(primary_key) if not resource: return self.response_json( data={}, status_code=404, message=response_messages.ErrorDoesNotExist.format(primary_key) ) for key, value in request_data: setattr(resource, key, value) resource.save() return self.response_json( data=model_to_dict(resource), status_code=200, message=response_messages.SuccessOk ) except Exception as e: log.error(traceback.print_exc()) return self.response_json( message=str(e), status_code=500 )
Example #14
Source File: db.py From restpie3 with MIT License | 5 votes |
def serialize(self): """Serialize the model into a dict.""" d = model_to_dict(self, recurse=False, exclude=self.EXCLUDE_FIELDS) d["id"] = str(d["id"]) # unification: id is always a string return d
Example #15
Source File: web.py From renrenBackup with MIT License | 5 votes |
def blog_detail_page(blog_id=0): blog = model_to_dict(Blog.get(Blog.id == blog_id)) if not blog: abort(404) extra = entry_comments_api(entry_id=blog_id) return render_template("blog.html", blog=blog, **extra)
Example #16
Source File: models.py From renrenBackup with MIT License | 5 votes |
def create_or_update(cls, data): ex_data = cls.get_or_none(**data) if ex_data: ex_data = model_to_dict(ex_data) ex_data.update(data) else: ex_data = data cls.insert(**ex_data).on_conflict_replace().execute() return cls.get_or_none(**ex_data)
Example #17
Source File: web.py From renrenBackup with MIT License | 5 votes |
def photo_detail_page(photo_id=0): photo = model_to_dict(Photo.get(Photo.id == photo_id)) if not photo: abort(404) extra = entry_comments_api(entry_id=photo_id) return render_template("photo.html", photo=photo, **extra)
Example #18
Source File: web.py From renrenBackup with MIT License | 5 votes |
def album_detail_page(album_id=0, page=0): if page <= 0: abort(404) album = model_to_dict(Album.get(Album.id == album_id)) if not album: abort(404) total_page = int(math.ceil(album['count']*1.0 / config.ITEMS_PER_PAGE)) extra = entry_comments_api(entry_id=album_id) photos = list(Photo.select().where(Photo.album_id == album_id) .order_by(Photo.pos).paginate(page, config.ITEMS_PER_PAGE).dicts()) return render_template("album.html", album=album, page=page, total_page=total_page, photos=photos, **extra)
Example #19
Source File: postgres.py From gordo with GNU Affero General Public License v3.0 | 5 votes |
def report(self, machine: GordoMachine): """ Log a machine to Postgres where top level keys, 'name', 'dataset', 'model', and 'metadata' mappings to BinaryJSON fields. Parameters ---------- machine: gordo.machine.Machine Returns ------- None """ try: with self.db.atomic(): logger.info(f"Inserting machine {machine.name} in sql") # type: ignore # Ensure it's serializable using MachineEncoder record = json.loads(json.dumps(machine.to_dict(), cls=MachineEncoder)) model = dict_to_model(Machine, record, ignore_unknown=True) try: Machine.get(Machine.name == machine.name) except peewee.DoesNotExist: model.save() else: query = Machine.update(**model_to_dict(model)).where( Machine.name == machine.name ) query.execute() except Exception as exc: raise PostgresReporterException(exc)
Example #20
Source File: __init__.py From slim with zlib License | 5 votes |
def to_dict(self): return model_to_dict(self)
Example #21
Source File: __init__.py From aioshadowsocks with GNU General Public License v3.0 | 5 votes |
def to_dict(self, **kw): return shortcuts.model_to_dict(self, **kw)
Example #22
Source File: __init__.py From fpage with Do What The F*ck You Want To Public License | 5 votes |
def to_dict(self): return model_to_dict(self)
Example #23
Source File: all.py From ray with MIT License | 5 votes |
def to_json(self): return model_to_dict(self, recurse=False)
Example #24
Source File: manage.py From hellogithub.com with GNU Affero General Public License v3.0 | 5 votes |
def search_project(): project_url = request.args.get('project_url', '') if project_url: try: content = Content.select()\ .where(Content.project_url == project_url)\ .get() return jsonify(payload=model_to_dict(content)) except DoesNotExist: return jsonify(message='未找到') else: raise InvalidParams()
Example #25
Source File: tools.py From hellogithub.com with GNU Affero General Public License v3.0 | 5 votes |
def models_to_dicts(query_models): dict_list = [] for query_model in query_models: dict_list.append(model_to_dict(query_model)) return dict_list
Example #26
Source File: views.py From PyPlanet with GNU General Public License v3.0 | 4 votes |
def get_data(self): if self.cache and self.advanced == self.cache_advanced: return self.cache data = list() local_app_installed = 'local_records' in self.app.instance.apps.apps karma_app_installed = 'karma' in self.app.instance.apps.apps for m in self.app.instance.map_manager.maps: map_dict = model_to_dict(m) map_dict['local_record_rank'] = None map_dict['local_record_score'] = None map_dict['local_record_diff'] = None map_dict['local_record_diff_direction'] = None map_dict['karma'] = None # Skip if in performance mode or advanced is not enabled. if self.app.instance.performance_mode or not self.advanced: data.append(map_dict) continue if local_app_installed: # Get personal local record of the user. map_locals = await self.app.instance.apps.apps['local_records'].get_map_record(m) rank, record = await self.app.instance.apps.apps['local_records'].get_player_record_and_rank_for_map(m, self.player) if isinstance(rank, int) and rank >= 1: map_dict['local_record_rank'] = int(rank) if record: map_dict['local_record_score'] = record.score if map_locals['first_record'] and record: map_dict['local_record_diff'] = record.score - map_locals['first_record'].score # TODO: Convert to new relation styles. if karma_app_installed and hasattr(m, 'karma'): map_dict['karma'] = m.karma['map_karma'] data.append(map_dict) self.cache = data self.cache_advanced = self.advanced return self.cache
Example #27
Source File: query.py From nni with MIT License | 4 votes |
def query_nds_trial_stats(model_family, proposer, generator, model_spec, cell_spec, dataset, num_epochs=None, reduction=None): """ Query trial stats of NDS given conditions. Parameters ---------- model_family : str or None If str, can be one of the model families available in :class:`nni.nas.benchmark.nds.NdsTrialConfig`. Otherwise a wildcard. proposer : str or None If str, can be one of the proposers available in :class:`nni.nas.benchmark.nds.NdsTrialConfig`. Otherwise a wildcard. generator : str or None If str, can be one of the generators available in :class:`nni.nas.benchmark.nds.NdsTrialConfig`. Otherwise a wildcard. model_spec : dict or None If specified, can be one of the model spec available in :class:`nni.nas.benchmark.nds.NdsTrialConfig`. Otherwise a wildcard. cell_spec : dict or None If specified, can be one of the cell spec available in :class:`nni.nas.benchmark.nds.NdsTrialConfig`. Otherwise a wildcard. dataset : str or None If str, can be one of the datasets available in :class:`nni.nas.benchmark.nds.NdsTrialConfig`. Otherwise a wildcard. num_epochs : float or None If int, matching results will be returned. Otherwise a wildcard. reduction : str or None If 'none' or None, all trial stats will be returned directly. If 'mean', fields in trial stats will be averaged given the same trial config. Returns ------- generator of dict A generator of :class:`nni.nas.benchmark.nds.NdsTrialStats` objects, where each of them has been converted into a dict. """ fields = [] if reduction == 'none': reduction = None if reduction == 'mean': for field_name in NdsTrialStats._meta.sorted_field_names: if field_name not in ['id', 'config', 'seed']: fields.append(fn.AVG(getattr(NdsTrialStats, field_name)).alias(field_name)) elif reduction is None: fields.append(NdsTrialStats) else: raise ValueError('Unsupported reduction: \'%s\'' % reduction) query = NdsTrialStats.select(*fields, NdsTrialConfig).join(NdsTrialConfig) conditions = [] for field_name in ['model_family', 'proposer', 'generator', 'model_spec', 'cell_spec', 'dataset', 'num_epochs']: if locals()[field_name] is not None: conditions.append(getattr(NdsTrialConfig, field_name) == locals()[field_name]) if conditions: query = query.where(functools.reduce(lambda a, b: a & b, conditions)) if reduction is not None: query = query.group_by(NdsTrialStats.config) for k in query: yield model_to_dict(k)
Example #28
Source File: query.py From nni with MIT License | 4 votes |
def query_nb101_trial_stats(arch, num_epochs, isomorphism=True, reduction=None): """ Query trial stats of NAS-Bench-101 given conditions. Parameters ---------- arch : dict or None If a dict, it is in the format that is described in :class:`nni.nas.benchmark.nasbench101.Nb101TrialConfig`. Only trial stats matched will be returned. If none, architecture will be a wildcard. num_epochs : int or None If int, matching results will be returned. Otherwise a wildcard. isomorphism : boolean Whether to match essentially-same architecture, i.e., architecture with the same graph-invariant hash value. reduction : str or None If 'none' or None, all trial stats will be returned directly. If 'mean', fields in trial stats will be averaged given the same trial config. Returns ------- generator of dict A generator of :class:`nni.nas.benchmark.nasbench101.Nb101TrialStats` objects, where each of them has been converted into a dict. """ fields = [] if reduction == 'none': reduction = None if reduction == 'mean': for field_name in Nb101TrialStats._meta.sorted_field_names: if field_name not in ['id', 'config']: fields.append(fn.AVG(getattr(Nb101TrialStats, field_name)).alias(field_name)) elif reduction is None: fields.append(Nb101TrialStats) else: raise ValueError('Unsupported reduction: \'%s\'' % reduction) query = Nb101TrialStats.select(*fields, Nb101TrialConfig).join(Nb101TrialConfig) conditions = [] if arch is not None: if isomorphism: num_vertices = infer_num_vertices(arch) conditions.append(Nb101TrialConfig.hash == hash_module(arch, num_vertices)) else: conditions.append(Nb101TrialConfig.arch == arch) if num_epochs is not None: conditions.append(Nb101TrialConfig.num_epochs == num_epochs) if conditions: query = query.where(functools.reduce(lambda a, b: a & b, conditions)) if reduction is not None: query = query.group_by(Nb101TrialStats.config) for k in query: yield model_to_dict(k)
Example #29
Source File: query.py From nni with MIT License | 4 votes |
def query_nb201_trial_stats(arch, num_epochs, dataset, reduction=None): """ Query trial stats of NAS-Bench-201 given conditions. Parameters ---------- arch : dict or None If a dict, it is in the format that is described in :class:`nni.nas.benchmark.nasbench201.Nb201TrialConfig`. Only trial stats matched will be returned. If none, architecture will be a wildcard. num_epochs : int or None If int, matching results will be returned. Otherwise a wildcard. dataset : str or None If specified, can be one of the dataset available in :class:`nni.nas.benchmark.nasbench201.Nb201TrialConfig`. Otherwise a wildcard. reduction : str or None If 'none' or None, all trial stats will be returned directly. If 'mean', fields in trial stats will be averaged given the same trial config. Returns ------- generator of dict A generator of :class:`nni.nas.benchmark.nasbench201.Nb201TrialStats` objects, where each of them has been converted into a dict. """ fields = [] if reduction == 'none': reduction = None if reduction == 'mean': for field_name in Nb201TrialStats._meta.sorted_field_names: if field_name not in ['id', 'config', 'seed']: fields.append(fn.AVG(getattr(Nb201TrialStats, field_name)).alias(field_name)) elif reduction is None: fields.append(Nb201TrialStats) else: raise ValueError('Unsupported reduction: \'%s\'' % reduction) query = Nb201TrialStats.select(*fields, Nb201TrialConfig).join(Nb201TrialConfig) conditions = [] if arch is not None: conditions.append(Nb201TrialConfig.arch == arch) if num_epochs is not None: conditions.append(Nb201TrialConfig.num_epochs == num_epochs) if dataset is not None: conditions.append(Nb201TrialConfig.dataset == dataset) if conditions: query = query.where(functools.reduce(lambda a, b: a & b, conditions)) if reduction is not None: query = query.group_by(Nb201TrialStats.config) for k in query: yield model_to_dict(k)
Example #30
Source File: manage.py From hellogithub.com with GNU Affero General Public License v3.0 | 4 votes |
def manage_volume(): """ 期数管理 """ if request.method == 'GET': volume_id = request.args.get('volume_id') if volume_id: volume_object = Volume.select()\ .where(Volume.id == volume_id)\ .get() return jsonify(payload=model_to_dict(volume_object)) else: volume_objects = Volume.select().order_by(Volume.name) return render_template('manage/volume.html', volumes=volume_objects, page_title=u'Vol.管理') # 新增 Vol. elif request.method == 'POST': volume_name = request.form.get('volume_name') if volume_name: try: Volume.create(name=volume_name) return jsonify(message=u'新增一期:{},成功'.format(volume_name)) except IntegrityError: raise ParamsConflict(message=u'新增一期失败:{} 已存在' .format(volume_name)) else: raise InvalidParams(message=u'新增一期失败:name 不能为空') # 更新 Vol. elif request.method == 'PATCH': volume_name = request.form.get('volume_name') volume_id = request.form.get('volume_id') if not volume_name: raise InvalidParams(message=u'更新 Vol. 失败:name 不能为空') else: try: Volume.update(name=volume_name, update_time=datetime.now())\ .where(Volume.id == volume_id)\ .execute() return jsonify(message=u'更新 Vol. {} 信息成功' .format(volume_name)) except IntegrityError: raise ParamsConflict(message=u'更新 Vol. 失败:{} 已存在' .format(volume_name)) # 删除 Vol. elif request.method == 'DELETE': volume_id = request.form.get('volume_id') volume_name = request.form.get('volume_name') try: content_query = Content.select()\ .join(Volume)\ .where(Volume.id == volume_id)\ .get() project_url = content_query.project_url raise InvalidParams(message=u'删除 Vol. 失败:{project_url}项目所属' u'于这个 Vol.,请先修改该项目期数' .format(project_url=project_url)) except DoesNotExist: Volume.delete().where(Volume.id == volume_id).execute() return jsonify(message=u'删除 Vol.:{},成功' .format(volume_name))