Search code examples
google-app-engineflaskinternal-server-error

Flask only accept single json variable and crashed when setting two variables


I am building a web crawler app on Google App Engine. I want to use a post method to pass the variable to Flask. Then, the received variable became the input of my web crawler app. However, Flask only accept single variable from post. If I add another variable in the funciton, Flask would crash.

I have limited knowledge in Flask and Google app engine. I struggled with the problem for several days and your help will be highly appreciated.

Failed function

#server-side function that does not work,with 2 variable passed
@app.route('/bac',methods=['GET', 'POST'])
def bac():
    request_json = request.get_json()
    filename = request_json["filename"]
    url = request_json["url"]
    #baseconnect.Baseconnect(url=url,filename=filename).run()
    return filename,url

#The function to post on client side

import requests
req = requests.Session()
data = req.post('https://project.appspot.com/bac',json={"filename":"yuan","url":"https:...f5"})
print(data.text)

#output:
 Internal server eror 500

Succeeded function

#server-side function that works,with 1 variable passed
@app.route('/bac',methods=['GET', 'POST'])
def bac():
    request_json = request.get_json()
    filename = request_json["filename"]
    #url = request_json["url"]
    #baseconnect.Baseconnect(url=url,filename=filename).run()
    return filename

#The function to post on client side

import requests
req = requests.Session()
data = req.post('https://project.appspot.com/bac',json={"filename":"yuan"})
print(data.text)
#output:
 yuan

Flask seems only accept single variable. What is the problem....


Solution

  • The problem you have here is that Flask only returns Response object, and Flask will consider return filename, url a shortcut of return Response, status or header.

    In this case, url becomes the http status code or header, which is obviously not right.

    You need flask.jsonify() to return the proper format of so called 'multiple variables'.

    Something like this: (only the important part)

    # In server-side code
    from flask import jsonify
    @app.route('/bac',methods=['GET', 'POST'])
    def bac():
        request_json = request.get_json()
        filename = request_json["filename"]
        url = request_json["url"]
        # Do your logic here
        return jsonify({ filename_returned: filename, url_returned: url })
    
    
    # client-side
    import requests
    req = requests.Session()
    json_data = req.post('https://project.appspot.com/bac',json={"filename":"yuan", "url": "http:xxxxxxx"})
    real_data = json.loads(json_data)
    # real_data should be the result you want