上传到服务器的Python脚本
问题描述:
我是Python新手,它是第一篇文章。想要上传一个TXT文件到服务器,(到目前为止,它是本地主机)。每次我运行脚本,本地文件上传并更新到服务器上。我使用Requests模块上传到服务器的Python脚本
import requests, time
url ='http://192.168.49.205/test/database/data.txt' # where i want to write
files = {'file':('data.txt','C:\Python27\data.txt','rb')}
#r = requests.post(url,files=files) # this works too
r= requests.post('http://192.168.49.205/test/database/data.txt',
data={'upload_type': 'standard', 'upload_to': '0'},files=files)
print r.status_code
print r.text
data.txt
没有更新。只是看到旧的数据(我创建文件时,我把一些值)。我没有使用PHP或HTML中的任何表单。可以用方法上传吗?
相信,我得到了一些清晰张贴的问题后。现在,服务器端的PHP文件正在侦听客户端。这是“post.php”。所以,这将取代客户端的文本文件。 PHP文件从客户端得到的名称,任务,价值和张贴到服务器上的“A.TXT”(本地)
<?php
if(isset($_GET["Name"])){
$name=$_GET["Name"];
}
if(isset($_GET["Task"])){
$task=$_GET["Task"];
}
if(isset($_GET["Value"])){
$value=$_GET["Value"];
}
$f=fopen("a.txt","w") or exit("Unable to open file!");
fwrite($f,$name);
fwrite($f," ");
fwrite($f,$task);
fwrite($f," ");
fwrite($f,$value);
fclose($f);
?>`
所以现在请这个样子
import requests, time
url = 'http://192.168.49.205/test/test.php'
post_data = {'Name':'job','Task':'008','Value':'8'}
r= requests.post('http://192.168.49.205/test/post.php', data= post_data)
print r.status_code
print r.text
史迪威的值没有达到“A.TXT”。我错过了什么?请指教!
答
您没有阅读代码中的文件内容。该requests documentation状态:
文件 - “名”(可选)字典:文件类对象(或 {“名”(“文件名”,FileObj文件)})为多编码上传。
您的代码表明您要使用第二个选项。但是:
files = {'file':('data.txt','C:\Python27\data.txt','rb')}
你不创建结构的文档表明 - 你路过3个字符串的元组代替(字符串,file_obj)的元组。你可能想这样做:
files = {'file':('data.txt',open('C:\Python27\data.txt','rb'))}
错误可能是在服务器端。 – Matthias
'http:// 192.168.49.205/test/database/data.txt'是否接受'POST'请求?在那里听什么样的服务? – 2013-11-20 14:39:09
data.txt是纯文本文件。不要想,它需要POST请求或听。在你的问题后,我明白了。所以,服务器文件应该是接受POST请求的PHP文件。请承担我的无知。 – Chandra