helper.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import json
  2. import random
  3. import re
  4. import string
  5. import subprocess
  6. import uuid
  7. from collections.abc import Generator
  8. from datetime import datetime
  9. from hashlib import sha256
  10. from typing import Union
  11. from zoneinfo import available_timezones
  12. from flask import Response, stream_with_context
  13. from flask_restful import fields
  14. def run(script):
  15. return subprocess.getstatusoutput('source /root/.bashrc && ' + script)
  16. class TimestampField(fields.Raw):
  17. def format(self, value) -> int:
  18. return int(value.timestamp())
  19. def email(email):
  20. # Define a regex pattern for email addresses
  21. pattern = r"^[\w\.-]+@([\w-]+\.)+[\w-]{2,}$"
  22. # Check if the email matches the pattern
  23. if re.match(pattern, email) is not None:
  24. return email
  25. error = ('{email} is not a valid email.'
  26. .format(email=email))
  27. raise ValueError(error)
  28. def uuid_value(value):
  29. if value == '':
  30. return str(value)
  31. try:
  32. uuid_obj = uuid.UUID(value)
  33. return str(uuid_obj)
  34. except ValueError:
  35. error = ('{value} is not a valid uuid.'
  36. .format(value=value))
  37. raise ValueError(error)
  38. def alphanumeric(value: str):
  39. # check if the value is alphanumeric and underlined
  40. if re.match(r'^[a-zA-Z0-9_]+$', value):
  41. return value
  42. raise ValueError(f'{value} is not a valid alphanumeric value')
  43. def timestamp_value(timestamp):
  44. try:
  45. int_timestamp = int(timestamp)
  46. if int_timestamp < 0:
  47. raise ValueError
  48. return int_timestamp
  49. except ValueError:
  50. error = ('{timestamp} is not a valid timestamp.'
  51. .format(timestamp=timestamp))
  52. raise ValueError(error)
  53. class str_len:
  54. """ Restrict input to an integer in a range (inclusive) """
  55. def __init__(self, max_length, argument='argument'):
  56. self.max_length = max_length
  57. self.argument = argument
  58. def __call__(self, value):
  59. length = len(value)
  60. if length > self.max_length:
  61. error = ('Invalid {arg}: {val}. {arg} cannot exceed length {length}'
  62. .format(arg=self.argument, val=value, length=self.max_length))
  63. raise ValueError(error)
  64. return value
  65. class float_range:
  66. """ Restrict input to an float in a range (inclusive) """
  67. def __init__(self, low, high, argument='argument'):
  68. self.low = low
  69. self.high = high
  70. self.argument = argument
  71. def __call__(self, value):
  72. value = _get_float(value)
  73. if value < self.low or value > self.high:
  74. error = ('Invalid {arg}: {val}. {arg} must be within the range {lo} - {hi}'
  75. .format(arg=self.argument, val=value, lo=self.low, hi=self.high))
  76. raise ValueError(error)
  77. return value
  78. class datetime_string:
  79. def __init__(self, format, argument='argument'):
  80. self.format = format
  81. self.argument = argument
  82. def __call__(self, value):
  83. try:
  84. datetime.strptime(value, self.format)
  85. except ValueError:
  86. error = ('Invalid {arg}: {val}. {arg} must be conform to the format {format}'
  87. .format(arg=self.argument, val=value, format=self.format))
  88. raise ValueError(error)
  89. return value
  90. def _get_float(value):
  91. try:
  92. return float(value)
  93. except (TypeError, ValueError):
  94. raise ValueError('{} is not a valid float'.format(value))
  95. def timezone(timezone_string):
  96. if timezone_string and timezone_string in available_timezones():
  97. return timezone_string
  98. error = ('{timezone_string} is not a valid timezone.'
  99. .format(timezone_string=timezone_string))
  100. raise ValueError(error)
  101. def generate_string(n):
  102. letters_digits = string.ascii_letters + string.digits
  103. result = ""
  104. for i in range(n):
  105. result += random.choice(letters_digits)
  106. return result
  107. def get_remote_ip(request):
  108. if request.headers.get('CF-Connecting-IP'):
  109. return request.headers.get('Cf-Connecting-Ip')
  110. elif request.headers.getlist("X-Forwarded-For"):
  111. return request.headers.getlist("X-Forwarded-For")[0]
  112. else:
  113. return request.remote_addr
  114. def generate_text_hash(text: str) -> str:
  115. hash_text = str(text) + 'None'
  116. return sha256(hash_text.encode()).hexdigest()
  117. def compact_generate_response(response: Union[dict, Generator]) -> Response:
  118. if isinstance(response, dict):
  119. return Response(response=json.dumps(response), status=200, mimetype='application/json')
  120. else:
  121. def generate() -> Generator:
  122. yield from response
  123. return Response(stream_with_context(generate()), status=200,
  124. mimetype='text/event-stream')