Esempio n. 1
0
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")
Esempio n. 2
0
    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')
Esempio n. 3
0
    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})
Esempio n. 4
0
    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
Esempio n. 5
0
    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)
Esempio n. 6
0
    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])
Esempio n. 7
0
    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]
Esempio n. 8
0
    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})
Esempio n. 9
0
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
Esempio n. 10
0
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"
            )
Esempio n. 11
0
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')
Esempio n. 12
0
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'
Esempio n. 13
0
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())
Esempio n. 14
0
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())
Esempio n. 15
0
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")
Esempio n. 16
0
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'
Esempio n. 17
0
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"
                )
Esempio n. 18
0
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')
    )
Esempio n. 19
0
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"
                )
Esempio n. 20
0
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)
Esempio n. 23
0
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)
Esempio n. 24
0
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)
Esempio n. 25
0
 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
Esempio n. 26
0
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)

    
Esempio n. 27
0
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')
Esempio n. 28
0
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)
Esempio n. 31
0
def get_MongojoinTwwo():
    db = mongo_database()

    def db_query():
        return db.joinTwo()

    res = db_query()
    return json_response(result=res)
Esempio n. 32
0
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))
Esempio n. 33
0
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)
Esempio n. 34
0
def get_mysqlcount():
    db = mysql_database()

    def db_query():
        return db.count()

    res = db_query()
    return json_response(result=res)
Esempio n. 35
0
def get_mysqldeleteMore():
    db = mysql_database()

    def db_query():
        return db.deleteMore()

    res = db_query()
    return json_response(result=res)
Esempio n. 36
0
    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')
Esempio n. 37
0
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)
Esempio n. 38
0
def getManagers():
    managers = Manager.query.order_by(Manager.id).all()
    ids = []

    for manager in managers:
        ids.append(manager.id)

    return json_response(managerId=ids)
Esempio n. 39
0
    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'
Esempio n. 40
0
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)
Esempio n. 42
0
    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>'
Esempio n. 43
0
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)
Esempio n. 45
0
def get_mysqlfindAll():
    db = mysql_database()

    def db_query():
        return db.findAll()

    res = db_query()
    return json_response(result=res)
Esempio n. 46
0
    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>')
Esempio n. 47
0
def get_mysqljoinTwo():
    db = mysql_database()

    def db_query():
        return db.joinTwo()

    res = db_query()
    return json_response(result=res)
Esempio n. 48
0
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")
Esempio n. 50
0
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)
Esempio n. 51
0
def get_MongoCount():
    db = mongo_database()

    def db_query():
        return db.count()

    res = db_query()
    return json_response(result=res)
Esempio n. 52
0
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'})
Esempio n. 53
0
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)
Esempio n. 54
0
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"
    )
Esempio n. 55
0
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")
Esempio n. 56
0
 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)
Esempio n. 57
0
    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__>')
Esempio n. 58
0
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")