在一个包含此代码的网站中:
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'
答案 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')})