用Python编写一个简单的Http Server

Python内置了支持HTTP协议的模块,我们可以用来开发单机版功能较少的Web服务器。Python支持该功能的实现模块是BaseFTTPServer, 我们只需要在项目中引入就可以了:

  1. from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
  • 1

Hello world !

Let’s start with the first basic example. It just return “Hello World !” on the web browser.
让我们来看第一个基本例子,在浏览器上输出”Hello World ”
example1.py

  1. #!/usr/bin/python
  2. from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
  3. PORT_NUMBER = 8080
  4. #This class will handles any incoming request from
  5. #the browser
  6. class myHandler(BaseHTTPRequestHandler):
  7. #Handler for the GET requests
  8. def do_GET(self):
  9. self.send_response(200)
  10. self.send_header('Content-type','text/html')
  11. self.end_headers()
  12. # Send the html message
  13. self.wfile.write("Hello World !")
  14. return
  15. try:
  16. #Create a web server and define the handler to manage the
  17. #incoming request
  18. server = HTTPServer(('', PORT_NUMBER), myHandler)
  19. print 'Started httpserver on port ' , PORT_NUMBER
  20. #Wait forever for incoming htto requests
  21. server.serve_forever()
  22. except KeyboardInterrupt:
  23. print '^C received, shutting down the web server'
  24. server.socket.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

执行以下命令运行:

python example1.py

用你的浏览器打开这个地址http://your_ip:8080
浏览器上将会显示”Hello World !” 同时在终端上将会出现两条日志信息:

Started httpserver on port 8080
10.55.98.7 - - [30/Jan/2012 15:40:52] “GET / HTTP/1.1” 200 -
10.55.98.7 - - [30/Jan/2012 15:40:52] “GET /favicon.ico HTTP/1.1” 200 -

Serve static files

让我们来尝试下提供静态文件的例子,像index.html, style.css, javascript和images:

example2.py

  1. #!/usr/bin/python
  2. from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
  3. from os import curdir, sep
  4. PORT_NUMBER = 8080
  5. #This class will handles any incoming request from
  6. #the browser
  7. class myHandler(BaseHTTPRequestHandler):
  8. #Handler for the GET requests
  9. def do_GET(self):
  10. if self.path=="/":
  11. self.path="/index_example2.html"
  12. try:
  13. #Check the file extension required and
  14. #set the right mime type
  15. sendReply = False
  16. if self.path.endswith(".html"):
  17. mimetype='text/html'
  18. sendReply = True
  19. if self.path.endswith(".jpg"):
  20. mimetype='image/jpg'
  21. sendReply = True
  22. if self.path.endswith(".gif"):
  23. mimetype='image/gif'
  24. sendReply = True
  25. if self.path.endswith(".js"):
  26. mimetype='application/javascript'
  27. sendReply = True
  28. if self.path.endswith(".css"):
  29. mimetype='text/css'
  30. sendReply = True
  31. if sendReply == True:
  32. #Open the static file requested and send it
  33. f = open(curdir + sep + self.path)
  34. self.send_response(200)
  35. self.send_header('Content-type',mimetype)
  36. self.end_headers()
  37. self.wfile.write(f.read())
  38. f.close()
  39. return
  40. except IOError:
  41. self.send_error(404,'File Not Found: %s' % self.path)
  42. try:
  43. #Create a web server and define the handler to manage the
  44. #incoming request
  45. server = HTTPServer(('', PORT_NUMBER), myHandler)
  46. print 'Started httpserver on port ' , PORT_NUMBER
  47. #Wait forever for incoming htto requests
  48. server.serve_forever()
  49. except KeyboardInterrupt:
  50. print '^C received, shutting down the web server'
  51. server.socket.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62

这个新样例实现功能:

  • 检查请求文件扩展名
  • 设置正确的媒体类型返回给浏览器
  • 打开请求的文件
  • 发送给浏览器

输入如下命令运行它:

python example2.py

然后用你的浏览器打开 http://your_ip:8080
一个首页会出现在你的浏览器上

Read data from a form

现在探索下如何从html表格中读取数据

example3.py

  1. #!/usr/bin/python
  2. from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
  3. from os import curdir, sep
  4. import cgi
  5. PORT_NUMBER = 8080
  6. #This class will handles any incoming request from
  7. #the browser
  8. class myHandler(BaseHTTPRequestHandler):
  9. #Handler for the GET requests
  10. def do_GET(self):
  11. if self.path=="/":
  12. self.path="/index_example3.html"
  13. try:
  14. #Check the file extension required and
  15. #set the right mime type
  16. sendReply = False
  17. if self.path.endswith(".html"):
  18. mimetype='text/html'
  19. sendReply = True
  20. if self.path.endswith(".jpg"):
  21. mimetype='image/jpg'
  22. sendReply = True
  23. if self.path.endswith(".gif"):
  24. mimetype='image/gif'
  25. sendReply = True
  26. if self.path.endswith(".js"):
  27. mimetype='application/javascript'
  28. sendReply = True
  29. if self.path.endswith(".css"):
  30. mimetype='text/css'
  31. sendReply = True
  32. if sendReply == True:
  33. #Open the static file requested and send it
  34. f = open(curdir + sep + self.path)
  35. self.send_response(200)
  36. self.send_header('Content-type',mimetype)
  37. self.end_headers()
  38. self.wfile.write(f.read())
  39. f.close()
  40. return
  41. except IOError:
  42. self.send_error(404,'File Not Found: %s' % self.path)
  43. #Handler for the POST requests
  44. def do_POST(self):
  45. if self.path=="/send":
  46. form = cgi.FieldStorage(
  47. fp=self.rfile,
  48. headers=self.headers,
  49. environ={'REQUEST_METHOD':'POST',
  50. 'CONTENT_TYPE':self.headers['Content-Type'],
  51. })
  52. print "Your name is: %s" % form["your_name"].value
  53. self.send_response(200)
  54. self.end_headers()
  55. self.wfile.write("Thanks %s !" % form["your_name"].value)
  56. return
  57. try:
  58. #Create a web server and define the handler to manage the
  59. #incoming request
  60. server = HTTPServer(('', PORT_NUMBER), myHandler)
  61. print 'Started httpserver on port ' , PORT_NUMBER
  62. #Wait forever for incoming htto requests
  63. server.serve_forever()
  64. except KeyboardInterrupt:
  65. print '^C received, shutting down the web server'
  66. server.socket.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78

