def inspect_one_equipment(id):
    p_equipment = PurchaseEquipment.query.get_or_404(id)
    request_json = request.get_json()
    if p_equipment.purchase_order.state > -2:
        return bad_request('purchase order not at ready to inspect')
    if p_equipment.inspected == 1:
        return bad_request('already inspected in houseware')

    p_equipment.inspected = 1
    inspected_userid = int(
        request.args.get('inspected_userid')) if request.args.get(
            'inspected_userid') is not None else None
    if inspected_userid is None:
        inspected_userid = g.current_user.id
    inspect_ok_number = request_json.get('inspect_ok_number') or None
    if inspect_ok_number is not None:
        inspect_ok_number = int(inspect_ok_number)
    else:
        inspect_ok_number = p_equipment.quantity
    p_equipment.inspect_ok_number = inspect_ok_number
    p_equipment.inspect_message = request_json.get('inspect_message') or None
    p_equipment.inspect_time = datetime.datetime.now().strftime(
        "%Y-%m-%d %H:%M:%S")
    p_equipment.inspected_user = inspected_userid
    db.session.commit()
    return jsonify({
        'error': 0,
        'msg': 'inspect one equipment successful',
        'data': {}
    })
Beispiel #2
0
def update_payment(userid, payment_methodid):
    try:
        if request.method == 'PUT':
            if request.json:
                payment_keys = post_payment_keys
                payment_keys.append('ppreferred')
                for key in payment_keys:
                    if key not in request.json:
                        return missing_parameters_error()
                errors = validate_payment(request.json)
                if errors:
                    return jsonify({'Errors': errors}), 400
                billing_addressid = dbm.fetch_user_preferences(
                    userid)['billing_address']['aid']
                if billing_addressid:
                    pid = dbm.update_payment_method(userid, payment_methodid,
                                                    request.json,
                                                    billing_addressid)
                    return jsonify({'payment_methodid': pid}), 201
                else:
                    return jsonify({
                        'Error':
                        'Preferred Billing Address Not Found For User {0}'.
                        format(userid)
                    }), 400
            return bad_request()
        elif request.method == 'DELETE':
            result = dbm.deactivate_user_payment_method(
                userid, payment_methodid)
            if result:
                return jsonify(result)
            return bad_request()
    except Exception as e:
        print e.message
        return internal_server_error()
def receive_one_equipment(id):
    p_equipment = PurchaseEquipment.query.get_or_404(id)
    request_json = request.get_json()
    print request_json
    if p_equipment.purchase_order.state > -2:
        return bad_request('purchase order not at ready to receive ')
    if p_equipment.received == 1:
        return bad_request('already received')

    p_equipment.received = 1
    received_userid = int(
        request.args.get('received_userid')) if request.args.get(
            'received_userid') is not None else None
    if received_userid is None:
        received_userid = g.current_user.id
    p_equipment.received_user = received_userid
    p_equipment.receive_message = request_json.get('receive_message') or None
    p_equipment.receive_temperature = request_json.get(
        'receive_temperature') or None
    p_equipment.receive_time = datetime.datetime.now().strftime(
        "%Y-%m-%d %H:%M:%S")
    db.session.commit()
    return jsonify({
        'error': 0,
        'msg': 'receive one equipment successful',
        'data': {}
    })
Beispiel #4
0
def get_demo_pages(user_id):

	conn = g.mysql.connection
	cursor = conn.cursor()

	if not user_id:
		return bad_request('User ID is not provided')

	try:
		cursor.execute("""
			SELECT 
				p.id,
				p.address,
				p.title,
				p.description,
				p.is_private,
				p.created
			FROM demo_pages dp, pages p
			WHERE dp.user_id='{user_id}'
			AND dp.page_id = p.id
			ORDER BY p.created DESC
		""".format(
			user_id=user_id
		))
		pages = cursor.fetchall()

	except Exception, error:
		print 'ERROR: ', error
		return bad_request(error)
