Browse Source

feat: coding module

dev
dnomd343 2 years ago
parent
commit
7bc654868e
  1. 30
      Basis/Functions.py
  2. 32
      Utils/Common/Coding.py
  3. 5
      Utils/Common/__init__.py

30
Basis/Functions.py

@ -4,12 +4,10 @@
import re
import time
import uuid
import base64
import psutil
import random
import hashlib
from IPy import IP
import urllib.parse
from Basis.Logger import logging
@ -113,34 +111,6 @@ def toBool(raw) -> bool:
raise RuntimeError('Unable convert to bool')
def urlEncode(content: str) -> str:
return urllib.parse.urlencode(content)
def urlDecode(content: str) -> str:
return urllib.parse.unquote(content)
def base64Encode(content: str, urlSafe: bool = False, isPadding: bool = True) -> str:
content = base64.b64encode(content.encode(encoding = 'utf-8')).decode(encoding = 'utf-8')
if urlSafe:
content = content.replace('+', '-')
content = content.replace('/', '_')
if not isPadding:
content = content.replace('=', '')
return content
def base64Decode(content: str) -> str or None:
try:
content = content.replace('-', '+').replace('_', '/')
if len(content) % 4 in range(2, 4): # remainder -> 2 or 3
content = content.ljust((len(content) // 4 + 1) * 4, '=') # increase to 4n
return base64.b64decode(content).decode(encoding = 'utf-8')
except:
raise RuntimeError('Invalid base64 encode')
def getAvailablePort(rangeStart: int = 1024, rangeEnd: int = 65535, waitTime: int = 10) -> int: # get available port
if rangeStart > rangeEnd or rangeStart < 1 or rangeEnd > 65535:
raise RuntimeError('Invalid port range')

32
Utils/Common/Coding.py

@ -0,0 +1,32 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import base64
import urllib.parse
def urlEncode(content: str) -> str: # url encode (RFC3986)
return urllib.parse.quote(content, encoding = 'utf-8')
def urlDecode(content: str) -> str: # url decode (RFC3986)
return urllib.parse.unquote(content, encoding = 'utf-8')
def base64Encode(content: str, urlSafe: bool = True, padding: bool = False) -> str: # base64 encode
content = base64.b64encode(content.encode(encoding = 'utf-8')).decode(encoding = 'utf-8')
if urlSafe:
content = content.replace('+', '-') # `+` => `-`
content = content.replace('/', '_') # `/` => `_`
if padding:
return content
return content.replace('=', '') # remove `=` padding
def base64Decode(content: str) -> str: # base64 decode
try:
content = content.replace('-', '+').replace('_', '/') # compatible urlSafe
if len(content) % 4 in range(2, 4): # remainder -> 2 or 3
content = content.ljust((len(content) // 4 + 1) * 4, '=') # increase to 4n
return base64.b64decode(content).decode(encoding = 'utf-8')
except:
raise RuntimeError('Invalid base64 encode')

5
Utils/Common/__init__.py

@ -0,0 +1,5 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Utils.Common.Coding import urlEncode, urlDecode
from Utils.Common.Coding import base64Encode, base64Decode
Loading…
Cancel
Save