如何用python模拟一个上传文件的表单提交?

classic Classic list List threaded Threaded
19 messages Options
Reply | Threaded
Open this post in threaded view
|

如何用python模拟一个上传文件的表单提交?

马踏飞燕
就是用python提供的urllib这类的库来模拟一个上传文件的表单的提交动作,把本地文件提交到服务器上。

应该怎么写呢?
一般的urllib.urlopen用post打开的url怎么把文件的数据流也写过去呢?
接收方是用django写的,谢谢啦。
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 如何用python模拟一个上传文件的表单提交?

jessinio liang
你想做一下本地和服务器端通信的东西?
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 如何用python模拟一个上传文件的表单提交?

马踏飞燕
在 07-6-6,jessinio smith<[hidden email]> 写道:
> 你想做一下本地和服务器端通信的东西?
> _______________________________________________

对的。
就相当于模拟一个IE的FILE类型的input框,主要是我想做一个批量上传文件的程序,直接写一个循环把大量的文件上传到服务器上。
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 如何用python模拟一个上传文件的表单提交?

Zoom.Quiet
On 6/6/07, 马踏飞燕 <[hidden email]> wrote:
> 在 07-6-6,jessinio smith<[hidden email]> 写道:
> > 你想做一下本地和服务器端通信的东西?
> > _______________________________________________
>
> 对的。
> 就相当于模拟一个IE的FILE类型的input框,主要是我想做一个批量上传文件的程序,直接写一个循环把大量的文件上传到服务器上。
> _______________________________________________
大量文件上传的话使用 socket 稳定连接,
FTP等等协议进行吧,HTTP 的实在不靠谱,而且也不安全

> python-chinese
> Post: send [hidden email]
> Subscribe: send subscribe to [hidden email]
> Unsubscribe: send unsubscribe to  [hidden email]
> Detail Info: http://python.cn/mailman/listinfo/python-chinese


--
'''Time is unimportant, only life important!
http://zoomquiet.org
blog@http://blog.zoomquiet.org/pyblosxom/
wiki@http://wiki.woodpecker.org.cn/moin/ZoomQuiet
scrap@http://floss.zoomquiet.org
douban@http://www.douban.com/people/zoomq/
____________________________________
Pls. use OpenOffice.org to replace M$ Office.
     http://zh.openoffice.org
Pls. use 7-zip to replace WinRAR/WinZip.
     http://7-zip.org/zh-cn/
You can get the truely Freedom 4 software.
'''
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 如何用python模拟一个上传文件的表单提交?

jessinio liang
In reply to this post by 马踏飞燕
我也想知道能不能.
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 如何用python模拟一个上传文件的表单提交?

jessinio liang
In reply to this post by Zoom.Quiet
如果是少量数据库呢??怎么做??给点代码看一下嘛~!~
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 如何用python模拟一个上传文件的表单提交?

马踏飞燕
In reply to this post by Zoom.Quiet
在 07-6-6,Zoom. Quiet<[hidden email]> 写道:

> On 6/6/07, 马踏飞燕 <[hidden email]> wrote:
> > 在 07-6-6,jessinio smith<[hidden email]> 写道:
> > > 你想做一下本地和服务器端通信的东西?
> > > _______________________________________________
> >
> > 对的。
> > 就相当于模拟一个IE的FILE类型的input框,主要是我想做一个批量上传文件的程序,直接写一个循环把大量的文件上传到服务器上。
> > _______________________________________________
> 大量文件上传的话使用 socket 稳定连接,
> FTP等等协议进行吧,HTTP 的实在不靠谱,而且也不安全
>

道理是这样,不过现在web应用已经开发好了,就是编辑抱怨老是在网页上一个一个的选文件,太烦了,所以想做一个小工具,直接批量的把文件传到server上就好了阿,毕竟不是所有的人都喜欢用ftp的,呵呵。
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 如何用python模拟一个上传文件的表单提交?