Beispiel #5
0
def get_page(page_id):
	conn = g.mysql.connection
	cursor = conn.cursor()

	if not page_id:
		return bad_request('Page ID is not provided')

	try:
		cursor.execute("""
			SELECT 
				p.id,
				p.address,
				p.title,
				p.description,
				p.is_private,
				p.created,
				p.user_id
			FROM pages p
			WHERE id='{page_id}'
		""".format(
			page_id=page_id
		))
		page = cursor.fetchone()
		is_private, user_id = page[4], page[6]

		if is_private and not authorized(user_id):
			return forbidden()

	except Exception, error:
		print 'ERROR: ', error
		return bad_request(error)
Beispiel #6
0
def auth_user():

    email = request.form['email']
    password = request.form['password']

    conn = g.mysql.connection
    cursor = conn.cursor()

    if not email:
        return bad_request('Email is not provided')

    if not password:
        return bad_request('Password is not provided')

    try:
        cursor.execute("""
			SELECT 
				u.id,
				u.email,
				u.password,
				u.profile_type,
				u.created
			FROM users u
			WHERE u.email='{email}'
		""".format(email=email))
        user = cursor.fetchone()

    except Exception, error:
        print 'ERROR: ', error
        return bad_request(error)
Beispiel #7
0
def get_new_firmware():
    ver = request.args.get("ver", default=None)
    if ver is None or not ver.isdigit():
        return bad_request(
            "Required parameter 'ver' is missing or not an int.")

    dev_type = request.args.get("dev_type", default=None)
    if dev_type is None:
        return bad_request("Required parameter 'dev_type' is missing.")
    dev_type = dev_type.lower()

    dev_id = request.args.get("dev_id", default=None)
    if dev_id is None:
        return bad_request("Required parameter 'dev_id' is missing.")

    app.logger.debug("ver: " + ver + ", dev: " + dev_type + " dev_id: " +
                     dev_id)

    latest_firmware = find_latest_firmware(ver, dev_type)
    if latest_firmware is None:
        app.logger.debug("Device already up to date")
        return error_response(304, "Device already up to date")

    app.logger.debug("Found firmware version: " + latest_firmware)
    return send_from_directory(
        directory=os.path.join(ROOT_DIR, "firmwares"),
        filename=latest_firmware,
        as_attachment=True,
        mimetype="application/octet-stream",
        attachment_filename=latest_firmware,
    )
Beispiel #8
0
def login():
    if g.token_used:
        bad_request('must use password login')
    return jsonify({
        'token': g.current_user.generate_auth_token().encode('ascii'),
        'profile': {
            'name': g.current_user.name
        }
    })
def login():
    if g.token_used:
        bad_request('must use password login')
    return jsonify({
        'token':
        g.current_user.generate_auth_token().encode('ascii'),
        'profile': {
            'name': g.current_user.name
        }
    })
Beispiel #10
0
 def wrapped(*args, **kwargs):
     s = Serializer(current_app.config['SECRET_KEY'])
     token = request.headers.get('eD-Token', '')
     if not token:
         return bad_request('Missing token')
     try:
         data = s.loads(token)
     except:
         return bad_request('Token incorrect')
     g.session_data = data
     return f(*args, **kwargs)
Beispiel #11
0
 def wrapped(*args, **kwargs):
     s = Serializer(current_app.config['SECRET_KEY'])
     token = request.headers.get('eD-Token', '')
     if not token:
         return bad_request('Missing token')
     try:
         data = s.loads(token)
     except:
         return bad_request('Token incorrect')
     g.session_data = data
     return f(*args, **kwargs)
Beispiel #12
0
def get_files(address):

    conn = g.mysql.connection
    cursor = conn.cursor()

    if not address:
        return bad_request('Page address is not provided')
    else:
        cursor.execute("""
			SELECT
				id,
				address,
				title,
				description,
				is_private,
				created,
				user_id
			FROM pages
			WHERE address='{address}'
		""".format(address=address))
        page = cursor.fetchone()
        is_private, user_id = page[4], page[6]

        if not page:
            return bad_request('Can\'t find page by provided address')

        if is_private and not authorized(user_id):
            return forbidden()

    try:
        cursor.execute("""
			SELECT 
				f.id,
				f.name,
				f.size,
				f.type,
				f.ipfs_hash,
				f.tx_id,
				f.title,
				f.description,
				UNIX_TIMESTAMP(f.created),
				p.user_id
			FROM files f, pages p
			WHERE p.id=f.page_id
			AND p.address='{address}'
			ORDER BY f.created DESC
		""".format(address=address))
        files = cursor.fetchall()

    except Exception, error:
        print 'ERROR: ', error
        return bad_request(error)
