问题描述
我使用 SimpleHTTPServer
测试我正在处理的一些网页。它工作伟大,但我需要做一些跨域请求。这需要在网页允许访问的域中设置一个 Access-Control-Allow-Origin
标题。
I'm using SimpleHTTPServer
to test some webpages I'm working on. It works great, however I need to do some cross-domain requests. That requires setting a Access-Control-Allow-Origin
header with the domains the page is allowed to access.
有一个简单的方法来设置一个头与SimpleHTTPServer和服务原始内容?
Is there an easy way to set a header with SimpleHTTPServer and serve the original content? The header would be the same on each request.
推荐答案
这是一个黑客,因为它改变了 end_headers()
行为,但我认为它比复制和粘贴整个 SimpleHTTPServer.py
文件稍微好一些。
This is a bit of a hack because it changes end_headers()
behavior, but I think it's slightly better than copying and pasting the entire SimpleHTTPServer.py
file.
我的方法在子类中覆盖 end_headers()
,并且调用 send_my_headers()
然后调用超类的 end_headers()
。
My approach overrides end_headers()
in a subclass and in it calls send_my_headers()
followed by calling the superclass's end_headers()
.
这不是1 - 2行,主要是样板。
It's not 1 - 2 lines either, less than 20 though; mostly boilerplate.
#!/usr/bin/env python
import SimpleHTTPServer
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Access-Control-Allow-Origin", "*")
if __name__ == '__main__':
SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
这篇关于我可以设置一个标题与python的SimpleHTTPServer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!