[英]Python convert curl command to urllib.request
我想將我的 curl 轉換為 urllib.request 命令到 python,curl 命令:
curl -v -i -X POST http://api.textart.io/img2txt.json --form image=@path/to/dir/file.jpg
我的代碼:
import json
from urllib import request, parse
data = parse.urlencode({
"image": open("path/to/dir/file.jpg", "rb")
}).encode()
req = request.Request("http://api.textart.io/img2txt.json")
req.add_header('User-Agent', 'Mozilla/5.0')
response = json.loads(request.urlopen(req, data).read())
response = json.dumps(response, indent=4)
print(response)
回復:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>500 Internal Server Error</title>
</head><body>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error or
misconfiguration and was unable to complete
your request.</p>
<p>Please contact the server administrator at
webmaster@api.textart.io to inform them of the time this error occurred,
and the actions you performed just before this error.</p>
<p>More information about this error may be available
in the server error log.</p>
</body></html>
而使用 curl 有效,請幫助。
如果您將使用模塊requests
而不是urllib
那么您可以使用門戶http://curlconverter.com來轉換它。 但有時它可能會創建錯誤的代碼。
如果您將使用程序郵遞員來測試網頁,那么它也具有以不同語言生成代碼的功能 - 它應該具有在 Python 中為urllib
生成的功能。
您還可以使用門戶https://httpbin.org (和 url httpbin.org/post)來測試curl
和python
請求。 Portal 發回它在請求中獲得的所有數據,您可以比較在curl
和python
發送的數據。
但我在 Linux 本地程序netcat上使用模擬服務器並查看raw
請求。
nc -l localhost 8080
然后使用http://localhost:8080
測試curl
和urllib
並創建了應該與api.textart.io
一起使用的api.textart.io
from urllib import request
import json
file_data = open("path/image.jpg", "rb").read()
BOUNDARY = b'------------------------360768b014779354'
data = [
b'--' + BOUNDARY,
b'Content-Disposition: form-data; name="image"; filename="image.jpg"',
b'Content-Type: image/jpeg',
b'',
file_data,
b'--' + BOUNDARY + b'--',
b'',
]
data = b'\r\n'.join(data)
#print(data)
url = "http://api.textart.io/img2txt.json"
#url = "https://httpbin.org/post"
#url = 'http://localhost:8080'
req = request.Request(url)
req.add_header("Content-Type", 'multipart/form-data; boundary={}'.format(BOUNDARY.decode())),
#req.add_header("Content-Length", str(len(data)))
#req.add_header("Accept", "*/*")
response = json.loads(request.urlopen(req, data).read())
response = json.dumps(response, indent=4)
print(response)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.