Beispiel #13
0
def delete_particle(particle_id):
    particle = Particle.query.filter_by(id=particle_id).first()
    if request.json is None:
        return bad_request('JSON Request is invaild')
    if request.json.get('author_id') is None:
        return bad_request('author`s ID is invaild')
    if int(request.json.get('author_id')) != particle.author_id:
        return forbidden('Cannot delete other user\'s particle')

    Like.query.filter(Like.particle_id == particle.id).delete()
    db.session.delete(particle)
    db.session.commit()
    return '', 204
Beispiel #14
0
def create_proof():
    try:
        conn = g.mysql.connection
        cursor = conn.cursor()

        address = str(request.form['address'])
        age_to_prove = int(request.form['ageToProve'])
        title = 'Age is greater than {0}'.format(age_to_prove)

        cursor.execute("""
			SELECT age
			FROM users
			WHERE address='{address}'
		""".format(address=address))
        user = cursor.fetchone()

        if not user:
            return bad_request('User not found')

        print '\nPROOF\n'

        proof = '0000000000000000000000000000000027ae41e4649b934ca495991b7852b855'
        print '0', proof

        for index, i in enumerate(xrange(1 + user[0] - age_to_prove)):
            proof = hashlib.sha256(proof).hexdigest()
            print index + 1, proof
            # h = pyblake2.blake2b(digest_size=32)
            # h.update(proof)
            # proof = h.hexdigest()

        print '\nENC AGE\n'

        enc_age = '0000000000000000000000000000000027ae41e4649b934ca495991b7852b855'
        for index, i in enumerate(xrange(user[0])):
            enc_age = hashlib.sha256(enc_age).hexdigest()
            print index, enc_age
            # enc_age = pyblake2.blake2b(enc_age).hexdigest()
            # h = pyblake2.blake2b(digest_size=32)
            # h.update(enc_age)
            # enc_age = h.hexdigest()

        proof_id = str(uuid.uuid4())
        cursor.execute("""
			INSERT INTO proofs (id, address, proof, title)
			VALUES('{id}', '{address}', '{proof}', '{title}')
		""".format(id=proof_id, address=address, title=title, proof=proof))

    except Exception, error:
        print 'ERROR: ', error
        return bad_request(error)
Beispiel #15
0
def update_file(file_id):

    conn = g.mysql.connection
    cursor = conn.cursor()

    title = str(request.form['title'].encode('utf-8'))
    description = str(request.form['description'].encode('utf-8'))

    if not file_id:
        return bad_request('File ID is not provided')

    try:
        cursor.execute("""
			UPDATE files 
			SET 
				title='{title}',
				description='{description}'
			WHERE id='{file_id}'
		""".format(file_id=file_id,
             title=title.replace('\'', '\'\''),
             description=description.replace('\'', '\'\'')))
        conn.commit()

        cursor.execute("""
			SELECT 
				f.id,
				f.name,
				f.size,
				f.type,
				f.title,
				f.description,
				f.ipfs_hash,
				f.tx_id,
				UNIX_TIMESTAMP(f.created),
				p.id,
				p.address,
				p.title,
				p.description,
				UNIX_TIMESTAMP(p.created),
				u.id,
				UNIX_TIMESTAMP(u.created)
			FROM files f
			LEFT JOIN pages p ON f.page_id=p.id
			LEFT JOIN users u ON p.user_id=u.id
			WHERE f.id='{file_id}'
			AND f.page_id = p.id
		""".format(file_id=file_id))
        file_data = cursor.fetchone()
    except Exception, error:
        print 'ERROR: ', error
        return bad_request(error)
