preface

Django is a Web framework developed in Python. It is popular for its powerful and fast development. I have gained 47K+ Star on Github, and its community and surrounding libraries are also extremely active. Here I will share some libraries that I often use in my work, which will get twice the result with half the effort and greatly increase the development efficiency. You can work in 3 hours for a whole day, and the rest time can be paddled (study)!

In addition to listing, I will also combine the actual use of the use of demonstration, convenient for everyone according to the need to screen. The following content is longer, it is suggested to collect and see again.

All of the libraries in this article have been tested above Django 2.1, and some libraries are available above Django 1.11.

The body of the

Django Rest Framework

The Django Rest Framework is the most recommended and necessary library for developing Django services. Maybe it is well-known enough that I do not need to expand the introduction, I will briefly introduce its use (not enough details to write 😂).

Django Rest Framework provides Django with a set of Restful apis and a series of supporting functions, such as authentication, authentication, and rate limiting. It also provides a UI test interface.

pip install djangorestframework
Copy the code

With Django’s Model, it takes only three steps to develop a Restful API.

1.1 Creating Serializer for Model

Serializer is the serialization class used to convert Model objects to AND from API Json structures. The simplest implementation is shown below.

The basic Model Field is automatically mapped to the Serializer Field without additional writing. Special fields are also provided, such as foreign key IDS that can be converted to other fields, and even the entire associated object can be introduced during serialization.

1.2 Creating a View View

Views fall into three categories: method views, class views, and Model-based viewsets.

A) Method view

The method view is a method, similar to Django’s method view, but with a decorator.

The argument to the method API_view can qualify the Http method, which defaults to GET and returns a Response object.

B) class view

The class view maps Http methods to the methods of the class.

C) ViewSet view

The ViewSet view is simpler and can be directly bound to the Model and view.

1.3 Binding a Route

Finally, bind the route to access.

You can either use Django’s Path binding or use a Router object.

There are other authentication, authentication, speed limit and other powerful functions, too much content, here will not expand.

django-filter

This library provides filtering capabilities to the Django API. Used with the Rest Framework, it provides a powerful filtering API for models in one line of code.

pip install django-filter
Copy the code

You can then filter by URL parameters.

http://example.com/api/users/1/?name=huoyan&age=20
Copy the code

Django CORS Headers

For a forward-to-back architecture, the back-end API needs to add CORS headers to provide cross-domain access. You can add it to each of the corresponding headers. Of course, you already have wheels, so why not?

pip install django-cors-headers
Copy the code

It’s as simple as adding installed_app and Middlewares.

It also provides a custom configuration function that can be configured directly in Django Settings.

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
    'DELETE'.'GET'.'OPTIONS'.'PATCH'.'POST'.'PUT'.'VIEW',
)

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest'.'X_FILENAME'.'accept-encoding'.'authorization'.'content-type'.'origin'.'user-agent'.'x-csrftoken'.'x-requested-with'.'Pragma'.)Copy the code

Django Debug Toolbar

The Django Debug Toolbar provides a powerful Debug bar for testing, allowing you to view configurations, Http headers, SQL, logs, and more directly in your browser.

pip install django-debug-toolbar
Copy the code

It’s also very simple to use.

Installed_app, static resource path, and Middlewares need to be configured.

Finally, add a route and enable the Debug function when it is True.

We then add a debug bar to the side when we access the API or view.

Django Environ

For online services, multiple environments with different configurations are a must, and that’s where Django Environ comes in. Django Environ makes it easy to incorporate environment variables into your Django Settings configuration.

pip install django-environ
Copy the code

We usually write this in setting.py

Then get the values on the Settings that need to be configured dynamically.

We can load the configuration using environment variables or an environment variable file (the only one that reads the environment variable ENV_FILE directly).

Env files look like this (on/off is automatically converted to a Boolean value)

DEBUG=on
CORS=on
LOG_LEVEL=INFO
LOG_FILE=app.log
Copy the code

At the same time, you can directly convert database and cache configurations into an environment variable.

This is configured in settings.py

Then write this in the environment variable or.env file

DATABASE_URL = PSQL: / / postgres: 123456 @127.0.0.1:5432 / postgres CACHE_URL = rediscache: / / 127.0.0.1:6379/1Copy the code

