Skillfully using Python enumeration class to design status code information

introduction

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

Common 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      : "Access too frequently",
    RETCODE.NECESSARYPARAMERR  : "Missing required parameters",
}

Use a dictionary alone to compare the status code information. In this way, once there are many status codes, it is not easy to compare, and it is not so convenient in the process of reuse. Simply try to organize a successful information

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

Skillfully using enumeration class to design status code information

Using enumeration classes, you can skillfully design status code information

Definition of 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, 'error')
    SERVER_ERR = (500, 'Server exception')

An ordinary class inherits the enum class in the enum module and becomes an enumeration class.

Use of enumeration classes

Test and use in ipython

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, 'error')

Each attribute in the enumeration class returns an enumeration object. The enumeration object has two important attributes name and value

  • Name the property name of the enumeration object in the 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, 'error')

Organize a successful response information by enumerating 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 is compared one by one and is very concise, it is still a little troublesome to use. Another thing is

Syntax such as StatusCodeEnum.OK.value[0] cannot be immediately known. Therefore, you also need to encapsulate the enumeration class

Encapsulating enumeration classes

#!/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, 'error')
    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]

The @ property decorator uses the type method as a property. Since the enumeration class and property name correspond to different enumeration objects, the status code and information are well encapsulated. 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]: 'error'

The specific usage of @ property decorator is explained in detail. You can move to Tips for using 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 a 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, 'error')
    SERVER_ERR = (500, 'Server exception')

    IMAGE_CODE_ERR = (4001, 'Graphic verification code error')
    THROTTLING_ERR = (4002, 'Access too frequently')
    NECESSARY_PARAM_ERR = (4003, 'Missing required parameters')
    USER_ERR = (4004, 'User name error')
    PWD_ERR = (4005, 'Password error')
    CPWD_ERR = (4006, 'Inconsistent passwords')
    MOBILE_ERR = (4007, 'Wrong phone number')
    SMS_CODE_ERR = (4008, 'Error in SMS verification code')
    ALLOW_ERR = (4009, 'Agreement not checked')
    SESSION_ERR = (4010, 'User 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, 'New password error')
    OPENID_ERR = (5005, 'invalid openid')
    PARAM_ERR = (5006, 'Parameter error')
    STOCK_ERR = (5007, 'Insufficient inventory')

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

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

Posted by jcrocker on Mon, 06 Dec 2021 12:40:25 -0800