问题描述
我喜欢使用Python的SimpleHTTPServer进行各种Web应用程序的本地开发,这些Web应用程序需要通过Ajax调用等来加载资源.
I like to use Python's SimpleHTTPServer for local development of all kinds of web applications which require loading resources via Ajax calls etc.
当我在URL中使用查询字符串时,服务器始终会重定向到相同的URL,并附加一个斜杠.
When I use query strings in my URLs, the server always redirects to the same URL with a slash appended.
例如,/folder/?id=1
使用HTTP 301响应重定向到/folder/?id=1/
.
For example /folder/?id=1
redirects to /folder/?id=1/
using a HTTP 301 response.
我只是使用python -m SimpleHTTPServer
启动服务器.
I simply start the server using python -m SimpleHTTPServer
.
有什么想法可以摆脱重定向行为吗?这是Python 2.7.2.
Any idea how I could get rid of the redirecting behaviour? This is Python 2.7.2.
推荐答案
好的.在Morten的帮助下,我想出了这一切,这似乎就是我所需要的:只需忽略查询字符串(如果存在)并提供静态文件即可.
Okay. With the help of Morten I've come up with this, which seems to be all I need: Simply ignoring the query strings if they are there and serving the static files.
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()
这篇关于为什么当我请求?querystring时,SimpleHTTPServer重定向到?querystring/?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!