简单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
  1. #!/usr/bin/python
  2. # _ __ __ _ __ __ _____
  3. # / / _|/ _(_)_ __ | / | ____|
  4. # / _ | |_| |_| / / | |/| | _|
  5. # / ___ | _| _| |> < _| | | | |___
  6. # /_/ \_\_| |_| |_/_/\_(_)_| |_|_____|
  7. #
  8. # Title : Simple Python HTTP Server
  9. # Author : Affix <[email protected]>
  10. # Website : http://Affix.ME
  11. # License : GNU/GPL V3
  12. # Description : Serves simple HTML Pages
  13. # stored inside a folder called htdocs in the
  14. # same directory as this script.
  15. #
  16. # DO NOT EXPECT UPDATES I WAS BORED
  17.  
  18. #################################################
  19. #### DO NOT EDIT BELOW THIS LINE ####
  20. #################################################
  21.  
  22. import socket, os, re
  23.  
  24. serverSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  25.  
  26. print "+ Server Launched "
  27. serverSock.bind(('', 8000))
  28. serverSock.listen(1)
  29. while True:
  30. chan, details = serverSock.accept()
  31. data = chan.recv(100)
  32. print data
  33.  
  34. re1='(GET)'
  35. re2='.*?'
  36. re3='((?:\/[\w\.\-]+)+)'
  37. re4='.*?'
  38. re5='((?:[a-z][a-z]+))'
  39.  
  40. rg = re.compile(re1+re2+re3+re4+re5,re.IGNORECASE|re.DOTALL)
  41. m = rg.search(data)
  42. if m:
  43. word1=m.group(1)
  44. unixpath1=m.group(2)
  45. word2=m.group(3)
  46. print "("+word1+")"+"("+unixpath1+")"+"("+word2+")"+" "
  47. if unixpath1 == "/1.1":
  48. unixpath1 = "/index.html"
  49.  
  50. print "+ Attempting to serve "+ unixpath1 +" "
  51. if os.path.exists("htdocs" + unixpath1):
  52. file = open("htdocs" + unixpath1, "r")
  53. chan.send(file.read())
  54. else:
  55. print "+ File was not found! "
  56. 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>")
  57. chan.close()

以上是关于简单Python HTTP服务器的主要内容,如果未能解决你的问题,请参考以下文章

简单的 Javascript http 请求片段但不起作用

Python练习册 第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-),(http://tieba.baidu.com/p/2166231880)(代码片段

node 环境下简单web服务器搭建代码

简单的方法来分享/讨论/协作的代码片段?

Python实现简单HTTP服务器

Python学习总结