Esempio n. 1
0
def put(body, order, id):
    try:
        #Update Order
        if body.get('user_id'):
            order['user_id'] = body['user_id']

        if body.get('item_description'):
            order['item_description'] = body['item_description']

        if body.get('item_quantity'):
            order['item_quantity'] = body['item_quantity']

        if body.get('item_price'):
            order['item_price'] = body['item_price']

        if body.get('total_value'):
            order['total_value'] = body['total_value']

        order['updated_at'] = datetime.now()

        #Persist on database
        es.index(index='orders', doc_type='_doc', id=id, body=order)

        return corsify_response(jsonify({'msg': 'Order Updated!'})), 200
    except:
        return corsify_response(jsonify({'msg': 'Bad Request!'})), 400
Esempio n. 2
0
def post(body):
    #check if there is no other user with the same name
    user = User.query.filter_by(name=body['name']).first()
    if user:
        return corsify_response(jsonify({'msg': 'User already exists!'})), 400

    try:
        #Insert New User
        newuser = User(name=body['name'],
                       cpf=Crypt(body['cpf'][:11]),
                       email=Crypt(body['email'][:100]),
                       phone_number=Crypt(body['phone_number'][:15]))
        db.session.add(newuser)
        db.session.commit()

        #Select this user on DB for Return Id
        newuser = User.query.filter_by(name=body['name']).first()
        res = user_schema.dump(newuser)
        doc = {
            'id': res['id'],
            'name': res['name'],
            'cpf': Decrypt(res['cpf']),
            'email': Decrypt(res['email']),
            'phone_number': Decrypt(res['phone_number']),
            'created_at': res['created_at'],
            'updated_at': res['updated_at']
        }

        #Clear Cache
        clientmc.set('query_all_users', '')
        return corsify_response(jsonify(doc)), 201
    except:
        return corsify_response(jsonify({'msg': 'Bad Request!'})), 400
Esempio n. 3
0
def getAllUsers():
    #get query from cache
    usersCache = clientmc.get('query_all_users')
    updateCache = False

    #check if it is not in cache
    if (usersCache):
        #Getting data from Cache
        all_users = usersCache
        res = all_users

    else:

        #Getting data from Database
        updateCache = True
        all_users = User.query.all()

        if all_users:
            res = users_schema.dump(all_users)

            for i in res:
                i['cpf'] = Decrypt(i['cpf'])
                i['email'] = Decrypt(i['email'])
                i['phone_number'] = Decrypt(i['phone_number'])

    #if not is empty
    if not all_users:
        return corsify_response(jsonify({'msg': 'No users found!'})), 204

    #Update Cache
    if updateCache:
        clientmc.set('query_all_users', res)

    return corsify_response(jsonify(res)), 200
Esempio n. 4
0
def post(body):
    try:

        msg = json.dumps(body)

        producer.poll(0)
        producer.produce('input_users', msg.encode('utf-8'), callback=delivery_report)
        producer.flush()

        return corsify_response(jsonify(body)), 201            
    except Exception as e:
        print(e)
        return corsify_response(jsonify({'msg': 'Bad Request!', 'error': str(e)})), 400
Esempio n. 5
0
def delete(user):
    db.session.delete(user)
    db.session.commit()

    #Clear Cache
    clientmc.set('query_all_users', '')
    return corsify_response(jsonify({'msg': 'User Deleted!'})), 200
Esempio n. 6
0
def post(body):
    try:
        document = {
            'user_id': body['user_id'],
            'item_description': body['item_description'],
            'item_quantity': body['item_quantity'],
            'item_price': body['item_price'],
            'total_value': body['total_value'],
            'created_at': datetime.now(),
            'updated_at': ''
        }

        #Create a new Order
        res = es.index(index='orders', doc_type='_doc', body=document)

        return corsify_response(jsonify(res)), 201
    except:
        return corsify_response(jsonify({'msg': 'Bad Request!'})), 400
Esempio n. 7
0
def getAllOrders():
    query = {"size": 10000, "query": {"match_all": {}}}

    #get all orders from ElasticSearch
    all_orders = es.search(index="orders",
                           doc_type="_doc",
                           body=query,
                           scroll='1m')['hits']

    #if not is empty
    if not all_orders:
        return jsonify({'msg': 'No Orders found!'}), 204

    #Define new array
    resultarray = []

    #Mount new Object with data of "User"
    for i in all_orders['hits']:
        try:
            #Get user in microservice "User"
            res = requests.get(MS_USER_HOST + str(i['_source']['user_id']))
            user = res.json()

            doc = {
                'id': i['_id'],
                'user_id': i['_source']['user_id'],
                'user_name': user['name'],
                'user_cpf': user['cpf'],
                'user_email': user['email'],
                'user_phone_number': user['phone_number'],
                'item_description': i['_source']['item_description'],
                'item_quantity': i['_source']['item_quantity'],
                'item_price': i['_source']['item_price'],
                'total_value': i['_source']['total_value'],
                'created_at': i['_source']['created_at'],
                'updated_at': i['_source']['updated_at']
            }

            resultarray.append(doc)
        except:
            #if result == 404 (User not found)

            #Return only order
            doc = {
                'id': i['_id'],
                'user_id': i['_source']['user_id'],
                'item_description': i['_source']['item_description'],
                'item_quantity': i['_source']['item_quantity'],
                'item_price': i['_source']['item_price'],
                'total_value': i['_source']['total_value'],
                'created_at': i['_source']['created_at'],
                'updated_at': i['_source']['updated_at']
            }
            resultarray.append(doc)

    return corsify_response(jsonify(resultarray)), 200
