在 Django 中使用 REST API 框架而不是简单的 URL 和视图创建的优势? [英] Advantages of using REST API framework over simple URL and view creation in Django?

查看:22
本文介绍了在 Django 中使用 REST API 框架而不是简单的 URL 和视图创建的优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这对很多人来说可能是一个愚蠢的问题,但我为什么不能呢

It might be a silly question for many, but why can't I instead

  • 在 django 中创建一个接受请求并以 JSON 格式返回 HttpResponse 的视图
  • 将视图映射到 URL
  • 从我的浏览器或其他服务器点击 URL 并使用结果?

谢谢.

编辑 - 两种方法:导入一些 djangorestframework 或tastypie 并在我的应用程序中构建一个 api,它将抛出 json 响应 VS 构建一个视图并告诉它返回 json 响应.使用第一个有什么巨大的优势吗?

EDIT - Two approaches: Import some djangorestframework or tastypie and build an api in my application which will throw json responses VS building a view and tell it to return json response. Is there any huge advantage of using the first one?

推荐答案

我认为您可以对任何扩展库提出相同的论点.这仅取决于您想要重建多少以及现有库中对您的项目有益的内容.

I think you could make the same argument about any extension library. It just depends on how much you want to rebuild and what the existing library has that would be beneficial to your project.

在我的项目中处理 ajax 请求时,很多时候我创建了没有 API 库的自定义端点.对于这种情况,使用 API 包是一种矫枉过正的做法.但是为了拥有一个完整的 API 服务器,Django rest 框架提供了很多功能.

Many times I've created custom endpoints without an API library when working with ajax requests inside my project. For that instance, using an API package is overkill. But for having a full API server, Django rest framework offers a lot of functionality.

当然,您可以按照您的建议创建视图.但在某些时候,您是否希望通过 HTTP 请求进行身份验证?你要过滤吗?您是要授予权限,还是只是打开所有端点?您要防范 CORS 吗?

Sure, you can make views that do what you suggested. But at some point are you going to want to authenticate through an HTTP request? Are you going to want to filter? Are you going to want to make permissions, or just have all endpoints open? Are you going to want to protect against CORS?

您可以在 API 库的所有功能列表中向下浏览,并询问有关您希望通过项目完成什么的问题.如果您正在使用任何类型的外部应用程序并且您的 django 项目仅用于 API 服务器,通常最好使用 Rest Framework.如果您只有一些一次性端点来接收 ajax 请求,通常您只想构建自定义端点.

You can kind of go down the list of all the features of an API library and ask these questions about what you want to accomplish with your project. If you're working with any type of external application and your django project is just for an API server, usually it's best to go with Rest Framework. If you just have some one-off endpoints to receive ajax requests, usually you just want to build custom endpoints.

这篇关于在 Django 中使用 REST API 框架而不是简单的 URL 和视图创建的优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