示例#1
0
def myInfo():
    user = app.apictx.getUser()
    if user == None: raise UnauthorizedAccessError()
    minfo = {}
    for fn in ('username', 'email', 'first_name', 'last_name'):
        minfo[fn] = getattr(user, fn)
    return apiresponse({'record': minfo})
示例#2
0
def todos():
    user = app.apictx.getUser()
    if user == None: raise UnauthorizedAccessError()
    (order_by,
     order_asc) = orderByValidate(request.args.get('order_by',
                                                   'id, asc'), 'order_by',
                                  ('title', 'id', 'created_at'), Todo)
    ints = intsValidate(
        request.args,
        (IntColumnDef('offset', 0, 0, None), IntColumnDef(
            'limit', 10, 1, 1000), IntColumnDef('checked', -1, 0, 1)))
    filter_by_extra = {}
    if ints['checked'] != -1:
        filter_by_extra['checked'] = ints['checked']
    with app.apictx.dbsession_scope() as dbs:
        items = dbs.query(Todo) \
           .filter_by(owner_id=user.id, **filter_by_extra) \
           .order_by(order_by.asc() if order_asc else order_by.desc()) \
           .offset(ints['offset']).limit(ints['limit'])
        count = dbs.query(Todo) \
           .filter_by(owner_id=user.id, **filter_by_extra) \
           .count()
        return apiresponse({
            'records': [jsonFromRecord(i, todo_columns) for i in items],
            'count':
            count
        })
示例#3
0
def todoDelete(todo_id):
    user = app.apictx.getUser()
    if user == None: raise UnauthorizedAccessError()
    with app.apictx.dbsession_scope() as dbs:
        todo = dbs.query(Todo).filter_by(owner_id=user.id, id=todo_id).first()
        if todo == None:
            raise HttpApiError("The todo item does not exists!", 404)
        dbs.delete(todo)
    return apiresponse({})
示例#4
0
def todo(todo_id):
    if request.method == 'DELETE':
        return todoDelete(todo_id)
    user = app.apictx.getUser()
    if user == None: raise UnauthorizedAccessError()
    dbs = app.apictx.dbsession()
    try:
        item = dbs.query(Todo).filter_by(owner_id=user.id, id=todo_id).one()
        return apiresponse({'record': jsonFromRecord(item, todo_columns)})
    except MultipleResultsFound:
        raise Exception("Panic!, Multiple value for filter pk is not allowed")
    except NoResultFound:
        raise HttpApiError("The todo item does not exists!", 404)
    finally:
        dbs.close()
示例#5
0
def register():
    udata = {}
    # required paramters
    # also check limit
    udata = simpleValidate(request.form, User, \
      ('username', 'password', 'first_name', 'last_name', 'email'))
    emailValidate(udata['email'])
    # check username availability
    with app.apictx.dbsession_scope() as dbs:
        if dbs.query(User).filter_by(username=udata['username']).count() > 0:
            raise HttpInputError("Username is not available!")
        salt = bcrypt.gensalt()
        udata['password'] = bcrypt.hashpw(udata['password'].encode('UTF-8'),
                                          salt).decode('UTF-8')
        user = User(**udata)
        dbs.add(user)
    return apiresponse({})  # no need to send id
示例#6
0
def todoCreate():
    user = app.apictx.getUser()
    if user == None: raise UnauthorizedAccessError()
    data = simpleValidate(request.form, Todo, ('title', ))
    ints = intsValidate(request.form, [IntColumnDef('checked', 0, 0, 1)])
    data['checked'] = ints['checked']
    data['owner_id'] = user.id
    data['created_at'] = sqlfunc.current_timestamp()
    data['description'] = request.form.get('description', '')
    if 'image' in request.files:
        uploadImageValidate(request.files['image'])
    with app.apictx.dbsession_scope() as dbs:
        todo = Todo(**data)
        dbs.add(todo)
        dbs.commit()
        if 'image' in request.files:
            f = request.files['image']
            (fbasename, fext) = os.path.splitext(secure_filename(f.filename))
            ffn = todoMkImageFN(todo, fext)
            image_path = '%s/%s' % (UPLOAD_PATH, ffn)
            f.save(image_path)
            todo.image = ffn
        return apiresponse({'id': todo.id})
示例#7
0
def login():
    for cn in ('username', 'password'):
        val = request.form.get(cn, '')
        if len(val) == 0:
            raise HttpInputError("`%s' is required" % cn)
    dbs = app.apictx.dbsession()
    try:
        user = dbs.query(User).filter_by(
            username=request.form['username']).one()
        try:
            if bcrypt.checkpw(request.form['password'].encode('UTF-8'),
                              user.password.encode('UTF-8')):
                session['user_id'] = user.id
                return apiresponse({})
        except ValueError:
            pass
    except MultipleResultsFound:
        raise Exception("Panic!, Multiple username is not allowed")
    except NoResultFound:
        pass
    finally:
        dbs.close()
    raise HttpApiError("Username or Password are not correct", 403)
示例#8
0
def logout():
    session.pop('user_id', None)
    return apiresponse({})