Return JSON response from Flask view
I have a function that analyzes a CSV file with Pandas and produces a dict with summary information. I want to return the results as a response from a Flask view. How do I return a JSON response?
@app.route("/summary")
def summary():
d = make_summary()
# send it back as json
python json flask
add a comment |
I have a function that analyzes a CSV file with Pandas and produces a dict with summary information. I want to return the results as a response from a Flask view. How do I return a JSON response?
@app.route("/summary")
def summary():
d = make_summary()
# send it back as json
python json flask
add a comment |
I have a function that analyzes a CSV file with Pandas and produces a dict with summary information. I want to return the results as a response from a Flask view. How do I return a JSON response?
@app.route("/summary")
def summary():
d = make_summary()
# send it back as json
python json flask
I have a function that analyzes a CSV file with Pandas and produces a dict with summary information. I want to return the results as a response from a Flask view. How do I return a JSON response?
@app.route("/summary")
def summary():
d = make_summary()
# send it back as json
python json flask
python json flask
edited Jan 26 '17 at 16:45
davidism
65.8k12178191
65.8k12178191
asked Oct 26 '12 at 5:56
Code NinjaCode Ninja
1,83131111
1,83131111
add a comment |
add a comment |
9 Answers
9
active
oldest
votes
Pass the summary data to the jsonify
function, which returns a JSON response.
from flask import jsonify
@app.route('/summary')
def summary():
d = make_summary()
return jsonify(d)
As of Flask 0.11, you can pass any JSON-serializable type, not just dict, as the top level object.
As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.
– Wolfgang Kuehn
Feb 21 at 16:24
Why is the browser output an ugly string?app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
, does nothing
– F. Malina
Mar 13 at 15:31
add a comment |
jsonify
serializes the data you pass it to JSON. If you want to serialize the data yourself, do what jsonify
does by building a response with status=200
and mimetype='application/json'
.
from flask import json
@app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
status=200,
mimetype='application/json'
)
return response
@Tjorriemorrie Might not want a top level list. See stackoverflow.com/questions/3503102/…
– rob
Jun 16 '15 at 0:41
8
you can return status code with jsonify tooreturn jsonify({"Error" : "Access restricted"}), 403
– naXa
Apr 11 '16 at 20:46
2
or justreturn json.dumps(data), 200, 'application/json'
is shorter
– CpILL
Aug 27 '18 at 9:33
For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.
– Patrick Mutuku
Feb 15 at 14:59
add a comment |
Pass keyword arguments to flask.jsonify
and they will be output as a JSON object.
@app.route('/_get_current_user')
def get_current_user():
return jsonify(
username=g.user.username,
email=g.user.email,
id=g.user.id
)
{
"username": "admin",
"email": "admin@localhost",
"id": 42
}
can you please elaborate me with the code to identify filename.
– Code Ninja
Oct 26 '12 at 8:23
@CodeNinja What do you mean? If you want to putput thef
dict from your original code, you should doreturn jsonify(**f)
.
– Markus Unterwaditzer
Oct 30 '12 at 6:59
1
What if I want to return structure like{ 'names': { 'first': 'Frank', last: 'Sinatra'}, 'age': 98}
?
– David Sergey
Nov 13 '13 at 15:39
3
It's just a nested dict. Try this:jsonify({ 'names': { 'first': 'Frank', 'last': 'Sinatra'}, 'age': 98})
– zengr
Nov 13 '13 at 16:06
add a comment |
If you don't want to use jsonify
for some reason, you can do what it does manually. Call flask.json.dumps
to create JSON data, then return a response with the application/json
content type.
from flask import json
@app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
mimetype='application/json'
)
return response
import json
(instead offrom flask ...
) works just as well.
– Uri Goren
Jan 11 at 18:03
add a comment |
If you want to analyze a file uploaded by the user, the Flask quickstart shows how to get files from users and access them. Get the file from request.files
and pass it to the summary function.
from flask import request, jsonify
from werkzeug import secure_filename
@app.route('/summary', methods=['GET', 'POST'])
def summary():
if request.method == 'POST':
csv = request.files['data']
return jsonify(
summary=make_summary(csv),
csv_name=secure_filename(csv.filename)
)
return render_template('submit_data.html')
Replace the 'data'
key for request.files
with the name of the file input in your HTML form.
add a comment |
You can write a decorator to convert the return value from a view function into a JSON response.
def return_json(view):
@functools.wraps(view)
def wrapped_view(**values):
return jsonify(view(**values))
return wrapped_view
@app.route('/test/<arg>')
@return_json
def test(arg):
if arg == 'list':
return [1, 2, 3]
elif arg == 'dict':
return {'a': 1, 'b': 2}
elif arg == 'bool':
return True
return 'non of them'
1
@return_json doesn't work with status codes.
– Roman Orac
Sep 24 '18 at 9:11
add a comment |
Prior to Flask 0.11, jsonfiy
would not allow returning an array directly. Instead, pass the list as a keyword argument.
@app.route('/get_records')
def get_records():
results = [
{
"rec_create_date": "12 Jun 2016",
"rec_dietary_info": "nothing",
"rec_dob": "01 Apr 1988",
"rec_first_name": "New",
"rec_last_name": "Guy",
},
{
"rec_create_date": "1 Apr 2016",
"rec_dietary_info": "Nut allergy",
"rec_dob": "01 Feb 1988",
"rec_first_name": "Old",
"rec_last_name": "Guy",
},
]
return jsonify(results=list)
add a comment |
Like said previously jsonify is the best way or you could also use Flask-responses' package at https://github.com/Parkayun/flask-responses
@app.route("/json")
def hello():
return json_response(your_dict, status_code=201)
add a comment |
You can try this approach:
from flask import jsonify, Flask
app = Flask(__name__)
@app.route("/summary")
def summary():
d = make_summary()
return jsonify(d)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13081532%2freturn-json-response-from-flask-view%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
Pass the summary data to the jsonify
function, which returns a JSON response.
from flask import jsonify
@app.route('/summary')
def summary():
d = make_summary()
return jsonify(d)
As of Flask 0.11, you can pass any JSON-serializable type, not just dict, as the top level object.
As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.
– Wolfgang Kuehn
Feb 21 at 16:24
Why is the browser output an ugly string?app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
, does nothing
– F. Malina
Mar 13 at 15:31
add a comment |
Pass the summary data to the jsonify
function, which returns a JSON response.
from flask import jsonify
@app.route('/summary')
def summary():
d = make_summary()
return jsonify(d)
As of Flask 0.11, you can pass any JSON-serializable type, not just dict, as the top level object.
As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.
– Wolfgang Kuehn
Feb 21 at 16:24
Why is the browser output an ugly string?app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
, does nothing
– F. Malina
Mar 13 at 15:31
add a comment |
Pass the summary data to the jsonify
function, which returns a JSON response.
from flask import jsonify
@app.route('/summary')
def summary():
d = make_summary()
return jsonify(d)
As of Flask 0.11, you can pass any JSON-serializable type, not just dict, as the top level object.
Pass the summary data to the jsonify
function, which returns a JSON response.
from flask import jsonify
@app.route('/summary')
def summary():
d = make_summary()
return jsonify(d)
As of Flask 0.11, you can pass any JSON-serializable type, not just dict, as the top level object.
edited Jan 26 '17 at 16:41
davidism
65.8k12178191
65.8k12178191
answered Oct 26 '12 at 15:33


codegeekcodegeek
18.6k84859
18.6k84859
As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.
– Wolfgang Kuehn
Feb 21 at 16:24
Why is the browser output an ugly string?app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
, does nothing
– F. Malina
Mar 13 at 15:31
add a comment |
As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.
– Wolfgang Kuehn
Feb 21 at 16:24
Why is the browser output an ugly string?app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
, does nothing
– F. Malina
Mar 13 at 15:31
As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.
– Wolfgang Kuehn
Feb 21 at 16:24
As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.
– Wolfgang Kuehn
Feb 21 at 16:24
Why is the browser output an ugly string?
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
, does nothing– F. Malina
Mar 13 at 15:31
Why is the browser output an ugly string?
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
, does nothing– F. Malina
Mar 13 at 15:31
add a comment |
jsonify
serializes the data you pass it to JSON. If you want to serialize the data yourself, do what jsonify
does by building a response with status=200
and mimetype='application/json'
.
from flask import json
@app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
status=200,
mimetype='application/json'
)
return response
@Tjorriemorrie Might not want a top level list. See stackoverflow.com/questions/3503102/…
– rob
Jun 16 '15 at 0:41
8
you can return status code with jsonify tooreturn jsonify({"Error" : "Access restricted"}), 403
– naXa
Apr 11 '16 at 20:46
2
or justreturn json.dumps(data), 200, 'application/json'
is shorter
– CpILL
Aug 27 '18 at 9:33
For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.
– Patrick Mutuku
Feb 15 at 14:59
add a comment |
jsonify
serializes the data you pass it to JSON. If you want to serialize the data yourself, do what jsonify
does by building a response with status=200
and mimetype='application/json'
.
from flask import json
@app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
status=200,
mimetype='application/json'
)
return response
@Tjorriemorrie Might not want a top level list. See stackoverflow.com/questions/3503102/…
– rob
Jun 16 '15 at 0:41
8
you can return status code with jsonify tooreturn jsonify({"Error" : "Access restricted"}), 403
– naXa
Apr 11 '16 at 20:46
2
or justreturn json.dumps(data), 200, 'application/json'
is shorter
– CpILL
Aug 27 '18 at 9:33
For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.
– Patrick Mutuku
Feb 15 at 14:59
add a comment |
jsonify
serializes the data you pass it to JSON. If you want to serialize the data yourself, do what jsonify
does by building a response with status=200
and mimetype='application/json'
.
from flask import json
@app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
status=200,
mimetype='application/json'
)
return response
jsonify
serializes the data you pass it to JSON. If you want to serialize the data yourself, do what jsonify
does by building a response with status=200
and mimetype='application/json'
.
from flask import json
@app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
status=200,
mimetype='application/json'
)
return response
edited Jan 26 '17 at 16:51
davidism
65.8k12178191
65.8k12178191
answered Nov 16 '14 at 20:16


