Flexible use of Python enumeration class to realize design status code information

  • 2021-12-04 19:22:23
  • OfStack

Introduction

In web In projects, we often use custom status codes to inform the requester of the request results and the request status; In Python How to design custom status code information in?

Ordinary class plus dictionary design status code


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: Hui
# @Desc: {  Project response code module  }
# @Date: 2021/09/22 23:37


class RETCODE:
    OK                  = "0"
    ERROR               = "-1"
    IMAGECODEERR        = "4001"
    THROTTLINGERR       = "4002"
    NECESSARYPARAMERR   = "4003"
    

err_msg = {
    RETCODE.OK                 : " Success ",
    RETCODE.IMAGECODEERR       : " Graphic verification code error ",
    RETCODE.THROTTLINGERR      : " Visits are too frequent ",
    RETCODE.NECESSARYPARAMERR  : " Missing required parameter ",
}

Single use of a dictionary for status code information comparison, such a design of 1-denier status code is not easy to compare, and then use the process is not so convenient, simply try to organize a successful information


data = {
    'code': RETCODE.OK,
    'errmsg': err_msg[RETCODE.OK]
}

Designing status code information with enumeration class skillfully

Using enumeration classes can skillfully design status code information

Definition of an enumeration class


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: Hui
# @Desc: {  Project enumeration class module  }
# @Date: 2021/09/23 23:37

from enum import Enum


class StatusCodeEnum(Enum):
    """ Status code enumeration class """

    OK = (0, ' Success ')
    ERROR = (-1, ' Errors ')
    SERVER_ERR = (500, ' Server exception ')

Ordinary class inheritance enum In the module Enum Class becomes an enumeration class.

Use of enumeration classes

In ipython Test use in the following


In [21]: ok = StatusCodeEnum.OK

In [22]: type(ok)
Out[22]: <enum 'StatusCodeEnum'>

In [23]: error = StatusCodeEnum.ERROR

In [24]: type(error)
Out[24]: <enum 'StatusCodeEnum'>

In [26]: ok.name
Out[26]: 'OK'

In [27]: ok.value
Out[27]: (0, ' Success ')

In [28]: error.name
Out[28]: 'ERROR'

In [29]: error.value
Out[29]: (-1, ' Errors ')

Every attribute in the enumeration class returns an enumeration object, where the enumeration object has two important attributes name , value

name Enumeration Object Property Name in Enumeration Class value is the value of the corresponding attribute name of the enumeration object in the enumeration class

# StatusCodeEnum.OK ->
#    name     value
#	'OK'   (200, ' Success ')

# StatusCodeEnum.ERROR ->
#    name       value
#	'ERROR'   (-1, ' Errors ')

Organize 1 successful response information with enumerated class groups


code = StatusCodeEnum.OK.value[0]
errmsg = StatusCodeEnum.OK.value[1]
data = {
    'code': code,
    'errmsg': errmsg
}

At first glance, although the status code information 11 is compared, it is also very concise, but it is still a little troublesome to use, and there is another point

StatusCodeEnum.OK.value[0] This kind of grammar can't be known by name immediately. Therefore, the enumeration class needs to be encapsulated

Enumeration class encapsulation


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: Hui
# @Desc: {  Project enumeration class module  }
# @Date: 2021/09/23 23:37

from enum import Enum


class StatusCodeEnum(Enum):
    """ Status code enumeration class """

    OK = (0, ' Success ')
    ERROR = (-1, ' Errors ')
    SERVER_ERR = (500, ' Server exception ')

    @property
    def code(self):
        """ Get status code """
        return self.value[0]

    @property
    def errmsg(self):
        """ Get status code information """
        return self.value[1]

Pass @property The decorator uses the method of the type as an attribute, because the enumeration class. The attribute name corresponds to different enumeration objects, which encapsulates the status code and information well. Look at the results of external calls


In [32]: StatusCodeEnum.OK.code
Out[32]: 0

In [33]: StatusCodeEnum.OK.errmsg
Out[33]: ' Success '

In [34]: StatusCodeEnum.ERROR.code
Out[34]: -1

In [35]: StatusCodeEnum.ERROR.errmsg
Out[35]: ' Errors '

Specific @property Detailed explanation of the use of decorators can be moved to the use skills of property in Python

Continue to simulate organizational response data


data = {
    'code': StatusCodeEnum.OK.code,
    'errmsg': StatusCodeEnum.OK.errmsg
}

This is finally acceptable.

Status code information enumeration class

Share 1 wave of status code information enumeration classes I usually use for your reference.


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: Hui
# @Desc: {  Project enumeration class module  }
# @Date: 2021/09/23 23:37

from enum import Enum


class StatusCodeEnum(Enum):
    """ Status code enumeration class """

    OK = (0, ' Success ')
    ERROR = (-1, ' Errors ')
    SERVER_ERR = (500, ' Server exception ')

    IMAGE_CODE_ERR = (4001, ' Graphic verification code error ')
    THROTTLING_ERR = (4002, ' Visits are too frequent ')
    NECESSARY_PARAM_ERR = (4003, ' Missing required parameter ')
    USER_ERR = (4004, ' User name error ')
    PWD_ERR = (4005, ' Password error ')
    CPWD_ERR = (4006, ' Password No 1 To ')
    MOBILE_ERR = (4007, ' Wrong mobile phone number ')
    SMS_CODE_ERR = (4008, ' Wrong SMS verification code ')
    ALLOW_ERR = (4009, ' Protocol not checked ')
    SESSION_ERR = (4010, ' User is not logged in ')

    DB_ERR = (5000, ' Data error ')
    EMAIL_ERR = (5001, ' Mailbox error ')
    TEL_ERR = (5002, ' Fixed telephone error ')
    NODATA_ERR = (5003, ' No data ')
    NEW_PWD_ERR = (5004, ' Wrong new password ')
    OPENID_ERR = (5005, ' Invalid openid')
    PARAM_ERR = (5006, ' Parameter error ')
    STOCK_ERR = (5007, ' Insufficient stock ')

    @property
    def code(self):
        """ Get status code """
        return self.value[0]

    @property
    def errmsg(self):
        """ Get status code information """
        return self.value[1]

Final language

Write the world with Code to make life more interesting. ️

Qian Shan is always in love. Can you praise it before you go? ️

The code word is not easy, and I hope you heroes will give me more support. ️


Related articles: