Python 3请求 - 如何发布帖子请求,填写表单并提交

时间:2017-01-05 12:01:44

标签: python forms python-3.x python-requests

在一个包含此代码的网站中:

from flask import Flask, request

app = Flask(__name__)


@app.route('/upload', methods=["POST", "GET"])
def upload():
    return """
        <html>
          <body>
            <h1>Guess what! I am a title!</h1>
              <form action="/run" method="POST" name="upload">
                <input type="password" name="password">
                <input type="file" name="file" />
              </form>
          </body>
        </html>"""


@app.route('/run', methods=["POST"])
def download_file():
    if request.form['password'] == 'hey':
        request.files['file'].save('/home/james/site.txt')
        return "File uploaded successfully!"
    else:
        return "Wrong password"

如何运行正确的帖子请求并获取/run的输出? 到目前为止,我已经尝试过:

upload = {'password': 'whatever',
          'file': open(my_files_location, 'rb')}
r = requests.post('http://jamesk.pythonanywhere.com/upload', data=upload)

但网站既没有运行表单也没有返回我想要的内容。这是我运行r.content时得到的结果:

b'\n        <html>\n          <body>\n            <h1>Guess what! I am a title!</h1>\n              <form action="/run" method="POST" name="upload">\n                <input type="password" name="password">\n                <input type="file" name="file" />\n              </form>\n          </body>\n        </html>'

当我预料到b'Wrong password'

1 个答案:

答案 0 :(得分:1)

您要发布到表单路径,而不是表单 handler 路径。您的浏览器会读取表单上的action="/run"属性,并将其用作要发布到的目标。你需要做同样的事情:

url = 'http://jamesk.pythonanywhere.com/run'

请注意,网址以/run /upload结尾。

接下来,您需要修复表单处理;您需要配置表单以使用right mimetype并使用requests中的files option to upload files

@app.route('/upload', methods=["POST", "GET"])
def upload():
    return """
        <html>
          <body>
            <h1>Guess what! I am a title!</h1>
              <form action="/run" method="POST" name="upload" enctype="multipart/form-data">
                <input type="password" name="password">
                <input type="file" name="file" />
              </form>
          </body>
        </html>"""

r = requests.post(url, 
    data={'password': 'hey'}, 
    files={'file': open(my_files_location, 'rb')})