问题
I have this python code snippet and need help with a clojure equivalent.
user_id = row.get('user_id')
if user_id:
user_id_bytes = base64.urlsafe_b64decode(user_id)
creation_timestamp = int.from_bytes(user_id_bytes[:4],
byteorder='big')
dc_id = int.from_bytes(user_id_bytes[4:5], byteorder='big') & 31
if creation_timestamp > WHEN_WE_SET_UP_DC_IDS:
row['dc_id'] = dc_id}
回答1:
You can use clojure's java compatibility to leverage the java.util.Base64 class.
user> (import java.util.Base64)
java.util.Base64
user> ;; encode a message
(let [message "Hello World!"
message-bytes (.getBytes message)
encoder (Base64/getUrlEncoder)]
(.encodeToString encoder message-bytes))
"SGVsbG8gV29ybGQh"
user> ;; Decode a message
(let [encoded-message "SGVsbG8gV29ybGQh"
decoder (Base64/getUrlDecoder)]
(String. (.decode decoder encoded-message)))
"Hello World!"
回答2:
The Tupelo library has Clojure wrappers around the Java Base64 and Base64Url functionality. A look at the unit tests show the code in action:
(ns tst.tupelo.base64
(:require [tupelo.base64 :as b64] ))
code-str (b64/encode-str orig)
result (b64/decode-str code-str) ]
(is (= orig result))
where the input & output values are plain strings (there is also a variant for byte arrays).
The API docs are here.
来源:https://stackoverflow.com/questions/39642549/clojure-equivalent-of-pythons-base64-encode-and-decode