Last active
July 4, 2016 09:19
-
-
Save limboinf/58beb6b9e3bd6c10a3b2cc007258c6d8 to your computer and use it in GitHub Desktop.
Two ways to check the request of the integrity of the fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
""" | |
Two ways to check the request of the integrity of the fields | |
valid_req_field: Primitive way | |
valid_req_field_by_compress: itertools.compress() | |
""" | |
import itertools | |
def valid_req_field(req_data, *args): | |
check_fields = args | |
if not check_fields: | |
check_fields = ('token', 'security_key', 'timestarp', 'sign') | |
check = map(lambda x: x in req_data, check_fields) | |
if all(check) is False: | |
dic = dict(zip(check_fields, check)) | |
missing_fields = ','.join([k for k, v in dic.items() if v is False]) | |
raise ValueError('Missing fields %s' % missing_fields) | |
def valid_req_field_by_compress(req_data, *args): | |
check_fields = args | |
if not check_fields: | |
check_fields = ('token', 'security_key', 'timestarp', 'sign') | |
check_fields = set(check_fields) | |
checked = map(lambda x: x in req_data, check_fields) | |
t = itertools.compress(check_fields, checked) | |
miss_fileds = check_fields - set(t) | |
if miss_fileds: | |
raise ValueError('Missing fields %s' % ','.join(miss_fileds)) | |
if __name__ == '__main__': | |
"Test" | |
req_data = {'token': 'xxx', 'time': 1, 'sign':1} | |
valid_req_field_by_compress(req_data) | |
valid_req_field(req_data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment