从BaseHTTPRequestHandler调用redirect func

时间:2017-09-03 17:27:29

标签: python redirect basehttprequesthandler

我有一个从BaseHTTPRequestHandler扩展的类:

class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
    # send headers
    self.send_response(200)
    self.send_header('Content-type', 'text/html; charset=utf-8')
    self.end_headers()
    if re.findall(r'^/favicon.ico$', self.path) \
        or re.findall(r'^/public/.*$', self.path):
        pass
    else:
        run = Router(self.path)
        data = run.run_action()
        print(data)
        self.wfile.write(data.encode())

def do_POST(self):
    length = int(self.headers.get('Content-length', 0))
    data = self.rfile.read(length).decode()
    message = clean(parse_qs(data))
    self.send_response(200)
    self.send_header('Content-type', 'text/html; charset=utf-8')
    self.end_headers()
    if re.findall(r'^/favicon.ico$', self.path) \
            or re.findall(r'^/public/.*$', self.path):
        pass
    else:
        run = Router(self.path, message)
        data = run.run_action()
        self.wfile.write(data.encode())

def redirect(self, url):
    self.send_response(302)
    self.send_header('Location', url)
    self.end_headers()

我想为重定向用户创建功能。例如,提交POST后。如何在此课程外调用重定向功能?

P.S:我发现了分析输入数据的决定。我通过以下方式更改了代码:

class Handler(http.server.BaseHTTPRequestHandler):
def send_headers(self, status, content_type, value):
    self.send_response(status)
    self.send_header(content_type, value)
    self.end_headers()

def do_GET(self):
    if re.findall(r'^/favicon.ico$', self.path) \
            or re.findall(r'^/public/.*$', self.path):
        pass
    else:
        run = Router(self.path)

        data = run.run_action()
        uri = re.findall(r"'Location': '([\/a-z0-9-]+)'", data)
        if bool(uri):
            self.redirect(uri[0])
            run = Router(uri[0])
            data = run.run_action()
            self.wfile.write(data.encode())
        else:
            self.send_headers(200, 'Content-type',
                              'text/html; charset=utf-8')
            self.wfile.write(data.encode())

def do_POST(self):
    length = int(self.headers.get('Content-length', 0))
    data = self.rfile.read(length).decode()
    message = clean(parse_qs(data))
    self.send_headers(200, 'Content-type', 'text/html; charset=utf-8')

    if re.findall(r'^/favicon.ico$', self.path) \
            or re.findall(r'^/public/.*$', self.path):
        pass
    else:
        run = Router(self.path, message)
        data = run.run_action()
        self.wfile.write(data.encode())

def redirect(self, url):
    self.send_headers(302, 'Location', url)

重定向的功能如下:

def redirect(url):
   return "'Location': '{}'".format(url)

决定是有效的,但也许有人可以提供更好的方法?

我在python doc

中找到了
  

注意CGIHTTPRequestHandler类运行的CGI脚本无法执行重定向(HTTP代码302),因为在执行CGI脚本之前会发送代码200(后面的脚本输出)。这会抢占状态代码。

0 个答案:

没有答案