serve json file to user in django - json

How do you serve a JSON file to user?
Currently I have a JSON object that I want the user to download.
I tried:
res = HttpResponse(json_data, content_type='application/json')
res['Content_disposition'] = 'attachment; filename=result.json'
but it still serves the json in the browser instead of making user download it.

Taken from the official docs:
response = HttpResponse(json_data, content_type='application/json')
response['Content-Disposition'] = 'attachment; filename="result.json"'

Related

Retrieving binary file from post request

Sending a POST request (Apache httpclient, here Kotlin source code):
val httpPost = HttpPost("http://localhost:8000")
val builder = MultipartEntityBuilder.create()
builder.addBinaryBody("file", File("testFile.zip"),
ContentType.APPLICATION_OCTET_STREAM, "file.ext")
val multipart = builder.build()
httpPost.entity = multipart
val r = httpClient.execute(httpPost)
r.close()
I receive the request in my post handler as a via spark-java Request-object. How do I retrieve the original file (plus the file name as a bonus) from the post request? The request.bodyAsBytes() method seems to add some bytes because the body is larger than the original file.
Thanks, Jörg
Near the bottom of Spark's Documentation page there is a section "Examples and FAQ". The first example is "How do I upload something?".
From there, it links further to an example on GitHub.
In short:
post("/yourUploadPath", (request, response) -> {
request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));
try (InputStream is = request.raw().getPart("file").getInputStream()) {
// Use the input stream to create a file
}
return "File uploaded";
});
To access the original file name:
request.raw().getPart("file").getSubmittedFileName()
To handle multiple files or parts, I usually have code similar to the following (assuming only files are included in the multi-part encoded upload):
for (Part part : req.raw().getParts()) {
try (InputStream stream = part.getInputStream()) {
String filename = part.getSubmittedFileName();
// save the input stream to the filesystem, and the filename to a database
}
}

KeyError reading a JSON file

EDIT: Here's a bit more context to how the JSON is received. I'm using the ApiAI API to generate a request to their platform, and they have a method to retrieve it, like this:
# instantiate ApiAI
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
# declare a request obect, fill in in lower lines
request = ai.text_request()
# send ApiAI the request
request.query = "{}".format(textobject.body)
# get response from ApiAI
response = request.getresponse()
response_decode = response.read().decode("utf-8")
response_data = json.loads(response_decode)
I'm coding a webapp in Django and trying to read through a JSON response POSTed to a webhook. The code to read through the JSON, after it has been decoded, is:
if response_data['result']['action'] != "":
Request.objects.create(
request = response_data['result']['resolvedQuery']
)
When I try to run this code, I get this error:
KeyError: 'result'
on the line
if response_data['result']['action'] != "":
I'm confused because it looks to me like 'result' should be a valid key to this JSON that is being read:
{
'id':'65738806-eb8b-4c9a-929f-28dc09d6a333',
'timestamp':'2017-07-10T04:59:46.345Z',
'lang':'en',
'result':{
'source':'agent',
'resolvedQuery':'Foobar',
'action':'Baz'
},
'alternateResult':{
'source':'domains',
'resolvedQuery':'abcdef',
'actionIncomplete':False,
},
'status':{
'code':200,
'errorType':'success'
}
}
Is there another way I should be reading this JSON in my program?
Try:
import JSON
if 'action' in response_data:
parsed_data = json.loads(response_data)
if parsed_data['result']['action'] != "":
Request.objects.create(request = parsed_data['result']['resolvedQuery'])
Thanks for everyone's thoughts. It turned out there was an another error with how I was trying to implement the ApiAI API, and that was causing this error. It now reads through the JSON fine, and I'm using #sasuke's suggestion.

Django, handle Response from external server

The question is how can I handle HttpResponce from an external server?
The idea is that I send json data to an external server
(e.g search data {'keyword': keyword, 'limit':limit, 'db':db})
response = requests.post(url, json = userupload, headers=headers)
after that I'm getting response from the server with json data
return HttpResponse(response)
It is on the screen, but as you can understand not in a good view for user...
So how can I add this data in a proper html table for example? (the best option is if I can print it out on the same page)
If I understand you correctly, you want to render the output of the post request which is in JSON format into a HTML file.
To do this, pass the json-encoded object from the view to the template:
views.py:
import json
def myview(request):
obj = requests.post(url, json = userupload, headers=headers)
return render_to_response("template.html", {"obj_as_json": json.dumps(obj.json())})
template.html:
<html>
<head>
<script type="text/javascript">
var obj = {{ obj_as_json }};
</script>
</head>
...
</html>
https://docs.djangoproject.com/en/1.9/intro/tutorial03/
In the django tutorial you learn how to render a response with html and context data.
If you are using requests you can do like:
response = requests.api.post(...
context = json.loads(response.json())
return render(request, 'index.html', context)
One of the big advanteges with json api's is that you can access it asynchronously with javascript. You should look in to that if you just want to render a response without calling your database to manipulate data from the json api.

File upload to Web API using Multipart request

I have a Silverlight application that uses Web API to upload a document that is stored in a Database as a Filestream. Currently it's done by a POST with a Content-Type: application/json. The object containing a byte array of the File along with some metadata about the file is serialized to JSON and posted to the Web API. Web API then saves the byte array as a Filestream to the Database.
Following is a sample of the current request:
{"FileContent":"JVBERi0xLjUNJeLjz9MNCjEwIDAgb2JqDTw8L0xpbmVhcml6ZWQgMS9MIDI3MTg2L08gMTIvRSAyMjYyNi9OIDEvVCAyNjg4NC9IIFsgNDg5IDE2OF0+Pg1lbmRvYmoNICAgICAgICAgICAgICAgICAgDQoyNyAwIG9iag08PC9EZWNvZGVQYXJtczw8L0NvbHVtbnMgNC9QcmVkaWN0b3IgMTIg0K","ProductId":"85c98324-092a-4d10-bab0-03912e437234","OrderId":"7b826322-7526-4a69-b67c-5c88a04f4c60","FileName":"test.pdf","FileType":1,"FileDescription":"test"}
I would like to change this logic to Post as a Content-Type of Multipart. What would be the best way to form my request? Also, what's the best way to structure my Web API Controller to process the Multipart request?
This is a sample for a Multipart upload.
[HttpPost]
[Route("upload")]
public async Task<IHttpActionResult> Upload()
{
MultipartFileData file = null;
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
return UnsupportedMediaType();
}
// initialize path and provider
string root = HttpContext.Current.Server.MapPath("~/App_Data");
if (Directory.Exists(root) == false) Directory.CreateDirectory(root);
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
try
{
// we take the first file here
file = provider.FileData[0];
// and the associated datas
int myInteger;
if (int.TryParse(provider.FormData["MyIntergerData"], out myInteger) == false)
throw new ArgumentException("myInteger is missing or not valid.");
var fileContent = File.ReadAllBytes(file.LocalFileName);
// do something with your file!
}
finally
{
// get rid of temporary file
if (file != null)
File.Delete(file.LocalFileName);
}
// successfull!
return NoContent();
}
This is a sample I got from an API of mine. You can have multiple files for each upload (check the provider.FileData array), and different datas inside the provider.FormData array.
For the client side aspect of this I suggest you to check this answer for a sample of a JS call to this API.
Hope it helps!

WinRT: downloading file

I want to download file from server and show the progress of loading. How may I do this?
For downloading I use this:
HttpClient client = new HttpClient();
Stream response = await client.GetStreamAsync(url);
But I don't know how to get size of downloading file and don't know how much it was downloaded
Thanks for any help
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
There is StatusCode property in response object, you can analyze this property whether you get OK or PartialContent.
You can also watch the following links for further details:
http://social.msdn.microsoft.com/Forums/en/winappswithcsharp/thread/f27c385a-e783-4062-a0b8-e21bf1704f95
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh781241.aspx