def store_one_equipment(id):
    p_equipment = PurchaseEquipment.query.get_or_404(id)
    request_json = request.get_json()
    print request_json
    if p_equipment.purchase_order.state > -2:
        return bad_request('purchase order not at ready to store state')
    if p_equipment.stored == 1:
        return bad_request('already stored in houseware')

    p_equipment.stored = 1
    stored_userid = int(request.args.get('stored_userid')) if request.args.get(
        'stored_userid') is not None else None
    if stored_userid is None:
        stored_userid = g.current_user.id
    p_equipment.stored_user = stored_userid
    p_equipment.store_message = request_json.get('store_message') or None
    p_equipment.store_temperature = request_json.get(
        'store_temperature') or None
    p_equipment.store_time = datetime.datetime.now().strftime(
        "%Y-%m-%d %H:%M:%S")

    equipments = p_equipment.purchase_order.purchase_equipments
    part_stored = False
    for e in equipments:
        if e.stored != 1:
            part_stored = True
            break
    #部分入库
    p_equipment.purchase_order.total_stored = 1
    p_equipment.purchase_order.state = -3
    if not part_stored:
        #完全入库
        p_equipment.purchase_order.total_stored = 2
        p_equipment.purchase_order.state = -4
    db.session.commit()
    #add store element
    new_store = Store()
    new_store.equipment_id = p_equipment.equipment_id
    new_store.purchase_id = p_equipment.purchase_order.id
    new_store.store_number = p_equipment.quantity
    new_store.state = 1
    db.session.add(new_store)
    db.session.commit()
    return jsonify({
        'error': 0,
        'msg': 'store one equipment successful',
        'data': {}
    })
Beispiel #17
0
def confirm_sale_order(id):
    sale_order = SaleOrder.query.get_or_404(id)
    if sale_order.state != 0:
        return bad_request('cannot store a sale order, that\'s state is not confirmed')
    sale_order.state = -2
    db.session.commit()
    return jsonify({'error' : 0, 'msg' : ''})
Beispiel #18
0
def create_clan():

    connection = client.connect(g.db)
    cursor = connection.cursor()

    try:
        data = request.get_json()
        name = data['name']
        img = data['img']

        clan_id = str(uuid.uuid4())
        cursor.execute("""
			INSERT INTO clans(
				id,
				name,
				img
			) VALUES(
				'{id}',
				'{name}',
				'{img}'
			)
		""".format(id=clan_id, name=name, img=img))

    except Exception, error:
        print 'ERROR: ', error
        return bad_request(error)
Beispiel #19
0
def del_users(uid):
    user = Users.query.filter_by(id=uid).first_or_404()
    if user == g.current_user:
        return bad_request('Did Not Delete Yourself')
    db.session.delete(user)
    db.session.commit()
    return jsonify({'code': 200, 'message': 'Delete User Success'})
Beispiel #20
0
def user_preferences(userid):
    try:
        if request.method == 'GET':
            preferences = dbm.fetch_user_preferences(userid)
            if preferences:
                return jsonify(preferences)
            return not_found()
        elif request.method == 'PUT':
            if ('shipping_addressid' or 'billing_addressid'
                    or 'cid') not in request.json:
                return missing_parameters_error()
            errors = validate_user_preferences(request.json, userid)
            if errors:
                return jsonify({'errors': errors}), 400
            if 'shipping_addressid' in request.json:
                dbm.update_user_preferred_shipping(
                    request.json['shipping_addressid'], userid)
            if 'billing_addressid' in request.json:
                dbm.update_user_preferred_billing(
                    request.json['billing_addressid'], userid)
            if 'cid' in request.json:
                dbm.update_user_preferred_payment(request.json['cid'], userid)
            preferences = dbm.fetch_user_preferences(userid)
            if preferences:
                return jsonify(preferences)
            return bad_request()
    except Exception as e:
        print e.message
        return internal_server_error()
