Django 或 Django 休息框架

我在 Django 中开发了一个特定的应用程序,我知道 Django RestFramework 是用来构建 API 的。然而,当我开始在他们的网站上阅读 Django Rest Framework 时,我注意到 空气污染指南中的每一个东西(如请求、响应、视图等)都声称它优于 Django (请求、响应、视图等)。

我不明白的是,这些 API 是否会取代我现有的 Django 模型、视图等,或者我如何在我现有的 Django 代码中以不同的方式使用它们?

我非常熟悉 Django,但是即使花了一些时间在上面,我也不能准确地理解 Django 剩余框架是什么。(我知道它用于 API。)还有,我真的需要 API 吗?我的应用程序能够在没有 API 的情况下向服务器发送数据,那么在什么情况下我需要 API 呢?

49250 次浏览

Django Rest Framework makes it easy to use your Django Server as an REST API.

REST stands for "representational state transfer" and API stands for application programming interface.

You can build a restful api using regular Django, but it will be very tedious. DRF makes everything easy. For comparison, here is simple GET-view using just regular Django, and one using Django Rest Framework:

Regular:

from django.core.serializers import serialize
from django.http import HttpResponse




class SerializedListView(View):
def get(self, request, *args, **kwargs):
qs = MyObj.objects.all()
json_data = serialize("json", qs, fields=('my_field', 'my_other_field'))
return HttpResponse(json_data, content_type='application/json')

And with DRF this becomes:

from rest_framework import generics




class MyObjListCreateAPIView(generics.ListCreateAPIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = MyObjSerializer

Note that with DRF you easily have list and create views as well as authentication.

Whether you need an api depends on what you want to do. For example, if you want to access everything in your Django models from a mobile device AND a web-app, you would want to use DRF.

Why? Consider the case that you are developing an iOS app that users can sign into and you want to use Django as your backend. If you also want to have a website that they can use to change around their app's profile information (say, update their email address or upload a picture), you would need a way to share the information in your Django models with both a website and the iOS device. How can this be done? By giving the user the ability to create/read/update/delete data by simply telling it a url to go to. Now, if you want to access information from the model you can do it from multiple devices, since any device can visit a url.

However, if you're just building a simple webapp/webpage and keep it all in one place, you can just use straight Django.

Side note: it's a pretty popular opinion that you should try to separate your frontend from your backend as much as possible. In this case, if you want to use some frontend development framework like React, Angular, or Vue, it's gonna get messy trying to include all those resources in the Django template pages even if you only want a simple web app/web page. In this case, you would use DRF to set up your backend, and just hit the urls from the frontend using a tool like axios. In this scenario, your frontend would likely be hosted on something like Node.

Again, what you decide to use really just depends on what you want out of your app/site and how comfortable you are with each tool.

The basic purpose of DRF is to provide APIs. APIs are the touch point in an app. Imagine a project where you have a Django wizard and someone on your team is a JavaScript expert and you want to develop mobile app. The JavaScript expert talks about web elements and threading and the Django expert talks templates and ORM, now what? API is your answer. Let Django wiz give APIs and JSON and let JavaScript wiz do his front end magic. Simplest answer I can think of.

Here is a link which might give you some insights on what you are looking for. This explains how a django app can be converted into Django Rest Service, and it also explains what a REST Service actually is

https://opensourceforu.com/2017/11/converting-django-app-rest-api/

In simple words,

Django: provides features for standard web app

Django Rest Framework: provides features to build standard REST API.

Simply saying: with just Django you can create server side rendered websites; and with DRF you can create SPAs with a vuejs or react frontend part.

the old school used Jinja2 with html5, css3, but this became inconvenient when Single Page Applications became popular.API helps to provide information more convenient for the frontend programmer. You no longer work with the frontend. The API is convenient when developing as Web applications and when developing applications for the phone.

Let's sum up,

Django :

Tightly coupled with Django Templates.

Django Rest Framework :

Open for building views of my own choices with REST APIs.

  1. Do you actually need Api? It depends on your requirement and resources. If you only need a web application then django provides everything you require to develop a web application. If you need to develop a mobile application that will communicate with a backend server then you will have to implement Api. If you have remote iot devices that needs to publish its data to your server, you will need Api. If you are good at frontend app development, mobile app development, and iot app development or you have resources to have separate team for frontend, backend, mobile and iot app development then it is good design to separate backend and frontend applications. To achieve this separation, your backend will be api based and your frontend, mobile and iot app will communicate with your backend using your backend api. With this design, any changes in backend will have minimal impact on your other apps.

  2. Will these APIs replace your existing Django models? Ideally it should not but I am not sure if using drf will change your django models. I have not used drf to implement api. But if you just use django to implement your api, it will definitely will not change your models. You just need to define your api urls and api views.

  3. Do you require external packages like drf to implement api endpoint in Django? No. You can easily implement Api endpoints using pure Django framework.

  4. A simple way to implement api using pure Django.

    Define your api url -

    urlpatterns = [
    path('get_all_user/',UserApiView.as_view(),name='get_all_user'),
    ]
    

    Define your view

    @method_decorator(csrf_exempt,name='dispatch')
    class UserApiView(View):
    
    
    def post(self, request):
    response_data = {}
    json_data = json.loads(request.body)
    response_data['user'] = YourMethodToGetModelData(json_data)
    return JsonResponse(response_data)
    

enter image description here

You can use django to build a complete web application, then what is the need of api?

Let's take a example for suppose at first you build a website for your startup using django. Your site grew popular, and for easier access in Android you thought of building a mobile application. Then are you going to maintain a separate database? Nope, because not only it's difficult to maintain, but migrating the old data is also a headache. So here what django rest framework comes into play. You can set up apis to be used by your Android application, hence have to maintain a single database against multiple apps.

Suppose you are building a web application.

In order to complete your app, if you want to code more python / Django code then use Django, to the contrary if you want to code more JavaScript code then use Django restful API.

For web application itself I like using Django ,because it is based on python ,it is much cleaner and shorter than js.