运行这个例子:

python example3.py

在 “Your name” 标签旁边输入你的名字

用Python编写一个简单的Http Server的更多相关文章

  1. 编写一个简单的Web Server

    编写一个简单的Web Server其实是轻而易举的.如果我们只是想托管一些HTML页面,我们可以这么实现: 在VS2013中创建一个C# 控制台程序 编写一个字符串扩展方法类,主要用于在URL中截取文 ...

  2. 为Python编写一个简单的C语言扩展模块

    最近在看pytorh方面的东西,不得不承认现在这个东西比较火,有些小好奇,下载了代码发现其中计算部分基本都是C++写的,这真是要我对这个所谓Python语音编写的框架或者说是库感觉到一丢丢的小失落,细 ...

  3. 使用Python创建一个简易的Web Server

    Python 2.x中自带了SimpleHTTPServer模块,到Python3.x中,该模块被合并到了http.server模块中.使用该模块,可以快速创建一个简易的Web服务器. 我们在C:\U ...

  4. 写了一个简单的CGI Server

    之前看过一些开源程序的源码,也略微知道些Apache的CGI处理程序架构,于是用了一周时间,用C写了一个简单的CGI Server,代码算上头文件,一共1200行左右,难度中等偏上,小伙伴可以仔细看看 ...

  5. 用Python写一个简单的Web框架

    一.概述 二.从demo_app开始 三.WSGI中的application 四.区分URL 五.重构 1.正则匹配URL 2.DRY 3.抽象出框架 六.参考 一.概述 在Python中,WSGI( ...

  6. 用python实现一个简单的词云

    对于在windows(Pycharm工具)里实现一个简单的词云还是经过了几步小挫折,跟大家分享下,如果遇到类似问题可以参考: 1. 导入wordcloud包时候报错,当然很明显没有安装此包. 2. 安 ...

  7. 一个简单的mock server

    在前后端分离的项目中, 前端无需等后端接口提供了才调试, 后端无需等第三方接口提供了才调试, 基于“契约”,可以通过mock server实现调试, 下面是一个简单的mock server,通过pyt ...

  8. 手把手教你编写一个简单的PHP模块形态的后门

    看到Freebuf 小编发表的用这个隐藏于PHP模块中的rootkit,就能持久接管服务器文章,很感兴趣,苦无作者没留下PoC,自己研究一番,有了此文 0×00. 引言 PHP是一个非常流行的web ...

  9. python中一个简单的webserver

     python中一个简单的webserver 2013-02-24 15:37:49 分类: Python/Ruby 支持多线程的webserver   1 2 3 4 5 6 7 8 9 10 11 ...

随机推荐

  1. 《FPGA全程进阶---实战演练》第一章之FPGA介绍

    1 什么是FPGA FPGA也即是Field Programmable Gate Array的缩写,翻译成中文就是现场可编程门阵列.FPGA是在PAL.GAL.CPLD等可编程器件的基础上发展起来的新 ...

  2. 实验二 C#程序设计 总结

    通过本次实验,我按照书上的例子,一个例子一个例子地写下来,前七点感觉和C语言差不多,除了语法稍稍不同外,大体上是一样的.到了第八点,对异常的处理,另我十分印象深刻.因为我做例3.21的时候,按照例子要 ...

  3. oracle PLSQL基础学习

    --oracle 练习: /**************************************************PL/SQL编程基础************************** ...

  4. 2013年第四届蓝桥杯C/C++B组省赛题目解析

    一. 高斯日记 大数学家高斯有个好习惯:无论如何都要记日记. 他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210 后来人们知道,那个整数就是日期,它表示那一天是高斯出生后 ...

  5. Aizu_Insertion Sort

    原题链接:https://vjudge.net/problem/Aizu-ALDS1_1_A 题目描述 Write a program of the Insertion Sort algorithm ...

  6. 获取select 的 val 和 text [转引]

    (原文地址:http://apps.hi.baidu.com/share/detail/6152780) jQuery获取Select选择的Text和Value:语法解释:1. $("#se ...

  7. Maven Web应用

    创建Web应用程序 要创建一个简单的java web应用程序,我们将使用Maven的原型 - web应用插件.因此,让我们打开命令控制台,进入到C: MVN目录并执行以下命令mvn命令. C:MVN& ...

  8. e613. Modifying the Focus Traversal Order

    JFrame frame = new JFrame(); JButton component1 = new JButton("1"); JButton component2 = n ...

  9. C语言中 Float 数据结构的存储计算

    1.了解float存储结构 float存储结构请看另一篇文章http://blog.csdn.net/whzhaochao/article/details/12885875 2.float最大值 fl ...

  10. Linux Shell的 & 、&& 、 ||

    Linux Shell的 & .&& . || 收藏 hanzhankang 发表于 3年前 阅读 18472 收藏 20 点赞 4 评论 0 开程序员的淘宝店!寻找开源技术服 ...