Beispiel #21
0
def user(userid):
    try:
        if request.method == 'GET':
            cg_user = dbm.fetch_user_info(userid=userid)
            if cg_user:
                return jsonify(cg_user)
            return not_found()
        elif request.method == 'PUT':
            if request.json:
                # Verify request json contains needed parameters
                if not ('uname' or 'ufirstname' or 'ulastname' or 'uemail'
                        or 'uphone' or 'udob' in request.json):
                    return missing_parameters_error()
                # Verify that parameters are valid
                errors = validate_update_account_data(request.json)
                if errors:
                    return jsonify({'Errors': errors}), 400
                # Update user account:
                if dbm.update_user_account(userid, request.json):
                    response = jsonify(request.json)
                    response.status_code = 201
                    return response
                return not_found()
            else:
                return bad_request()
    except Exception as e:
        print e
        return internal_server_error()
Beispiel #22
0
def update_announcement(aid):
    try:
        if request.json:
            for key in announcement_keys:
                if key not in request.json:
                    return jsonify({
                        "error":
                        "Paramenter {0} missing in request".format(key)
                    })
            if int(request.json['platformid']) > 0:
                result = dbm.edit_platform_announcement(
                    request.json['a_img'], request.json['a_title'],
                    request.json['active'], request.json['aid'],
                    request.json['platformid'])
            else:
                result = dbm.edit_store_announcement(request.json['a_img'],
                                                     request.json['a_title'],
                                                     request.json['active'],
                                                     request.json['aid'])
            return jsonify({'aid': result})
        else:
            return bad_request()
    except Exception as e:
        print e.message
        return internal_server_error()
def inspect_all_equipments(id):
    p_order = PurchaseOrder.query.get_or_404(id)
    request_json = request.get_json()
    print request_json
    if p_order.state > -2:
        return bad_request('purchase order not at ready to store state')

    for p_equipment in p_order.purchase_equipments:
        if p_equipment.inspected == 1:
            continue
        p_equipment.inspected = 1
        inspected_userid = int(
            request.args.get('inspected_userid')) if request.args.get(
                'inspected_userid') is not None else None
        if inspected_userid is None:
            inspected_userid = g.current_user.id
        p_equipment.inspected_user = inspected_userid
        p_equipment.inspect_ok_number = inspect_ok_number
        p_equipment.inspect_message = request_json.get(
            'inspect_message') or None
        p_equipment.inspect_time = datetime.datetime.now().strftime(
            "%Y-%m-%d %H:%M:%S")
    db.session.commit()

    return jsonify({
        'error': 0,
        'msg': 'inspect all equipment successful',
        'data': {}
    })
Beispiel #24
0
def add_transaction():
    """User send transaction details to be uploaded to the database
    Data is received in json format"""

    # parse the request
    data = request.get_json() or {}
    # check required fields
    required_fields = ["user_id", "shop_name", "category", "amount", "date"]
    for f in required_fields:
        if f not in data:
            return bad_request("Required field " + f + " is missing")
    # add labeled field
    data["labeled"] = len(
        data["category"]) == 0  # user provided the category or not
    # connect to db
    session = get_database_client()
    # update db
    try:
        session.execute(
            """
        INSERT INTO fisci.transactions (transaction_id, user_id, shop_name, category, labeled, amount, date)
        VALUES (now(), %s, %s, %s, %s, %s, %s);
        """, (data["user_id"], data["shop_name"], data["category"],
              data["labeled"], float(data["amount"]), data["date"]))
    except Exception as err:
        return error_response(500,
                              "Error in updating the database. " + str(err))

    return {"message": "success"}
