本文介绍了如何在Django中构建JSON REST API(没有Django REST框架)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django项目。我已经将其连接起来,因此可以为很多模型提供很多视图。现在,我想添加一个端点,该端点会将数据库的大部分内容转储为json。

I have a django project. 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.

我假设您执行此操作的方法是将URL添加到视图类/方法中,该方法返回一个充满json的HTTPResponseObject。不幸的是,经过大量的搜索之后,我只能找到对的引用。您可能会认为Django会在内部提供此类内容,而不是将其作为外部插件库的一部分。但是搜索django文档并不能立即得到答案-我认为没有任何有关如何构建仅提供一堆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. Unfortunately, after quite a bit of googling, all I can find are references to Django REST framework. This is the sort of thing you would think Django would provide internally not as part of an external plugin library. 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 REST框架来提供服务吗?

  • 我是否忽略了Django中用于提供json的文档?

  • 在Django项目中提供json的规范方法是什么? / li>
  • Do I really need "Django REST framework" to serve json in django?
  • Did I overlook docs in Django for serving json?
  • What is the canonical way to serve json in a django project?

推荐答案

经过更多的搜索后,我在Django文档中找到了所需的内容:

After more googling, I found what I was looking for in the Django docs: JsonResponse

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

我认为使用 REST一词进行谷歌搜索是一种红色鲱鱼,这使得搜索空间始终将我的查询引向 Django REST framework。尽管我要做要添加一个RESTful API,但这不是我想要的。

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.

这篇关于如何在Django中构建JSON REST API(没有Django REST框架)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:51