How is this better than loading environment variables directly with os.environ.get?

  • Provides environment variables file loading, if the local debugging, write all variables to the file is of course the most convenient.
  • Provides a uniform place to write the initial values of environment variables (where they are initialized), while specifying variable data types.
  • Support for data type conversions, because environment variable values are strings, variable type conversions help us handle conversions easily.
  • Support for multi-line environment variables.
  • Databases, Redis, etc., support a URL environment variable value, no need for a bunch of environment variables.
  • Support for environment variable references.

Django-Redis

Caching is common in Django, but redis is the easiest and most useful tool to use. The Django Redis library allows you to configure Redis directly as a Django cache or Session backend.

pip install django-redis
Copy the code

Configuration Settings. Py

This is even easier with django-environ above, which I usually use in combination with one line of configuration code and one environment variable.

CACHES = {
    'default': env.cache(),
}
Copy the code

The environment variable

CACHE_URL = rediscache: / / 127.0.0.1:6379/1Copy the code

Used as the Session backend

SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
Copy the code

django-rest-framework-simplejwt

Djangos Rest Framework uses Django-based authentication by default (such as sessions or tokens). If you need JWT authentication, there are wheels available.

pip install djangorestframework-simplejwt
Copy the code

Example Modify the authentication configuration of Rest Framekwork

Then add the Token fetch and refresh API

To obtain the token, use the following request

curl \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "admin"}' \
  http://localhost:8000/api/token/

{
  "access":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MT IzNDU2LCJqdGkiOiJmZDJmOWQ1ZTFhN2M0MmU4OTQ5MzVlMzYyYmNhOGJjYSJ9.NHlztMGER7UADHZJlxNG0WSi22a2KaYSfd1S-AuT7lU"."refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimIMiLCJleHAiOj IzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4"
}
Copy the code

This is how to refresh the token after the temporary token is invalid

curl \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimI MiLCJleHAiOjIzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4 "} ' \
  http://localhost:8000/api/token/refresh/

{"access":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MT IzNTY3LCJqdGkiOiJjNzE4ZTVkNjgzZWQ0NTQyYTU0NWJkM2VmMGI0ZGQ0ZSJ9.ekxRxgb9OKmHkfy-zs1Ro_xs1eMLXiR17dIDBVxeT-w"}
Copy the code

In the project with the separation of front and back ends, our front end uses axios interceptor to refresh automatically, business does not need to care about, and the code is very simple.

Grappelli

Grappelli is a skin on the Django Admin interface that provides a more user-friendly experience.

pip install django-grappelli
Copy the code

It’s easy to use.

Configure installed_app

INSTALLED_APPS = (
    'grappelli'.'django.contrib.admin'.)Copy the code

Add the routing

urlpatterns = [
    path('grappelli/', include('grappelli.urls')), # grappelli URLS
    path('admin/', admin.site.urls), # admin site
]
Copy the code

Add a request context handler

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [...'django.template.context_processors.request'. ] ,}},]Copy the code

Then reprocess the static file.

python manage.py collectstatic
Copy the code

django-celery-results/django-celery-beat

If your Django service needs Celery for asynchronous tasks, then these two libraries are not bad, so write them together.

Django-celery -results is used to store the results of django’s ORM as celery asynchronous tasks in a Django configured database when the results of asynchronous tasks need to be stored for long periods and analysed.

pip install django-celery-results
Copy the code

Simple configuration

Perform database creation

python manage.py migrate django_celery_results
Copy the code

Django-celery -beat is used to store tasks in the django database, which is useful if we need to customize tasks in the admin background.

pip install django-celery-beat
Copy the code

Simple configuration

Perform database creation

python manage.py migrate
Copy the code

Finally, specify the scheduler when starting Celery Beat

celery -A proj beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler
Copy the code

Afterword.

This is a selection of Django libraries that have been developed over the years. If you have any questions, please feel free to comment on them. If the number of users of individual libraries is large, you can write a detailed guide to use and avoid pits. If you find it useful, don’t be stingy with the likes and collections!

I am the fire eye gentleman, may my writing dispel the loneliness of the heart.

reference

  • Django
  • Django Rest Framework
  • django-filter
  • Django CORS Headers
  • Django Debug Toolbar
  • Django Environ
  • Django-Redis
  • django-rest-framework-simplejwt
  • Grappelli
  • django-celery-results
  • django-celery-beat
  • zhuanlan.zhihu.com/p/105009911