Beispiel #25
0
def get_categories():
    text = request.json.get('article')
    if text is None:
        return bad_request('Input string is empty or null')
    
    doc = {
        "type": "PLAIN_TEXT",
        "language": "en",
        "content": text
        }

    body = {
            "document": doc
            }
    try:
        response = requests.post("https://language.googleapis.com/v1/documents:classifyText",json=body,params = parameters)
        categories = response.json()
        return jsonify({"categories":[i['name'].replace('/','') for i in categories['categories']],"status":"OK","gcp_res_code":response.status_code})
        response.raise_for_status()
    except requests.exceptions.RequestException as err:
        return jsonify({"error":"OOps: Something Else"+err,"gcp_res_code":response.status_code})
    except requests.exceptions.HTTPError as errh:
        return jsonify({"error":"Http Error: "+err,"gcp_res_code":response.status_code})
    except requests.exceptions.ConnectionError as errc:
        return jsonify({"error":"Error Connecting: "+errc,"gcp_res_code":response.status_code})
    except requests.exceptions.Timeout as errt:
        return jsonify({"error":"Timeout Error: "+errc,"gcp_res_code":response.status_code})
Beispiel #26
0
def put_group(group_id):
    old_group = Group.query.get(group_id)
    if old_group is None:  # 그룹이 존재 하지 않을 경우
        return not_found('group does not exist')
    if request.json is None:  # 요청이 올바르지 않은 경우
        return bad_request('JSON request is invaild')
    if g.current_user.id != old_group.create_user:
        return forbidden('User cannot modify group')

    name = request.json.get('name')
    description = request.json.get('description')
    users = request.json.get('users')
    if users is None or users == []:
        old_group.users = [g.current_user]

    user_list = list(users)

    old_group.name = name
    old_group.description = description

    if type(user_list
            ) == list and user_list is not None and len(user_list) >= 1:
        old_group.users = [ User.query.filter_by(username=user_name).first() for user_name in user_list\
     if User.query.filter_by(username=user_name).count() != 0 ]
    db.session.commit()
    return jsonify(old_group.to_json())
Beispiel #27
0
    def delete_emulation(self, emulation_id):
        print '\n--> Deleting Emulation ID:', emulation_id

        connection = client.connect(g.db)
        cursor = connection.cursor()
        try:
            cursor.execute("""
          SELECT id FROM nodes
          WHERE emulation_id='{emulation_id}'
        """.format(emulation_id=emulation_id))
            nodes = cursor.fetchall()
            nodes_ids = '\'' + '\',\''.join([str(node[0])
                                             for node in nodes]) + '\''

            cursor.execute("""
          DELETE FROM nodes
          WHERE emulation_id='{emulation_id}'
        """.format(emulation_id=emulation_id))

            cursor.execute("""
          DELETE FROM blocks
          WHERE node_id IN ({nodes_ids})
        """.format(nodes_ids=nodes_ids))

            cursor.execute("""
          DELETE FROM emulations
          WHERE id='{emulation_id}'
        """.format(emulation_id=emulation_id))

        except Exception, error:
            return bad_request(error)
Beispiel #28
0
def user_payment(userid):
    try:
        if request.method == 'GET':
            payment_method = dbm.fetch_user_payment_methods(userid)
            if payment_method:
                return jsonify(payment_method)
            return not_found()
        elif request.method == 'POST':
            if request.json:
                payment_keys = post_payment_keys
                payment_keys.append('ppreferred')
                for key in payment_keys:
                    if key not in request.json:
                        return jsonify(
                            {"Errors":
                             "Missing {0} in request.".format(key)}), 400
                errors = validate_payment(request.json)
                if errors:
                    return jsonify({'Errors': errors}), 400
                billing_addressid = dbm.fetch_user_preferences(
                    userid)['billing_address']['aid']
                if billing_addressid:
                    pid = dbm.create_user_payment_method(
                        userid, request.json, billing_addressid)
                    return jsonify({'payment_methodid': pid}), 201
                else:
                    return jsonify({
                        'error':
                        'Preferred Billing Address Not Found For User {0}'.
                        format(userid)
                    }), 400
            return bad_request()
    except Exception as e:
        print e.message
        return internal_server_error()
Beispiel #29
0
def get_emotion(filelocate):
    emotion_result = labeling_face(os.path.join(UPLOAD_FOLDER, filelocate))

    if emotion_result is False:
        return bad_request('File Request in invaild')

    return jsonify(emotion_result)
