Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

ember.js - Python SimpleHTTPServer

Is there a way to make Python SimpleHTTPServer supports mod_rewrite?

I'm trying things with Ember.js with leveraging History API as the location API, and to make it work, I have to :

1) add some vhosts config in WAMP (not simple), or
2) run python -m simpleHTTPServer (very simple)

So when I opened it in the browser, localhost:3000 and clicked around the navigation (about and users for example), it worked well. The URLs are changed by Ember.js to localhost:3000/about and localhost:3000/users respectively.

But when I tried to open localhost:3000/about directly in new tab, the python web server simply returns 404.

I had my .htaccess redirecting everything to index.html, but I suspect python simple web server doesn't really read the htaccess file (am I right on this?)

I've tried downloading PHP 5.4.12 and run the built in web server, the url and htaccess mod_rewrite works well. But I'm still reluctant to upgrade from stable 5.3 to (probably still unstable enough) 5.4.12, so if there's a way to support mod_rewrite in python simple web server, that would be preferrable.

Thanks for the answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By modifying pd40's answer, I came up with this which doesn't redirect, it does your traditional "send index.html instead of 404". Not at all optimized, but it works for testing and development which is all I needed.

import SimpleHTTPServer, SocketServer
import urlparse, os

PORT = 3456

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
   def do_GET(self):

       # Parse query data to find out what was requested
       parsedParams = urlparse.urlparse(self.path)

       # See if the file requested exists
       if os.access('.' + os.sep + parsedParams.path, os.R_OK):
          # File exists, serve it up
          SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self);
       else:
          # send index.hmtl
          self.send_response(200)
          self.send_header('Content-Type', 'text/html')
          self.end_headers()
          with open('index.html', 'r') as fin:
            self.copyfile(fin, self.wfile)

Handler = MyHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...