我正在尝试在 python 上运行服务器。我决定在有人打开链接(通过 GET)时生成一个令牌。因此,在 GET 方法中,我一直在尝试使用“Set-Cookie”,为此我必须弄乱标题。问题是当我这样做时,服务器的标题(或类似的东西)出现在我的 HTML 页面的最顶部。
这是我的代码:
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=DIRECTORY, **kwargs)
def do_GET(self):
print("Someone visited the page")
self.send_response(200)
self.send_header("Content-type", "text/html")
cookie = http.cookies.SimpleCookie()
token = binascii.hexlify(os.urandom(32)).decode()
TOKEN_LIST.append(token)
cookie['token'] = token
for morsel in cookie.values():
self.send_header("Set-Cookie", morsel.OutputString())
self.end_headers()
http.server.SimpleHTTPRequestHandler.do_GET(self)
当我打开页面时,我就在顶部
HTTP/1.0 200 OK Server: SimpleHTTP/0.6 Python/3.10.0 Date:.... Content-Length: 4943
(以及我遗漏的其他标题以防万一)
我想摆脱那些出现在我的 HTML 页面顶部的标题(它出现在页面的源代码上)。可能一种 hacky 方法是自己设置这些标题并将它们设置为空。但是,我没有尝试过,因为我确信必须有另一种方法。