python超简单的web服务器
今天无意google时看见,心里突然想说,python做web服务器,用不用这么简单啊,看来是我大惊小怪了.
web1.py
1
2
3
|
#!/usr/bin/python
import SimpleHTTPServer
SimpleHTTPServer.test()
|
web2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#!/usr/bin/python
import SimpleHTTPServer
import SocketServer
import os
PORT = 80
WEBDIR = "f:/python语言学习"
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def translate_path(self, path):
os.chdir(WEBDIR)
return SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self,path)
try:
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "dir %s serving at port %s"%(repr(WEBDIR), PORT)
httpd.serve_forever()
except:pass
|
web3.py , cgi server ,7777端口, 在web3.py执行目录下新建cgi-bin目录 , 在cgi-bin目录写hello.py
web3.py
1
2
3
4
5
|
from CGIHTTPServer import CGIHTTPRequestHandler
from BaseHTTPServer import HTTPServer
server_address=('',7777)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()
|
hello.py
1
2
3
4
5
6
7
8
|
#!c:/Python24/python.exe
print "HTTP/1.0 200 OK"
print "Content-Type: text/html"
print ""
print "<p>"
print "Hello World!"
print "</p>"
|
以下这些是需要安装了 twisted 才能使用的
web4.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
from twisted.web.resource import Resource
from twisted.web import server
from twisted.web import static
from twisted.internet import reactor
class ReStructured( Resource ):
def __init__( self, filename, *a ):
self.rst = open( filename ).read( )
def render( self, request ):
return self.rst
PORT=8888
resource = static.File('/')
resource.processors = { '.html' : ReStructured }
resource.indexNames = [ 'index.html']
reactor.listenTCP(
PORT,
server.Site( resource )
)
reactor.run( )
|
web5.py, 这是又是支持cgi的,又是需要twisted模块的,也是需要在cgi-bin目录下执行,上边的hello.py也能用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# -*- coding: utf-8 -*-
from twisted.internet import reactor
from twisted.web import static, server, twcgi
from twisted.web.resource import Resource
class Collection(Resource):
def render_GET(self, request):
return "hello world 你好"
root = static.File('./')
root.putChild('', Collection())
root.putChild('img', static.File('./img'))
root.putChild('cgi-bin', twcgi.CGIDirectory('cgi-bin'))
reactor.listenTCP(80, server.Site(root))
reactor.run()
|
当然,想实现复杂功能还是需要自己搞代码的,只不过想惊叹python的模块集成得太多功能了.
python超简单的web服务器。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
2013-09-21 RMAN备份-未使用catalog-控制文件丢失
2013-09-21 alter system [switch logfile]与[archive log current]的区别
2013-09-21 RMAN备份介质的移动与再恢复测试 [ catalog start with ‘dir’ ]
2013-09-21 RMAN基础恢复测试
2013-09-21 controlfile与备份恢复
2013-09-21 热备份细节--归档日志
2013-09-21 模拟controfile丢失与重建