junyi sun
flash有个控件可以批量选中并且上传
很多视频网站的上传就是用它做的

 
On 6/6/07, 马踏飞燕 <[hidden email]> wrote:
在 07-6-6,Zoom. Quiet<[hidden email]> 写道:
> On 6/6/07, 马踏飞燕 < [hidden email]> wrote:
> > 在 07-6-6,jessinio smith<[hidden email]> 写道:
> > > 你想做一下本地和服务器端通信的东西?
> > > _______________________________________________
> >
> > 对的。
> > 就相当于模拟一个IE的FILE类型的input框,主要是我想做一个批量上传文件的程序,直接写一个循环把大量的文件上传到服务器上。
> > _______________________________________________
> 大量文件上传的话使用 socket 稳定连接,
> FTP等等协议进行吧,HTTP 的实在不靠谱,而且也不安全
>

道理是这样,不过现在web应用已经开发好了,就是编辑抱怨老是在网页上一个一个的选文件,太烦了,所以想做一个小工具,直接批量的把文件传到server上就好了阿,毕竟不是所有的人都喜欢用ftp的,呵呵。
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese


_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

tuple如何转换成list?

weizi-2
In reply to this post by 马踏飞燕
这样的tuple((1,1),(2,2),(3,3))如何转换成list [[1,1],[2,2],[3,3]]

Aaa = []
A = ((1,1),(2,2),(3,3))
for aa in a:
    aaa.append(list(aa))

这样太难看了,有没有更优雅的做法。
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: tuple如何转换成list?

IQDoctor
aaa = [list(tuple) for tuple in a]

weizi 写道:

> 这样的tuple((1,1),(2,2),(3,3))如何转换成list [[1,1],[2,2],[3,3]]
>
> Aaa = []
> A = ((1,1),(2,2),(3,3))
> for aa in a:
>     aaa.append(list(aa))
>
> 这样太难看了,有没有更优雅的做法。
> _______________________________________________
> python-chinese
> Post: send [hidden email]
> Subscribe: send subscribe to [hidden email]
> Unsubscribe: send unsubscribe to  [hidden email]
> Detail Info: http://python.cn/mailman/listinfo/python-chinese

_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: tuple如何转换成list?

yi huang-3
In reply to this post by weizi-2
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> def to_list(t):
...   return [i if not isinstance(i, tuple) else to_list(i) for i in t]
...
>>> to_list( ((1,2), (2,3)) )
[[1, 2], [2, 3]]

On 6/6/07, weizi <[hidden email]> wrote:
这样的tuple((1,1),(2,2),(3,3))如何转换成list [[1,1],[2,2],[3,3]]

Aaa = []
A = ((1,1),(2,2),(3,3))
for aa in a:
   aaa.append(list(aa))

这样太难看了,有没有更优雅的做法。
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese



--
http://codeplayer.blogspot.com/
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: tuple如何转换成list?

wang_zheng_yong
In reply to this post by weizi-2
t = ((2,3),(3,4))
 
print t
 
q = [[i,j] for i,j in t]
 
print q
 
 

wang_zheng_yong
2007-06-06

发件人: weizi
发送时间: 2007-06-06 14:05:32
收件人: [hidden email]
抄送:
主题: [python-chinese]tuple如何转换成list?
 
这样的tuple((1,1),(2,2),(3,3))如何转换成list [[1,1],[2,2],[3,3]]
 
Aaa = []
A = ((1,1),(2,2),(3,3))
for aa in a:
    aaa.append(list(aa))
 
这样太难看了,有没有更优雅的做法。
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]

_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

答复: tuple如何转换成list?

weizi-2
非常感谢。可以了。

> -----邮件原件-----
> 发件人: [hidden email]
> [mailto:[hidden email]] 代表 wang_zheng_yong
> 发送时间: 2007年6月6日 14:18
> 收件人: [hidden email]
> 主题: Re: [python-chinese] tuple如何转换成list?
>
> t = ((2,3),(3,4))
>
> print t
>
> q = [[i,j] for i,j in t]
>
> print q
>
>
>
> ________________________________
>
> wang_zheng_yong
> 2007-06-06
> ________________________________
>
> 发件人: weizi
> 发送时间: 2007-06-06 14:05:32
> 收件人: [hidden email]
> 抄送:
> 主题: [python-chinese]tuple如何转换成list?
>
> 这样的tuple((1,1),(2,2),(3,3))如何转换成list [[1,1],[2,2],[3,3]]
>
> Aaa = []
> A = ((1,1),(2,2),(3,3))
> for aa in a:
>     aaa.append(list(aa))
>
> 这样太难看了,有没有更优雅的做法。
> _______________________________________________
> python-chinese
> Post: send [hidden email]
> Subscribe: send subscribe to [hidden email]
> Unsubscribe: send unsubscribe to  [hidden email]
> Detail Info: http://python.cn/mailman/listinfo/python-chinese
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 如何用python模拟一个上传文件的表单提交?

