Exemplo n.º 1
0
def create_user():
    if not request.json:
        raise InvalidUsage('Invalid Request Sent', status_code=400)

    username = request.json['username'].lower()
    password = request.json['password'].lower()
    firstName = request.json['firstName']
    lastName = request.json['lastName']
    sleep_time = request.json['sleep_time']
    time_between = request.json['time_between']

    cursor.execute("select username from client where username = %s",
                   (username, ))

    if cursor.rowcount != 0:
        raise InvalidUsage('Account with username already exists',
                           status_code=400)

    cursor.execute(
        "insert into client(password, firstName, lastName, username, sleep_time, time_between) values (%s, %s, %s, %s, %s, %s);",
        (
            password,
            firstName,
            lastName,
            username,
            sleep_time,
            time_between,
        ))

    con.commit()

    return jsonify({'user': '******'}), 201
Exemplo n.º 2
0
def specific_stations_quantity(Station, Quantity):
    over = o()
    if Station in [
            Tstation.name for Tstation in over.stations
    ] and Quantity in [Tquantity.name for Tquantity in over.quantities]:
        return jsonify(over.overview()[Station][Quantity])
    elif Station not in [Tstation.name for Tstation in over.stations]:
        raise InvalidUsage("Station " + Station + " not found.",
                           status_code=404)  # 406: not acceptable
    else:
        raise InvalidUsage("Quantity " + Quantity + " not found.",
                           status_code=404)  # 406: not acceptable
Exemplo n.º 3
0
def hasAudienceNow():

    if request.method == 'GET' is False:
        raise InvalidUsage('GET invalido', status_code=404)

    try:
        val = Camera.hasAudience()
        audience = {'hasAudience': val}

        return app.response_class(response=json.dumps(audience),
                                  status=200,
                                  mimetype='application/json')

    except Exception as exp:
        raise InvalidUsage('GET: {0}'.format(str(exp)), status_code=404)
Exemplo n.º 4
0
def specific_stations(Station):
    over = o()
    if Station in [Tstation.name for Tstation in over.stations]:
        return jsonify(over.overview()[Station])
    else:
        raise InvalidUsage("Station " + Station + " not found.",
                           status_code=404)  # 406: not acceptable
Exemplo n.º 5
0
def get_user():
    username = request.args.get('username', type=str).lower()

    cursor.execute("select * from client where username = %s;", (username, ))

    user = cursor.fetchone()
    if user is None:
        raise InvalidUsage('User not found', status_code=400)
    return jsonify({'user': user})
Exemplo n.º 6
0
def make_order():
    data = request.get_json()

    if data.get('side'):
        symbol = data['symbol']
        logger.debug("   Symbol: " + symbol)
    else:
        raise InvalidUsage('Missing symbol parameter', status_code=400)

    if data.get('side'):
        side = data['side']
        logger.debug("   Side: " + side)
    else:
        raise InvalidUsage('Missing side parameter', status_code=400)

    if data.get('type'):
        order_type = data['type']
        logger.debug("   Order type: " + order_type)
    else:
        raise InvalidUsage('Missing type parameter', status_code=400)

    if data.get('amount'):
        amount = data['amount']
        logger.debug("   Amount: " + amount)
    else:
        raise InvalidUsage('Missing price parameter', status_code=400)

    if data.get('price'):
        price = data['price']
        logger.debug("   Price: " + price)
    else:
        price = None

    if order_type == "market":
        if side == "buy":
            return json.dumps(exchange.create_market_buy_order(symbol, amount))
        elif side == "sell":
            return json.dumps(exchange.create_market_sell_order(
                symbol, amount))
        else:
            raise InvalidUsage('Invalid order side', status_code=400)
    elif order_type == "limit":
        if not data.get('price'):
            raise InvalidUsage('Missing price parameter', status_code=400)

        if side == "buy":
            return json.dumps(
                exchange.create_limit_buy_order(symbol, amount, price))
        elif side == "sell":
            return json.dumps(
                exchange.create_limit_sell_order(symbol, amount, price))
        raise InvalidUsage('Invalid order side', status_code=400)
    else:
        raise InvalidUsage('Invalid order type', status_code=400)