Esempio n. 8
0
def getOrdersbyUser(id):
    query = {"size": 10000, "query": {"match": {"user_id": id}}}

    #Get all Orders from this User
    all_orders = es.search(index="orders",
                           doc_type="_doc",
                           body=query,
                           scroll='1m')['hits']

    #if not is empty
    if not all_orders:
        return corsify_response(jsonify({'msg': 'No Orders found!'})), 204

    #Get user in microservice "User"
    res = requests.get(MS_USER_HOST + str(id))
    user = res.json()

    #check if user exists
    if not user.get('name'):
        return corsify_response(jsonify({'msg': 'User not found!'})), 404

    #Define new array
    resultarray = []

    #Mount new Object with data of "User"
    for i in all_orders['hits']:
        doc = {
            'id': i['_id'],
            'user_id': i['_source']['user_id'],
            'user_name': user['name'],
            'user_cpf': user['cpf'],
            'user_email': user['email'],
            'user_phone_number': user['phone_number'],
            'item_description': i['_source']['item_description'],
            'item_quantity': i['_source']['item_quantity'],
            'item_price': i['_source']['item_price'],
            'total_value': i['_source']['total_value'],
            'created_at': i['_source']['created_at'],
            'updated_at': i['_source']['updated_at']
        }
        resultarray.append(doc)

    return corsify_response(jsonify(resultarray)), 200
Esempio n. 9
0
def getUserbyId(user):
    res = user_schema.dump(user)
    doc = {
        'id': res['id'],
        'name': res['name'],
        'cpf': Decrypt(res['cpf']),
        'email': Decrypt(res['email']),
        'phone_number': Decrypt(res['phone_number']),
        'created_at': res['created_at'],
        'updated_at': res['updated_at']
    }
    return corsify_response(jsonify(doc)), 200
Esempio n. 10
0
def users_id(id):

    ### Get User From Database ###
    user = getUserFromDB(id)
    if not user:
        return corsify_response(jsonify({'msg': 'User not found!'})), 404

    ### GET ###
    if (request.method == 'GET'):
        return getUserbyId(user)

    ### PUT ###
    if (request.method == 'PUT'):
        return put(request.get_json(), user)

    ### DELETE ###
    if (request.method == 'DELETE'):
        return delete(user)
Esempio n. 11
0
def orders_id(id):

    ### Get Order From Database ###
    try:
        order = getOrderFromDB(id)
    except:
        return corsify_response(jsonify({'msg': 'Order not found!'})), 404

    ### GET ###
    if (request.method == 'GET'):
        return getOrderbyId(order, id)

    ### PUT ###
    if (request.method == 'PUT'):
        return put(request.get_json(), order, id)

    ### DELETE ###
    if (request.method == 'DELETE'):
        return delete(id)
Esempio n. 12
0
def put(body, user):
    #Update User
    if body.get('name'):
        user.name = body['name']

    if body.get('cpf'):
        user.cpf = Crypt(body['cpf'][:11])

    if body.get('email'):
        user.email = Crypt(body['email'][:100])

    if body.get('phone_number'):
        user.phone_number = Crypt(body['phone_number'][:15])

    db.session.commit()

    #Clear Cache
    clientmc.set('query_all_users', '')
    return corsify_response(jsonify({'msg': 'User Updated!'})), 200
Esempio n. 13
0
def getOrderbyId(order, id):
    try:
        #Get user in microservice "User"
        res = requests.get(MS_USER_HOST + str(order['user_id']))
        user = res.json()

        document = {
            'id': id,
            'user_id': order['user_id'],
            'user_name': user['name'],
            'user_cpf': user['cpf'],
            'user_email': user['email'],
            'user_phone_number': user['phone_number'],
            'item_description': order['item_description'],
            'item_quantity': order['item_quantity'],
            'item_price': order['item_price'],
            'total_value': order['total_value'],
            'created_at': order['created_at'],
            'updated_at': order['updated_at']
        }
    except:
        #if result == 404 (User not found)

        #Return only order
        document = {
            'id': id,
            'user_id': order['user_id'],
            'item_description': order['item_description'],
            'item_quantity': order['item_quantity'],
            'item_price': order['item_price'],
            'total_value': order['total_value'],
            'created_at': order['created_at'],
            'updated_at': order['updated_at']
        }

    return corsify_response(jsonify(document)), 200
Esempio n. 14
0
def get():
    global messages
    return corsify_response(jsonify(messages)), 200
Esempio n. 15
0
def delete(id):
    es.delete(index='orders', doc_type='_doc', id=id)
    return corsify_response(jsonify({'msg': 'Order Deleted!'})), 200
Esempio n. 16
0
def get():
    document = {
            'msg': 'Hello World, Producer API Running!'
    }

    return corsify_response(jsonify(document)), 200