如何在pygeoapi流程中传递文件作为输入参数?
问题:pygeoapi流程如何传递文件输入参数
我构建了一个读取"hello world"文本文件的测试pygeoapi流程,已成功部署至REST端点http://localhost:5000/processes/myprocess,但不清楚如何将文本文件作为输入参数传递,也未找到相关示例。
现有代码片段
输入元数据(myprocess.py)
'inputs': { 'file': { 'title': 'file', 'description': 'what ever file', "schema": { "type": "string", "contentEncoding": "binary", "contentMediaType": "application/octet-stream" }, 'minOccurs': 1, 'maxOccurs': 1, 'metadata': None, 'keywords': ['file'] } },
流程执行代码(myprocess.py)
def execute(self, data): mimetype = 'application/json' file= data.get('file', None) with open(file, mode='rb') as myfile: # b is important -> binary fileContent = myfile.read() outputs = { 'result': fileContent } return mimetype, outputs
调用流程的Python脚本
filePath=r'C:\dev\test.txt' url='http://localhost:5000/processes/myprocess/execution' with open(filePath, "rb") as text_file: data = { "inputs": { "file": text_file } } r = requests.post(url, json=data) print(r.content)
遇到的问题
- 直接传递
BufferedReader对象时,触发JSON序列化错误:TypeError: Object of type BufferedReader is not JSON serializable - 尝试base64编码二进制内容时,收到流程返回的“参数缺失”提示
解决方法
1. 修正输入元数据定义
pygeoapi对二进制文件输入的规范要求,若使用base64编码传递,需明确contentEncoding为base64,同时根据文件类型设置准确的contentMediaType(文本文件用text/plain更合适):
'inputs': { 'file': { 'title': 'file', 'description': 'what ever file', "schema": { "type": "string", "contentEncoding": "base64", "contentMediaType": "text/plain" }, 'minOccurs': 1, 'maxOccurs': 1, 'metadata': None, 'keywords': ['file'] } },
2. 调整流程执行代码
传递的参数是base64编码字符串,需先解码为二进制内容再处理:
import base64 def execute(self, data): mimetype = 'application/json' file_base64 = data.get('file', None) # 解码base64字符串为二进制内容 file_content = base64.b64decode(file_base64) outputs = { 'result': file_content.decode('utf-8') # 转为字符串返回,便于查看结果 } return mimetype, outputs
3. 修改调用脚本
读取文件二进制内容后,编码为base64字符串再放入JSON请求体:
import requests import base64 filePath=r'C:\dev\test.txt' url='http://localhost:5000/processes/myprocess/execution' with open(filePath, "rb") as text_file: # 读取二进制内容并编码为base64字符串 file_base64 = base64.b64encode(text_file.read()).decode('utf-8') data = { "inputs": { "file": file_base64 } } r = requests.post(url, json=data) print(r.content)
额外说明
- 若处理的是图片等二进制文件,将
contentMediaType改为application/octet-stream即可,执行代码中无需转成字符串,直接返回二进制内容或按需处理。 - 确保流程输入参数名称与请求中的参数名完全一致(此处均为
file),避免因名称不匹配导致“参数缺失”。
内容的提问来源于stack exchange,提问作者Matshopp
相关产品推荐
相关产品推荐