Exemplo n.º 7
0
def get_intakes():
    userId = request.args.get('userId', type=int)

    if userId is None:
        raise InvalidUsage('Invalid Request Sent', status_code=400)

    cursor.execute(
        "SELECT * FROM intake JOIN drink ON drink=drink.id WHERE user_id = %s",
        (userId, ))

    intakes = cursor.fetchall()
    con.commit()

    return jsonify({'intakes': intakes})
Exemplo n.º 8
0
def newzzxxccA1():

    if request.method != 'POST':
        raise InvalidUsage('Invalido', status_code=404)

    try:
        s_payload = request.form['json']
        s_json_payload = s_payload.replace("'", "\"")
        payload = json.loads(s_json_payload)

        date = payload['date']
        print('Enqueued: ' + str(date))
        name_file = './imgs/{0}.jpg'.format(date)
        img = request.files['file']
        if img is not None:
            img.save(name_file)

        Camera.queue_in.put(name_file)

        return "ok"

    except Exception as exp:
        raise InvalidUsage('Falha Arquivo: {0}'.format(str(exp)),
                           status_code=404)
Exemplo n.º 9
0
def post_intake():
    if not request.json:
        raise InvalidUsage('Invalid Request Sent', status_code=400)

    userId = request.json['userId']
    drink = request.json['drink']

    cursor.execute(
        "insert into intake(user_id, timestamp, drink) values (%s, %s, %s);", (
            userId,
            datetime.now(),
            drink,
        ))

    return jsonify({'intake': 'intake created'}), 201
Exemplo n.º 10
0
def create_drinks():
    if not request.json:
        raise InvalidUsage('Invalid Request Sent', status_code=400)

    name = request.json['name']
    caffeine = request.json['caffeine']
    fluidOunces = request.json['fluidOunces']

    cursor.execute(
        "insert into drink(name, caffeine, fluidOunces) values(%s, %s, %s)", (
            name,
            caffeine,
            fluidOunces,
        ))

    return jsonify({'drink': 'drink created'}), 201
Exemplo n.º 11
0
def update_settings():
    if not request.json:
        raise InvalidUsage('Invalid Request Sent', status_code=400)

    user_id = request.json['user_id']
    sleep_time = request.json['sleep_time']
    time_between = request.json['time_between']

    cursor.execute(
        "update client set sleep_time = %s, time_between = %s where id = %s", (
            sleep_time,
            time_between,
            user_id,
        ))

    return jsonify({'settings': 'User settings updated'})
Exemplo n.º 12
0
def should_drink():
    username = request.args.get('username', type=str).lower()

    cursor.execute("select * from client where username = %s;", (username, ))

    user = cursor.fetchone()
    if user is None:
        raise InvalidUsage('User not found', status_code=400)

    cursor.execute("SELECT * FROM intake WHERE timestamp BETWEEN %s AND %s", (
        datetime.now() - timedelta(minutes=user[5]),
        datetime.now(),
    ))

    # return jsonify({'should_drink': cursor.fetchall()})

    if cursor.rowcount == 0:
        return jsonify({'should_drink': True})
    else:
        return jsonify({'should_drink': False})
Exemplo n.º 13
0
def get_closed_orders(symbol):
    if exchange.hasFetchClosedOrders:
        return json.dumps(exchange.fetch_closed_orders(symbol=symbol))
    else:
        raise InvalidUsage('Exchange does not support fetching closed orders',
                           status_code=422)
Exemplo n.º 14
0
def get_open_orders(symbol):
    if exchange.hasFetchOpenOrders:
        return json.dumps(exchange.fetch_open_orders(symbol=symbol))
    else:
        raise InvalidUsage('Exchange does not support fetching open orders',
                           status_code=422)
Exemplo n.º 15
0
exchange.password = api_keys.EXCHANGE['passphrase']
logger.debug('Exchange API keys loaded successfully')

if sandbox and exchange.urls['test']:
    exchange.urls['api'] = exchange.urls['test']
    logger.info('Running in SANDBOX MODE')
else:
    logger.info('Running in PRODUCTION MODE')
logger.debug('Exchange API URL: ' + exchange.urls['api'])

# Check for bad exchange API keys early
try:
    exchange.fetch_balance()
# Handle bad keys
except ccxt.base.errors.AuthenticationError as e:
    raise InvalidUsage(str(e), status_code=403)


