Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does SimpleHTTPServer redirect to ?querystring/ when I request ?querystring?

I like to use Python's SimpleHTTPServer for local development of all kinds of web applications which require loading resources via Ajax calls etc.

When I use query strings in my URLs, the server always redirects to the same URL with a slash appended.

For example /folder/?id=1 redirects to /folder/?id=1/ using a HTTP 301 response.

I simply start the server using python -m SimpleHTTPServer.

Any idea how I could get rid of the redirecting behaviour? This is Python 2.7.2.

like image 920
Marian Avatar asked Oct 18 '12 11:10

Marian


2 Answers

The right way to do this, to ensure that the query parameters remain as they should, is to make sure you do a request to the filename directly instead of letting SimpleHTTPServer redirect to your index.html

For example http://localhost:8000/?param1=1 does a redirect (301) and changes the url to http://localhost:8000/?param=1/ which messes with the query parameter.

However http://localhost:8000/index.html?param1=1 (making the index file explicit) loads correctly.

So just not letting SimpleHTTPServer do a url redirection solves the problem.

like image 57
Pratik Mandrekar Avatar answered Sep 25 '22 01:09

Pratik Mandrekar


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()
like image 42
Marian Avatar answered Sep 21 '22 01:09

Marian