Writing in the front

After talking about the operations of the Django REST Framework in the previous article, today I thought of a small feature that is not important but is extremely useful, so I am writing to share the API documentation and logging of the Django REST Framework. The same concrete code is still the same as the previous framework.

The text start

1. Core API

The Core API is a documented specification that describes the API. It is used to provide an internal representation of the available paths and the possible interactions exposed by the API. It can be used on the server side or the client side.

When used on the server side, the coreAPI allows apis to support rendering of a wide range of profiles or hypermedia formats.

# Environment Preparation
pipenv install coreapi
pip install coreapi-cli

# Basic use of core API
# Add authentication
$ coreapi credentials add 127.0.0.1 admin:admin --auth basic
Added credentials
127.0.0.1 "Basic YWRtaW46YWRtaW4="

# Basic usage{$coreapi get http://127.0.0.1:8000/api/article/1"id": 1,
    "creator": "admin"."tag": "Modern Poetry"."title": "如果"."content": "I'll never think of you again in my whole life except on some nights when tears are wet and if you want to."
}
Copy the code

The coreAPI is designed to work with DRF’s built-in admin style and provides a command-line tool to test our interface. In general, the built-in interface for interface debugging has been enough, and the overall style is relatively simple and beautiful.

2. Swagger

Because of the large number of internal Java projects, Spring projects are mostly integrated with Swagger tools as interface documents. Of course, DRF also has a corresponding plug-in to support DRF-YASG. The following is a demonstration of the corresponding use.

Pipenv install DRF-yASG 2. Project configuration# settings.py

INSTALLED_APPS = [
   ...
   'django.contrib.staticfiles'.# required for serving swagger ui's css/js files
   'drf_yasg'. ]# urls.py. from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi ... schema_view = get_schema_view( openapi.Info( title="Demo API",
        default_version='v1',
        description="Demo description",
        terms_of_service="",
        contact=openapi.Contact(email="[email protected]"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=(permissions.AllowAny, ),
)

urlpatterns = [
   url(r'^swagger(? P
      
       \.json|\.yaml)$'
      , schema_view.without_ui(cache_timeout=0), name='schema-json'),
   url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
   url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),... ]Copy the code
  • Open a browser to http://127.0.0.1:8000/swagger/

  • Open a browser to http://127.0.0.1:8000/redoc/

  • Open a browser to http://127.0.0.1:8000/swagger.json

  • Open a browser to http://127.0.0.1:8000/swagger.yaml

Four styles of API-style display are supported. Have to really is the development of sharp tools, the next time there are front-end students looking for you to interface documents, you just need to throw him four links, so that he can always find a point he likes and practical interface documents.

3. Logs

  • Configure the log format and log file
# setting.py adds log configuration

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '{asctime} {filename}[line:{lineno}] {levelname} {message} {thread}-{process}'.'datefmt': "%a, %d %b %Y %H:%M:%S".'style': '{',},'simple': {
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'}},'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',}},'handlers': {
        'console': {
            # Actual development suggests using WARNING
            'level': 'DEBUG'.'filters': ['require_debug_true'].'class': 'logging.StreamHandler'.'formatter': 'simple'
        },
        'file': {
            # Actual development suggests using WARNING
            'level': 'WARNING'.'class': 'logging.handlers.RotatingFileHandler'.Log location, log file name, and log saving directory must be created manually. Note: The file path here should be BASE_DIR
            'filename': os.path.join(os.path.dirname(BASE_DIR), "logs"."demo.log"),
            The maximum value of the log file is 300M
            'maxBytes': 300 * 1024 * 1024,
            Set maximum number of log files to 10
            'backupCount': 10,
            Log format: detailed format
            'formatter': 'standard'.# File content encoding
            'encoding': 'utf-8'}},# Log object
    'loggers': {
        'demo': {
            'handlers': ['console'.'file'].'propagate': True,  Whether to allow log information to continue to bubble to other log processing systems}}},# Create folder
mkdir logs
Copy the code
  • Using logging
# Use log

import logging
logger = logging.getLogger('demo')
logger.error("Hello world")
Copy the code

conclusion

For developers, the logging and documentation functions should be served by developers; Documentation is more useful for developers to debug their development tasks, and logging is more useful for recording problems and re-bugs. So with these tools, the older generation of developers have already laid a solid foundation for you, you need to understand it and use it.

The resources

  • Drf-yasg
  • Django log
  • Django REST Framework Chinese documentation