def create_task(): print "Inserting Task" if not request.json or not 'title' in request.json: abort(400) task = Task.create(title=request.json['title'], done=False, lastModified=request.json.get('lastModified', "")) print "Saving", model_to_dict(task) return jsonify({'task': model_to_dict(task)}), 201
def _cell_to_dict(cell): kv = model_to_dict(cell) kv['nodes'] = [] for cnode in cell.nodes: cn_kv = model_to_dict(cnode) cn_kv['node'] = cn_kv['node']['id'] del cn_kv['cell'] kv['nodes'].append(cn_kv) return kv
def nodes(): _data = {} Parent = Category.alias() query = (Category .select(Category, Category.parent.alias('parent_id'), Parent.parent.alias('parent_id')) .join(Parent, JOIN.LEFT_OUTER, on=(Category.parent == Parent.id))) g1, g2, g3 = list(), list(), list() for category in query: if not category.parent_id: g1.append(category) elif not category.parent.parent_id: g2.append(category) else: g3.append(category) for c in g1: d = model_to_dict(c, recurse=False, exclude=[Category.parent]) d['count'] = 0 d['children'] = {} _data[c.id] = d for c in g2: d = model_to_dict(c, recurse=False, exclude=[Category.parent]) d['count'] = 0 d['children'] = [] _data[c.parent_id]['children'][c.id] = d subquery = Course.select(fn.COUNT(Course.id)).where(Course.category == Category.id) query = (Category .select(Category, Category.parent.alias('parent_id'), Parent.parent.alias('parent_id'), subquery.alias('course_count')) .join(Parent, JOIN.LEFT_OUTER, on=(Category.parent == Parent.id)) .where(Category.id << g3)) for category in query: d = model_to_dict(category, recurse=False, exclude=[Category.parent, Category.name]) d['label'] = '%s(%d)' % (category.name, category.course_count) ancestor = _data[category.parent.parent_id] parent = ancestor['children'][category.parent_id] parent['children'].append(d) parent['count'] += category.course_count ancestor['count'] += category.course_count data = list(_data.values()) for c1 in data: c1['label'] = '%s(%d)' % (c1['name'], c1['count']) del (c1['name']) c1['children'] = list(c1['children'].values()) for c2 in c1['children']: c2['label'] = '%s(%d)' % (c2['name'], c2['count']) del (c2['name']) response = make_response(json.dumps(data, ensure_ascii=True)) response.mimetype = 'application/json' return response
def setting_user(): rtn = dict() rtn["selectedMenu"] = "Users" rtn["accounts"] = [ model_to_dict(a, False, only=[Account.id, Account.name]) for a in Account.select().where(Account.fk_user == session["id"]) ] rtn["myProfile"] = model_to_dict(User.get(User.id == session["id"])) rtn["newUser"] = dict() return rtn
def read_skeleton(self, *args, **kwargs): """Retrieve a record""" key = kwargs[self.pk_n] if self.pk_n in kwargs else args[0] if len(args) > 0 else None if key: x = self.model.get(self.model._meta.fields[self.pk_n] == key) result = {self.base: model_to_dict(x)} else: x = self.model.select() result = {self.base: [model_to_dict(r) for r in x]} return {self.base: result}
def inject_menu(): if is_login(): accountsList = [dict(model_to_dict(x, False, only=[Bank.id,Bank.name]), \ **{'accounts':[model_to_dict(y, only=[Account.id, Account.name]) \ for y in x.accounts.select(Account.id, Account.name).where(Account.fk_user == session['id'])]}) \ for x in Bank.select(Bank.id,Bank.name).distinct().join(Account).where(Account.fk_user == session['id'])] envelopesList = [model_to_dict(x, only=[Envelope.id, Envelope.name]) \ for x in Envelope.select(Envelope.id, Envelope.name)] return dict(accountsList=accountsList, envelopesList=envelopesList) return dict()
def on_post(self, req, resp): try: user_dict = json.loads(req.stream.read().decode()) except ValueError: user = md.User(id=-1) resp.body = json.dumps(ps.model_to_dict(user)) else: # Don't recreate if already existing... user = md.User.create(name=user_dict.get("name", "")) resp.body = json.dumps(ps.model_to_dict(user))
def showUsers(): # if 'name' parameter is presented then we query by name # otherwise we return all records if (request.form.get('name')): name = request.form.get('name') user = User.get(User.username == name) return json.dumps(model_to_dict(user)) else: users = [] for user in User.select(): users.append(model_to_dict(user)) return json.dumps(users)
def converter(self, obj): if isinstance(obj, datetime.time) or isinstance(obj, datetime.date) or isinstance(obj, datetime.datetime): return obj.isoformat() if isinstance(obj, set): return list(obj) if isinstance(obj, peewee.Model): return model_to_dict(obj) if isinstance(obj, models.MySQLModel): # TODO: I don't understand this, because it doesn't work return model_to_dict(obj) logging.warning("Converter doesn't know how convert data (%s [%s])" % (obj, type(obj))) return None
def setting_bank(b_id=None): rtn = dict() rtn['selectedMenu'] = "Banks" rtn['editBank'] = None if b_id is not None: rtn['editBank'] = dict(id=0, name='') if b_id != 0: try: rtn['editBank'] = dict_to_inline(model_to_dict(Bank.get(Bank.id==b_id))) except: pass rtn['banks'] = [dict_to_inline(model_to_dict(x, False)) for x in list(Bank.select())] return rtn
def setting_mode(m_id=None): rtn = dict() rtn['selectedMenu'] = "Modes" rtn['editMode'] = None if m_id is not None: rtn['editMode'] = dict(id=0, name='') if m_id != 0: try: rtn['editMode'] = dict_to_inline(model_to_dict(Mode.get(Mode.id==m_id))) except: pass rtn['modes'] = [dict_to_inline(model_to_dict(x, False)) for x in list(Mode.select())] return rtn
def setting_payee(p_id=None): rtn = dict() rtn['selectedMenu'] = "Payees" rtn['editPayee'] = None if p_id is not None: rtn['editPayee'] = dict(id=0, name='') if p_id != 0: try: rtn['editPayee'] = dict_to_inline(model_to_dict(Payee.get(Payee.id==p_id))) except: pass rtn['payees'] = [dict_to_inline(model_to_dict(x, False)) for x in list(Payee.select())] return rtn
def setting_account(a_id=None): rtn = dict() rtn['selectedMenu'] = "Accounts" rtn['banks'] = [dict_to_inline(model_to_dict(x, False)) for x in Bank.select()] rtn['editAccount'] = None if a_id is not None: rtn['editAccount'] = dict(id=0, name='') if a_id != 0: try: rtn['editAccount'] = dict_to_inline(model_to_dict(Account.get((Account.id==a_id) & (Account.fk_user==session['id'])))) except: pass rtn['accounts'] = [dict_to_inline(model_to_dict(x, False)) for x in Account.select().where(Account.fk_user==session['id'])] return rtn
def raw_data(): """ Gets raw data for pokemons/gyms/pokestops via REST """ pokemons, gyms, pokestops = [], [], [] for pokemon in Pokemon.select(): pokemons.append(model_to_dict(pokemon)) for gym in Gym.select(): gyms.append(model_to_dict(gym)) for pokestop in Pokestop.select(): pokestops.append(model_to_dict(pokestop)) return flask.jsonify( pokemons=pokemons, gyms=gyms, pokestops=pokestops )
def m2d(models): """ model to dict :param models: list or peewee Model :return: dict list or dict or None """ try: if models: result = model_to_dict(models) else: result = {} except: result = [model_to_dict(m) for m in models] return result
def list_to_dict(models): ''' Converts a list of models to dictionarys which can be converted to json. ''' model_list = {'items': []} if not isinstance(models, list): model_list['items'].append(model_to_dict(models, backrefs=True)) else: for model in models: model_list['items'].append(model_to_dict(model, backrefs=True)) return model_list
def get_weektasks(user_id, year, month_num, week_num): weektasks_query = get_weektasks_query(user_id, year, month_num, week_num) weektasks = DefaultListOrderedDict() for wt in weektasks_query: # for wt in wts: weektasks[wt.category_id].append(model_to_dict(wt)) return weektasks
def to_dict(self, recurse=False, backrefs=False, only=None, exclude=None, seen=None): """ Convert a model instance (and any related objects) to a dictionary. **Parameters** :param recurse: Whether foreign-keys should be recursed. Defaults to `False`. :param backrefs: Whether lists of related objects should be recursed. Defaults to `False`. :param only: A list (or set) of field instances indicating which fields should be included. Defaults to `None`. :param exclude: A list (or set) of field instances that should be excluded from the dictionary. Defaults to `None`. :param seen: Internally used. Defaults to `None`. :type recurse: bool :type backrefs: bool :type only: list :type exclude: list """ return model_to_dict(self, recurse, backrefs, only, exclude, seen)
def to_dict(self): model_dict = model_to_dict(self, backrefs=False, recurse=False) model_dict = dict_datetime_to_timestamp(model_dict) for field in self._meta.sorted_fields: if isinstance(field, peewee.ForeignKeyField): model_dict.pop(field.name) return model_dict
def default_json_format(obj): """Default JSON serializer.""" if isinstance(obj, datetime.datetime): obj = str(obj) if isinstance(obj, int): obj = str(obj) if isinstance(obj, datetime.date): obj = str(obj) if obj.__class__.__name__ == "Order": return model_to_dict(obj, recurse=False) if obj.__class__.__name__ == "Shop": return model_to_dict(obj, recurse=False) if obj.__class__.__name__ == "Address": return model_to_dict(obj, recurse=False) return obj
def getAllWhiskies(self, currentPage, itemsPerPage, sortField='name'): ''' Get all whiskies - paged. First page returned is 1 (not 0)''' self.logger.debug("Requesting page %d from allWhiskies", currentPage) # Cap itemsPerPage at 100 if itemsPerPage > 100: self.logger.warn("Requested %d itemsPerPage exceeded max of 100", itemsPerPage) itemsPerPage = 100 sf = None if sortField == 'name' : sf = peewee_models.Whiskey.name elif sortField == 'price' : sf = peewee_models.Whiskey.price elif sortField == 'proof' : sf = peewee_models.Whiskey.proof elif sortField == 'style' : sf = peewee_models.Whiskey.style elif sortField == 'age' : sf = peewee_models.Whiskey.age else : sf = peewee_models.Whiskey.name whiskies = [] self.db.connect() for whiskey in peewee_models.Whiskey.select(peewee_models.Whiskey.name, peewee_models.Whiskey.price, peewee_models.Whiskey.proof, peewee_models.Whiskey.style, peewee_models.Whiskey.age, peewee_models.Whiskey.icon, peewee_models.Whiskey.url).order_by(sf).paginate(currentPage, itemsPerPage): whiskies.append(model_to_dict(whiskey)) self.db.close self.logger.debug("Returning whiskies: %s", simplejson.dumps(whiskies)) return simplejson.dumps(whiskies)
def on_get(self, req, resp, datatype=None): if datatype == "0": stats = models_stats.Sumario.select().first() response = model_to_dict(stats) resp.body = json.dumps(response, cls=JSONEncoderPlus, sort_keys=True) elif datatype == "1": gasto_organismos = models_stats.MinisterioOrganismoMonto.select( models_stats.MinisterioOrganismoMonto.nombre_ministerio.concat("-") .concat(models_stats.MinisterioOrganismoMonto.nombre_organismo) .alias("nombre"), cast(models_stats.MinisterioOrganismoMonto.monto, "bigint").alias("monto"), ).order_by(peewee.SQL("nombre")) output = BytesIO() csvwriter = csv.writer(output, encoding="utf-8") for go in gasto_organismos.tuples(): csvwriter.writerow(go if len(go) == 4 else go + ("null", "null")) resp.content_type = "text/csv" output.seek(0) resp.stream = output else: raise falcon.HTTPNotFound()
def put(self, request): person = self._get_person(request) person_dict = yield from request.json() person.name = person_dict['name'] person.email = person_dict['email'] person.save() return model_to_dict(person)
def query_by_code(code): try: event = Event.get(Event.code == code) result = shortcuts.model_to_dict(event) except peewee.DoesNotExist: result = {} return result
def pull_user_info(openid, web_access_token=None): if web_access_token: pull_user_info_url = wxconfig.pull_user_info_url.format(web_access_token, openid) http_client = AsyncHTTPClient() response = yield http_client.fetch(pull_user_info_url) logging.debug(response.body.decode()) user_dict = json.loads(response.body.decode()) user = dict_to_model(User, user_dict, ignore_unknown=True) else: user = User(openid='openid') user_id = None try: _user = dbutil.do(User.get, User.openid == openid) user_id = _user.get_id() exists = True except DoesNotExist: exists = False if exists: assert user_id user.set_id(user_id) user.updatetime = datetime.datetime.now() else: user.createtime = datetime.datetime.now() yield dbutil.do(user.save) user = yield dbutil.do(User.get, User.openid == openid) return model_to_dict(user)
def get_user_info(openid): id = None try: _user = yield dbutil.do(User.get, User.openid == openid) id = _user.get_id() except DoesNotExist: pass access_token = yield get_access_token() get_user_info_url = wxconfig.get_user_info_url.format(access_token, openid) http_client = AsyncHTTPClient() response = yield http_client.fetch(get_user_info_url) result = json.loads(response.body.decode()) logging.debug(result) try: # 未关注微信号时,会出错 result['errcode'] except Exception: user = dict_to_model(User, result, ignore_unknown=True) if id: user.set_id(id) user.updatetime = datetime.datetime.now() else: user.createtime = datetime.datetime.now() # yield dbutil.do(user.save) return model_to_dict(user) logging.error('拉取用户信息出错:{0}'.format(result))
def _dict(self, delete_empty=True, **kwargs): # Experimental kwargs['recurse'] = kwargs.get('recurse', False) d = model_to_dict(self, **kwargs) if delete_empty: d = { k: v for k, v in d.items() if v is not None } return d
def get_monthtasks(user_id, year, month_num): monthtasks = DefaultListOrderedDict() monthtasks_query = get_monthtasks_query(user_id, year, month_num) for mt in monthtasks_query: # for mt in mts: monthtasks[mt.category_id].append(model_to_dict(mt)) return monthtasks
def delete_skeleton(self, *args, **kwargs): """Delete an existing record""" key = kwargs[self.pk_n] if self.pk_n in kwargs else args[0] if len(args) > 0 else None error = False error_messages = [] try: x = self.model.get(self.model._meta.fields[self.pk_n] == key) x.delete_instance() except DoesNotExist: error = True error_messages.append({ "message": "{0} with key: {1} was not found".format(self.model.__name__, key), "code": 404 }) except IntegrityError: error = True error_messages.append({ "message": "{0} with key: {1} could not be deleted".format(self.model.__name__, key), "code": 404}) # if not error: message = {"success": "deleted entry", "model": model_to_dict(x)} else: message = {"errors": error_messages} # return {self.base: message}
def createUser(): # if 'name' parameter is presented then we query by name # otherwise we return all records if (request.form.get('name') and request.form.get('phone')): user = User.create(username=request.form.get('name'), phoneNumber=request.form.get('phone')) return json.dumps(model_to_dict(user)) else: return 'Please supply phone and name parameters'
async def get(self, request, item_id): data = ShanghaiPersonInfo.get(id=item_id) return json(model_to_dict(data))
def as_dict(self): d = model_to_dict(self, recurse=False, exclude=[Label.id]) d["user"] = self.user.name return d
def to_dict(self): return model_to_dict(self, recurse=True, only=self._visible_fields)
def accounts_get(id): account = Account.get_or_none(id) if account is None: return abort(404) return jsonify(model_to_dict(account))
def transactions_get(id): transaction = Transaction.get_or_none(id) if transaction is None: return abort(404) return jsonify(model_to_dict(transaction))
def get(self): data = ShopService.getAll() return {'shops': [model_to_dict(item) for item in data]}
def get(self): data = UserService.getAll() return {'users': [model_to_dict(item) for item in data]}
def __str__(self): return str(model_to_dict(self))
def get_bookings_of_user(user_name): query = Booking.select().where(Booking.who==user_name) user_bookings = [model_to_dict(c) for c in query] return user_bookings
def register(): """ eg = { "username": "******", "password": "******", "name": "陈炳蔚", "phone": 15988731660, "school": "浙江大学", "student_id": "12358", "identify_number": "30032323232322" "openid": "o48xV1b3vqrGQgGX--UrLACbmbHY" } "username": "******", "password": "******", "name": "Ren", "phone": 15701683747, "school": "浙江大学", "student_id": "00001", "identify_number": "3003232323232211" :return: :rtype: """ data = request.get_json() username = data.pop('username') password = data.pop('password') if username is None or password is None: return jsonify({'response': 'invalid user or password'}), 400 try: added_user = user_service.add( username=username, password=password, name=data.pop("name"), school=data.pop("school"), student_id=data.pop("student_id"), phone=data.pop("phone"), identify_number=data.pop("identify_number"), # 注释项 是可选项 we_chat_id=data.pop("openid"), # account=data.pop("account"), # account_type=data.pop("account_type"), **data) added_user = model_to_dict(added_user) added_user.pop('password') return jsonify({'response': added_user}), 200 except Error: return jsonify({'response': { "message": "xxx", "error": Error, }}), 400 except Exception as e: print(e) error = e.args[1] message = "字段错误" if "PRIMARY" in error: message = "用户名已存在" if "user_identify_number" in error: message = "身份证号码重复" if "phone" in error: message = "手机号码重复" return jsonify({'response': { "message": message, "error": error, }}), 400
async def get(self) -> Dict: """Games list get method.""" games = await Game.manager.execute(Game.select()) return {'games': [model_to_dict(game) for game in games]}
def get_user_info(): username = get_jwt_identity() user = user_service.get(username=username) user = model_to_dict(user, recurse=False) user.pop("password") return jsonify({'response': user}), 200
def event(id): try: return model_to_dict(Event.get(Event.id == id)) except DoesNotExist: return "Event not found", 404
def get(idx: int) -> [dict, None]: image = ImageModel.get_or_none(id=idx) if image: return model_to_dict(image) return
def get(self): data = ProductService.getAll() return {'products': [model_to_dict(item) for item in data]}
def to_dict(self): return model_to_dict(self)
def get(self, product_id): data = ProductService.getById(product_id) return {'data': [model_to_dict(item) for item in data]}
# API api = RestAPI(app) api.register(ExploreCard) << << << < HEAD @ app.route('/db/explorecard/', methods=['GET']) @ app.route('/db/explorecard/<id>', methods=['GET']) def get_items(id=None): if id: return jsonify(ExploreCard.get(ExploreCard.id == id)) else: cards = [] for card in ExploreCard.select(): cards.append(model_to_dict(person)) cards = [] for card in ExploreCard.select(): cards.append(model_to_dict(person)) return jsonify(cards) @ app.route('/db/explorecard/name/', methods=['GET']) @ app.route('/db/explorecard/name/<name>', methods=['GET']) def get_items(name=None): if name: return jsonify(ExploreCard.get(ExploreCard.name == name)) else: cards = [] for card in ExploreCard.select(): cards.append(model_to_dict(person))
def get(self, shop_id): data = ShopService.getById(shop_id) return {'data': [model_to_dict(item) for item in data]}
def __str__(self): return json.dumps(model_to_dict(self), indent=2, default=json_serial)
def get(self, user_id): data = UserService.getById(user_id) return {'data': [model_to_dict(item) for item in data]}
def get_small_data(self): return model_to_dict(self, recurse=False, backrefs=False)
def accounts(): accounts = [] for account in Account.select(): accounts.append(model_to_dict(account)) return jsonify(accounts)
def to_dict(self, recurse=False, backrefs=False): return model_to_dict( self, recurse=recurse, backrefs=backrefs, exclude=[Category.updated_at, Category.created_at])
def as_dict(self): return model_to_dict( self, recurse=False, exclude=[Note.room, Note.location, Note.user] )
def get(self): args = request.args data = ProductService.find(args['q']) return {'products': [model_to_dict(item) for item in data]}
def podcasts(): """ Retreive all podcasts """ response = [model_to_dict(x) for x in Podcast.select()] return json.dumps(response, cls=DateTimeEncoder)
def get(self): args = request.args data = ShopService.find(args['q']) return {'shops': [model_to_dict(item) for item in data]}
def to_dict(self, **kw): return shortcuts.model_to_dict(self, **kw)
def disciplinas(professor): return [model_to_dict(disciplina) for disciplina in Disciplina.select().where(Disciplina.professor == professor)]