sclsscls
6,53862839
6,53862839
@Tjorriemorrie Might not want a top level list. See stackoverflow.com/questions/3503102/…
– rob
Jun 16 '15 at 0:41
8
you can return status code with jsonify tooreturn jsonify({"Error" : "Access restricted"}), 403
– naXa
Apr 11 '16 at 20:46
2
or justreturn json.dumps(data), 200, 'application/json'
is shorter
– CpILL
Aug 27 '18 at 9:33
For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.
– Patrick Mutuku
Feb 15 at 14:59
add a comment |
@Tjorriemorrie Might not want a top level list. See stackoverflow.com/questions/3503102/…
– rob
Jun 16 '15 at 0:41
8
you can return status code with jsonify tooreturn jsonify({"Error" : "Access restricted"}), 403
– naXa
Apr 11 '16 at 20:46
2
or justreturn json.dumps(data), 200, 'application/json'
is shorter
– CpILL
Aug 27 '18 at 9:33
For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.
– Patrick Mutuku
Feb 15 at 14:59
@Tjorriemorrie Might not want a top level list. See stackoverflow.com/questions/3503102/…
– rob
Jun 16 '15 at 0:41
@Tjorriemorrie Might not want a top level list. See stackoverflow.com/questions/3503102/…
– rob
Jun 16 '15 at 0:41
8
8
you can return status code with jsonify too
return jsonify({"Error" : "Access restricted"}), 403
– naXa
Apr 11 '16 at 20:46
you can return status code with jsonify too
return jsonify({"Error" : "Access restricted"}), 403
– naXa
Apr 11 '16 at 20:46
2
2
or just
return json.dumps(data), 200, 'application/json'
is shorter– CpILL
Aug 27 '18 at 9:33
or just
return json.dumps(data), 200, 'application/json'
is shorter– CpILL
Aug 27 '18 at 9:33
For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.
– Patrick Mutuku
Feb 15 at 14:59
For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.
– Patrick Mutuku
Feb 15 at 14:59
add a comment |
Pass keyword arguments to flask.jsonify
and they will be output as a JSON object.
@app.route('/_get_current_user')
def get_current_user():
return jsonify(
username=g.user.username,
email=g.user.email,
id=g.user.id
)
{
"username": "admin",
"email": "admin@localhost",
"id": 42
}
can you please elaborate me with the code to identify filename.
– Code Ninja
Oct 26 '12 at 8:23
@CodeNinja What do you mean? If you want to putput thef
dict from your original code, you should doreturn jsonify(**f)
.
– Markus Unterwaditzer
Oct 30 '12 at 6:59
1
What if I want to return structure like{ 'names': { 'first': 'Frank', last: 'Sinatra'}, 'age': 98}
?
– David Sergey
Nov 13 '13 at 15:39
3
It's just a nested dict. Try this:jsonify({ 'names': { 'first': 'Frank', 'last': 'Sinatra'}, 'age': 98})
– zengr
Nov 13 '13 at 16:06
add a comment |
Pass keyword arguments to flask.jsonify
and they will be output as a JSON object.
@app.route('/_get_current_user')
def get_current_user():
return jsonify(
username=g.user.username,
email=g.user.email,
id=g.user.id
)
{
"username": "admin",
"email": "admin@localhost",
"id": 42
}
can you please elaborate me with the code to identify filename.
– Code Ninja
Oct 26 '12 at 8:23
@CodeNinja What do you mean? If you want to putput thef
dict from your original code, you should doreturn jsonify(**f)
.
– Markus Unterwaditzer
Oct 30 '12 at 6:59
1
What if I want to return structure like{ 'names': { 'first': 'Frank', last: 'Sinatra'}, 'age': 98}
?
– David Sergey
Nov 13 '13 at 15:39
3
It's just a nested dict. Try this:jsonify({ 'names': { 'first': 'Frank', 'last': 'Sinatra'}, 'age': 98})
– zengr
Nov 13 '13 at 16:06
add a comment |
Pass keyword arguments to flask.jsonify
and they will be output as a JSON object.
@app.route('/_get_current_user')
def get_current_user():
return jsonify(
username=g.user.username,
email=g.user.email,
id=g.user.id
)
{
"username": "admin",
"email": "admin@localhost",
"id": 42
}
Pass keyword arguments to flask.jsonify
and they will be output as a JSON object.
@app.route('/_get_current_user')
def get_current_user():
return jsonify(
username=g.user.username,
email=g.user.email,
id=g.user.id
)
{
"username": "admin",
"email": "admin@localhost",
"id": 42
}
edited Jan 26 '17 at 20:30
davidism
65.8k12178191
65.8k12178191
answered Oct 26 '12 at 6:11


zengrzengr
26.4k32110179
26.4k32110179
can you please elaborate me with the code to identify filename.
– Code Ninja
Oct 26 '12 at 8:23
@CodeNinja What do you mean? If you want to putput thef
dict from your original code, you should doreturn jsonify(**f)
.
– Markus Unterwaditzer
Oct 30 '12 at 6:59
1
What if I want to return structure like{ 'names': { 'first': 'Frank', last: 'Sinatra'}, 'age': 98}
?
– David Sergey
Nov 13 '13 at 15:39
3
It's just a nested dict. Try this:jsonify({ 'names': { 'first': 'Frank', 'last': 'Sinatra'}, 'age': 98})
– zengr
Nov 13 '13 at 16:06
add a comment |
can you please elaborate me with the code to identify filename.
– Code Ninja
Oct 26 '12 at 8:23
@CodeNinja What do you mean? If you want to putput thef
dict from your original code, you should doreturn jsonify(**f)
.
– Markus Unterwaditzer
Oct 30 '12 at 6:59
1
What if I want to return structure like{ 'names': { 'first': 'Frank', last: 'Sinatra'}, 'age': 98}
?
– David Sergey
Nov 13 '13 at 15:39
3
It's just a nested dict. Try this:jsonify({ 'names': { 'first': 'Frank', 'last': 'Sinatra'}, 'age': 98})
– zengr
Nov 13 '13 at 16:06
can you please elaborate me with the code to identify filename.
– Code Ninja
Oct 26 '12 at 8:23
can you please elaborate me with the code to identify filename.
– Code Ninja
Oct 26 '12 at 8:23
@CodeNinja What do you mean? If you want to putput the
f
dict from your original code, you should do return jsonify(**f)
.– Markus Unterwaditzer
Oct 30 '12 at 6:59
@CodeNinja What do you mean? If you want to putput the
f
dict from your original code, you should do return jsonify(**f)
.– Markus Unterwaditzer
Oct 30 '12 at 6:59
1
1
What if I want to return structure like
{ 'names': { 'first': 'Frank', last: 'Sinatra'}, 'age': 98}
?– David Sergey
Nov 13 '13 at 15:39
What if I want to return structure like
{ 'names': { 'first': 'Frank', last: 'Sinatra'}, 'age': 98}
?– David Sergey
Nov 13 '13 at 15:39
3
3
It's just a nested dict. Try this:
jsonify({ 'names': { 'first': 'Frank', 'last': 'Sinatra'}, 'age': 98})
– zengr
Nov 13 '13 at 16:06
It's just a nested dict. Try this:
jsonify({ 'names': { 'first': 'Frank', 'last': 'Sinatra'}, 'age': 98})
– zengr
Nov 13 '13 at 16:06
add a comment |
If you don't want to use jsonify
for some reason, you can do what it does manually. Call flask.json.dumps
to create JSON data, then return a response with the application/json
content type.
from flask import json
@app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
mimetype='application/json'
)
return response
import json
(instead offrom flask ...
) works just as well.
– Uri Goren
Jan 11 at 18:03
add a comment |
If you don't want to use jsonify
for some reason, you can do what it does manually. Call flask.json.dumps
to create JSON data, then return a response with the application/json
content type.
from flask import json
@app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
mimetype='application/json'
)
return response
import json
(instead offrom flask ...
) works just as well.
– Uri Goren
Jan 11 at 18:03
add a comment |
If you don't want to use jsonify
for some reason, you can do what it does manually. Call flask.json.dumps
to create JSON data, then return a response with the application/json
content type.
from flask import json
@app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
mimetype='application/json'
)
return response
If you don't want to use jsonify
for some reason, you can do what it does manually. Call flask.json.dumps
to create JSON data, then return a response with the application/json
content type.
from flask import json
@app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
mimetype='application/json'
)
return response
edited Jul 25 '18 at 23:15
davidism
65.8k12178191
65.8k12178191
answered Jan 23 '18 at 19:54
Anthony AwuleyAnthony Awuley
64469
64469
import json
(instead offrom flask ...
) works just as well.
– Uri Goren
Jan 11 at 18:03
add a comment |
import json
(instead offrom flask ...
) works just as well.
– Uri Goren
Jan 11 at 18:03
import json
(instead of from flask ...
) works just as well.– Uri Goren
Jan 11 at 18:03
import json
(instead of from flask ...
) works just as well.– Uri Goren
Jan 11 at 18:03
add a comment |
If you want to analyze a file uploaded by the user, the Flask quickstart shows how to get files from users and access them. Get the file from request.files
and pass it to the summary function.
from flask import request, jsonify
from werkzeug import secure_filename
@app.route('/summary', methods=['GET', 'POST'])
def summary():
if request.method == 'POST':
csv = request.files['data']
return jsonify(
summary=make_summary(csv),
csv_name=secure_filename(csv.filename)
)
return render_template('submit_data.html')
Replace the 'data'
key for request.files
with the name of the file input in your HTML form.
add a comment |
If you want to analyze a file uploaded by the user, the Flask quickstart shows how to get files from users and access them. Get the file from request.files
and pass it to the summary function.
from flask import request, jsonify
from werkzeug import secure_filename
@app.route('/summary', methods=['GET', 'POST'])
def summary():
if request.method == 'POST':
csv = request.files['data']
return jsonify(
summary=make_summary(csv),
csv_name=secure_filename(csv.filename)
)
return render_template('submit_data.html')
Replace the 'data'
key for request.files
with the name of the file input in your HTML form.
add a comment |
If you want to analyze a file uploaded by the user, the Flask quickstart shows how to get files from users and access them. Get the file from request.files
and pass it to the summary function.
from flask import request, jsonify
from werkzeug import secure_filename
@app.route('/summary', methods=['GET', 'POST'])
def summary():
if request.method == 'POST':
csv = request.files['data']
return jsonify(
summary=make_summary(csv),
csv_name=secure_filename(csv.filename)
)
return render_template('submit_data.html')
Replace the 'data'
key for request.files
with the name of the file input in your HTML form.
If you want to analyze a file uploaded by the user, the Flask quickstart shows how to get files from users and access them. Get the file from request.files
and pass it to the summary function.
from flask import request, jsonify
from werkzeug import secure_filename
@app.route('/summary', methods=['GET', 'POST'])
def summary():
if request.method == 'POST':
csv = request.files['data']
return jsonify(
summary=make_summary(csv),
csv_name=secure_filename(csv.filename)
)
return render_template('submit_data.html')
Replace the 'data'
key for request.files
with the name of the file input in your HTML form.
edited Jan 26 '17 at 16:58
davidism
65.8k12178191
65.8k12178191
answered Dec 5 '13 at 16:44
teechapteechap
54656
54656
add a comment |
add a comment |
You can write a decorator to convert the return value from a view function into a JSON response.
def return_json(view):
@functools.wraps(view)
def wrapped_view(**values):
return jsonify(view(**values))
return wrapped_view
@app.route('/test/<arg>')
@return_json
def test(arg):
if arg == 'list':
return [1, 2, 3]
elif arg == 'dict':
return {'a': 1, 'b': 2}
elif arg == 'bool':
return True
return 'non of them'
1
@return_json doesn't work with status codes.
– Roman Orac
Sep 24 '18 at 9:11
add a comment |
You can write a decorator to convert the return value from a view function into a JSON response.
def return_json(view):
@functools.wraps(view)
def wrapped_view(**values):
return jsonify(view(**values))
return wrapped_view
@app.route('/test/<arg>')
@return_json
def test(arg):
if arg == 'list':
return [1, 2, 3]
elif arg == 'dict':
return {'a': 1, 'b': 2}
elif arg == 'bool':
return True
return 'non of them'
1
@return_json doesn't work with status codes.
– Roman Orac
Sep 24 '18 at 9:11
add a comment |
You can write a decorator to convert the return value from a view function into a JSON response.
def return_json(view):
@functools.wraps(view)
def wrapped_view(**values):
return jsonify(view(**values))
return wrapped_view
@app.route('/test/<arg>')
@return_json
def test(arg):
if arg == 'list':
return [1, 2, 3]
elif arg == 'dict':
return {'a': 1, 'b': 2}
elif arg == 'bool':
return True
return 'non of them'
You can write a decorator to convert the return value from a view function into a JSON response.
def return_json(view):
@functools.wraps(view)
def wrapped_view(**values):
return jsonify(view(**values))
return wrapped_view
@app.route('/test/<arg>')
@return_json
def test(arg):
if arg == 'list':
return [1, 2, 3]
elif arg == 'dict':
return {'a': 1, 'b': 2}
elif arg == 'bool':
return True
return 'non of them'
edited Jul 25 '18 at 23:13
davidism
65.8k12178191
65.8k12178191
answered Jun 10 '16 at 13:37


