Describing the content

When developing a WEB project with Django, we usually use the inherited View class to implement basic API View scheduling. Of course, you can implement your requirements, but you need to write a lot of code to restrict and anticipate functionality. This is usually written in the form of:

from django import views

class Medusa(views.View) :
    def get(self, request, *args, **kwargs) :
        pass
Copy the code

Including the way you write the full stack without separating the front and back ends may also involve a lot of code, so is there a better way to do this? Get rid of cumbersome judgment control code and write a secure and efficient RestfulAPI in a more concise way?

Efficient solution

Assuming you are currently using standard RestfulAPI development to write JSON data returns, I highly recommend using django_rest_framework, which contains parameter judgment control/user authentication/total selection control/data filtering/request separation integration/visual API documentation, etc. This is already used heavily in many Json apis, but when you use it you just need to write:

from rest_framework import mixins

class MedusaViewSet(mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet) :
    def list(self, request, *args, **kwargs) :
        """GET request list data """
        pass
    
    def update(self, request, *args, **kwargs) :
        """PUT Updates data """
        pass
    
    def delete(self, request, *args, **kwargs) :
        """DELETE Deletes data """
        pass
        
    def create(self, request, *args, **kwargs) :
        """POST New data ""
        pass
        
    def retreve(self, request, *args, **kwargs) :
        """GET request details data ""
        pass
Copy the code

When you inherit a Class, you can override the corresponding methods of that Class to implement what you want, and of course it can implement other constraints by specifying the values of various attributes. For example, querySet = model.objects.all() declares that this ViewSet is requesting that table’s data. Other parameters can be found in the official documentation, and there will be a blog post about Rest_framework later.

So how can we simplify our code without separating the front end from the back end? For example, if I created a basic. HTML framework under templates in a Django project, I would simply add tags and content to it:

<! DOCTYPEHTML>

<html lang="en">
<head>
    <title>MedusaSorcerer-Blog</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link rel="stylesheet" href="/static/css/main.css"/>
    <link rel="stylesheet" href="/static/css/cool.css">
    {% block header %}

    {% endblock %}
</head>

<body>
    {% block body %}

    {% endblock %}
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/jquery.scrollex.min.js"></script>
    <script src="/static/js/jquery.scrolly.min.js"></script>
    <script src="/static/js/skel.min.js"></script>
    <script src="/static/js/util.js"></script>
    <! --[if lte IE 8]> <script src="/static/js/ie/respond.min.js"></script><! [endif]-->
    <script src="/static/js/main.js"></script>
</body>
</html>
Copy the code

So we just need to use the basic template basic.html to fill the body part, or we can fill the header part if needed:

{% extends "basic.html" %}

{% block header %}
    <! -- You need to fill in the header part of the code -->
{% endblock %}

{% block body %}
    <! -- The code you need to fill in the body part -->
{% endblock %}
Copy the code

In this case, your HTML is a new HTML file that inherits the template and refills it. If you have an index. HTML static file, how can you write a static file access API with simple code?

from django.views.generic import TemplateView


class TemplateViewSet(TemplateView) :
    template_name = 'bloglist.html'
Copy the code

If {{data.name}} exists in our interface, how do we pass parameters?

Implement instance methods in TemplateViewSet

def get_context_data(self, **kwargs) :
    context = super().get_context_data(**kwargs)
    context['data'] = dict(name='Medusa')
    return context
Copy the code

So what if I implement judgment redirection in get_context_data? The answer is no, this method can only return Dict data, so where does this need to be implemented?

from django.http import HttpResponseRedirect

Implement instance methods in TemplateViewSet

def dispatch(self, request, *args, **kwargs) :
    return super().dispatch(request, *args, **kwargs) if kwargs.get('sign') = ='medusa' else HttpResponseRedirect('/notfound')
Copy the code

In the Django framework, there are a lot of wheels at our disposal that let us get rid of heavy, complex and redundant blocks of code so that a few lines of code can do a lot of complex things.