def get_projects(self, data):
        from misc import gen_fields

        print data

        data = json.loads(data)

        programs = data.get("programs", [])
        fields = data.get("fields", [])

        with db_session:
            if programs or fields:
                res = eval("select({0} for p in Project {1})".format(
                    gen_fields('p', fields),
                    "" if not programs else "if p.program in programs"))
            else:
                res = select(p for p in Project)

            _data = res[:] if programs or fields else res.first()
            if __debug__:
                print res.get_sql()
                print to_dict(_data)

            try:
                return json.dumps(dict(status="ok", data=to_dict(_data)))
            except Exception, e:
                return json.dumps(dict(status="fail", msg=e.message))
def select_speakers():
	print '\nSpeakers'
	print '--------------'
	countSpeakers =  Speaker.select().count()
	print '\nNumber speakers ' + str(countSpeakers)
	#The select() class method it returns all instances in the table.
	for speaker in select(speaker for speaker in Speaker):
		print to_dict(speaker)
		print speaker.name.encode('utf-8')
示例#3
0
 def read_user_cameras(user_id: int):
     user = models.User[user_id]
     data = to_dict(user.cameras)
     if data:
         return [value for key, value in data['Camera'].items()]
     else:
         return {}
示例#4
0
 def test1(self):
     s4 = Student[4]
     self.assertEqual(s4.group, None)
     d = to_dict(s4)
     self.assertEqual(d, dict(Student={
         4 : dict(id=4, name='S4', group=None, dob=None, gpa=None, scholarship=None, courses=[])
         }))
示例#5
0
 def user_transactions(self, *args, **kwargs):
     user_id = int(request.args.get('user_id'))
     if not User.get(id=user_id):
         abort(404)
     query = StockTransaction.select(lambda t: t.user_id.id == user_id
                                     and t.date == date.today())
     data = query[:]
     return convert_data(to_dict(data))
示例#6
0
def get_menu(restaurant_id):
    restaurant = Restaurant.select(lambda r: r.id == restaurant_id).first()

    if not restaurant:
        return '{"error": "There is no such restaurant"}', 400

    menu_items = (item for item in orm.select(mi for mi in MenuItem if mi.restaurant == restaurant))
    return serialization.to_dict(menu_items)
示例#7
0
def history(student_id):
    u = User.getBySid(str(student_id))
    h = to_dict(u.histories)
    return json.dumps({
        'result':True, 
        'user':u.to_dict(exclude='password'), 
        'history':h
        })
示例#8
0
文件: views.py 项目: aloari/flask-app
def person(person_id):
    try:
        person = Person[person_id]
        person = to_dict(person)
    except ObjectNotFound:
        msg = 'Person ID {} not found'.format(person_id)
        app.logger.info(msg)
        return jsonify(dict(detail=msg)), 404
    return jsonify(person), 200
示例#9
0
文件: api.py 项目: aloari/flask-app
def user(user_id):
    try:
        user = User[user_id]
        user = to_dict(user)
    except ObjectNotFound:
        msg = 'User ID {} not found'.format(user_id)
        app.logger.info(msg)
        return jsonify(dict(detail=msg)), 404
    return jsonify(user), 200
    def dictify(self):
        r_data = serialization.to_dict(self)
        reimbursement = r_data['TravelReimbursement'][self.id]

        reimbursement['status_text'] = self.status_text
        reimbursement['applied'] = reimbursement['applied'].isoformat()

        reimbursement['amount'] = 0.25 * self.distance

        return reimbursement
示例#11
0
def is_valid(checksum):

    artifact_dict = {"Artifactory": {}}
    artifact = Artifactory.select(
        lambda a: a.artifactChecksum == checksum).first()
    if (artifact == None):
        app.logger.info('artifact with checksum ' + checksum + ' is None')
    else:
        artifact_dict = to_dict(artifact)

    jenkins_dict = {"Jenkins": {}}
    jenkins = Jenkins.select(lambda j: j.artifactChecksum == checksum).first()
    if (jenkins == None):
        app.logger.info('jenkins is None for checksum:' + checksum)
    else:
        jenkins_dict = to_dict(jenkins)

    github_dict = {"Github": {}}
    github = None
    if (artifact != None):
        github = Github.select(
            lambda g: g.commitId == artifact.commitId).first()
        if (github == None):
            app.logger.info('github is None for commitid:' + artifact.commitId)
        else:
            github_dict = to_dict(github)

    rawData = jsonify(artifact_dict, jenkins_dict,
                      github_dict).get_data(as_text=True)

    application = Application(artifactoryOk=artifact != None,
                              jenkinsOk=jenkins != None,
                              githubOk=github != None,
                              rawData=rawData)

    if (artifact != None and github != None and jenkins != None):
        app.logger.info('all validations passed')
        return True
    else:
        app.logger.info('some validations failed')
        return False
示例#12
0
    def __start(self, program):
        print "Task: {0}\n".format(program)

        t = Template[program]
        if not t.is_running:
            return

        if t.numretry <= 0:
            t.is_running = 0
            return

        if __debug__:
            print to_dict(t)
        t.numretry -= 1
        self.timeout = t.timeout

        self.__start_callback(program)

        time.sleep(self.timeout)

        return True
示例#13
0
文件: app.py 项目: yobooooi/CICD
 def get(self, id):
     """
     GET method for the /user/<int:id> app route. This function looks up a user in the users list given the id
     in the context path of the URL
     :param id: The id in the context path of the URL, type integer
     :return: JSON response will be return either containing the data of the user to be looked up
     or an error stating that the user cannot be found
     """
     user = Person.get(id=id)
     if user is None:
         return {'error': 'user not found'}, 400
     else:
         return jsonify(to_dict(user))
示例#14
0
def borrowed(student_id):
    u = User.getBySid(str(student_id))
    r = to_dict(u.readings)['Reading']
    r = [r[b] for b in r]
    result = []
    for row in r:
        del row['user']
        result.append(row)
    return json.dumps({
        'result':True,
        'user':u.to_dict(exclude='password'),
        'readings':result
        })
 def response_status(code, data=None):
     try:
         status = dict(vars(HTTPStatus))['_value2member_map_'][code]
         return json(
             {
                 'status': status.phrase,
                 'description': status.description,
                 'code': status.value,
                 'data': to_dict(data) if type(data) == Query else data
             },
             status=status.value)
     except KeyError as e:
         print(e)
         return json({})
示例#16
0
文件: views.py 项目: aloari/flask-app
def create_person():
    data = request.get_json()
    try:
        with db_session:
            person = Person(name=data.get('name'),
                            city=data.get('city'),
                            phone=data.get('phone'))
    except Exception as err:
        app.logger.info(
            'There was an error trying to create a person: {}'.format(
                repr(err)))
        return jsonify(status='ko'), 404
    person = to_dict(person)
    app.logger.info('Person created successfully: {}'.format(person))
    return jsonify(person), 201
示例#17
0
 def test1(self):
     s4 = Student[4]
     self.assertEqual(s4.group, None)
     d = to_dict(s4)
     self.assertEqual(
         d,
         dict(
             Student={
                 4:
                 dict(id=4,
                      name='S4',
                      group=None,
                      dob=None,
                      gpa=None,
                      scholarship=None,
                      courses=[])
             }))
示例#18
0
 def populate_lines(self, id):
     date_from = request.args.get('date_from', '1970-01-01')[:10]
     date_to = request.args.get('date_to', str(datetime.date.today()))[:10]
     if Stock.get(id=id):
         stock = Stock[id]
         history_dict = ystockquote.get_historical_prices(stock.code, date_from, date_to)
         for date, values in history_dict.items():
             new_vals = {
                 'date': date, 'volume': values['Volume'], 'high': values['High'],
                 'low': values['Low'], 'open': values['Open'], 'close': values['Close']
             }
             if not StockHistory.get(stock=stock, date=date):
                 stock.history_lines.create(**new_vals)
             else:
                 StockHistory.get(stock=stock, date=date).set(**new_vals)
         return convert_stocks(to_dict(Stock[id]))
     abort(404)
示例#19
0
文件: api.py 项目: aloari/flask-app
def update_user(user_id):
    data = request.get_json()
    try:
        validate_data(data, 'user')
    except ValidationError as err:
        return jsonify(dict(detail=err.message))
    try:
        user = User[user_id]
        user.set(**data)
        user = to_dict(user)
        db.commit()
        app.logger.warning('User "{}" updated successfully'.format(user_id))
        return jsonify(user), 200
    except Exception as err:
        app.logger.warning(
            'There was an error trying to update the user "{}": {}'.format(
                user_id, repr(err)))
        return jsonify(dict(detail='Invalid format')), 404