Nicholas Ding-2
In reply to this post by junyi sun
楼主要的这个功能挺常用的,不就是个文件上传嘛,用下面的代码就成。

import MultipartPostHandler, urllib2, cookielib

cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),
MultipartPostHandler.MultipartPostHandler)
params = { "username" : "bob", "password" : "riviera",
"file" : open("filename", "rb") }
opener.open("http://wwww.bobsite.com/upload/", params)
The code is at: http://odin.himinbi.org/MultipartPostHandler.py

On 6/6/07, junyi sun < [hidden email]> wrote:
flash有个控件可以批量选中并且上传
很多视频网站的上传就是用它做的

 
On 6/6/07, 马踏飞燕 <[hidden email]> wrote:
在 07-6-6,Zoom. Quiet<[hidden email]> 写道:
> On 6/6/07, 马踏飞燕 < [hidden email]> wrote:
> > 在 07-6-6,jessinio smith<[hidden email]> 写道:
> > > 你想做一下本地和服务器端通信的东西?
> > > _______________________________________________
> >
> > 对的。
> > 就相当于模拟一个IE的FILE类型的input框,主要是我想做一个批量上传文件的程序,直接写一个循环把大量的文件上传到服务器上。
> > _______________________________________________
> 大量文件上传的话使用 socket 稳定连接,
> FTP等等协议进行吧,HTTP 的实在不靠谱,而且也不安全
>

道理是这样,不过现在web应用已经开发好了,就是编辑抱怨老是在网页上一个一个的选文件,太烦了,所以想做一个小工具,直接批量的把文件传到server上就好了阿,毕竟不是所有的人都喜欢用ftp的,呵呵。
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: <a href="http://python.cn/mailman/listinfo/python-chinese" target="_blank" onclick="return top.js.OpenExtLink(window,event,this)">http://python.cn/mailman/listinfo/python-chinese


_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to   [hidden email]
Detail Info: <a onclick="return top.js.OpenExtLink(window,event,this)" href="http://python.cn/mailman/listinfo/python-chinese" target="_blank"> http://python.cn/mailman/listinfo/python-chinese



--
Nicholas @ Nirvana Studio
http://www.nirvanastudio.org
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: tuple如何转换成list?

Zhihao Yuan
In reply to this post by yi huang-3
黄毅 wrote:

> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
> (Intel)] on win
> 32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> def to_list(t):
> ...   return [i if not isinstance(i, tuple) else to_list(i) for i in t]
> ...
> >>> to_list( ((1,2), (2,3)) )
> [[1, 2], [2, 3]]
>
这个非常高超。
弱弱地问一句:在邮件列表里怎么回别人的帖子啊?
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 如何用python模拟一个上传文件的表单提交?

散漫酷男孩
In reply to this post by 马踏飞燕
给你代码参考!

import socket, string

CRLF = "\r\n"

def http_get(host, port = 80, document = "/"):

        try:
                http = miniclient(host, port)

        except Exception, e:

                if e[0] == 111:
                        print "Connection refused by server %s on port %d" % (host,port)

                raise

        http.writeline("GET %s HTTP/1.1" % str(document))
        http.writeline("HOST: %s" % host)
        http.writeline("User-Agent: GameSpyHTTP/1.0")
        http.writeline("Connection: close") # do not keep-alive
        http.writeline("")
        http.shutdown() # be nice, tell the http server we're done sending the request
       
        # Determine Status
        status = string.split(http.readline())
        if status[0] != "HTTP/1.1":
                print "MiniClient: Unknown status response (%s)" % str(status[0])
       
        try:
                status = string.atoi(status[1])
        except ValueError:
                print "MiniClient: Non-numeric status code (%s)" % str(status[1])
       
        #Extract Headers
        headers = []
        while 1:
                line = http.readline()
                if not line:
                        break
                headers.append(line)
       
        http.close() # all done

        #Check we got a valid HTTP response
        if status == 200:
                return http.read()
        else:
                return "E\nH\terr\nD\tHTTP Error\n$\tERR\t$"
       


