用Python编写一个简单的Http Server

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

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

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer PORT_NUMBER = 8080 #This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler): #Handler for the GET requests
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
self.wfile.write("Hello World !")
return try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER #Wait forever for incoming htto requests
server.serve_forever() except KeyboardInterrupt:
print '^C received, shutting down the web server'
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

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep PORT_NUMBER = 8080 #This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler): #Handler for the GET requests
def do_GET(self):
if self.path=="/":
self.path="/index_example2.html" try:
#Check the file extension required and
#set the right mime type sendReply = False
if self.path.endswith(".html"):
mimetype='text/html'
sendReply = True
if self.path.endswith(".jpg"):
mimetype='image/jpg'
sendReply = True
if self.path.endswith(".gif"):
mimetype='image/gif'
sendReply = True
if self.path.endswith(".js"):
mimetype='application/javascript'
sendReply = True
if self.path.endswith(".css"):
mimetype='text/css'
sendReply = True if sendReply == True:
#Open the static file requested and send it
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type',mimetype)
self.end_headers()
self.wfile.write(f.read())
f.close()
return except IOError:
self.send_error(404,'File Not Found: %s' % self.path) try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER #Wait forever for incoming htto requests
server.serve_forever() except KeyboardInterrupt:
print '^C received, shutting down the web server'
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

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import cgi PORT_NUMBER = 8080 #This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
if self.path=="/":
self.path="/index_example3.html" try:
#Check the file extension required and
#set the right mime type sendReply = False
if self.path.endswith(".html"):
mimetype='text/html'
sendReply = True
if self.path.endswith(".jpg"):
mimetype='image/jpg'
sendReply = True
if self.path.endswith(".gif"):
mimetype='image/gif'
sendReply = True
if self.path.endswith(".js"):
mimetype='application/javascript'
sendReply = True
if self.path.endswith(".css"):
mimetype='text/css'
sendReply = True if sendReply == True:
#Open the static file requested and send it
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type',mimetype)
self.end_headers()
self.wfile.write(f.read())
f.close()
return except IOError:
self.send_error(404,'File Not Found: %s' % self.path) #Handler for the POST requests
def do_POST(self):
if self.path=="/send":
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
}) print "Your name is: %s" % form["your_name"].value
self.send_response(200)
self.end_headers()
self.wfile.write("Thanks %s !" % form["your_name"].value)
return try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER #Wait forever for incoming htto requests
server.serve_forever() except KeyboardInterrupt:
print '^C received, shutting down the web server'
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. Python之collections.defaultdict

    转自:http://www.jb51.net/article/88147.htm

  2. 第三百六十五节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)的基本查询

    第三百六十五节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)的基本查询 1.elasticsearch(搜索引擎)的查询 elasticsearch是功能 ...

  3. 定制库到Maven本地资源库

    这里有2个案例,需要手动发出Maven命令包括一个 jar 到 Maven 的本地资源库. 要使用的 jar 不存在于 Maven 的中心储存库中. 您创建了一个自定义的 jar ,而另一个 Mave ...

  4. e803. 获得和设置JProgressBar的值

    // To create a progress bar, see e801 创建一个JProgressBar组件 // Get the current value int value = progre ...

  5. e802. 创建一个位置大小的JProgressBar组件

    A progress bar with an unknown maximum typically displays an animation until the task is complete. N ...

  6. Python——uuid

    uuid模块在Python 2.5以后引入,接口包括:不可变对象UUID(UUID类)和函数uuid1().uuid3().uuid4()和uuid5(),后面的四个函数用于生成 RFC 4122 规 ...

  7. Python_问题收录总结

    python IndentationError: unindent does not match any outer indentation level的问题 用python编个作业,我先用的note ...

  8. resharper安装后,F12不能转到定义,也不是反编译,而是转到对象浏览器(object browser)

    问: resharper安装后,一不小心点错了(选择了object browser)以上配置在哪里设置?转到定义用习惯了. 回答 :打开Resharper,选择Options,然后选择Tools中的E ...

  9. 有空研究一下 superwebsocket (底层是 supersocket) 用来实现 web聊天什么的

    参考:http://superwebsocket.codeplex.com/ 一个老外写的 asp.net 下socket的多钟方案推荐 :http://www.codeproject.com/Art ...

  10. iptables规则备份和恢复 firewalld的9个zone firewalld关于zone的操作 firewalld关于service的操作

    iptables规则备份和恢复 保存和备份iptables规则Service iptables save //会把规则保存到/etc/sysconfig/iptables把iptables规则备份到m ...