Is there a way to return a response (from make_response() object or similar) with certain properties so that it doesn't render the page again and doesn't do anything else either. I am trying to run a code on the server without generating any output
A simple 'return None' produces:
ValueError: View function did not return a response
This should be possible because the following only downloads a file and doesn't render the template:
myString = "First line of a document"
response = make_response(myString)
response.headers["Content-Disposition"] = "attachment; filename=myFile.txt"
return response
You are responding to a request, your HTTP server must return something. The HTTP 'empty response' response is 204 No Content:
return ('', 204)
Note that returning a file to the browser is not an empty response, just different from a HTML response.
Use Flask Response
with status 204 (no content)
from flask import Response
return Response(status=204)
Related
I need to insert in a response information in the body of this with c#.
Currently I have a function that inserts a custom message in an HttpResponseMessageProperty object which is validated from the web client observing response.statusText.
When accessing from https we discover that this data is not being sent since the requests are being made from http \ 2.
Instead of how we are sending it, I would like to know in what way I could send that data through the body.
The following code works with http 1.1. And response is of class Message
if (message.Length > 0) {
property.StatusDescription = message
}
response.Properties[HttpResponseMessageProperty.Name] = property;
Later that Message object is returned through RequestContext Reply.
How can I include data that I can later read from response.data in javascript?
Thank you all
EDIT:
I'm using Net Framework 3.5
I have an old application based on Python SimpleHTTPServer that I'm trying to convert to Flask.
In the old application, I had an HTML form that was submitting a POST request to the SimpleHTTPServer. The form also had an iframe. There, I had a do_POST method that was reading the values in the text boxes and producing some results. I then wrapped the results into a JSON object and wrote to the wfile method of SIMPLEHTTPServer. This caused the result to get populated into the iframe. The iframe had an onload method on the JS side and here, the results would be read from it and populated into various text-boxes.
I now want to convert this to Flask from SimpleHTTPServer. What is the best way to translate the logic I have in place to Flask? Basically, what is the equivalent of writing to the wfile object?
Also, on the Flask side, I also have some #app.route methods where I can form a URL with input parameters and get the results as JSON objects (example: http://localhost/calculate?input1=3&input2=5). Is it possible to leverage these URLs instead of the POST request to get the result into JavaScript?
Here is hello world of flask to get the data from URL parameters and do the stuff and return a json
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/')
def hello_world():
param1 = request.args.get('param1')
param2 = request.args.get('param2')
res = param1 + param2
return jsonify({
"result": res
})
if __name__ == '__main__':
app.run()
example request
GET http://127.0.0.1:5000/?param1=hi¶m2=there
Example response
{
"result": "hithere"
}
I am using the following PHP code to respond to a JavaScript fetch() request.
$json = json_encode(array(
'status' => 200,
'resources' => $dataObj
));
http_response_code(200);
header('Content-Type: application/json');
echo $json;
exit;
Back in my JavaScript code, after I get the response, I can do the following:
console.log(response.status);
console.log(response.resources);
console.log(JSON.stringify(response.resources));
The first line works and shows a value of 200. The other lines display undefined.
Now, if I add response.json() before my code, all three console lines show correctly.
let resp = await response.json();
console.log(resp.status);
console.log(resp.resources);
console.log(JSON.stringify(resp.resources));
My question is: Why in the first example can I correctly see the status of 200, but I need to use the json() function in order to see the data object?
When you make an http request - any http request - you will get back a status code. This is available on the response object.
You have also sent a status property as part of your response body, and until you explicitly tell your code to read the response body as json (response.json()) you wont be able to read any of your custom response.
So, basically, the status you can read is the one sent back by the server - not the one on your json.
If you're using the Fetch API you will always get an object back which you don't need to parse. It's already an object literal, specifically a https://developer.mozilla.org/en-US/docs/Web/API/Response.
This object has a property called status which returns 200 in your first case.
If you do however call the method json() on this object, it will parse the body of your response, not the whole thing. In this body you have your status from the backend not the status of the Response.
That's why let resp = await response.json() will return you your actual response data with your resources and such.
the response is actuallay a string:
"{'status':200,'resources':'sth'}"
and that string hasnt a resources property. You first need to parse it to an object literal.
To clear up some confusion:
The server sends a full response, so the upper is just the body , while a http response also consists of a header. If you do:
response.status
thats actually the headers status.
onMessage object is not receiving any data from backend. Why it is happening. Here is my code using flask in backend.
flask.py
#app.route("/ride-list/",methods=["POST","GET"])
#cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
def ride_list():
conn=sqlite3.connect('shyori.db')
cursor=conn.cursor()
result=cursor.execute("SELECT * FROM ride;")
result=list(result)
conn.commit()
conn.close()
resp=jsonify(ride=result)
resp.content_type="text/event-stream"
return resp
demo.js
<script>
var source=new EventSource("http://127.0.0.1:5000/ride-list/");
console.log(source.onMessage);
source.onMessage=function (e) {
console.log(e);
};
</script>
You should use data: msg like this,
before your msg put data:...
Event Stream Format
Sending an event stream from the source is a matter of constructing a plaintext response, served with a text/event-stream Content-Type, that follows the SSE format. In its basic form, the response should contain a "data:" line, followed by your message, followed by two "\n" characters to end the stream:
data: My message\n\n
I've configured FineUploader to use CORS and work with my Amazon Web Services S3 bucket.
The problem I face, is that a successful upload does not return any response content (Status code 204 though, but the response content is empty). So even though the upload happens (I've verified the file is uploaded), the error event is triggered. Presumably, this is because there is no response.
How do I handle this case? Is there a way for me to manually trigger a 'success' by catching this error in the 'onError' callback?
Edit:
I've made some progress digging here. The error seems to stem from handler.xhr.js.
In particular, inside the parseResponse(xhr) function.
try{
response = qq.parseJson(xhr.responseText);
}
catch(error) {
log('Error when attempting to parse xhr response text (' + error + ')', 'error');
response = {};
}
This seems to throw an error since the response is empty.
Does anyone know what a proper response should be? I'm thinking of adding a line here checking for an empty response and then manually plugging in what a correct response should be.
The issue was with the parseResponse() function after all. It expects successful uploads to return the JSON string {"success": true} after a successful upload.
In my case, Amazon returns an empty response with a 204 status code. The 204 status code implies no response is needed.
I've fixed this in my case by modifying the section mentioned in my edit as follows:
try {
if(xhr.status == 204 && xhr.responseText.length == 0){
response = qq.parseJson('{"success": true}');
}
else{
response = qq.parseJson(xhr.responseText);
}
}
Hopefully this will help others who run into this issue in the future.