imaniman
9,22162421
9,22162421
1
@return_json doesn't work with status codes.
– Roman Orac
Sep 24 '18 at 9:11
add a comment |
1
@return_json doesn't work with status codes.
– Roman Orac
Sep 24 '18 at 9:11
1
1
@return_json doesn't work with status codes.
– Roman Orac
Sep 24 '18 at 9:11
@return_json doesn't work with status codes.
– Roman Orac
Sep 24 '18 at 9:11
add a comment |
Prior to Flask 0.11, jsonfiy
would not allow returning an array directly. Instead, pass the list as a keyword argument.
@app.route('/get_records')
def get_records():
results = [
{
"rec_create_date": "12 Jun 2016",
"rec_dietary_info": "nothing",
"rec_dob": "01 Apr 1988",
"rec_first_name": "New",
"rec_last_name": "Guy",
},
{
"rec_create_date": "1 Apr 2016",
"rec_dietary_info": "Nut allergy",
"rec_dob": "01 Feb 1988",
"rec_first_name": "Old",
"rec_last_name": "Guy",
},
]
return jsonify(results=list)
add a comment |
Prior to Flask 0.11, jsonfiy
would not allow returning an array directly. Instead, pass the list as a keyword argument.
@app.route('/get_records')
def get_records():
results = [
{
"rec_create_date": "12 Jun 2016",
"rec_dietary_info": "nothing",
"rec_dob": "01 Apr 1988",
"rec_first_name": "New",
"rec_last_name": "Guy",
},
{
"rec_create_date": "1 Apr 2016",
"rec_dietary_info": "Nut allergy",
"rec_dob": "01 Feb 1988",
"rec_first_name": "Old",
"rec_last_name": "Guy",
},
]
return jsonify(results=list)
add a comment |
Prior to Flask 0.11, jsonfiy
would not allow returning an array directly. Instead, pass the list as a keyword argument.
@app.route('/get_records')
def get_records():
results = [
{
"rec_create_date": "12 Jun 2016",
"rec_dietary_info": "nothing",
"rec_dob": "01 Apr 1988",
"rec_first_name": "New",
"rec_last_name": "Guy",
},
{
"rec_create_date": "1 Apr 2016",
"rec_dietary_info": "Nut allergy",
"rec_dob": "01 Feb 1988",
"rec_first_name": "Old",
"rec_last_name": "Guy",
},
]
return jsonify(results=list)
Prior to Flask 0.11, jsonfiy
would not allow returning an array directly. Instead, pass the list as a keyword argument.
@app.route('/get_records')
def get_records():
results = [
{
"rec_create_date": "12 Jun 2016",
"rec_dietary_info": "nothing",
"rec_dob": "01 Apr 1988",
"rec_first_name": "New",
"rec_last_name": "Guy",
},
{
"rec_create_date": "1 Apr 2016",
"rec_dietary_info": "Nut allergy",
"rec_dob": "01 Feb 1988",
"rec_first_name": "Old",
"rec_last_name": "Guy",
},
]
return jsonify(results=list)
edited Jul 25 '18 at 23:10
davidism
65.8k12178191
65.8k12178191
answered Jun 26 '16 at 15:42


