简体   繁体   English

如何在 django 中构建 json REST API(没有 Django REST 框架)

[英]How to build a json REST API in django (without Django REST framework)

Preface前言

I have a django project.我有一个 Django 项目。 I've wired it up so it serves a bunch of views for a bunch of models.我已经把它连接起来,所以它为一堆模型提供了一堆视图。 Now I want to add an endpoint which just dumps a good fraction of the database out as json.现在我想添加一个端点,它只是将数据库的很大一部分转储为 json。

The way I would assume you do this is add a URL to a view class / method which returns a HTTPResponseObject full of json.我假设你这样做的方法是向视图类/方法添加一个 URL,它返回一个充满 json 的 HTTPResponseObject。 Unfortunately, after quite a bit of googling, all I can find are references to Django REST framework .不幸的是,经过相当多的谷歌搜索后,我只能找到对Django REST framework 的引用。 This is the sort of thing you would think Django would provide internally not as part of an external plugin library.这是你认为 Django 会在内部提供而不是作为外部插件库的一部分的那种东西。 But searching the django docs doesn't yield an immediate answer -- I don't think there are any docs about how to build an endpoint which just serves a bunch of json.但是搜索 django 文档并没有立即得到答案——我认为没有关于如何构建一个只提供一堆 json 的端点的文档。

Questions:问题:

  • Do I really need "Django REST framework" to serve json in django?我真的需要“Django REST framework”来在 Django 中提供 json 服务吗?
  • Did I overlook docs in Django for serving json?我是否忽略了 Django 中为 json 提供服务的文档?
  • What is the canonical way to serve json in a django project?在 Django 项目中提供 json 的规范方式是什么?

After more googling, I found what I was looking for in the Django docs: JsonResponse经过更多的谷歌搜索,我在 Django 文档中找到了我想要的东西: JsonResponse

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

I think googling using the word "REST" was kind of a red herring which made the search space always direct my queries towards "Django REST framework" which is not what I wanted, though I do want to add a RESTful API.我认为使用“REST”这个词在谷歌上搜索是一种红鲱鱼,这使得搜索空间总是将我的查询导向“Django REST framework”,这不是我想要的,尽管我确实想添加一个 RESTful API。

You can write GET API using this method, but for POST method this will not work.您可以使用此方法编写 GET API,但对于 POST 方法,这不起作用。 For Post method we need to use some REST Library.对于 Post 方法,我们需要使用一些 REST 库。

POST Method will check for CSRF token in the cookies and where it fails to execute the request, as your django server will treat this request as forged. POST 方法将检查 cookie 中的 CSRF 令牌以及它无法执行请求的位置,因为您的 django 服务器会将此请求视为伪造的。

You should go with Django Rest Framework but if you want to do it yourself then:你应该使用 Django Rest Framework 但如果你想自己做,那么:

  1. For POST request, if the client is sending you data as JSON, then you can use the json module to read the data from the request body.对于 POST 请求,如果客户端将数据作为 JSON 发送给您,那么您可以使用 json 模块从请求正文中读取数据。
import json

def add_new_user(self, request):
    data = request.body.decode('utf8')
    data = json.loads(data)
  1. If plain name/value pair is sent, then use request.POST or request.GET如果发送纯名称/值对,则使用 request.POST 或 request.GET

  2. Use JsonResponse to send the response使用 JsonResponse 发送响应

  3. After authentication, the server usually send a token to the client.认证后,服务器通常会向客户端发送一个令牌。 The client then sends that token when sending a request to 'protected' api end-point.然后,客户端在向“受保护”api 端点发送请求时发送该令牌。 A custom header (like auth_token) is used to send the token.自定义标头(如 auth_token)用于发送令牌。

In the server code, you need to do something like request.META['HTTP_AUTH_TOKEN'] to get the token (see Custom HTTP Header in Django )在服务器代码中,您需要执行诸如 request.META['HTTP_AUTH_TOKEN'] 之类的操作来获取令牌(请参阅Django 中的自定义 HTTP 标头

There are more things to consider like CSRF token or JWT.还有更多的事情需要考虑,比如 CSRF 令牌或 JWT。

See this site for a complete examplehttps://jee-appy.blogspot.com/2018/02/make-rest-api-django.html .请参阅此站点以获取完整示例https://jee-appy.blogspot.com/2018/02/make-rest-api-django.html Be warned, it use old version of django.请注意,它使用旧版本的 django。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM