Implementation of rapidjson parameter verification in Python

Time:2021-10-16
catalogue
  • preface
  • Introduction and installation of rapidjson
  • Basic use of rapidjson
    • Dumps() method
      • skipkeys
      • ensure_ascii
      • sort_keys
    • Dump() method
    • Validator class

      preface

      When using Django framework to develop front-end and back-end separated projects, it is usually necessary to verify the parameters passed from the front-end. There are many verification methods, including DRF or JSON. This paper introduces the basic use of rapidjson in Python and how to verify the parameters.

      Introduction and installation of rapidjson

      Rapidjson is a very good C + + JSON parser and serialization library. It is packaged as an extension package of Python 3, that is, rapidjson can be used for data serialization and deserialization in Python 3, and parameters can be verified, which is very convenient and easy to use.

      Rapidjson installation command:pip install python-rapidjson

      Basic use of rapidjson

      The basic usage methods of rapidjson and JSON module are the same, but rapidjson is incompatible with JSON module in some parameters. These parameters are not commonly used, so we won’t introduce them here. For details, please refer to the official documentation of rapidjson. Basically, the two serialization methods dump / dumps are introduced, and the deserialized load / loads can use the JSON module.

      Dumps & dump both methods serialize Python instance objects into JSON format strings. Their usage and parameters are roughly the same. The dump method has one more necessary file than the dumps method_ Like parameter.

      Dumps() method

      The result returned by this method is a Python string instance. There are many parameters. Only three parameters that are often used are introduced here.

      
      rapidjson.dumps(obj, *, skipkeys=False, ensure_ascii=True, write_mode=WM_COMPACT, indent=4, default=None, sort_keys=False, number_mode=None, datetime_mode=None, uuid_mode=None, bytes_mode=BM_UTF8, iterable_mode=IM_ANY_ITERABLE, mapping_mode=MM_ANY_MAPPING, allow_nan=True)
      

      skipkeys

      This parameter indicates whether to skip the key of the unavailable dictionary for serialization. If it is false by default, if it is modified to true, if the key of the dictionary does not belong to one of the basic data types (STR int float bool none), it will skip the key without throwing an exception of typeerror.

      
      import rapidjson
      from pprint import pprint
      
      dic = {
          True: False,
          (0,): 'python'
      }
      res = rapidjson.dumps(dic)
      pprint(res)  # TypeError: {True: False, (0,): 'python'} is not JSON serializable
      
      res = rapidjson.dumps(dic, skipkeys=True)
      pprint(res)  # '{}'
      
      

      ensure_ascii

      This parameter indicates whether the serialization result contains only ASCII characters. The default value is true. After serializing the python instance, all non ASCII characters will be escaped. If the value of this parameter is changed to false, the characters will be output as is.

      dic = {
          'name': 'Lili',
          'name1': 'lili'
      }
      res = rapidjson.dumps(dic)
      pprint(res)   # '{"name":"\\u4E3D\\u4E3D","name1":"lili"}'
      
      res = rapidjson.dumps(dic, ensure_ascii=False)
      Pprint (RES) # '{"name": "Lili", "name1": "Lili"}'

      sort_keys

      This parameter indicates whether dictionary keys are sorted alphabetically during serialization. The default is false. If it is modified to true, the results of dictionary serialization are sorted in alphabetical order of dictionary keys.

      dic = {
          'name': 'Lili',
          'age': '10'
      }
      res = rapidjson.dumps(dic, ensure_ascii=False, sort_keys=True)
      Pprint (RES) # '{"age": "10", "name": "Lili"}'

      Dump() method

      This method is very similar to the dumps method, except that it requires an additional required parameter – a file like writable streaming object, such as a file object. The first parameter obj is serialized and written into the writable streaming object.

      
      rapidjson.dump(obj, stream, *, skipkeys=False, ensure_ascii=True, write_mode=WM_COMPACT, indent=4, default=None, sort_keys=False, number_mode=None, datetime_mode=None, uuid_mode=None, bytes_mode=BM_UTF8, iterable_mode=IM_ANY_ITERABLE, mapping_mode=MM_ANY_MAPPING, chunk_size=65536, allow_nan=True)
      

      The following is the basic use of this method:

      #Write file
      dic = {
          'name': 'Lili',
          'age': '10'
      }
      f = open('1.py', 'w', encoding='utf8')
      res = rapidjson.dump(dic, f)
      pprint(res)
      
      #Or the following usage
      import io
      
      stream = io.BytesIO()
      dump('bar', stream)
      print(stream.getvalue())  # b'"bar"'

      Validator class

      The validator class in rapidjson can be used for parameter verification. The parameter of validator is JSON schema. When we need to know the expected fields in JSON data and the representation of values, this is the use of JSON schema. It is a declaration format for describing JSON data structure. It can also be popularly understood as a parameter verification rule. If the JSON schema is unavailable JSON formatted data, an exception of JSON decodeerror will be thrown.

      The parameter of class is the verification rule. If the given JSON data fails to pass the verification, a validationerror exception will be thrown. The exception includes three parts: the type of error, the verification rule and the location of the error in the JSON string.

      import rapidjson
      from pprint import pprint
      
      Validate = rapidjson. Validator ('{"required": ["a", "B"]}') # indicates that the parameters a and B are required
      Validate ('{' a ': null,' B ': 1}') # conforms to the rule
      validate('{"a": null, "c": false}')  # rapidjson.ValidationError: ('required', '#', '#')
      Validate = rapidjson. Validator ('{"type": "array",' # parameter type is array
                           'items': {type': 'string'}, # each element type in the array is string
                           '"minitems": 1}') # the minimum number of elements in the array is 1
      
      Validate ('["foo", "bar"]') # meets the rule
      validate('[]')  #  rapidjson.ValidationError: ('minItems', '#', '#')

      For more parameter verification rules and definition specifications of JSON schema, please refer to * official document of JSON schema *. The following is a JSON schema format for reference only:

      
      LOGIN_SCHEMA = {
          "type": "object",
          "properties": {
              "token": "string",
              "number": "integer"
          },
          "required": ["token"],
      }   
      }
      
      validate = rapidjson.Validator(rapidjson.dumps(LOGIN_SCHEMA))
      data = {
          'token': 'python',
          'number': 10
      }
      validate(rapidjson.dumps(data))

      This is the end of this article about the implementation of rapidjson parameter verification in Python. For more information about Python rapidjson parameter verification, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!