See github open source: github.com/githublitao…

Environment set up

New project

  • Select the Django framework + Virtual Environment

Database Configuration

  1. Modify the Settings. Py

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql'.'HOST': '127.0.0.1'.# database host
            'PORT': 3306,  # database port
            'USER': 'root'.Database user name
            'PASSWORD': 'admin1234'.Database user password
            'NAME': 'api_test'  # database name}}Copy the code
  2. Install related libraries:

    PIP install mysqlclient = = 1.4.6

    pip install wheel

Middleware configuration

  1. Prerequisite: Use the REST-Framework framework

    • Installation:

      pip install djangorestframework

    • Modify the Settings. Py:

      Add ‘rest_framework’ to INSTALLED_APPS

  2. Format response output

    • Create a new utils folder and create custom_response_middleware.py

      class CustomResponseMiddleware:
      def __init__(self, get_response):
          self.get_response = get_response
           Configure and initialize
      
      def __call__(self, request):
      
          Write the code here that needs to be executed before the view and the middleware behind it are called
          This is actually the code for the old process_request() method
          response = self.get_response(request)
          # if "code" not in response.data:
          #
          # data = response.data
          # response.data={
          # "code":"0000",
          # "message":" query successful ",
          # "data":response.data
          #}
          To render response, you need to manually render it once
          # response._is_rendered = False
          # response.render()
          # response["content-length"]=len(response.content)
          Write the code that needs to be executed after the view call
          This is actually the code for the old process_response() method
          return response
      
      def process_template_response(self, request, response):# recommended
          if "code" not in response.data:
              data = response.data
              response.data={
                  "code":"0000"."message":"Operation successful"."data":response.data
              }
          Write the code that needs to be executed after the view call
          This is actually the code for the old process_response() method
      
          return response
      Copy the code
    • Modify the Settings. Py:

      Increase the front in MIDDLEWARE ‘utils. Custom_response_middleware. CustomResponseMiddleware’. (Response middleware is first, request middleware is last)

    • Override the exception class utils/custom_exception.py

      from rest_framework import status from rest_framework.exceptions import ValidationError from rest_framework.views import  exception_handler as drf_exception_handler from utils.custom_response import CustomResponse def exception_handler(exc,context):"""Custom exception handling :param exc: Exceptions thrown elsewhere are passed to exc: param context: dictionary form. The context in which the exception was thrown (that is, the source from which the exception was thrown; The view that throws an exception) :return: Response""
          response = drf_exception_handler(exc,context)
          if response is None:
              # exception that DRF cannot handle
              print('%s - %s - %s' % (context['view'], context['request'].method, exc))
              return CustomResponse({'detail': 'Server error'}, code=500,msg="Server internal error",status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
          if isinstance(exc,ValidationError):
              message = ""
              data = response.data
              for key in data:
                  message += ";".join(data[key])
              return CustomResponse(None,code="9999",msg=message)
          return response
      
      Copy the code

      Modify the Settings. Py

      REST_FRAMEWORK = {
          'EXCEPTION_HANDLER':'utils.custom_exception.exception_handler',}Copy the code
    • Override the response utils/custom_response.py

      from rest_framework.response import Response
      
      
      # override response
      class CustomResponse(Response):
      
          def __init__(self, *args, code='0000', msg="Success", **kwargs):
              # format data
              data = {
                  "code": code,
                  "message": msg
              }
              if args is not None:
                  data["data"] = args[0]
                  kwargs["data"] = data
              elif "data" in kwargs:
                  data["data"] = kwargs["data"]
                  kwargs["data"] = data
      
              super().__init__(**kwargs)
      
      Copy the code

The new application

  • python manage.py startapp guoya_api
  • Add an application tosettings.pytheINSTALLED_APPSIn the

Routing distribution

Urlpatterns = [path('admin/', admin.site.urls), path('v01/', include('guoya_api.urls'))),] subpaths:  ``` urlpatterns = [ ] ```Copy the code

models

File location: guoya_API > Models

Use models directly from the open source code:

Github.com/githublitao…

  • Data migration

    Generate migration script:

    python manage.py makemigrations

    Performing migration of specimens:

    python manage.py migrate

Create a serializer for the model

File location: guoya_API >serializers. Py

Use serializers directly in open source code:

Github.com/githublitao…