python - Python 将 curl 命令转换为 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来转换它。但有时它可能会创建有错误的代码。
如果您要使用程序postman来测试网页,那么它还具有生成不同语言代码的功能 - 它应该具有urllib
在 Python 中生成的功能。
您还可以使用门户网站https://httpbin.orgcurl
(和 url httpbin.org/post)在和中测试请求python
。Portal 发回它在请求中获得的所有数据,您可以比较您发送的内容curl
和python
.
但是我在Linux本地程序netcat上使用了模拟服务器并查看raw
请求。
nc -l localhost 8080
然后测试curl
并urllib
使用http://localhost:8080
并创建了应该使用的代码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)
推荐阅读
- angular - 从网络服务器调用时,Angular 没有缓存 localhost api url
- c# - 是否可以获得 Azure 资源类型的所有可用指标?
- android - 以较小的尺寸显示模拟器窗口
- haskell - 我可以在单子上使用地图吗?
- reactjs - 从完成列表中删除一个项目我试图以多种方式做到这一点
- java - 如何在不是字段联系人的模板中添加属性(Sendinblue)
- android - 与 BLE 的通信不工作,很少工作
- mongodb - 有没有办法将毫秒字符串转换为 mongodb 可识别的日期格式?
- sql - Oracle Rownum,获取第 n 行
- c# - 如何对 Web API 项目进行故障排除?