def http_postSnapshot(host, port = 80, document = "/", snapshot = ""):

        try:
                http = miniclient(host, port)

        except Exception, e:

                if e[0] == 111:
                        print "Connection refused by server %s on port %d" % (host,port)
               
                raise

        try:
                http.writeline("POST %s HTTP/1.1" % str(document))
                http.writeline("HOST: %s" % str(host))
                http.writeline("User-Agent: GameSpyHTTP/1.0")
                http.writeline("Content-Type: application/x-www-form-urlencoded")
                http.writeline("Content-Length: %s" % str(len(snapshot)))
                http.writeline("Connection: close")
                http.writeline("")
                http.writeline(str(snapshot))
                http.writeline("")
                http.shutdown() # be nice, tell the http server we're done sending the request

                # Check that SnapShot Arrives.
                # Determine Status
                status = string.split(http.readline())
                if status[0] != "HTTP/1.1":
                        print "MiniClient: Unknown status response (%s)" % str(status[0])
               
                try:
                        status = string.atoi(status[1])
                except ValueError:
                        print "MiniClient: Non-numeric status code (%s)" % str(status[1])
               
                #Extract Headers
                headers = []
                while 1:
                        line = http.readline()
                        if not line:
                                break
                        headers.append(line)
                       
                http.close() # all done
               
                if status == 200:
                        print "SNAPSHOT Received: OK"
                        returnCode = 1
                else:
                        print "SNAPSHOT Received: ERROR"
                        returnCode = 0
               
                return status

        except Exception, e:
                raise

class miniclient:
        "Client support class for simple Internet protocols."

        def __init__(self, host, port):
                "Connect to an Internet server."
               

                self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.sock.settimeout(30)

                try:
                        self.sock.connect((host, port))
                        self.file = self.sock.makefile("rb")

                except socket.error, e:

                        #if e[0] == 111:
                        # print "Connection refused by server %s on port %d" % (host,port)

                        raise


        def writeline(self, line):
                "Send a line to the server."
               
                try:
                        self.sock.send(line + CRLF) # unbuffered write

                except socket.error, e:
                        if e[0] == 32 : #broken pipe
                                self.sock.close() # mutual close
                                self.sock = None
                       
                        raise e

                except socket.timeout:
                        self.sock.close() # mutual close
                        self.sock = None

                        raise

        def readline(self):
                "Read a line from the server.  Strip trailing CR and/or LF."

               
                s = self.file.readline()
               
                if not s:
                        raise EOFError
               
                if s[-2:] == CRLF:
                        s = s[:-2]
               
                elif s[-1:] in CRLF:
                        s = s[:-1]
               
                return s


        def read(self, maxbytes = None):
                "Read data from server."
               
                if maxbytes is None:
                        return self.file.read()
               
                else:
                        return self.file.read(maxbytes)


        def shutdown(self):
               
                if self.sock:
                        self.sock.shutdown(1)


        def close(self):
               
                if self.sock:
                        self.sock.close()
                        self.sock = None

在 07-6-6,马踏飞燕<[hidden email]> 写道:

> 就是用python提供的urllib这类的库来模拟一个上传文件的表单的提交动作,把本地文件提交到服务器上。
>
> 应该怎么写呢?
> 一般的urllib.urlopen用post打开的url怎么把文件的数据流也写过去呢?
> 接收方是用django写的,谢谢啦。
> _______________________________________________
> python-chinese
> Post: send [hidden email]
> Subscribe: send subscribe to [hidden email]
> Unsubscribe: send unsubscribe to  [hidden email]
> Detail Info: http://python.cn/mailman/listinfo/python-chinese
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 如何用python模拟一个上传文件的表单提交?

Nicholas Ding-2
楼上的代码是不对的,文件上传和POST不太一样,你需要使用Multipart,不然你是不可能让django用request.FILES来获取的。

On 6/6/07, 散漫酷男孩 <[hidden email]> wrote:
给你代码参考!

import socket, string

CRLF = "\r\n"

def http_get(host, port = 80, document = "/"):

        try:
                http = miniclient(host, port)

        except Exception, e:

                if e[0] == 111:
                        print   "Connection refused by server %s on port %d" % (host,port)

                raise

        http.writeline("GET %s HTTP/1.1" % str(document))
        http.writeline("HOST: %s" % host)
        http.writeline("User-Agent:     GameSpyHTTP/1.0")
        http.writeline("Connection: close") # do not keep-alive
        http.writeline("")
        http.shutdown() # be nice, tell the http server we're done sending the request

        # Determine Status
        status = string.split(http.readline())
        if status[0] != "HTTP/1.1":
                print "MiniClient: Unknown status response (%s)" % str(status[0])

        try:
                status = string.atoi(status[1])
        except ValueError:
                print "MiniClient: Non-numeric status code (%s)" % str(status[1])

        #Extract Headers
        headers = []
        while 1:
                line = http.readline()
                if not line:
                        break
                headers.append(line)

        http.close() # all done

        #Check we got a valid HTTP response
        if status == 200:
                return http.read()
        else:
                return "E\nH\terr\nD\tHTTP Error\n$\tERR\t$"



def http_postSnapshot(host, port = 80, document = "/", snapshot = ""):

        try:
                http = miniclient(host, port)

        except Exception, e:

                if e[0] == 111:
                        print   "Connection refused by server %s on port %d" % (host,port)

                raise

        try:
                http.writeline("POST %s HTTP/1.1" % str(document))
                http.writeline("HOST:   %s" % str(host))
                http.writeline ("User-Agent: GameSpyHTTP/1.0")
                http.writeline("Content-Type: application/x-www-form-urlencoded")
                http.writeline("Content-Length: %s" % str(len(snapshot)))
                http.writeline("Connection: close")
                http.writeline("")
                http.writeline(str(snapshot))
                http.writeline("")
                 http.shutdown() # be nice, tell the http server we're done sending the request

                # Check that SnapShot Arrives.
                # Determine Status
                status = string.split(http.readline ())
                if status[0] != "HTTP/1.1":
                        print "MiniClient: Unknown status response (%s)" % str(status[0])

                try:
                        status = string.atoi(status[1])
                except ValueError:
                        print "MiniClient: Non-numeric status code (%s)" % str(status[1])

                #Extract Headers
                headers = []
                while 1:
                        line = http.readline()
                        if not line:
                                break
                        headers.append(line)

                 http.close() # all done

                if status == 200:
                        print "SNAPSHOT Received: OK"
                        returnCode = 1
                else:
                        print "SNAPSHOT Received: ERROR"
                        returnCode = 0

                return status

        except Exception, e:
                raise

class miniclient:
        "Client support class for simple Internet protocols."

        def __init__(self, host, port):
                "Connect to an Internet server."


                self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.sock.settimeout (30)

                try:
                        self.sock.connect((host, port))
                        self.file = self.sock.makefile("rb")

                except socket.error, e:

                        #if e[0]        == 111:
                        #       print   "Connection refused by server %s on port %d" % (host,port)

                        raise


        def writeline(self, line):
                "Send a line to the server."

                try:
                        self.sock.send(line + CRLF) # unbuffered write

                except socket.error, e:
                        if e[0] == 32 : #broken pipe
                                 self.sock.close() # mutual close
                                self.sock = None

                        raise e

                except socket.timeout:
                        self.sock.close() # mutual close
                        self.sock = None

                        raise

        def readline(self):
                "Read a line from the server.  Strip trailing CR and/or LF."


                s = self.file.readline()

                if not s:
                        raise EOFError

                if s[-2:] == CRLF:
                        s = s[:-2]

                elif s[-1:] in CRLF:
                        s = s[:-1]

                return s


        def read(self, maxbytes = None):
                "Read data from server."

                if maxbytes is None:
                        return self.file.read()

                else:
                        return self.file.read(maxbytes)


        def shutdown(self):

                if self.sock:
                        self.sock.shutdown (1)


        def close(self):

                if self.sock:
                        self.sock.close()
                        self.sock = None

在 07-6-6,马踏飞燕<[hidden email]> 写道:

> 就是用python提供的urllib这类的库来模拟一个上传文件的表单的提交动作,把本地文件提交到服务器上。
>
> 应该怎么写呢?
> 一般的urllib.urlopen用post打开的url怎么把文件的数据流也写过去呢?
> 接收方是用django写的,谢谢啦。
> _______________________________________________
> python-chinese
> Post: send [hidden email]
> Subscribe: send subscribe to [hidden email]
> Unsubscribe: send unsubscribe to  [hidden email]
> Detail Info: http://python.cn/mailman/listinfo/python-chinese
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese



--
Nicholas @ Nirvana Studio
http://www.nirvanastudio.org
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 如何用python模拟一个上传文件的表单提交?

Nicholas Ding-2
In reply to this post by 散漫酷男孩
楼上的代码是不对的,文件上传和普通POST不太一样,你需要使用Multipart,不然你是不可能让django用request.FILES来获取的。

On 6/6/07, 散漫酷男孩 <[hidden email] > wrote:
给你代码参考!

import socket, string

CRLF = "\r\n"

def http_get(host, port = 80, document = "/"):

        try:
                http = miniclient(host, port)

        except Exception, e:

                if e[0] == 111:
                        print   "Connection refused by server %s on port %d" % (host,port)

                raise

        http.writeline("GET %s HTTP/1.1" % str(document))
        http.writeline("HOST: %s" % host)
        http.writeline("User-Agent:     GameSpyHTTP/1.0")
        http.writeline("Connection: close") # do not keep-alive
        http.writeline("")
        http.shutdown() # be nice, tell the http server we're done sending the request

        # Determine Status
        status = string.split(http.readline())
        if status[0] != "HTTP/1.1":
                print "MiniClient: Unknown status response (%s)" % str(status[0])

        try:
                status = string.atoi(status[1])
        except ValueError:
                print "MiniClient: Non-numeric status code (%s)" % str(status[1])

        #Extract Headers
        headers = []
        while 1:
                line = http.readline()
                if not line:
                        break
                headers.append(line)

        http.close() # all done

        #Check we got a valid HTTP response
        if status == 200:
                return http.read()
        else:
                return "E\nH\terr\nD\tHTTP Error\n$\tERR\t$"



def http_postSnapshot(host, port = 80, document = "/", snapshot = ""):

        try:
                http = miniclient(host, port)

        except Exception, e:

                if e[0] == 111:
                        print   "Connection refused by server %s on port %d" % (host,port)

                raise

        try:
                http.writeline("POST %s HTTP/1.1" % str(document))
                http.writeline("HOST:   %s" % str(host))
                http.writeline ("User-Agent: GameSpyHTTP/1.0")
                http.writeline("Content-Type: application/x-www-form-urlencoded")
                http.writeline("Content-Length: %s" % str(len(snapshot)))
                http.writeline("Connection: close")
                http.writeline("")
                http.writeline(str(snapshot))
                http.writeline("")
                 http.shutdown() # be nice, tell the http server we're done sending the request

                # Check that SnapShot Arrives.
                # Determine Status
                status = string.split(http.readline ())
                if status[0] != "HTTP/1.1":
                        print "MiniClient: Unknown status response (%s)" % str(status[0])

                try:
                        status = string.atoi(status[1])
                except ValueError:
                        print "MiniClient: Non-numeric status code (%s)" % str(status[1])

                #Extract Headers
                headers = []
                while 1:
                        line = http.readline()
                        if not line:
                                break
                        headers.append(line)

                 http.close() # all done

                if status == 200:
                        print "SNAPSHOT Received: OK"
                        returnCode = 1
                else:
                        print "SNAPSHOT Received: ERROR"
                        returnCode = 0

                return status

        except Exception, e:
                raise

class miniclient:
        "Client support class for simple Internet protocols."

        def __init__(self, host, port):
                "Connect to an Internet server."


                self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.sock.settimeout (30)

                try:
                        self.sock.connect((host, port))
                        self.file = self.sock.makefile("rb")

                except socket.error, e:

                        #if e[0]        == 111:
                        #       print   "Connection refused by server %s on port %d" % (host,port)

                        raise


        def writeline(self, line):
                "Send a line to the server."

                try:
                        self.sock.send(line + CRLF) # unbuffered write

                except socket.error, e:
                        if e[0] == 32 : #broken pipe
                                 self.sock.close() # mutual close
                                self.sock = None

                        raise e

                except socket.timeout:
                        self.sock.close() # mutual close
                        self.sock = None

                        raise

        def readline(self):
                "Read a line from the server.  Strip trailing CR and/or LF."


                s = self.file.readline()

                if not s:
                        raise EOFError

                if s[-2:] == CRLF:
                        s = s[:-2]

                elif s[-1:] in CRLF:
                        s = s[:-1]

                return s


        def read(self, maxbytes = None):
                "Read data from server."

                if maxbytes is None:
                        return self.file.read()

                else:
                        return self.file.read(maxbytes)


        def shutdown(self):

                if self.sock:
                        self.sock.shutdown (1)


        def close(self):

                if self.sock:
                        self.sock.close()
                        self.sock = None

