开发者

Building a file upload API on Django with user authentication

I have a Django app that lets a user upload a file and does some processing on it, and I need to write an API for this app. The requirements are:

  • The API must accept file uploads (this is really the only thing the API will be responsible for)
  • User authentication must be supported, meaning each file uploaded must be associated with an existing Django u开发者_如何学Pythonser

I wrote the first part quite easily by just telling Django to listen for POST'ed data on a specific URL (which I hit by passing a file to curl), but that obviously won't give me user auth.

How can I add that in? Should I try something like tastypie since it's for building API's and has support for user auth, even though I will only barely scratch the surface of its functionality with this basic API? Or could I just get away with telling Django to accept a username and password in the POST along with the file? Is there a best practice for authenticating a user through an API built on top of Django?


My take on this would be to simply use the django.contrib.auth application and before handling the actual file data in the POST request just verify that the POST request also contains valid authentication info. You can do that by calling the authenticate function, see https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.authenticate

The above applies in case you want the whole process to happen in a single request. That, however, means that the whole file will be uploaded before checking the authentication info. If you can afford to split this into one auth request followed by a file upload, you can just create a view that will take care of the authentication and then protect your file upload view by the login_required decorator. This will require sessions...


Unless it's overkill for your application, I would consider using OAuth for authentication to your API. There is a django module called oauth2app that lets you guard a URL behind oauth authentication.


Auth

  • Add an authid for API. Such as url/uploadfile?file=1.txt&authid=xxx
  • The auth id can be got from another API with username & password auth.

Please refer to my code for file upload & API auth at git.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