def place_amenity_id(place_id, amenity_id): query = Place.select().where(Place.id == place_id) if query.wrapped_count() < 1: return json_response(status_=404, msg="that place does not exist") query = Amenity.select().where(Amenity.id == amenity_id) if query.wrapped_count() < 1: return json_response(status_=404, msg="that amenity does not exist") query = PlaceAmenities.select().where(PlaceAmenities.amenity == amenity_id, PlaceAmenities.place == place_id) if query.wrapped_count() > 0: return json_response(status_=404, msg="amenity already set for given place") if request.method == "POST": insert = PlaceAmenities(place=place_id, amenity=amenity_id) insert.save() return jsonify(insert.to_dict()), 201 elif request.method == "DELETE": amenity = PlaceAmenities.get(PlaceAmenities.amenity == amenity_id, PlaceAmenities.place == place_id) amenity.delete_instance() amenity.save() return json_response(status_=200, msg="amentiy delete for given place")
def test_custom_obj_default_for_json(self): class MyJsonItem(object): def for_json(self): return '<for_json>' with pytest.raises(TypeError) as e: json_response(item=MyJsonItem()) assert str(e.value).endswith(' is not JSON serializable')
def test_simple_status_param(self): self.app.config['JSON_ADD_STATUS'] = True r = json_response(some='val', data=42, add_status_=False) assert_dict_equal(r.json, {'some': 'val', 'data': 42}) self.app.config['JSON_ADD_STATUS'] = False r = json_response(some='val', data=42, add_status_=True) assert_dict_equal(r.json, {'some': 'val', 'data': 42, 'status': 200})
def test_response_class(self): r = json_response(one=12) assert isinstance(r, JsonTestResponse) assert r.json == dict(status=200, one=12) r = json_response(two='hello') assert isinstance(r, JsonTestResponse) assert r.json['two'] == 'hello' assert r.json['status'] == 200
def test_response_class(self): r = json_response(one=12) assert_is_instance(r, JsonTestResponse) assert_dict_equal(r.json, dict(status=200, one=12)) r = json_response(two='hello') assert_is_instance(r, JsonTestResponse) assert_equals(r.json['two'], 'hello') assert_equals(r.json['status'], 200)
def test_iterable(self): # set r = json_response(lst=set([1, 2, 3])) assert_equals(r.json['lst'], [1, 2, 3]) # generator r = json_response(lst=(x for x in [3, 2, 42])) assert_equals(r.json['lst'], [3, 2, 42]) # iterator r = json_response(lst=iter([1, 2, 3])) assert_equals(r.json['lst'], [1, 2, 3])
def test_iterable(self): # set r = json_response(lst=set([1, 2, 3])) assert r.json['lst'] == [1, 2, 3] # generator r = json_response(lst=(x for x in [3, 2, 42])) assert r.json['lst'] == [3, 2, 42] # iterator r = json_response(lst=iter([1, 2, 3])) assert r.json['lst'] == [1, 2, 3]
def test_simple(self): r = json_response() assert_equals(r.status_code, 200) assert_equals(r.mimetype, 'application/json') # Set custom HTTPS status. r = json_response(status_=400) assert_equals(r.status_code, 400) # Response will contains status by default. r = json_response(some='val', data=4) assert_equals(r.status_code, 200) assert_dict_equal(r.json, {'status': 200, 'some': 'val', 'data': 4})
def books(place_id): if request.method == 'GET': query = Place.select().where(Place.id == place_id) if not query.exists(): return json_response(status_=404, msg="place does not exist") query = PlaceBook.select().where(PlaceBook.place == place_id) return ListStyle.list(query, request), 200 elif request.method == 'POST': if "name" not in request.form or "date_start" not in request.form: return json_response(status_=400, code=40000, msg="missing parameters") test = Place.select().where(Place.id == place_id) if test.wrapped_count() < 1: return json_response(status_=404, code=10002, msg="no place with such id") test = User.select().where(User.id == request.form["user"]) if test.wrapped_count() < 1: return json_response(status_=404, msg="no user with given id") try: start = datetime.strptime(request.form['date_start'], '%Y/%m/%d %H:%M:%S') except ValueError: return json_response(status_=400, msg="incorrect date format") end = start + timedelta(days=int(request.form['number_nights'])) bookings = PlaceBook.select().where(PlaceBook.place == place_id) for booking in bookings: start_b = booking.date_start end_b = start_date + timedelta(days=booking.number_nights) if start >= start_b and start < end_b: return json_response(status=410, msg="Place unavailable at this date", code=110000) elif start_b >= start and start_b < end: return json_response(status=410, msg="Place unavailable at this date", code=110000) elif end > start_b and end <= end_b: return json_response(status=410, msg="Place unavailable at this date", code=110000) place_book = PlaceBook(place=place_id, user=request.form['user'], date_start=datetime.strptime(request.form['date_start'], '%Y/%m/%d %H:%M:%S')) if "is_validated" in request.form: place_book.is_validated = request.form["is_validated"] elif "number_nights" in request.form: place_book.number_nights = request.form["number_nights"] place_book.save() return jsonify(place_book.to_dict()), 201
def users(): """Handle GET and POST requests to /users route. Return a list of all users in the database in the case of a GET request. Create a new user record in the database in the case of a POST request. """ # handle GET requests: # -------------------------------------------------------------------------- if request.method == 'GET': list = ListStyle.list(User.select(), request) return jsonify(list) # handle POST requests: # -------------------------------------------------------------------------- elif request.method == 'POST': try: record = User( email=request.form["email"], password=request.form["password"], first_name=request.form["first_name"], last_name=request.form["last_name"] ) record.save() return jsonify(record.to_hash()) # return 409 if user with given email already exists except IntegrityError: return json_response( add_status_=False, status_=409, code=10000, msg="Email already exists" )
def delete_node(id): s = Node.query.filter_by(id=id).first() if s is not None: db.session.delete(s) db.session.commit() return json_response(response='ok') raise JsonError(error='node not in database')
def state_id(state_id): """Handle GET and DELETE requests to /states/<state_id> route. Return a hash of the appropriate record in the database in the case of a GET request. Delete the appropriate record in the case of a DELETE request. """ # check whether resource exists: # -------------------------------------------------------------------------- try: record = State.get(State.id == state_id) # return 404 not found if it does not except State.DoesNotExist: return json_response( add_status_=False, status_=404, code=404, msg="not found" ) # if exception does not arise: # -------------------------------------------------------------------------- # handle GET requests if request.method == 'GET': return jsonify(record.to_hash()) # handle DELETE requests elif request.method == "DELETE": record.delete_instance() record.save() return 'deleted state\n'
def api(version): apis = {'v1': 'ApiV1', 'v2': 'ApiV2'} api_class = apis[version] order = api_class(request.get_json()) if order.check(): order.save() return json_response(check=order.check())
def users(): if request.method == "POST": # get data from post request data = request.data first_name = data['first_name'] last_name = data['last_name'] email = data['email'] password = data['password'] # if email already exists in database, return error message email_check = User.get(User.email == email) if email_check: return json_response(code=10000, msg="Email already exists") # if email_check is empty, create new user with post request info entry = User.insert(first_name=first_name, last_name=last_name, email=email, password=User.set_password(password)) entry.execute() # return json of data added to User table user = User.select().where(first_name=first_name, last_name=last_name, email=email).get() return json.dumps(user.to_hash()) elif request.method == "GET": # returns list of all users list_users = User.select() return json.dumps(list_users.to_hash())
def delete_sketch(id): s = Node.query.filter_by(id=id).first() if s is not None: db.session.delete(s) db.session.commit() return json_response(response="ok") raise JsonError(error="sketch not in database")
def amenity_id(amenity_id): """Handle GET, PUT & DELETE requests to /amenities/<amenity_id> route. Return a hash of the appropriate record in the case of a GET request. Delete appropriate record in case of DELETE request. """ # check whether resource exists: # -------------------------------------------------------------------------- try: record = Amenity.get(Amenity.id == amenity_id) # return 404 not found if it does not except Amenity.DoesNotExist: return json_response( add_status_=False, status_=404, code=404, msg="not found" ) # if exception does not arise: # -------------------------------------------------------------------------- # handle GET requests if request.method == 'GET': return jsonify(record.to_hash()) # handle PUT requests elif request.method == "DELETE": record.delete_instance() record.save() return 'deleted booking\n'
def city(state_id): """Handle GET and POST requests to /states/<state_id>/cities route. Return a list of all cities in state (according to database) in the case of a GET request. Create a new city record in the given state in the database in the case of a POST request. """ # handle GET requests: # -------------------------------------------------------------------------- if request.method == 'GET': list = ListStyle.list(City.select().where(City.state == state_id), request) return jsonify(list) # handle POST requests: # -------------------------------------------------------------------------- elif request.method == 'POST': try: record = City(name=request.form["name"], state=state_id) record.save() return jsonify(record.to_hash()) # return 409 if city with given name already exists except IntegrityError: return json_response( add_status_=False, status_=409, code=10002, msg="City already exists in this state" )
def index(): """Serve a simple hash for any requests to / with status 200.""" return json_response( status="OK", utc_time=datetime.utcnow().strftime('%d/%m/%Y %H:%M:%S'), time=utc_to_local(datetime.utcnow()).strftime('%d/%m/%Y %H:%M:%S') )
def states(): """Handle GET and POST requests to /states route. Return a list of all states in the database in the case of a GET request. Create a new state in the database in the case of a POST request """ # handle GET requests: # -------------------------------------------------------------------------- if request.method == 'GET': list = ListStyle.list(State.select(), request) return jsonify(list) # handle POST requests: # -------------------------------------------------------------------------- elif request.method == 'POST': try: record = State(name=request.form["name"]) record.save() return jsonify(record.to_hash()) # return 409 state with given name already exists except IntegrityError: return json_response( add_status_=False, status_=409, code=10001, msg="State already exists" )
def amenities(): """Handle GET and POST requests to /amenities route. Return a list of all amenities in database in the case of a GET request. Create a new amenity record in the database in the case of a POST request. """ # handle GET requests: # -------------------------------------------------------------------------- if request.method == 'GET': list = ListStyle.list(Amenity.select(), request) return jsonify(list) # handle POST requests: # -------------------------------------------------------------------------- elif request.method == 'POST': try: record = Amenity(name=request.form['name']) record.save() return jsonify(record.to_hash()) # return 409 if amenity with given name already exists except IntegrityError: return json_response( add_status_=False, status_=409, code=10003, msg="Name already exists" )
def getOperations(id): operations = Operation.query.order_by(Operation.courierId == id).all() operationsId = [] for operation in operations: operationsId.append(operation.id) return json_response(operationId = operationsId)
def getFreeOrders(): orders = Order.query.order_by(Order.statusId == 5).all() ordersId = [] for order in orders: ordersId.append(order.id) return json_response(orderId=ordersId)
def inspect_api(): try: docker_id = request.args['id'] docker_long_id, response = metadata.docker_inspect(docker_id) response['EcsMetadata'] = metadata.ecs_inspect(docker_long_id) except Exception as ex: raise JsonError(success=False, error=str(ex)) return json_response(result=response, success=True)
def delete_folder(): params = request.values folder_id = request.values['id'] sub_folder = FolderTree.query.filter( FolderTree.parent_id == folder_id).all() if sub_folder: return json_response(success=False, data=dict(error='Sub folder found')) reports = Reports.query.filter(Reports.folder_id == folder_id).all() if reports: return json_response(success=False, data=dict(error='Reports found in this folder')) folder = FolderTree.query.filter(FolderTree.id == folder_id).first() if folder: db.session.delete(folder) db.session.flush() return json_response(success=True, data=folder)
def test_with_headers_tuple(self): hdr = (('MY-HEADER', 'my value'), ('X-HEADER', 42)) r = json_response(headers_=hdr) assert r.status_code == 200 assert r.mimetype == 'application/json' assert r.headers.get('Content-Type') == 'application/json' assert r.headers.get('MY-HEADER') == 'my value' assert r.headers.get('X-HEADER', type=int) == 42
def del_selections(): params=request.values selection = Selection.query.filter(Selection.name==params['name']).first() db.session.delete(selection) result=db.session.flush() return json_response(success=True,data=result)
def searchSymbol(): try: return json_response( stockNews=Twelvedata.searchSymbol(request.args.get('symbol'))) except Exception as e: print(e) raise JsonError(status=400, error='Could not search any stock for symbol')
def store_event(): require_fields(['token', 'action', 'data', 'ts']) db = get_db() event_id = db.events.store(db.sessions.get(request.form.get('token')), request.form.get('action'), request.form.get('data'), request.form.get('ts')) return json_response(event_id=event_id)
def predict_price(): print(request.data) inputs = ApiInputs(request) if not inputs.validate(): print(inputs.errors) return json_response(401, text=inputs.errors) inputs = PredictInputs(request) if not inputs.validate(): print(inputs.errors) return json_response(401, text=inputs.errors) params = get_feature_array_from_json(request.get_json()) predicted = get_prediction(params) return json_response(predicted_price=predicted)
def getCouriers(): couriers = Courier.query.order_by(Courier.id).all() ids = [] for courier in couriers: ids.append(courier.id) return json_response(courierId = ids)
def get_MongojoinTwwo(): db = mongo_database() def db_query(): return db.joinTwo() res = db_query() return json_response(result=res)
def analysis_aspect(task_name: str, analysis_id: str, aspect_name: str): "Get aspect result" try: aspect_builder = getattr(aspect, aspect_name) except AttributeError: raise JsonError(description="Unknown aspect: " + aspect_name, status_=404) return json_response(aspect_builder(analysis_id))
def check_flask_card(card_id): data = request.get_json() result = data.get("result") # known: unknown: user_id = current_identity.id card = FlashCards.query.filter_by(id=card_id).first() if card is None: return json_response(status=404, msg="抽记卡未找到,可能已经被删除了哦") check_card(card, result) book = FlashCardBooks.query.filter_by(id=card.book_id, user_id=user_id).first() if book is None: return json_response(status=404, msg="抽记卡本未找到,可能已经被删除了哦") next_card = get_next_card(book) return json_response(data=next_card)
def get_mysqlcount(): db = mysql_database() def db_query(): return db.count() res = db_query() return json_response(result=res)
def get_mysqldeleteMore(): db = mysql_database() def db_query(): return db.deleteMore() res = db_query() return json_response(result=res)
def test_nospeaklater(self): # Let's pretend we have no speaklater imported to test behaviour # without speaklater even if it installed. flask_json._LazyString = None r = json_response(text=time()) assert_equals(r.status_code, 200) assert_equals(r.json['text'], '00:00:00')
def set_mute(): data = request.get_json(force=True) if 'value' not in data: return json_response(error={'value not passed'}) muted = data['value'] if not isinstance(muted, bool): if muted == 'on': mute_setting = 'mute' else: mute_setting = 'unmute' answer = send_amixer_command('sset', mute_setting) volume = request_amixer_volume() print(volume) return json_response(result=volume)
def getManagers(): managers = Manager.query.order_by(Manager.id).all() ids = [] for manager in managers: ids.append(manager.id) return json_response(managerId=ids)
def test_nospeaklater(self): # Let's pretend we have no speaklater imported to test behaviour # without speaklater even if it installed. flask_json._LazyString = None r = json_response(text=time()) assert r.status_code == 200 assert r.json['text'] == '00:00:00'
def increment_value(): data = request.get_json( force=True) # skim mimetype, have shorte curl command try: value = int(data['value']) except (KeyError, TypeError, ValueError): raise JsonError(description='Invalid value.') return json_response(value=value + 1)
def getClients(): clients = Client.query.order_by(Client.id).all() ids = [] for client in clients: ids.append(client.id) return json_response(clientId=ids)
def test_custom_obj_for_json(self, app): class MyJsonItem(object): def for_json(self): return '<for_json>' app.config['JSON_USE_ENCODE_METHODS'] = True r = json_response(item=MyJsonItem()) assert r.json['item'] == '<for_json>'
def get_mysqlupdateOne(): db = mysql_database() def db_query(): return db.updateOne() res = db_query() return json_response(result=res)
def getOrders(): orders = Order.query.order_by(Order.dateOfCreation).all() ordersId = [] for order in orders: ordersId.append(order.id) return json_response(orderId=ordersId)
def get_mysqlfindAll(): db = mysql_database() def db_query(): return db.findAll() res = db_query() return json_response(result=res)
def test_custom_obj_for_json(self): class MyJsonItem(object): def for_json(self): return '<for_json>' self.app.config['JSON_USE_ENCODE_METHODS'] = True r = json_response(item=MyJsonItem()) assert_equals(r.json['item'], '<for_json>')
def get_mysqljoinTwo(): db = mysql_database() def db_query(): return db.joinTwo() res = db_query() return json_response(result=res)
def amenities_place(place_id): if request.method == "GET": try: query = Amenity.select().join(PlaceAmenities).where(PlaceAmenities.place == place_id) return ListStyle.list(query, request), 200 except: return json_response(status_=404, msg="Not found")
def test_handler_json(self): with self.req("/?callback=foo"): r = json_response(val=100, add_status_=False) val = _json_p_handler(r, callbacks=["callback"], optional=False) assert_equals(val.get_data(as_text=True), 'foo({"val": 100});') assert_equals(val.status_code, 200) assert_equals(val.headers["Content-Type"], "application/javascript")
def login(): data = json.loads(request.data) email = data['email'] if Users.query.filter_by(email=email): return json_response(status=200) else: return abort(400)
def get_MongoCount(): db = mongo_database() def db_query(): return db.count() res = db_query() return json_response(result=res)
def get_logs(): rs = [] try: p = subprocess.Popen( ["tail", "-n", "10", "/var/log/accel-ppp/accel-ppp.log"], stdout=subprocess.PIPE) output, err = p.communicate() ansi_escape = re.compile(r'\x1b[^m]*m') output = ansi_escape.sub('', output) data = output.split('\n') for line in data: response = {} response['log'] = line rs.append(response) return json_response(data=rs) except: return json_response(data=[], error={'Error to get value of log file'})
def increment_value(): # We use 'force' to skip mimetype checking to have shorter curl command. data = request.get_json(force=True) try: value = int(data['value']) except (KeyError, TypeError, ValueError): raise JsonError(description='Invalid value.') return json_response(value=value + 1)
def not_found(e): """Serve a 404, not found json for any requests to / with status 404.""" return json_response( add_status_=False, status_=404, code=404, msg="not found" )
def users_id(user_id): if request.method == "GET": try: query = User.get(User.id == user_id) return jsonify(query.to_dict()), 200 except User.DoesNotExist: return json_response(status_=404, msg="not found") elif request.method == "PUT": try: query = User.get(User.id == user_id) for key in request.form: if key == "last_name": query.last_name = str(request.form[key]) elif key == "first_name": query.first_name = str(request.form[key]) elif key == "is_admin": query.is_admin = str(request.form[key]) elif key == "password": query.password = str(request.form[key]) elif key == "email": return json_response(status_=400, msg="not allowed to update email") query.save() return jsonify(query.to_dict()), 200 except User.DoesNotExist: return json_response(status_=404, msg="not found") elif request.method == "DELETE": try: user = User.get(User.id == user_id) user.delete_instance() user.save() return json_response(status_=200, msg="Success") except User.DoesNotExist: return json_response(status_=404, msg="not found")
def test_with_headers_tuple(self): hdr = (('MY-HEADER', 'my value'), ('X-HEADER', 42)) r = json_response(headers_=hdr) assert_equals(r.status_code, 200) assert_equals(r.mimetype, 'application/json') assert_equals(r.headers.get('Content-Type'), 'application/json') assert_true(r.headers.get('Content-Length', type=int) > 0) assert_equals(r.headers.get('MY-HEADER'), 'my value') assert_equals(r.headers.get('X-HEADER', type=int), 42)
def test_custom_obj_json(self): class MyJsonItem(object): def __json__(self): return '<__json__>' # To use __json__() and for_json() we have to set this config. self.app.config['JSON_USE_ENCODE_METHODS'] = True r = json_response(item=MyJsonItem()) assert_equals(r.json['item'], '<__json__>')
def states_id(state_id): if request.method == 'GET': try: state = State.get(State.id == state_id) return jsonify(state.to_dict()), 200 except State.DoesNotExist: return json_response(status_=404, msg="not found") elif request.method == 'DELETE': try: state = State.get(State.id == state_id) state.delete_instance() state.save() return json_response(status_=200, msg="State succesfully deleted") except State.DoesNotExist: return json_response(status_=404, msg="state does not exist")