mania_devicemania_device
11517
11517
add a comment |
add a comment |
Like said previously jsonify is the best way or you could also use Flask-responses' package at https://github.com/Parkayun/flask-responses
@app.route("/json")
def hello():
return json_response(your_dict, status_code=201)
add a comment |
Like said previously jsonify is the best way or you could also use Flask-responses' package at https://github.com/Parkayun/flask-responses
@app.route("/json")
def hello():
return json_response(your_dict, status_code=201)
add a comment |
Like said previously jsonify is the best way or you could also use Flask-responses' package at https://github.com/Parkayun/flask-responses
@app.route("/json")
def hello():
return json_response(your_dict, status_code=201)
Like said previously jsonify is the best way or you could also use Flask-responses' package at https://github.com/Parkayun/flask-responses
@app.route("/json")
def hello():
return json_response(your_dict, status_code=201)
edited May 3 '16 at 16:56
answered Jul 28 '15 at 19:05
Papouche GuinslyzinhoPapouche Guinslyzinho
2,40742753
2,40742753
add a comment |
add a comment |
You can try this approach:
from flask import jsonify, Flask
app = Flask(__name__)
@app.route("/summary")
def summary():
d = make_summary()
return jsonify(d)
add a comment |
You can try this approach:
from flask import jsonify, Flask
app = Flask(__name__)
@app.route("/summary")
def summary():
d = make_summary()
return jsonify(d)
add a comment |
You can try this approach:
from flask import jsonify, Flask
app = Flask(__name__)
@app.route("/summary")
def summary():
d = make_summary()
return jsonify(d)
You can try this approach:
from flask import jsonify, Flask
app = Flask(__name__)
@app.route("/summary")
def summary():
d = make_summary()
return jsonify(d)
edited Jan 21 at 10:32


iamdanchiv
2,67642432
2,67642432
answered Jan 21 at 9:49


theophilus okoyetheophilus okoye
1
1
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13081532%2freturn-json-response-from-flask-view%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown