def delete(self, url): parser = RequestParser() parser.add_argument(arg_token) args = parser.parse_args() if not args['token']: return error('notoken'), 403 user = User.query.filter_by(token=args['token']).first() if not user: return error('wrongtoken'), 403 res = do_delete_image(user, url) if res == 'success': return {'status': 'success'} else: return error(res), 403
class UserCreate(Resource): def __init__(self): self.reqparse = RequestParser() self.reqparse.add_argument( 'user', type = username, required = True, location = 'json' ) self.reqparse.add_argument( 'key', type = pubkey, required = True, location = 'json' ) super(UserCreate, self).__init__() def post(self): args = self.reqparse.parse_args() try: p.add_user( username=str(args['user']), pubkey=args['key'], hostname='va1.hashbang.sh' ) except ldap.SERVER_DOWN: return { 'message': 'Unable to connect to LDAP server'}, 400 except ldap.ALREADY_EXISTS: return { 'message': 'User already exists'}, 400 except: sys.stderr.write("Unexpected Error: %s\n" % sys.exc_info()[0]) return { 'message': 'User creation script failed'}, 400 return {'message': 'success'}
def post(self): # parse incoming POST data reqparse = RequestParser() reqparse.add_argument('blob', type=str, location='json') data = reqparse.parse_args() if not data.blob: return self.argument_required('blob') # encode content as bytestring tmp = base64.b64decode(data.blob) # calculate sha1 digest digest = hashlib.sha1(tmp).hexdigest() # write into temp file f = TemporaryFile() _ = f.write(tmp) f.flush() _ = f.seek(0) # upload blob created = self.blob_container.put(f, digest=digest) # response json and status code code = created and 201 or 409 response = dict( digest = digest, url = '/image/{0}'.format(digest) ) return response, code
def get(self): parser = RequestParser() parser.add_argument(arg_token) parser.add_argument('with_uploads', type=int, location='args') args = parser.parse_args() if not args['token']: return error('notoken'), 403 user = User.query.filter_by(token=args['token']).first() if not user: return error('wrongtoken'), 403 res = { 'name': user.name, 'email': user.email, 'profile_image_url': user.profile_image_url, 'uploads_count': user.uploads.count() } if args['with_uploads'] == 1: uploads = [] for upload in user.uploads: uploads.append({ 'type': upload.object.__tablename__, 'url': { 'page': BASE_URL % upload.url, 'direct': upload.direct_url }, 'title': upload.title, 'desc': upload.desc, 'upload_at': upload.time.strftime('%s'), 'view_count': upload.view_count, 'properties': upload.object.prop }) res['uploads'] = uploads return success({'user': res})
def post(self): parser = RequestParser() parser.add_argument(arg_token) parser.add_argument('file', type=FileStorage, location='files') parser.add_argument('desc', type=unicode, location='form') args = parser.parse_args() f = args['file'] user = args['token'] if user: user = User.query.filter_by(token=user).first() if not user: return error('wrongtoken'), 403 if not f: return error('imagenotattached'), 400 upload = do_upload_image(user, f, args['desc']) if isinstance(upload, str): return error(upload), 403 else: return success({ 'url': { 'part': upload.url, 'page': BASE_URL % upload.url, 'direct': upload.direct_url } }), 201
def wrapper(inst, *args, **kwargs): header_parser = RequestParser() header_parser.add_argument(User.Fields.USERNAME, type=str, required=True, location='headers', help='username needs to be present in header') header_parser.add_argument(User.Fields.PASSWORDHASH, type=str, required=True, location='headers', help='password hash needs to be present in header') headers = header_parser.parse_args() request._username = headers[User.Fields.USERNAME] request._passwordhash = headers[User.Fields.PASSWORDHASH] user = UserOperations.find_user_with_passwordhash( request._username, request._passwordhash ) if not user: cors_headers = { 'Access-Control-Allow-Origin': '*' } return "Cannot authenticte user", 401, cors_headers # raise UserException("Could not authenticate user") return func(inst, *args, **kwargs)
def post(self): parser = RequestParser() parser.add_argument('X-VERIFY-CREDENTIALS-AUTHORIZATION', type=str, location='headers', dest='authorization') parser.add_argument('X-AUTH-SERVICE-PROVIDER', type=str, location='headers', dest='authorization_url') parser.add_argument('media', type=FileStorage, location='files') parser.add_argument('message', type=unicode, location='form') parser.add_argument('source', type=unicode, location='form') args = parser.parse_args() if args['source'] != 'Tweetbot for iOS': return error('nottweetbot'), 403 f = args['media'] if not f: return error('imagenotattached'), 400 headers = {'Authorization': args['authorization']} r = requests.get(args['authorization_url'], headers=headers) json = r.json() user = User.query.filter_by(oauth_uid=json['id']).first() message = '' if json['protected'] else args.get('message') desc = "%svia Tweetbot for iOS" % ( ('%s\r\n\r\n' % message) if message else '') upload = do_upload_image(user, f, desc) if isinstance(upload, str): return error(upload), 403 else: return {'url': BASE_URL % upload.url}, 201
class Get(Resource): def __init__(self): super(Get, self).__init__() self.__mParser = RequestParser() self.__mParser.add_argument('bus_id', type=str, required=True) self.__mParser.add_argument('address', type=str, required=True) self.__mParser.add_argument('cmd', type=str) def get(self): lStatus = "ok" lCommand = "" lValue = "" lArgs = self.__mParser.parse_args() lBusId = int(lArgs['bus_id'], 0) lBus = SMBus(lBusId) lAddress = int(lArgs['address'], 0) try: if lArgs['cmd'] is None: lValue = lBus.read_byte(lAddress) else: lCommand = int(lArgs['cmd'], 0) lValue = lBus.read_byte_data(lAddress, lCommand) except IOError, pExc: lStatus = "Error reading from bus: " + str(pExc) return { 'bus_id': lBusId, 'address': lAddress, 'cmd': lCommand, 'value': lValue, 'status': lStatus }
class Set(Resource): def __init__(self): super(Set, self).__init__() self.__mParser = RequestParser() self.__mParser.add_argument('bus_id', type=str, required=True) self.__mParser.add_argument('address', type=str, required=True) self.__mParser.add_argument('value', type=str, required=True) self.__mParser.add_argument('cmd', type=str) def get(self): lStatus = 'ok' lArgs = self.__mParser.parse_args() lBusId = int(lArgs['bus_id'], 0) lAddress = int(lArgs['address'], 0) lValue = int(lArgs['value'], 0) lBus = SMBus(lBusId) try: if lArgs['cmd'] is None: lBus.write_byte(lAddress, lValue) else: lCommand = int(lArgs['cmd'], 0) lBus.write_byte_data(lAddress, lCommand, lValue) except IOError, pExc: lStatus = "Error writing data: " + str(pExc) return { 'bus_id': lBusId, 'address': lAddress, 'cmd': lCommand, 'value': lValue, 'status': lStatus }
def get(self): params_parser = RequestParser() params_parser.add_argument(User.Fields.NAME, type=str, required=False, location='args') params_parser.add_argument(User.Fields.SETTINGS, type=str, required=False, location='args') fields = params_parser.parse_args() name = fields.get(User.Fields.NAME, None) settings = fields.get(User.Fields.SETTINGS, None) d = dict() if name is not None: d[User.Fields.NAME] = name if settings is not None: d[User.Fields.SETTINGS] = settings updated_user = UserOperations.update_user( request._username, request._passwordhash, d ) user_dict = User.encode(updated_user) user_dict = remove_id_from_user_dict(user_dict) return user_dict, 200
def concrete_backend(): parser = RequestParser() for argument in arguments: parser.args.append(argument) user, created = func(parser.parse_args()) current_app.db.session.commit() login_user(user) return user, created
def concrete_backend(): parser = RequestParser() for argument in arguments: parser.args.append(argument) user, created = func(parser.parse_args()) current_app.db.session.commit() login_user(user) return user, created
def get_one(self, id): parser = RequestParser() # Look only in the querystring parser.add_argument('user', location='args', default=None) args = parser.parse_args(request) dao = TimerDAO() timer = dao.get(id) as_dict = TimerFormatter().model_to_dict(timer) resp = jsonify(as_dict) return resp
def get_one(self, id): parser = RequestParser() # Look only in the querystring parser.add_argument('user', location='args', default=None) args = parser.parse_args(request) dao = TimerDAO() timer = dao.get(id) as_dict = TimerFormatter().model_to_dict(timer) resp = jsonify(as_dict) return resp
def post(self): parser = RequestParser() parser.add_argument('image', type=FileStorage, location='files') parser.add_argument('file', type=FileStorage, location='files') args = parser.parse_args() file = args['image'] or args['file'] if not file: return jsonify({'error': 'not file for upload'}) else: filename = upload(file) return jsonify({'href': '%s%s' % (request.url_root, filename)})
def put(self, id): reqparse = RequestParser() reqparse.add_argument('text', type=str, location='json') data = reqparse.parse_args() if not data.text: return self.argument_required('text') self.cursor.execute(""" UPDATE {} SET text = ? WHERE id = ? """.format(self.__table__), (data.text, id)) self.refresh_table() return self.get(id)
def put(self, id): reqparse = RequestParser() reqparse.add_argument('text', type=str, location='json') data = reqparse.parse_args() if not data.text: return self.argument_required('text') self.cursor.execute( """ UPDATE {} SET text = ? WHERE id = ? """.format(self.__table__), (data.text, id)) self.refresh_table() return self.get(id)
def delete(self, url): parser = RequestParser() parser.add_argument(arg_token) args = parser.parse_args() if not args['token']: return error('notoken'), 403 user = User.query.filter_by(token=args['token']).first() if not user: return error('wrongtoken'), 403 res = do_delete_image(user, url) if res == 'success': return {'status': 'success'} else: return error(res), 403
def put(self, id): """Update tags for a score""" parser = RequestParser() parser.add_argument('tags', type=str, required=True) args = parser.parse_args() q = db.session.query score = q(models.Score).get(id) tag_names = [t.strip() for t in args.tags.split(',')] score.tags = _process_tags(tag_names, score.user_id) db.session.commit() score = q(models.Score).get(id) result = ScoreSerializer(score).data return {'result': result}
class UserCreate(Resource): def __init__(self): self.reqparse = RequestParser() self.reqparse.add_argument( 'user', type = username, required = True, location = 'json' ) self.reqparse.add_argument( 'key', type = pubkey, required = True, location = 'json' ) self.reqparse.add_argument( 'host', type = str, required = True, location = 'json' ) super(UserCreate, self).__init__() def post(self): args = self.reqparse.parse_args() print(args) try: p.add_user( username=str(args['user']), pubkey=args['key'], hostname=args['host'] ) except ldap.SERVER_DOWN: return {'message': 'Unable to connect to LDAP server'}, 400 except ldap.ALREADY_EXISTS: return {'message': 'User already exists'}, 400 except UNKNOWN_HOST: return {'message': 'Unknown shell server'}, 400 except: (typ, value, tb) = sys.exc_info() sys.stderr.write("Unexpected Error: %s\n" % typ) sys.stderr.write("\t%s\n" % value) traceback.print_tb(tb) return {'message': 'User creation script failed'}, 400 return {'message': 'success'}
class UserCreate(Resource): def __init__(self): self.reqparse = RequestParser() self.reqparse.add_argument( 'user', type = username, required = True, location = 'json' ) self.reqparse.add_argument( 'key', type = pubkey, required = True, location = 'json' ) self.reqparse.add_argument( 'host', type = str, required = True, location = 'json' ) super(UserCreate, self).__init__() def post(self): args = self.reqparse.parse_args() print(args) try: p.add_user( username=str(args['user']), pubkey=args['key'], hostname=args['host'] ) except ldap.SERVER_DOWN: return {'message': 'Unable to connect to LDAP server'}, 400 except ldap.ALREADY_EXISTS: return {'message': 'User already exists'}, 400 except UNKNOWN_HOST: return {'message': 'Unknown shell server'}, 400 except: (typ, value, tb) = sys.exc_info() sys.stderr.write("Unexpected Error: %s\n" % typ) sys.stderr.write("\t%s\n" % value) traceback.print_tb(tb) return {'message': 'User creation script failed'}, 400 return {'message': 'success'}
def get(self): parser = RequestParser() parser.add_argument(arg_token) parser.add_argument('with_uploads', type=int, location='args') args = parser.parse_args() if not args['token']: return error('notoken'), 403 user = User.query.filter_by(token=args['token']).first() if not user: return error('wrongtoken'), 403 res = {'name': user.name, 'email': user.email, 'profile_image_url': user.profile_image_url, 'uploads_count': user.uploads.count()} if args['with_uploads'] == 1: uploads = [] for upload in user.uploads: uploads.append({'type': upload.object.__tablename__, 'url': {'page': BASE_URL % upload.url, 'direct': upload.direct_url}, 'title': upload.title, 'desc': upload.desc, 'upload_at': upload.time.strftime('%s'), 'view_count': upload.view_count, 'properties': upload.object.prop}) res['uploads'] = uploads return success({'user': res})
def post(self): # parse incoming POST data reqparse = RequestParser() reqparse.add_argument('user', type=dict, location='json') reqparse.add_argument('text', type=str, location='json') reqparse.add_argument('image_ref', type=str, location='json') data = reqparse.parse_args() # check for required data if not data.text: return self.argument_required('text') if not data.get('user', {}).get('location'): return self.argument_required('location') # generate a new time based UUID post_id = str(uuid.uuid1()) # payload for querying Crate values = dict( id = post_id, created = datetime.now().isoformat(), user = data.user, text = data.text, image_ref = data.image_ref, like_count = 0, ) k = list(values.keys()) v = list(values.values()) # compile and execute INSERT statement self.cursor.execute("""INSERT INTO {} ({}) VALUES ({})""".format( self.__table__, ', '.join(k), ', '.join('?' * len(v)) ), v) # refresh table to make sure new record is immediately available self.refresh_table() # fetch new record self.cursor.execute(""" SELECT p.*, c.name as country, c.geometry as area FROM guestbook.posts AS p, guestbook.countries AS c WHERE within(p.user['location'], c.geometry) AND p.id = ? """, (post_id,)) # convert response from Crate into # json-serializable object array response = self.convert(self.cursor.description, self.cursor.fetchall()) return response, 201
def post(self): # parse incoming POST data reqparse = RequestParser() reqparse.add_argument('user', type=dict, location='json') reqparse.add_argument('text', type=str, location='json') reqparse.add_argument('image_ref', type=str, location='json') data = reqparse.parse_args() # check for required data if not data.text: return self.argument_required('text') if not data.get('user', {}).get('location'): return self.argument_required('location') # generate a new time based UUID post_id = str(uuid.uuid1()) # payload for querying Crate values = dict( id=post_id, created=datetime.now().isoformat(), user=data.user, text=data.text, image_ref=data.image_ref, like_count=0, ) k = list(values.keys()) v = list(values.values()) # compile and execute INSERT statement self.cursor.execute( """INSERT INTO {} ({}) VALUES ({})""".format( self.__table__, ', '.join(k), ', '.join('?' * len(v))), v) # refresh table to make sure new record is immediately available self.refresh_table() # fetch new record self.cursor.execute( """ SELECT p.*, c.name as country, c.geometry as area FROM guestbook.posts AS p, guestbook.countries AS c WHERE within(p.user['location'], c.geometry) AND p.id = ? """, (post_id, )) # convert response from Crate into # json-serializable object array response = self.convert(self.cursor.description, self.cursor.fetchall()) return response, 201
def post(self): parser = RequestParser() parser.add_argument(arg_token) parser.add_argument('file', type=FileStorage, location='files') parser.add_argument('desc', type=unicode, location='form') args = parser.parse_args() f = args['file'] user = args['token'] if user: user = User.query.filter_by(token=user).first() if not user: return error('wrongtoken'), 403 if not f: return error('imagenotattached'), 400 upload = do_upload_image(user, f, args['desc']) if isinstance(upload, str): return error(upload), 403 else: return success({'url': {'part': upload.url, 'page': BASE_URL % upload.url, 'direct': upload.direct_url}}), 201
class Report(Resource): def __init__(self): super(Report, self).__init__() self.__mParser = RequestParser() self.__mParser.add_argument('success', type=str, required=True) self.__mParser.add_argument('message', type=str) self.__mParser.add_argument('rangeId', type=int, required=True) def get(self): lArgs = self.__mParser.parse_args() lSuccess = lArgs['success'] lMessage = lArgs['message'] lRangeId = lArgs['rangeId'] Report.sModel.report( True if lSuccess == "true" else False, lRangeId, lMessage ) return {}
def post(self): # parse incoming POST data reqparse = RequestParser() reqparse.add_argument('query_string', type=str, location='json') data = reqparse.parse_args() # check for required data if not data.query_string: return self.argument_required('query_string') self.cursor.execute(""" SELECT p.*, p._score AS _score, c.name AS country, c.geometry AS area FROM guestbook.posts AS p, guestbook.countries AS c WHERE within(p.user['location'], c.geometry) AND match(text, ?) ORDER BY _score DESC """, (data.query_string,)) # convert response from Crate into # json-serializable object array response = self.convert(self.cursor.description, self.cursor.fetchall()) return response, 200
def post(self): # parse incoming POST data reqparse = RequestParser() reqparse.add_argument('query_string', type=str, location='json') data = reqparse.parse_args() # check for required data if not data.query_string: return self.argument_required('query_string') self.cursor.execute( """ SELECT p.*, p._score AS _score, c.name AS country, c.geometry AS area FROM guestbook.posts AS p, guestbook.countries AS c WHERE within(p.user['location'], c.geometry) AND match(text, ?) ORDER BY _score DESC """, (data.query_string, )) # convert response from Crate into # json-serializable object array response = self.convert(self.cursor.description, self.cursor.fetchall()) return response, 200
def get(self, soknad_id=None): if soknad_id: soknad = self.soknad_resource.get(soknad_id) ExternalResourceHelper.load_organisation(soknad) ExternalResourceHelper.load_persons([soknad]) ExternalResourceHelper.load_users([soknad]) return output_pdf(soknad, 200, template=u"pdf/soknad.html") # return output_csv(soknad, 200, fieldname_mapping=get_fieldname_mapping(), fields_to_ignore=get_fields_to_ignore()) else: parser = RequestParser() parser.add_argument("id", type=int, action="append", required=True) args = parser.parse_args() soknader = self.soknad_resource.get() soknader = [s for s in soknader if s["id"] in args["id"]] ExternalResourceHelper.load_organisations(soknader) ExternalResourceHelper.load_persons(soknader) ExternalResourceHelper.load_users(soknader) return output_csv( soknader, 200, fieldname_mapping=get_fieldname_mapping(), fields_to_ignore=get_fields_to_ignore() )
def post(self): # parse incoming POST data reqparse = RequestParser() reqparse.add_argument('blob', type=str, location='json') data = reqparse.parse_args() if not data.blob: return self.argument_required('blob') # encode content as bytestring tmp = base64.b64decode(data.blob) # calculate sha1 digest digest = hashlib.sha1(tmp).hexdigest() # write into temp file f = TemporaryFile() _ = f.write(tmp) f.flush() _ = f.seek(0) # upload blob created = self.blob_container.put(f, digest=digest) # response json and status code code = created and 201 or 409 response = dict(digest=digest, url='/image/{0}'.format(digest)) return response, code
class UserCreate(Resource): def __init__(self): self.reqparse = RequestParser() self.reqparse.add_argument("user", type=username, required=True, location="json") self.reqparse.add_argument("key", type=pubkey, required=True, location="json") self.reqparse.add_argument("host", type=str, required=True, location="json") super(UserCreate, self).__init__() def post(self): args = self.reqparse.parse_args() print(args) try: p.add_user(username=str(args["user"]), pubkey=args["key"], hostname="%s.hashbang.sh" % args["host"]) except ldap.SERVER_DOWN: return {"message": "Unable to connect to LDAP server"}, 400 except ldap.ALREADY_EXISTS: return {"message": "User already exists"}, 400 except: sys.stderr.write("Unexpected Error: %s\n" % sys.exc_info()[0]) return {"message": "User creation script failed"}, 400 return {"message": "success"}
def post(self): parser = RequestParser() parser.add_argument('X-VERIFY-CREDENTIALS-AUTHORIZATION', type=str, location='headers', dest='authorization') parser.add_argument('X-AUTH-SERVICE-PROVIDER', type=str, location='headers', dest='authorization_url') parser.add_argument('media', type=FileStorage, location='files') parser.add_argument('message', type=unicode, location='form') parser.add_argument('source', type=unicode, location='form') args = parser.parse_args() if args['source'] != 'Tweetbot for iOS': return error('nottweetbot'), 403 f = args['media'] if not f: return error('imagenotattached'), 400 headers = {'Authorization': args['authorization']} r = requests.get(args['authorization_url'], headers=headers) json = r.json() user = User.query.filter_by(oauth_uid=json['id']).first() message = '' if json['protected'] else args.get('message') desc = "%svia Tweetbot for iOS" % (('%s\r\n\r\n' % message) if message else '') upload = do_upload_image(user, f, desc) if isinstance(upload, str): return error(upload), 403 else: return {'url': BASE_URL % upload.url}, 201
def _get_args(self, request): parser = RequestParser() parser.add_argument('user', location='args', default=None) args = parser.parse_args(request) return args
def _get_args(self, request): parser = RequestParser() parser.add_argument('user', location='args', default=None) args = parser.parse_args(request) return args