Beispiel #30
0
def create_hero():
    connection = client.connect(g.db)
    cursor = connection.cursor()

    try:
        data = request.get_json()
        name = data['name']
        img = data['img']
        clan_id = data['clan_id']

        if not name:
            return bad_request('Name is not provided')
        if not clan_id:
            return bad_request('Clan ID is not provided')

        hero_id = str(uuid.uuid4())
        cursor.execute("""
			INSERT INTO heroes(
				id,
				name,
				img,
				balance,
				clan_id,
				army
			) VALUES(
				'{id}',
				'{name}',
				'{img}',
				'{balance}',
				'{clan_id}',
				[]
			)
		""".format(id=hero_id, name=name, img=img, balance=0, clan_id=clan_id))

        cursor.execute("""
			SELECT 
				id,
				name,
				img
			FROM clans
			WHERE id='{clan_id}'
		""".format(clan_id=clan_id))
        clan = cursor.fetchone()

    except Exception, error:
        print 'ERROR: ', error
        return bad_request(error)
Beispiel #31
0
def upload_to_ipfs():
    ipfs = ipfsapi.Client(g.ipfs, 5001)
    if not ipfs:
        return bad_request('IPFS server can not be reached')

    if len(request.files) == 0:
        return bad_request('No files to upload')

    ipfs_data = None
    file_type = None
    for file_name in request.files:
        dir_id = str(uuid.uuid4())
        file_id = str(uuid.uuid4())
        dir_path = './files/' + dir_id
        os.mkdir(dir_path)
        file_path = dir_path + '/' + file_id
        request.files[file_name].save(file_path)
        file_type = magic.from_file(file_path, mime=True)
        ipfs_data = ipfs.add(file_path, only_hash=True)

        file_size = int(ipfs_data['Size'])
        if file_size > g.file_size_limit:
            os.remove(file_path)
            os.rmdir(dir_path)
            return bad_request(
                'File size limit exceeded ({0} bytes over {1} bytes limit)'.
                format(file_size, g.file_size_limit))

        conn = g.mysql.connection
        cursor = conn.cursor()
        try:
            cursor.execute("""
				SELECT
					f.id, 
					f.name,
					f.size, 
					f.ipfs_hash, 
					f.tx_id, 
					f.created
				FROM files f
				WHERE ipfs_hash='{ipfs_hash}'
			""".format(ipfs_hash=ipfs_data['Hash']))
            db_file = cursor.fetchone()
        except Exception, error:
            print 'ERROR: ', error
            return bad_request(error)
        finally:
def purchase_can_store(id):
    p_order = PurchaseOrder.query.get_or_404(id)
    if p_order.state != 0:
        return bad_request(
            'cannot store a purchase order, that\'s state is not approved')
    p_order.state = -2
    db.session.commit()
    return jsonify({'error': 0, 'msg': ''})
Beispiel #33
0
def register():
    userinfo=request.json
    if userinfo['userName'] == '' or userinfo['userEmail'] == '' or userinfo['passWord'] == '':
        return bad_request('message was empty')
    user_by_email = User.query.filter_by(userEmail=userinfo['userEmail']).first()
    user_by_name = User.query.filter_by(userName=userinfo['userName']).first()
    if user_by_name is not None:
        return NotAccept('userName was aleady exist')
    if user_by_email is not None:
        return ResourceConflict('email was aleady exist')
    u=User(id=getPrimaryKeyId('isUser'), name='jxnugo_'+str(getPrimaryKeyId('isUser')), userName=userinfo['userName'], userEmail=userinfo['userEmail'],passWord=userinfo['passWord'])
    db.session.add(u)
    db.session.commit()
    token=u.generate_confirmation_token()
    send_email(u.userEmail,'激活你的账户',
                   'auth/email/confirm', User=u, token=token
                   )
    response=jsonify({"registerStatus":"successful"})
    response.status_code=200
    return response
Beispiel #34
0
def bad_request_error(e):
    return bad_request('invalid request')
Beispiel #35
0
def validation_error(e):
    return bad_request(str(e))
Beispiel #36
0
def validation_error(e):
    return bad_request(e.args[0])