本文最后更新于 2024年5月27日。
stirling PDF api没有官方教程,只有程序自带的接口swagger说明。
我不会用,问ai基本也不对。
所以忽然想到用在swagger中测试生成的curl语句让ai转成python实现方式再根据错误去修复,只用了两次就成功了。
把下面的功能用python实现
curl -X 'POST'
'[http://localhost:8080/api/v1/convert/img/pdf](http://localhost:8080/api/v1/convert/img/pdf)'
-H 'accept: _/_'
-H 'Content-Type: multipart/form-data'
-F 'fileInput=@P1签字.jpg;type=image/jpeg'
-F 'fitOption=fillPage'
-F 'colorType=color'
-F 'autoRotate=true'
🤖
要使用Python实现上述使用curl
命令执行的HTTP POST请求,可以使用requests
库。请确保已经安装了requests
库(可以通过pip install requests
命令进行安装)。以下是相应的Python代码:
Python
1import requests 2 3url = "http://localhost:8080/api/v1/convert/img/pdf" 4 5headers = { 6 "accept": "*/*", 7 "Content-Type": "multipart/form-data", 8} 9 10files = { 11 "fileInput": ("P1签字.jpg", open("P1签字.jpg", "rb"), "image/jpeg"), 12 "fitOption": ("fillPage",), 13 "colorType": ("color",), 14 "autoRotate": ("true",), 15} 16 17response = requests.post(url, headers=headers, files=files) 18 19# 检查响应状态码 20if response.status_code == 200: 21 print("请求成功") 22else: 23 print(f"请求失败,状态码:{response.status_code}") 24 25# 如果需要,可以进一步处理响应内容 26response_data = response.content
注意事项:
- 确保
P1签字.jpg
文件位于执行Python脚本的同一目录下,或者提供正确的文件路径。 - 请求头中的
Content-Type
在这里不需要手动指定,因为requests
库会根据提供的files
参数自动设置正确的Content-Type
和multipart/form-data
边界。 files
字典中,键对应表单字段名,值为元组(filename, file_object, content_type)
或(filename,)
。对于非文件字段(如fitOption
、colorType
和autoRotate
),只需提供一个空元组,因为这些字段的值就是它们对应的键名。
这段Python代码会向http://localhost:8080/api/v1/convert/img/pdf
发送一个POST请求,附带指定的文件和表单数据。响应内容存储在response.content
中,可以根据需要进行后续处理。
报错
\Anaconda3\lib\site-packages\requests\models.py", line 151, in _encode_files
fn, fp, ft, fh = v
ValueError: not enough values to unpack (expected 4, got 1)
🤖
Apologies for the confusion in my previous response. It seems I misunderstood the format for non-file fields in the files
dictionary when using the requests
library. Non-file fields should be passed as key-value pairs in a separate data
parameter instead of being included in the files
dictionary.
Here’s the corrected Python code:
import requests
url = "http://localhost:8080/api/v1/convert/img/pdf"
headers = {
"accept": "*/*",
}
data = {
"fitOption": "fillPage",
"colorType": "color",
"autoRotate": "true",
}
files = {
"fileInput": ("P1签字宇通-嘉瑞.jpg", open("P1签字宇通-嘉瑞.jpg", "rb"), "image/jpeg"),
}
response = requests.post(url, headers=headers, data=data, files=files)
# Check response status code
if response.status_code == 200:
print("请求成功")
else:
print(f"请求失败,状态码:{response.status_code}")
# If needed, further process the response content
response_data = response.content
In this updated version:
- The non-file fields (
fitOption
,colorType
, andautoRotate
) are moved to a separatedata
dictionary. - The
files
dictionary now only contains the file field (fileInput
).
This should resolve the ValueError
you encountered earlier and correctly send the POST request with both file and non-file form data.