Convert my java code to Python, code: /** * Gets the get request parameter string * *…
- User
Convert my java code to Python, code: /**
- Gets the get request parameter string
- @param param get/delete Request parameters map
- @return */ public static String getRequestParamString(Map<String, String> param) { if (MapUtils.isEmpty(param)) { return ""; } StringBuilder sb = new StringBuilder(1024); SortedMap<String, String> map = new TreeMap<>(param); for (Map.Entry<String, String> entry : map.entrySet()) { String key = entry.getKey(); String value = StringUtils.isBlank(entry.getValue()) ? "" : entry.getValue(); sb.append(key).append('=').append(urlEncode(value)).append('&'); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); }
public static String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8").replaceAll("\+", "%20"); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("UTF-8 encoding not supported!"); } }
/**
- signature */ public static String sign(SignVo signVo) { if (signVo.getRequestParam() == null) { signVo.setRequestParam(""); } String str = signVo.getAccessKey() + signVo.getReqTime() + signVo.getRequestParam(); return actualSignature(str, signVo.getSecretKey()); }
public static String actualSignature(String inputStr, String key) { Mac hmacSha256; try { hmacSha256 = Mac.getInstance("HmacSHA256"); SecretKeySpec secKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); hmacSha256.init(secKey); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("No such algorithm: " + e.getMessage()); } catch (InvalidKeyException e) { throw new RuntimeException("Invalid key: " + e.getMessage()); } byte[] hash = hmacSha256.doFinal(inputStr.getBytes(StandardCharsets.UTF_8)); return Hex.encodeHexString(hash); }
@Getter @Setter public static class SignVo { private String reqTime; private String accessKey; private String secretKey; private String requestParam; //get the request parameters are sorted in dictionary order, with & concatenated strings, POST should be a JSON string }
- Assistant
def get_request_param_string(param): if not param: return "" sb = [] map = sorted(param.items()) for key, value in map: value = value if value else "" sb.append(f"{key}={url_encode(value)}&") sb[-1] = sb[-1][:-1] return "".join(sb)
def url_encode(s): try: return urllib.parse.quote_plus(s, encoding="UTF-8").replace("+", "%20") except: raise ValueError("UTF-8 encoding not supported!")
def sign(sign_vo): if not sign_vo.request_param: sign_vo.request_param = "" str = sign_vo.access_key + sign_vo.req_time + sign_vo.request_param return actual_signature(str, sign_vo.secret_key)
def actual_signature(input_str, key): try: hmac_sha256 = hmac.new(key.encode("UTF-8"), input_str.encode("UTF-8"), hashlib.sha256) except: raise ValueError("No such algorithm") return hmac_sha256.hexdigest()
class SignVo: def init(self): self.req_time = "" self.access_key = "" self.secret_key = "" self.request_param = ""