This article is participating in Python Theme Month. See the link to the event for more details

Rest cannot be enjoyed by lazy people~

preface

When using the Django framework to develop a separate project, it is often necessary to verify the parameters passed from the front end in a variety of ways, such as using DRF or JSON. This article describes 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 for Python3, which means that Python3 can use rapidjson to serialize and deserialize data and validate parameters.

Rapidjson install command: PIP install python-rapidjson.

Rapidjson basic use

Rapidjson and THE JSON module use the same basic method, but rapidJSON is not compatible with the JSON module in some parameters, these parameters are not commonly used, so I will not introduce them here. For details, please refer to the official rapidJSON document. Introduces two basic use serialization methods dump/dumps, deserialize the load/loads using json module.

Both methods serialize Python instance objects into A STRING in the JSON format with roughly the same usage and arguments. The dump method has one more necessary file_like argument than the dumps method.

Dumps () method

The result returned by this method is an instance of a Python string. There are a lot of arguments, but here are only three that are used frequently.

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)
Copy the code

skipkeys

This parameter indicates whether to skip the key of the unavailable dictionary for serialization. If False is the default, if True the key of the dictionary is not one of the basic data types (STR int float bool None) it will skip the key without raising 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)  # '{}'
Copy the code

ensure_ascii

This parameter indicates whether the serialized result contains only ASCII characters. The default value is True. When the Python instance is serialized, all non-ASCII characters will be escaped.

dic = {
    'name': 'lily'.'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"}'
Copy the code

sort_keys

This parameter indicates whether the keys of the dictionary are sorted alphabetically when serialized. The default is False, and if changed to True, the result of the dictionary serialization is sorted alphabetically by the key of the dictionary.

dic = {
    'name': 'lily'.'age': '10'
}
res = rapidjson.dumps(dic, ensure_ascii=False, sort_keys=True)
pprint(res)  # '{"age":"10","name":" 1 "}'
Copy the code

The 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, to serialize the first parameter, obj, 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)
Copy the code

Here are some basic uses of this method:

# write to file
dic = {
    'name': 'lily'.'age': '10'
}
f = open('1.py'.'w', encoding='utf8')
res = rapidjson.dump(dic, f)
pprint(res)

# or the following
import io

stream = io.BytesIO()
dump('bar', stream)
print(stream.getvalue())  # b'"bar"'

Copy the code

Validator class

The Validator class in RapidJSON can be used for parameter validation. The Validator parameter is a JSON Schema. When we need to know the expected fields and value representation in the JSON data, this is where JSON Schema is used. It is a declaration format to describe the JSON data structure, and can also be commonly understood as a parameter validation rule. If the JSON Schema is not available for JSON-formatted data, an exception of JSONDecodeError is thrown.

If the given JSON data fails validation, the ValidationError exception is raised. The exception consists of the type of error, the validation 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 both arguments a and b are required
validate('{"a": null, "b": 1}')  # Comply with rules
validate('{"a": null, "c": false}')  # rapidjson.ValidationError: ('required', '#', '#')
Copy the code
validate = rapidjson.Validator('{"type": "array",'  # Parameter type is array
                     ' "items": {"type": "string"},'  Each element in an array is of type String
                     ' "minItems": 1}')  The number of elements in an array must be at least 1

validate('["foo", "bar"]')  # Comply with rules
validate('[]')  # rapidjson.ValidationError: ('minItems', '#', '#')
Copy the code

For more JSON Schema parameter validation rules and definition specifications, please refer to *JSON Schema official document *. 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))
Copy the code

conclusion

The article was first published in the wechat public account program Yuan Xiaozhuang, synchronized with nuggets.

Please explain where it came from. If you pass by, please put out your cute little finger and click like before you go (╹▽╹)