![](/img/trans.png)
[英]How to convert base64 encoded string to file without disk I/O in Python (for HTTP requests)
[英]how to send SOAP request including a Base64 encoded .csv file with python requests?
I'm trying to send a SOAP request with python requests module, where part of the SOAP Body contains a Base64 encoded.csv file. 基本請求有效。 該文件作為 Base64 編碼的字符串附加在<soapenv:Body>
內的任意標記內。
SOAP 服務是內部 email 服務的外觀,我也維護它。 我知道它正在工作,因為我得到的是 email,它有一個附件,但附件是亂碼,因為沒有更好的詞。
我對 python 還很陌生,所以很多這可能是錯誤的代碼,而不是 pythonic 等。
但是我從另一個開發人員那里復制了大部分代碼,並且 rest 正在工作,除了文件附件。
使用 python 3.8 並請求 2.26.0
我正在從本地文件中讀取.csv,其中包含以下內容:
file = open('myfile.csv', 'rb')
file_content = file.read()
base64_data = base64.b64encode(file_content)
我還嘗試使用base64.encodebytes(file_content)
得到類似的亂碼結果,盡管它們略有不同。 不知道這些方法的區別是什么,但其中一個似乎有更多的行,而另一個似乎有更少的行,我認為這是正確的,因為它是一個只有幾行的小文件。
然后使用以下內容創建請求:
def _createRequest(self, toemail, emailsubject, emailbody, file_to_attach):
soap_request = """<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Header>
...
</soap:Header>
<soap:Body>
<EmailRequest xmlns="...">
<AddressTo>
{to_email}
</AddressTo>
<From>blah</From>
<Subject>{subject}</Subject>
<Body><![CDATA[
{body}
]]></Body>
<BinaryAttachment filename="myfile.csv" MediaServer="N">{file_base64_encoded}</BinaryAttachment>
<ContentType>HTMLText</ContentType>
</EmailRequest>
</soap:Body>
</soap:Envelope>""".format(to_email=toemail, subject=emailsubject, body = emailbody, file_base64_encoded=file_to_attach)
return soap_request
我想知道它是否與標題有關。 我們在標題中使用基本身份驗證:
def __getBasicAuthHeaders(self, user_name, password):
authHeader = base64.b64encode(
(user_name + ':' + password).encode()).decode()
return {
'Authorization': 'Basic ' + authHeader,
'Content-Type': 'application/xml'
}
您是否有機會將base64_data
作為參數發送到_createRequest
function? 從您的代碼中,您似乎期望一個字符串,但您在那里得到字節。 例如:
>>> file = open('test.txt', 'rb')
>>> file_content = file.read()
>>> base64_data = base64.b64encode(file_content)
>>>
>>> soap_request1 = """<BinaryAttachment>{file_base64_encoded}</BinaryAttachment>""".format(file_base64_encoded=base64_data)
>>> soap_request1
"<BinaryAttachment>b'Tm90aGluZyB0byBzZWUgaGVyZSE='</BinaryAttachment>"
>>>
>>> soap_request2 = """<BinaryAttachment>{file_base64_encoded}</BinaryAttachment>""".format(file_base64_encoded=base64_data.decode())
>>> soap_request2
'<BinaryAttachment>Tm90aGluZyB0byBzZWUgaGVyZSE=</BinaryAttachment>'
>>>
查看soap_request1
和soap_request2
之間的區別,您可能會找到罪魁禍首。 也看看這個: 將字節轉換為字符串
使用您需要的任何數據編碼,很可能是 utf-8。
您還想知道基本身份驗證是否與此有關。 它沒有,但那些encode()
/ decode()
應該提供了一個線索。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.