validation.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/env python
  3. """ A list of validators and schemas for data validation and transformation """
  4. from voluptuous import *
  5. from voluptuous.schema_builder import message
  6. from voluptuous.validators import _url_validation
  7. from voluptuous.error import UrlInvalid
  8. from bson.objectid import ObjectId
  9. # validation errors
  10. class LengthInvalid(Invalid):
  11. pass
  12. class OneOfInvalid(Invalid):
  13. pass
  14. # validators
  15. def require(schema):
  16. return Required(schema=schema, msg=u'字段未传递')
  17. class Length(object):
  18. """The length of a value must be in a certain range."""
  19. def __init__(self, min=None, max=None, msg=None):
  20. self.min = min
  21. self.max = max
  22. self.msg = msg
  23. def __call__(self, v):
  24. if self.min is not None and len(v) < self.min:
  25. raise LengthInvalid(
  26. self.msg or u'字段长度至少为 %s' % self.min)
  27. if self.max is not None and len(v) > self.max:
  28. raise LengthInvalid(
  29. self.msg or u'字段长度至多为 %s' % self.max)
  30. return v
  31. def __repr__(self):
  32. return 'Length(min=%s, max=%s)' % (self.min, self.max)
  33. class OneOf(object):
  34. def __init__(self, msg=None, *options):
  35. self.options = set(options)
  36. self.msg = msg
  37. def __call__(self, v):
  38. if v not in self.options:
  39. raise OneOfInvalid(
  40. self.msg or u'字段只能为%s中其一'
  41. )
  42. return v
  43. @message(u'URL不合法'.encode('utf-8'), cls=UrlInvalid)
  44. def Url(v):
  45. """Verify that the value is a URL.
  46. """
  47. try:
  48. _url_validation(v)
  49. return v
  50. except:
  51. raise ValueError
  52. def digit_length_limit(digit, min_len, max_len):
  53. try:
  54. return min_len <= len(str(digit)) <= max_len
  55. except ValueError:
  56. raise Invalid("invalid digit length")
  57. def valid_objectId(oid):
  58. if not ObjectId.is_valid(oid):
  59. raise Invalid("Expected %s to be an ObjectId" % oid)
  60. else:
  61. return True
  62. def is_valid_ipv4_address_with_port(ipaddress_with_port):
  63. try:
  64. ipaddress, port = ipaddress_with_port.split(':')
  65. except ValueError:
  66. raise Invalid('invalid ipaddress with port %s, requires a colon(:)' % ipaddress_with_port)
  67. if not ( 0 < int(port) < 65535 ):
  68. raise Invalid('invalid port number %s' % port)
  69. parts = ipaddress.split('.')
  70. if len(parts) == 4 and all(x.isdigit() for x in parts):
  71. numbers = list(int(x) for x in parts)
  72. if all(0 <= num < 256 for num in numbers):
  73. return ipaddress_with_port
  74. else:
  75. raise Invalid('invalid ip address %s' % ipaddress)
  76. raise Invalid('invalid ip address %s' % ipaddress)
  77. def numeric_str(string, mode=int):
  78. try:
  79. mode(string)
  80. except:
  81. raise Invalid('expected a %s' % mode)
  82. return string
  83. # entry function
  84. def validate_payload(payload, schema, translation):
  85. """
  86. :param payload: 待验证的字段字典
  87. :type payload: dict
  88. :param schema: 用于验证字段的模型
  89. :type schema: Schema
  90. :param translation: 用于返回消息的翻译词典
  91. :type translation: dict
  92. :return:
  93. """
  94. try:
  95. schema(payload)
  96. except MultipleInvalid as e:
  97. return translation.get(e.path[0], u'输入有误请检查')
  98. wechatPayAppSchema = Schema(
  99. {
  100. 'appid': All(basestring, Length(min = 1)),
  101. 'mchid': All(basestring, Length(min = 1)),
  102. 'secret': All(basestring, Length(min = 1)),
  103. 'apikey': All(basestring, Length(min = 1)),
  104. 'sslcert_path': All(basestring, Length(min = 1)),
  105. 'sslkey_path': All(basestring, Length(min = 1)),
  106. 'manual_withdraw': bool,
  107. 'name': basestring,
  108. 'remarks': basestring
  109. }, extra = REMOVE_EXTRA)
  110. aliAppSchema = Schema(
  111. {
  112. 'appid': All(basestring, Length(min = 1)),
  113. 'public_key_path': All(basestring, Length(min = 1)),
  114. 'alipayPublicKeyContent': All(basestring, Length(min = 1)),
  115. 'appPublicKeyContent': All(basestring, Length(min = 1)),
  116. 'app_private_key_path': All(basestring, Length(min = 1)),
  117. 'shadow': bool,
  118. 'appName': basestring,
  119. 'companyName': basestring,
  120. 'remarks': basestring,
  121. 'aesEncryptKey': basestring
  122. }, extra = REMOVE_EXTRA)
  123. wechatManagerAppSchema = Schema(
  124. {
  125. Required('appid'): basestring,
  126. Required('secret'): basestring,
  127. Required('templateIdMap'): list,
  128. 'name': basestring,
  129. 'companyName': basestring,
  130. }, extra = REMOVE_EXTRA)