Python http服务器示例代码

Python http服务器示例代码:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 30 19:29:13 2018

@author: einsn
"""

from http.server import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            f = open(self.path[1:], 'rb')
            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 do_POST(self):
        print("get post:")
        print(self.path)

def main():
    try:
        s = HTTPServer(('', 8000), MyHandler)
        print('Welcome to the machine...', end='')
        print('Press CTRL+C once or twice to quit')
        s.serve_forever()
    except KeyboardInterrupt:
        print('^C received, shutting down server')
        s.socket.close()

if __name__ == '__main__':
    main()

打开浏览器,访问 http://localhost:8000, 或者使用curl 获取页面。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值