简体   繁体   English

通过需要文件的CGI表单字段将文本传递给python

[英]Pass text to python via a CGI form field that expects a file

I have two servers. 我有两台服务器。 Server A hosts a python script upload.py for uploading a file; 服务器A托管一个python脚本upload.py来上传文件; this script expects the file to be passed in a form field: 该脚本希望文件在表单字段中传递:

form = cgi.FieldStorage()

if "upload-file" not in form:
    print("Need an upload file")
else:
    fileItem = form["upload-file"]

    if not fileItem.file:
        print("Not a file")
    else:
        fileContent = fileItem.file.read()
        outFilePath = os.path.join("/some/path/", fileItem.filename)
        outFile = open(outFilePath, "wb")
        outFile.write(fileContent)
        # etc.

This script works, and the way it handles its input cannot be changed, because of an existing HTML/JavaScript UI that relies on this interface. 该脚本有效,并且由于依赖于此接口的现有HTML / JavaScript UI,因此无法更改其处理输入的方式。

Now I want to call the above script from another python script residing on server B. So I need to do something similar to this: 现在,我想从驻留在服务器B上的另一个python脚本调用上述脚本。因此,我需要执行以下操作:

import requests

# Call script on server A
response = requests.post(
    "http://10.20.30.40/cgi-bin/upload.py",
    files = { "upload-file": "some file content" })

This actually does create a file on server A, but it is named upload-file . 实际上,这确实在服务器A上创建了一个文件,但是它被命名为upload-file So I want to control the value of fileItem.filename (in the script on server A) when calling it from server B. How can I achieve that? 因此,当我从服务器B调用fileItem.filename的值时(在服务器A上的脚本中),我想控制它。如何实现? The CGI field name upload-file must not change. CGI字段名称upload-file不得更改。 I tried to use the params argument of the post method, but didn't get it to work that way (I'm new to python, and just googling things as I go along). 我尝试使用post方法的params参数,但没有使它以这种方式工作(我是python的新手,在继续学习时一直在搜索内容)。

Found the answer: 找到了答案:

files = {"upload-file": ("desired-file-name.xml", "some file content")}

response = requests.post(
    "http://10.20.30.40/cgi-bin/upload-xml.py",
    files = files)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM