python --web服务器

用python建立简单的web服务器

利用Python自带的包可以建立简单的web服务器。

  • 在DOS里cd到准备做服务器根目录的路径下,输入命令:
python -m Web服务器模块 [端口号,默认8000]

例如:

python -m SimpleHTTPServer 8080
  • 然后就可以在浏览器中输入

http://localhost:端口号/路径
来访问服务器资源。
例如:
http://localhost:8080/index.htm(当然index.htm文件得自己创建)
其他机器也可以通过服务器的IP地址来访问。

Web服务器模块,有如下三种:

  • BaseHTTPServer

    提供基本的Web服务和处理器类,分别是HTTPServer和BaseHTTPRequestHandler。

  • SimpleHTTPServer

    包含执行GET和HEAD请求的SimpleHTTPRequestHandler类。

  • CGIHTTPServer

    包含处理POST请求和执行CGIHTTPRequestHandler类。

**

用python编写一个简单的web服务器,如下:

**

# coding=utf-8

"""
@version: ??
@author: AA-ldc
@file: myhttpd.py
@time: 2017/3/23 14:12
@function:编写一个简单的web服务器
"""
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer


class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            f = open(self.path[1:], 'r')
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        except IOError:
            self.send_error(404, 'File Not Found:%s' % self.path)


def main():
    try:
        server = HTTPServer(('', 8088), MyHandler)
        print 'Welcome'
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()


if __name__ == '__main__':
    main()

然后启动服务器:

E:\study\python脚本\Python_Tool>python myhttpd.py
Welcome

启动完服务器,就可以在浏览器访问,例如:http://localhost:8088/index.html

其工作原理可参考:http://python.jobbole.com/81524/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值