Skip to content

Instantly share code, notes, and snippets.

@limboinf
Last active July 4, 2016 09:19
Show Gist options
  • Save limboinf/58beb6b9e3bd6c10a3b2cc007258c6d8 to your computer and use it in GitHub Desktop.
Save limboinf/58beb6b9e3bd6c10a3b2cc007258c6d8 to your computer and use it in GitHub Desktop.
Two ways to check the request of the integrity of the fields
# 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