如何在Python中构造对应指定CURL命令的POST请求
把CURL POST请求转换成Python实现
嘿,这就帮你把这条curl命令转换成Python的POST请求实现~我会用最常用的requests库来写,毕竟它简洁直观,是Python处理HTTP请求的首选工具之一。
首先,先确保你已经安装了requests:
pip install requests
接下来是完整的代码实现,每一部分我都会对应到你原来的curl命令:
import requests # 先替换成你自己的Watson用户名和密码 watson_username = "{username}" watson_password = "{password}" audio_file_path = "audio-file1.flac" # Speech to Text API的基础地址 api_url = "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" # 对应curl URL里的查询参数,requests会自动帮你处理URL编码 query_params = { "timestamps": "true", "word_alternatives_threshold": 0.9, "keywords": ["colorado", "tornado", "tornadoes"], "keywords_threshold": 0.5 } # 请求头,设置音频文件的类型 request_headers = { "Content-Type": "audio/flac" } # 读取音频文件的二进制内容并发送请求 with open(audio_file_path, "rb") as audio_file: response = requests.post( api_url, # 对应curl的-u参数,处理HTTP基本认证 auth=(watson_username, watson_password), headers=request_headers, params=query_params, # 对应curl的--data-binary,上传二进制音频数据 data=audio_file ) # 处理返回结果 if response.ok: print("语音识别结果:") print(response.json()) else: print(f"请求出错啦,状态码:{response.status_code}") print(response.text)
代码和原curl命令的对应说明:
auth=(watson_username, watson_password):完全对应curl里的-u "{username}":"{password}",requests会自动处理基本认证的编码工作,不用你手动拼接Authorization头。request_headers:对应--header "Content-Type: audio/flac",告诉API你上传的是FLAC格式的音频。query_params:对应curl URL末尾的所有查询参数,用字典的方式更清晰,requests会自动帮你处理URL编码(比如把关键词的引号、逗号转成符合URL规范的格式),比直接写在URL里更不容易出错。data=audio_file:对应--data-binary "@audio-file1.flac",用with open以二进制模式读取文件,既保证了文件内容正确,还能自动关闭文件。
如果你的环境不能用requests(比如限制只能用标准库),我也可以给你写基于urllib的实现,但requests确实要方便太多啦~
内容的提问来源于stack exchange,提问作者Omkar Singh
相关产品推荐
相关产品推荐

