简单Python HTTP服务器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单Python HTTP服务器相关的知识,希望对你有一定的参考价值。
A very simple HTTP Server written in Python out of boredom.USAGE :
1 . Create a htdocs folder in the directory of this script
2 . create an index.html file and you are good to go.
This works with multiple pages however index.html is the default
#!/usr/bin/python # _ __ __ _ __ __ _____ # / / _|/ _(_)_ __ | / | ____| # / _ | |_| |_| / / | |/| | _| # / ___ | _| _| |> < _| | | | |___ # /_/ \_\_| |_| |_/_/\_(_)_| |_|_____| # # Title : Simple Python HTTP Server # Author : Affix <[email protected]> # Website : http://Affix.ME # License : GNU/GPL V3 # Description : Serves simple HTML Pages # stored inside a folder called htdocs in the # same directory as this script. # # DO NOT EXPECT UPDATES I WAS BORED ################################################# #### DO NOT EDIT BELOW THIS LINE #### ################################################# import socket, os, re serverSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "+ Server Launched " serverSock.bind(('', 8000)) serverSock.listen(1) while True: chan, details = serverSock.accept() data = chan.recv(100) print data re1='(GET)' re2='.*?' re3='((?:\/[\w\.\-]+)+)' re4='.*?' re5='((?:[a-z][a-z]+))' rg = re.compile(re1+re2+re3+re4+re5,re.IGNORECASE|re.DOTALL) m = rg.search(data) if m: word1=m.group(1) unixpath1=m.group(2) word2=m.group(3) print "("+word1+")"+"("+unixpath1+")"+"("+word2+")"+" " if unixpath1 == "/1.1": unixpath1 = "/index.html" print "+ Attempting to serve "+ unixpath1 +" " if os.path.exists("htdocs" + unixpath1): file = open("htdocs" + unixpath1, "r") chan.send(file.read()) else: print "+ File was not found! " chan.send("<html><head><title>404</title></head><body><h1>404 File not Found</h1><br />The file you requested was not found on the server<hr /><small>Affix' Simple Python HTTP Server 0.0.1</small></body></html>") chan.close()
以上是关于简单Python HTTP服务器的主要内容,如果未能解决你的问题,请参考以下文章
Python练习册 第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-),(http://tieba.baidu.com/p/2166231880)(代码片段