HTTP
自python2.4之后,提供了httpserver库,所以我们可以很方便创建http服务器。
服务器端我们可以采用HTTPServer,这个类包含在BaseHTTPServer中,客户端我们使用httplib。先直接上服务器和客户端的代码,然后我们再研究。
http服务器端:
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer
import SocketServer
class MyHTTPRequestHandler( BaseHTTPRequestHandler ):
def do_GET( self ):
enc='utf-8'
self.send_response( 200 )
self.send_header("Content-type", "text/html;charset%s" %enc )
f = open('D:/Study/Python/test.py','r')
ct = f.read()
self.send_header('Content-length', str(len(ct)))
self.end_headers()
self.wfile.write( ct )
def do_POST( self ):
pass
def do_HEAD( self ):
pass
if __name__ == '__main__':
port = 8080
handler = SimpleHTTPRequestHandler
#httpd = SocketServer.TCPServer(("", port ), handler )
httpd = HTTPServer(('', port ), MyHTTPRequestHandler)
print "Server is running at port", port
httpd.serve_forever()
http客户端:
import httplib
if __name__ == '__main__':
con=httplib.HTTPConnection('localhost:8080')
con.request('GET','/')
res = con.getresponse()
dt = res.read()
print dt
con.close()
启动服务端,然后启动客户端,在客户端就可以看到服务端发过来的内容。服务端发过来的内容是什么呢?
其实就是
D:/Study/Python/test.py
这个文件的内容。这个文件可以你磁盘上面的任何文件了,只要有读的权限就可以。
HTTPS
接下来我们来实现https,这个需要依赖外部的库 pyopenssl,可以去官网下载:
https://launchpad.net/pyopenssl/main
下载windows的msi或者exe安装,记得下载跟你python版本对应的文件。
然后直接安装。
接下来看看怎么完成服务端和客户端的实现。
https服务端:
https客户端:
参考资料:
http://docs.python.org/library/httplib.html
http://docs.python.org/library/basehttpserver.html
http://adreaman.com/1126python-simplehttp-https-server-client.html
未完待续。。
版权所有,禁止转载. 如需转载,请先征得博主的同意,并且表明文章出处,否则按侵权处理.
分享到: