Mar*_*ian 13 python simplehttpserver webdev.webserver
我喜欢使用Python的SimpleHTTPServer来本地开发各种Web应用程序,这些应用程序需要通过Ajax调用等来加载资源.
当我在URL中使用查询字符串时,服务器总是重定向到附加了斜杠的同一URL.
例如,/folder/?id=1重定向到/folder/?id=1/使用HTTP 301响应.
我只是使用启动服务器python -m SimpleHTTPServer.
知道如何摆脱重定向行为吗?这是Python 2.7.2.
为了确保查询参数保持应有的状态,正确的方法是确保直接对文件名发出请求,而不是让SimpleHTTPServer重定向到您的文件名。index.html
例如http://localhost:8000/?param1=1,执行重定向 (301) 并更改http://localhost:8000/?param=1/与查询参数混淆的 url。
但是http://localhost:8000/index.html?param1=1(使索引文件显式)加载正确。
因此,只要不SimpleHTTPServer进行 url 重定向就可以解决问题。
好的。在 Morten 的帮助下,我想出了这个,这似乎就是我所需要的:只需忽略查询字符串(如果存在)并提供静态文件。
import SimpleHTTPServer
import SocketServer
PORT = 8000
class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def __init__(self, req, client_addr, server):
SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, req, client_addr, server)
def do_GET(self):
# cut off a query string
if '?' in self.path:
self.path = self.path.split('?')[0]
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
class MyTCPServer(SocketServer.ThreadingTCPServer):
allow_reuse_address = True
if __name__ == '__main__':
httpd = MyTCPServer(('localhost', PORT), CustomHandler)
httpd.allow_reuse_address = True
print "Serving at port", PORT
httpd.serve_forever()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4963 次 |
| 最近记录: |