File posting via RESTful api with django and tastypie

狂风中的少年 提交于 2020-01-01 03:07:09

问题


i am creating an RESTful api for a Django website. I am using tastypie for doing it. My problem is i could'nt design how to post images or files via this api. I mean, to create an object on database we are posting data in json format. But how can i put a file inside that json?

I found that there is two methods one of them is converting them Base64 format. I don't want to use it because in my tests, image which is 74kb is being 110kb-120kb when converted to Base64.

So can anybody explain me how can i post an object that contains files inside it?


回答1:


Look here: https://github.com/toastdriven/django-tastypie/issues/42

Looks like there were approaches todo that, but aren't working quite well.

After a long time playing around with various solutions ( https://github.com/klipstein/django-tastypie/commit/e0f86ddffeb46c77704328a3b5899ec08e18e4eb, https://github.com/klipstein/django-tastypie/commits/form-data) doing file-handling within tastypie I came to the conclusion that this can't be solved elegantly if you want to support file uploads from every browser.

Have a look on this fork

https://github.com/ff0000/django-tastypie/commit/1fbc0a




回答2:


Serializing the file into the JSON request is a slightly awkward way to do things, and also is going to mean you lose some of Django's file upload automatic niceness, eg writing the file to memory as the request comes in, and only switching to writing it to disk once it gets above a certain size.

For the file upload view you might want to drop out of tastypie, and write the view explicitly.

Then you could either use a standard multipart form, (and just access the file using request.FILES as usual, or (more complicated), create a view that will accept the raw file content.



来源:https://stackoverflow.com/questions/7193764/file-posting-via-restful-api-with-django-and-tastypie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!