# Authorize requests before any
@app.before_request
def authenticate_token():
    # Exclude the login route
    if request.path != '/login':

        auth_header = request.headers.get('Authorization')
        if auth_header:
            try:
                auth_token = auth_header.split(" ")[1]
            except IndexError:
                response_obj = {
                    'status': 'failure',
Exemplo n.º 16
0
	def __init__(self, quantity='', fromtime='', totime='', format='',
	             station='', sensor='', filter='', granularity='', page=''):
		# TODO this needs to be more dynamic - store in a table probably
		self.available_formats = {'georss': 'georss.xml', 'geojson': 'geojson.json'
			, 'sos': 'sos.xml', 'csv': 'csv.csv', 'flot': 'flot.json'}

		# TODO this needs to be more dynamic - store in a table probably
		self.available_filters = ['none', 'mean', 'median', 'max', 'min']

		self.page = 9999999
		# check quantity:
		if quantity is '':
			raise InvalidUsage('Quantity parameter is empty.')
		elif quantity not in [Tquantity.name for Tquantity in models.Quantities.query.all()]:
			raise InvalidUsage('Requested quantity is not supported.')
		else:
			self.quantity = models.Quantities.query.filter_by(name=quantity).first()

		if station is '':
			raise InvalidUsage('Station paremeter is empty.')
		elif station not in [Tstation.name for Tstation in models.Stations.query.all()]:
			raise InvalidUsage('Requested station is not supported')
		else:
			self.station = models.Stations.query.filter_by(name=station).first()

		if sensor is '':
			raise InvalidUsage('Sensor parameter is empty.')
		elif sensor not in [Tsensor.urn for Tsensor in models.Sensors.query.all()]:
			raise InvalidUsage('Requested sensor is not supported')
		else:
			self.sensor = models.Sensors.query.filter_by(urn=sensor).first()

		if filter is '':
			self.filter = 'none'
		elif filter.lower() not in self.available_filters:
			raise InvalidUsage('Requested filter is not supported')
		else:
			if granularity is '':
				self.granularity = "1h"
			self.filter = filter.lower()
			self.granularity = granularity

		if models.Sensors.query.filter_by(quantity_id=self.quantity.id).first().first_measurement is not None:

			# check fromtime:
			if fromtime is '':
				raise InvalidUsage('Fromtime parameter is empty.')
			else:
				# transform fromtime from string to datetime (easier comparisons
				# and db queries) fromtime format should be "2015-06-04 01:04:00"
				try:
					self.fromtime = datetime.strptime(fromtime, "%Y-%m-%d %H:%M:%S")
				except:
					raise InvalidUsage('Fromtime not in the correct format.')

				if (self.fromtime < models.Sensors.query.filter_by
					(quantity_id=self.quantity.id).first().first_measurement) \
						or (self.fromtime > models.Sensors.query.filter_by
							(quantity_id=self.quantity.id).first().last_measurement):
					raise InvalidUsage('Fromtime is out of boundaries.')

			if totime is '':
				# same as fromtime
				raise InvalidUsage('Totime parameter is empty')
			else:
				try:
					self.totime = datetime.strptime(totime, "%Y-%m-%d %H:%M:%S")
				except:
					raise InvalidUsage('Totime not in the correct format')

				if (self.totime < models.Sensors.query.filter_by
					(quantity_id=self.quantity.id).first().first_measurement) \
						or (self.totime > models.Sensors.query.filter_by
							(quantity_id=self.quantity.id).first().last_measurement):
					raise InvalidUsage('Totime is out of boundaries')

			if self.fromtime > self.totime:
				raise InvalidUsage('Fromtime > totime')
		else:
			raise InvalidUsage('Measurements with the give criteria does not exist')
		if format is '':
			raise InvalidUsage('Format parameter is empty')
		elif format not in self.available_formats.keys():
			raise InvalidUsage('Requested format is not supported')
		else:
			self.format = dict(type=format, file=self.available_formats[format]
			                   , content_type=self.available_formats[format].split('.')[1])
			# use regular expressions to check if page is in the correct format
			# to check that page is positive only int number I use: \D
		re1 = r'(\D)'
		if page is '':
			self.page = 1
		elif not re.findall(re1, page):
			self.page = int(page)