Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.


The introduction

In Web projects, we often use custom status codes to inform requesters of the result and status of the request. How do you design custom status code information in Python?


Plain class plus dictionary design status code

#! /usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: Hui
# @desc: {item 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      : "Too many visits",
    RETCODE.NECESSARYPARAMERR  : "Mandatory parameters missing",}Copy the code


Use a dictionary to compare status code information, so that once there are many status codes, it will be difficult to compare, and it will not be so convenient in the process of reuse. Simply try to organize a successful message

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


Clever use of enumeration classes to design status code information

Enumeration classes can be used to cleverly design status code information


Enumeration class definition

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

from enum import Enum


class StatusCodeEnum(Enum) :
    State code enumeration class

    OK = (0.'success')
    ERROR = (-1.'wrong')
    SERVER_ERR = (500.'Server exception')
Copy the code


Ordinary classes inherit enum classes from enum modules and become enumerated classes.


Use of enumeration classes

Test 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.'wrong')
Copy the code


Each property in an enumeration class returns an enumeration object with two important properties name, value

  • nameThe name of an enumeration object’s property in an enumeration class
  • valueIs the value of the property name corresponding to the enumeration object in the enumeration class
# StatusCodeEnum.OK ->
# name value
# 'OK' (200, 'successful ')

# StatusCodeEnum.ERROR ->
# name value
# 'ERROR' (-1, 'ERROR')
Copy the code


Organize a successful response with a set of enumerated classes

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

At first glance, although the status code information is cross-referenced and concise, it is still a bit cumbersome to use, and there is one other thing

The syntax StatusCodeEnum.OK. Value [0] is not immediately recognizable. Therefore, you also need to encapsulate the enumeration class


Encapsulated enumeration classes

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

from enum import Enum


class StatusCodeEnum(Enum) :
    State code enumeration class

    OK = (0.'success')
    ERROR = (-1.'wrong')
    SERVER_ERR = (500.'Server exception')

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

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


Using the @Property decorator to use methods of a type as properties, due to enumeration classes. Attribute names correspond to different enumeration objects, which encapsulates the status code and information. Look at the result of the external call

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] :'wrong'
Copy the code


For details on how to use the @Property decorator, you can move on to Python property techniques


Continue to simulate organizational response data

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

This is finally acceptable.


Enumeration class for status code information

Share a wave of status code information ENUMeration class I usually use for your reference.

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

from enum import Enum


class StatusCodeEnum(Enum) :
    State code enumeration class

    OK = (0.'success')
    ERROR = (-1.'wrong')
    SERVER_ERR = (500.'Server exception')

    IMAGE_CODE_ERR = (4001.'Graphic captcha error')
    THROTTLING_ERR = (4002.'Visited too often')
    NECESSARY_PARAM_ERR = (4003.'Mandatory parameters missing')
    USER_ERR = (4004.'Wrong username')
    PWD_ERR = (4005.'Password error')
    CPWD_ERR = (4006.'Inconsistent passwords')
    MOBILE_ERR = (4007.'Wrong phone number')
    SMS_CODE_ERR = (4008.'SMS verification code error')
    ALLOW_ERR = (4009.'Protocol not selected')
    SESSION_ERR = (4010.'User not logged in')

    DB_ERR = (5000.'Data error')
    EMAIL_ERR = (5001.'Email error')
    TEL_ERR = (5002.'Landline 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.'Understock')

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

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

Copy the code


The tail language

✍ Code writes the world and makes life more interesting. ❤ ️

✍ thousands of rivers and mountains always love, ✍ go again. ❤ ️

✍ code word is not easy, but also hope you heroes support. ❤ ️