4

Bit of a noob with Flask, sorry.

My application is collecting the value from a drop down then POSTing that string to my flask function. I can (sort of) get at the data by using:

@app.route("/lookupmember", methods=["POST"])
def lookupmember():
    member = request.data
    print(member)
    return member

Interestingly though when I print the value of "member" out there in the python function I see something like:

127.0.0.1 - - [19/Oct/2018 18:15:31] "POST /lookupmember HTTP/1.1" 200 - b'john doe'

Whats the b' before the name 'john doe'?

When I console.log the same value after passing it back in the Ajax caller only the name is printed in the browser console.

I reckon the b' part might be a key or identifier applied by flask? If so, it seems reasonable that there would be a way to use that to parse to get to just the name?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Indrid
  • 962
  • 4
  • 25
  • 39
  • 2
    the b is because it's a python `bytes` literal - i'm not sure why it's being printed that way on your console. What command are you running to run the http server? – AdamKG Oct 19 '18 at 17:26
  • Just running it from PyCharm: Its going to make processing the code a bit inelegant if I need to strip off the b' every time. Wonder how I could just get at the string? – Indrid Oct 19 '18 at 17:29
  • Possible duplicate of [Sending data from HTML form to a Python script in Flask](https://stackoverflow.com/questions/11556958/sending-data-from-html-form-to-a-python-script-in-flask) – dmulter Oct 19 '18 at 17:50

1 Answers1

3

If member is of type bytes, then you should convert it to a string using the decode() function. Then convert that result to JSON so that you can read it in your browser using the jsonify function:

@app.route("/lookupmember", methods=["POST"])
def lookupmember():
    member = request.data
    print(member)
    return jsonify(member.decode("utf-8"))
dana
  • 17,267
  • 6
  • 64
  • 88
  • I just get: TypeError: Object of type bytes is not JSON serializable – Indrid Oct 19 '18 at 17:44
  • Gotcha, then you have to convert the bytes to a string. I have updated my answer. – dana Oct 19 '18 at 17:48
  • 1
    you can also use `request.get_json()`, see [doc](https://flask.palletsprojects.com/en/1.1.x/api/#flask.Request.get_json) – jr6tp Sep 19 '19 at 06:47
  • Can you advice about this: https://stackoverflow.com/questions/63698809/flasks-request-data-returns-bytes-data-however-sometimes-automatically-decoded – variable Sep 02 '20 at 04:58