在 07-6-6,马踏飞燕<[hidden email]> 写道:

> 就是用python提供的urllib这类的库来模拟一个上传文件的表单的提交动作,把本地文件提交到服务器上。
>
> 应该怎么写呢?
> 一般的urllib.urlopen用post打开的url怎么把文件的数据流也写过去呢?
> 接收方是用django写的,谢谢啦。
> _______________________________________________
> python-chinese
> Post: send [hidden email]
> Subscribe: send subscribe to [hidden email]
> Unsubscribe: send unsubscribe to  [hidden email]
> Detail Info: http://python.cn/mailman/listinfo/python-chinese
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese



--
Nicholas @ Nirvana Studio
http://www.nirvanastudio.org
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 如何用python模拟一个上传文件的表单提交?

散漫酷男孩
HTTP协议很简单的。。。
稍微看看就明白了。。
这个可以自己扩展。。

在 07-6-6,Nicholas Ding<[hidden email]> 写道:

> 楼上的代码是不对的,文件上传和普通POST不太一样,你需要使用Multipart,不然你是不可能让django用request.FILES来获取的。
>
>
> On 6/6/07, 散漫酷男孩 <[hidden email] > wrote:
> > 给你代码参考!
> >
> > import socket, string
> >
> > CRLF = "\r\n"
> >
> > def http_get(host, port = 80, document = "/"):
> >
> >         try:
> >                 http = miniclient(host, port)
> >
> >         except Exception, e:
> >
> >                 if e[0] == 111:
> >                         print   "Connection refused by server %s on port
> %d" % (host,port)
> >
> >                 raise
> >
> >         http.writeline("GET %s HTTP/1.1" % str(document))
> >         http.writeline("HOST: %s" % host)
> >         http.writeline("User-Agent:     GameSpyHTTP/1.0")
> >         http.writeline("Connection: close") # do not keep-alive
> >         http.writeline("")
> >         http.shutdown() # be nice, tell the http server we're done sending
> the request
> >
> >         # Determine Status
> >         status = string.split(http.readline())
> >         if status[0] != "HTTP/1.1":
> >                 print "MiniClient: Unknown status response (%s)" %
> str(status[0])
> >
> >         try:
> >                 status = string.atoi(status[1])
> >         except ValueError:
> >                 print "MiniClient: Non-numeric status code (%s)" %
> str(status[1])
> >
> >         #Extract Headers
> >         headers = []
> >         while 1:
> >                 line = http.readline()
> >                 if not line:
> >                         break
> >                 headers.append(line)
> >
> >         http.close() # all done
> >
> >         #Check we got a valid HTTP response
> >         if status == 200:
> >                 return http.read()
> >         else:
> >                 return "E\nH\terr\nD\tHTTP Error\n$\tERR\t$"
> >
> >
> >
> > def http_postSnapshot(host, port = 80, document = "/", snapshot = ""):
> >
> >         try:
> >                 http = miniclient(host, port)
> >
> >         except Exception, e:
> >
> >                 if e[0] == 111:
> >                         print   "Connection refused by server %s on port
> %d" % (host,port)
> >
> >                 raise
> >
> >         try:
> >                 http.writeline("POST %s HTTP/1.1" % str(document))
> >                 http.writeline("HOST:   %s" % str(host))
> >                 http.writeline ("User-Agent: GameSpyHTTP/1.0")
> >                 http.writeline("Content-Type:
> application/x-www-form-urlencoded")
> >                 http.writeline("Content-Length: %s" % str(len(snapshot)))
> >                 http.writeline("Connection: close")
> >                 http.writeline("")
> >                 http.writeline(str(snapshot))
> >                 http.writeline("")
> >                  http.shutdown() # be nice, tell the http server we're
> done sending the request
> >
> >                 # Check that SnapShot Arrives.
> >                 # Determine Status
> >                 status = string.split(http.readline ())
> >                 if status[0] != "HTTP/1.1":
> >                         print "MiniClient: Unknown status response (%s)" %
> str(status[0])
> >
> >                 try:
> >                         status = string.atoi(status[1])
> >                 except ValueError:
> >                         print "MiniClient: Non-numeric status code (%s)" %
> str(status[1])
> >
> >                 #Extract Headers
> >                 headers = []
> >                 while 1:
> >                         line = http.readline()
> >                         if not line:
> >                                 break
> >                         headers.append(line)
> >
> >                  http.close() # all done
> >
> >                 if status == 200:
> >                         print "SNAPSHOT Received: OK"
> >                         returnCode = 1
> >                 else:
> >                         print "SNAPSHOT Received: ERROR"
> >                         returnCode = 0
> >
> >                 return status
> >
> >         except Exception, e:
> >                 raise
> >
> > class miniclient:
> >         "Client support class for simple Internet protocols."
> >
> >         def __init__(self, host, port):
> >                 "Connect to an Internet server."
> >
> >
> >                 self.sock = socket.socket(socket.AF_INET,
> socket.SOCK_STREAM)
> >                 self.sock.settimeout (30)
> >
> >                 try:
> >                         self.sock.connect((host, port))
> >                         self.file = self.sock.makefile("rb")
> >
> >                 except socket.error, e:
> >
> >                         #if e[0]        == 111:
> >                         #       print   "Connection refused by server %s
> on port %d" % (host,port)
> >
> >                         raise
> >
> >
> >         def writeline(self, line):
> >                 "Send a line to the server."
> >
> >                 try:
> >                         self.sock.send(line + CRLF) # unbuffered write
> >
> >                 except socket.error, e:
> >                         if e[0] == 32 : #broken pipe
> >                                  self.sock.close() #
> mutual close
> >                                 self.sock = None
> >
> >                         raise e
> >
> >                 except socket.timeout:
> >                         self.sock.close() # mutual close
> >                         self.sock = None
> >
> >                         raise
> >
> >         def readline(self):
> >                 "Read a line from the server.  Strip trailing CR and/or
> LF."
> >
> >
> >                 s = self.file.readline()
> >
> >                 if not s:
> >                         raise EOFError
> >
> >                 if s[-2:] == CRLF:
> >                         s = s[:-2]
> >
> >                 elif s[-1:] in CRLF:
> >                         s = s[:-1]
> >
> >                 return s
> >
> >
> >         def read(self, maxbytes = None):
> >                 "Read data from server."
> >
> >                 if maxbytes is None:
> >                         return self.file.read()
> >
> >                 else:
> >                         return self.file.read(maxbytes)
> >
> >
> >         def shutdown(self):
> >
> >                 if self.sock:
> >                         self.sock.shutdown (1)
> >
> >
> >         def close(self):
> >
> >                 if self.sock:
> >                         self.sock.close()
> >                         self.sock = None
> >
> > 在 07-6-6,马踏飞燕< [hidden email]> 写道:
> > > 就是用python提供的urllib这类的库来模拟一个上传文件的表单的提交动作,把本地文件提交到服务器上。
> > >
> > > 应该怎么写呢?
> > > 一般的urllib.urlopen用post打开的url怎么把文件的数据流也写过去呢?
> > > 接收方是用django写的,谢谢啦。
> > > _______________________________________________
> > > python-chinese
> > > Post: send [hidden email]
> > > Subscribe: send subscribe to
> [hidden email]
> > > Unsubscribe: send unsubscribe to
> [hidden email]
> > > Detail Info:
> http://python.cn/mailman/listinfo/python-chinese
> > _______________________________________________
> > python-chinese
> > Post: send [hidden email]
> > Subscribe: send subscribe to
> [hidden email]
> > Unsubscribe: send unsubscribe to
> [hidden email]
> > Detail Info:
> http://python.cn/mailman/listinfo/python-chinese
>
>
>
> --
> Nicholas @ Nirvana Studio
> http://www.nirvanastudio.org
> _______________________________________________
> python-chinese
> Post: send [hidden email]
> Subscribe: send subscribe to
> [hidden email]
> Unsubscribe: send unsubscribe to
> [hidden email]
> Detail Info:
> http://python.cn/mailman/listinfo/python-chinese
>
_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese