Search code examples
pythonflaskflask-restful

Flask show return data on request


I have some problems. I am new to python and flask.

I am building an API that makes queries to a database, a separate application front end and back end. But problems have come to rescue the search result with the Flask.

Example:

The Following 'curl' command registers a new user with username 'miguel' and password 'python':

$ Curl -X POST -H -i "Content-Type: application / json 
'd' {"username":" miguel","password":"python"} 'http://127.0.0.1:5000/api/users

RETURN:

HTTP / 1.0 201 CREATED Content-Type: application / json Content-Length: 27 Location: http://127.0.0.1:5000/api/users/1 Server: Werkzeug / Python 0.9.4 / 2.7.3 Date: Thu, 28 Nov 2013 19:56:39 GMT { "username": "miguel" }


Through doterminal we return the username, someone knows a way to retrieve and display the user's name on the front end.

Resaltar it should consider font end and back and running on different machines.

--------UPDATE-------

BACKEND

@app.route('/api/users', methods=['POST'])
def new_user():
    username = request.json.get('username')
    password = request.json.get('password')
    if username is None or password is None:
        abort(400)    # missing arguments
    if User.query.filter_by(username=username).first() is not None:
        abort(400)    # existing user
    user = User(username=username)
    user.hash_password(password)
    db.session.add(user)
    db.session.commit()
    return (jsonify({'username': user.username}), 201,
            {'Location': url_for('get_user', id=user.id, _external=True)})

FRONTEND

@home_blueprint.route('/cadastro', methods=['POST'])
def cadastro():
    username = request.form['username']
    password = request.form['password']

    if username and password:
        url = 'http://127.0.0.1:4000/api/users'
        payload = {'username': username,'password':password}
        headers = {'content-type': 'application/json'}
        r = requests.post(url, data=json.dumps(payload), headers=headers)

    else:
        return "ERRO"
    return "Create new user sucesso!"

Solution

  • (post my comment as an answer)

    You could simply use r.text to get the requests.post's retun data, from the document:

    When you make a request, Requests makes educated guesses about the encoding of the response based on the HTTP headers. The text encoding guessed by Requests is used when you access r.text.

    So just replace

    return "Create new user sucesso!"
    

    with

    return r.text
    

    In this case, r.text is requests.post(url, data=json.dumps(payload), headers=headers) return data, was created by:

    return (jsonify({'username': user.username}), 201,
            {'Location': url_for('get_user', id=user.id, _external=True)})