前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 3.5 HTTP服务器端重

Python 3.5 HTTP服务器端重

作者头像
py3study
发布2020-01-09 15:51:17
4990
发布2020-01-09 15:51:17
举报
文章被收录于专栏:python3python3
代码语言:javascript
复制
#!/usr/bin/python3
import sys
import socketserver
import socket
import http.server
import threading
import io

# Use supplied port
if sys.argv[1:]: 
    port = int(sys.argv[1])
else:
    port = 8889
        
class RedirectTestHandler(http.server.SimpleHTTPRequestHandler):
    def send_html_content(self, html_content):
        length = len(html_content)
        self.send_header("Content-Type", "text/html")
        self.send_header("Content-Length", str(length))
        self.send_header("Connection", "close")
        self.send_header("Cache-control", "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform")
        self.send_header("Pragma", "no-cache")
        self.end_headers()
        f = io.BytesIO()
        f.write(html_content)
        f.seek(0)
        self.copyfile(f, self.wfile)
        
    def do_GET(self):
        print("[%s]path=%s" % (threading.current_thread(), self.path))
        if self.path[1:]=='':
            path_num = 0
        else:
            try:
                path_num = int(self.path[1:])
            except ValueError:
                http.server.SimpleHTTPRequestHandler.do_GET(self) #默认还是基类的实现
                return
        if path_num==20: #重定向最大次数限制
            self.send_response(200)
            self.send_html_content(b"<body>Redirect Test OK!</body>") # b前缀代表bytes对象,默认是str对象
        else:
            path_num += 1
            self.send_response(307, "Location Moved")
            self.send_header("Location", "/%d" % path_num) #FIXME:站内path重定向 和 重定向到外部网站 有什么不同?CORS安全检查?
            self.send_header("Connection", "close") #也许测试重定向不需要?
            self.send_header("Cache-control", "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform")
            self.send_header("Pragma", "no-cache")
            self.end_headers()
            
# 
# set up and run the server 
# 
bind_addr = ('',port) 
handler = RedirectTestHandler #CGIHTTPServer.CGIHTTPRequestHandler
httpd = socketserver.ThreadingTCPServer(bind_addr, handler)
sa = httpd.socket.getsockname()
print("Serving Redirect Test Server on", sa[0], "port", sa[1], "...")
httpd.serve_forever() 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档