How is it possible to make the blueprint return a binary data, a pdf file for example.
Response 200 (application/json)
Attributes (byte[])
is this correct ?
Related
I'm trying to send an XML file as a payload over HTTP to a Django development server on my local machine. I have no issues sending HTTP POST requests with JSON payloads and I understand that XML functionality does not come with Django REST framework out of the box, so I installed djangorestframework-xml. I used a parser decorator in my api view function definition like so:
#api_view(['GET', 'POST'])
#parser_classes([XMLParser])
def my_view(request):
if request.method =='GET':
pass
if request.method == 'POST':
return Response({'received_data': request.data})
The issue is, the way the data is structured, the information I need to parse is stored as tag attributes, like so:
<CEF>
<Element>
<p x="1" y="2"/>
</Element>
</CEF>
And when it is received by Django, request.data does not include attribute tag data:
{
"received_data": {
"Element": {
"p": null
}
}
}
Is there a header I could add to the HTTP request to preserve the xml tag attribute data?
Any pointers are greatly appreciated!
I tried different configurations for the tag data, but ultimately, I have no control over the data source and the way the data is structured in the xml file.
I was able to find a solution for this, so a short description here in case someone ever needs it.
What worked for me was using the DRF built-in FileUploadParser rather than the XMLParser for my_view function. As per documentation, I included the appropriate header to the request: Content-Disposition: attachment; filename=upload.xml.
This allowed DRF to receive the entire XML file in the request, tags attributes included. The file can then be parsed via xml.etree.ElementTree, as was suggested by the first comment to the question.
I want to get a .bmp format image via HTTP request. When I send a test request via Postman there are headlines added such as Content-Type and when the request is saved to the stream they are automatically added to the generated .bmp file and the file doesn’t work properly. When I remove not needed headlines by hand in Nano the image can be opened the way I expect it to be.
Is there a way in cpprestsdk to not add the headlines and post only the image file or the headlines need to be deleted?
void Service::handlePost(http_request request)
{
auto fileStream = std::make_sharde<Concurrency::streams::ostream>();
utility::string_t file = "file.bmp";
// open stream to output file
*fileStream = Concurrency::streams::fstream::open_stream(file).get();
request.body().read_to_end(fileStream->streambuf()).wait();
fileStream.close();
//...
}
------------------------------553993878653478454105895
Content-Disposition: form-data; name="image"; filename="file.bmp"
Content-Type: image/bmp
BM /^#^#^#^#^#^#^#^#
(BMP binary file)
^#^#^#^#^#^#^#
------------------------------553993878653478454105895--
According to the documentation(https://github.com/Microsoft/cpprestsdk/wiki/Getting-Started-Tutorial), there is no such way, so you should remove the headers yourself.
i have post request to my python code. in the json body I need to send 1 parameter. and then I need to upload csv file.
I have 2 questions: 1. how to upload the csv from postman side 2. how to get it in my python code.
attached my post request and my python code.
post request screen shot
my code in python.
#cherrypy.tools.json_in()
#cherrypy.tools.json_out()
#cherrypy.tools.accept(media='application/json')
def POST(self):
body = cherrypy.request.json
If you want to use JSON to upload data. You need to convert csv file in to base64 string before you post your data. Because JSON format does not support file.
If you just want to get your data, you can select "form-data" in postman.
Code for 'form-data':
import cherrypy
#cherrypy.expose
#cherrypy.tools.json_out()
def uploadcsv(self, img=None, other=None):
print(img)
print(other)
return 'ok'
cherrypy.quickstart(HelloWorld())
Image of postman setting:
I have following code
class MyClass(restful.Resource):
def get(self):
headers = {'Content-Type': 'text/html'}
return make_response(render_template('myfile.html'),200,headers)
def post(self):
session['CONSUMER_KEY']=request.form.get('consumer_key')
session['CONSUMER_SECRET']=request.form.get('consumer_secret')
render_template('myfile.html')
api.add_resource(MyClass,"/mag/",endpoint="mag")
I have written following test:
def mytest(self):
content_type={"Content-Type": "application / x - www - form - urlencoded","Content-Disposition": "form-data"}
response = self.client.post(
api.url_for(MyClass), data = json.dumps({'consumer_key':'testconsumerkey',
'consumer_secret':'testconsumersecret'}),
headers=content_type
)
The issue is form data is blank and thats the values are not getting set in session. When i debug i see that request.data is populated but request.form is an empty dictionary. Can someone suggest how I can send form data in a post request from a test
EDIT: Environment details
Python 2.7, Flask web framework, self.client is . I am using flask.ext.testing
You seem to be confused as to what the expected format for the post body should be. Should it be JSON data (which is what you send in the test case), or should it be in the application/x-www-form-urlencoded format (which is what you claim to send in the test case, and what the endpoint will read)?
If you wish to receive JSON data, you'll need to change the endpoint to read the data from request.get_json(). You'll also need to use application/json as the Content-Type header in the test case.
If you wish to receive urlencoded post data, then just simplify the test case by removing the Content-Type header and the json.dumps. Just pass the data dict to the data argument.
I am using Apache HttpClient to connect to a server for downloading a .wav file. I am using HTTP POST method in my program.
The server correctly responds with the following header and body:
> HTTP/1.1 200 OK\r\n Content-Disposition: attachment;
> filename=saveme1.mp3\r\n Content-Length: 6264\r\n
> Content-Transfer-Encoding: binary\r\n Content-Type: audio/mp3\r\n
How do I now extract the saveme1.mp3 file from the HTTP response? I am using the following code:
ResponseHandler<String> responseHandler = new BasicResponseHandler();
byte[] data = httpclient.execute(httppost, responseHandler).getBytes();
However, I am getting garbage when I am writing the data to a file.
FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
for (int i = 0; i < data.length; i++)
fileoutputstream.write(data[i]);
If you want download mp3 I Think easiest way is :
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
Now you have entity and can call entity.getContent(); This give you you a inputStream , now you can save this stream with every method you want , ofcurse you need mime type and filename to save your file. if you have problem with filename and mime type tell me to add some sample code.
You are getting MIME attachment that you need to parse first. The BasicResponseHandler just return the response string, but you need the body of the attachment that contains the binary of your .mp3. You would need to do the following steps:
Understand the MIME format. You could skim the Wikipedia Entry for gaining quick familiarity
Once you understood, you need to create a MIME Parser. This would basically extract each part of the MIME message especially the body of your attachment. I think there should be something out there that you could reuse. You probably should look MimeMultipart. The only thing that I am not sure about it is whether it handles "binary" encoding in your message.
Create your own extension of ResponseHandler that will utilize the MIME Parser that you have in the previous step