Why is json.dumps () necessary in Flask?

(This is probably a stupid question, so please put on your dumb shields!) I was a PHP programmer and am now learning Python + Flask. Recently, I had to struggle a lot with sending data through AJAX and returning a response. Finally, the code that worked was:

@app.route('/save', methods=['POST']) def save_subscriptions(): if request.method == 'POST': sites = request.form.get('selected') print(sites) sites = sites[0:-1] g.cursor.execute('UPDATE users SET sites = %s WHERE email = %s', [sites, session.get('email')]) g.db.commit() return json.dumps({'status': 'success'}) 

If I change return json.dumps({'status': 'success'}) to return 1 , I get an exception that int is not callable . First of all, I don’t understand who is trying to call this int and why? Secondly, in PHP it was often possible just to echo 1; , and that would be the answer of AJAX. Why doesn't return 1 work in Flask, then?

+6
source share
1 answer

The logic of what should be returned by Flask views is described in detail in the docs :

The return value from the view function is automatically converted to the response object for you. If the return value is a string, it is converted to a response object with a string as the response body, 200 OK and text / html mimetype. The logic is that Flask is used to convert return values ​​to response objects as follows:

  • If the response object of the correct type is returned, it is directly returned from the view.

  • If it is a string, a response object is created with this data and default parameters.

  • If a tuple is returned, the items in the tuple may provide additional information. Such tuples must be in the form (response, status, headers), where at least one element has to be in the tuple. The status value will override the status code and the headers can be a list or a dictionary of additional header values.

  • If none of this works, Flask will consider the return value a valid WSGI application and convert it to a response object.

In your case, the integer 1 is returned - Flask applies the last rule and tries to convert it into a response object and fails. Inside, the make_response() method is called, which, in the case of an integer, calls the force_type() of the werkzeug.Response class, which ultimately could not create an instance of the BaseResponse class when trying to create an instance of the WSGI application:

 app_rv = app(environ, start_response) 

where app in your case is integer 1 .

+7
source

All Articles