def resolve_result(result, modelName):
    result = to_dict(result)
    model = get_model(modelName)
    if len(model.Meta.collections) > 0:
        try:
            instances = result[modelName]
        except KeyError as e:
            return []
        for instanceKey, instance in instances.items():
            instance.pop('Password', None)  # remove password field if exists
            for attr, mapping in model.Meta.collections:
                for i in range(0, len(instance[attr])):
                    key = instance[attr].pop(0)
                    result[mapping][key].pop(
                        'Password', None)  # remove password field if exists
                    instance[attr].append(result[mapping][key])

    return list(result[modelName].values())
    def dictify(self):
        r_data = serialization.to_dict(self)
        reimbursement = r_data['CostReimbursement'][self.id]
        explanations = r_data['Explanation']
        receipts = r_data.get('Receipt', [])

        reimbursement['receipts'] = [
            receipts[uuid] for uuid in reimbursement['receipts']
        ]
        reimbursement['explanations'] = [
            explanations[uuid] for uuid in reimbursement['explanations']
        ]
        reimbursement['status_text'] = self.status_text
        reimbursement['applied'] = reimbursement['applied'].isoformat()

        reimbursement['amount'] = sum(
            e['amount'] for e in reimbursement['explanations']
        )
        return reimbursement
示例#22
0
文件: api.py 项目: aloari/flask-app
def create_user():
    data = request.get_json()
    try:
        validate_data(data, 'user')
    except ValidationError as err:
        return jsonify(dict(detail=err.message))
    user = User(username=data.get("username"),
                email=data.get("email"),
                age=data.get("age"),
                phone=data.get("phone"),
                location=data.get("location"))
    try:
        db.commit()
        app.logger.info('User "{}" created successfully'.format(user.username))
        user = to_dict(user)
        return jsonify(user), 201
    except Exception as err:
        db.rollback()
        app.logger.info(
            'There was an error trying to create an user: {}'.format(
                repr(err)))
        return jsonify(dict(detail='Invalid format')), 404
示例#23
0
文件: api.py 项目: aloari/flask-app
def search():
    search_name = request.args.get('keyword')
    users = User.select(lambda u: search_name in u.username)
    users = to_dict(users)
    return jsonify(users), 200
示例#24
0
 def post(self):
     data = request.get_json(force=True)
     tag = Tag(**data)
     print(to_dict(tag))
示例#25
0
文件: api.py 项目: aloari/flask-app
def users():
    users = User.select().order_by(User.updated_at)
    users = to_dict(users)
    return jsonify(users), 200
示例#26
0
 def read(id: int) -> schemas.Camera:
     db_camera = models.Camera[id]
     data = to_dict(db_camera)['Camera'][id]
     return schemas.Camera(**data)
示例#27
0
 def read_by_connection_string(connection_string: str):
     db_camera = models.Camera.get(connection_string=connection_string)
     data = to_dict(db_camera)['Camera'][db_camera.id]
     return schemas.Camera(**data)
示例#28
0
 def get(self):
     stock_select = Stock.select()
     stocks = to_dict(stock_select)
     # Cast date in string
     return convert_stocks(stocks)
示例#29
0
def risks():
    #response = Response('[{"id": 1, "name": "Paraglider", "description": "Need to protect my investment on flying", "values": [2, 3, 5]},{"id": 2, "name": "Boat", "description": "a lot of money invested on it", "values": [1, 4]}]', 200)
    risks = select(r for r in Risk)[:]
    response = Response(json.dumps(to_dict(risks)['Risk']), 200)
    return response
示例#30
0
 def read(id: int) -> schemas.User:
     db_user = models.User[id]
     data = to_dict(db_user)['User'][id]
     return schemas.User(**data)
示例#31
0
 def get(self, id):
     # stock_dict = {'Stock':{}}
     # stock_dict.update(Stock=Stock[id].to_dict(with_collections=True))
     return convert_stocks(to_dict(Stock[id]))
示例#32
0
 def read_by_email(email: str) -> schemas.User:
     db_user = models.User.get(email=email)
     data = to_dict(db_user)['User'][db_user.id]
     return schemas.User(**data)
示例#33
0
 def read_all() -> List[schemas.User]:
     users = models.User.select()[:]
     data = [to_dict(u)['User'][u.id] for u in users]
     user_list = [schemas.User(**d) for d in data]
     return user_list
示例#34
0
 def getProfile(self):
     user = request.args.get('email')
     userProfile = Profile.get(email_user=user)
     return to_dict(userProfile)["Profile"][1]