我们正在开发 Backbone.js 应用程序,事实上我们可以通过输入
python -m SimpleHTTPServer
来启动 HTTP 服务器,这真是太棒了。
我们希望能够将任何 URL(例如
localhost:8000/path/to/something
)路由到我们的 index.html
,以便我们可以使用 HTML5 Backbone.Router
测试 pushState
。
实现这一目标最轻松的方法是什么? (为了快速原型制作的目的)
只需使用
BaseHTTPServer
中内置的Python功能
import BaseHTTPServer
class Handler( BaseHTTPServer.BaseHTTPRequestHandler ):
def do_GET( self ):
self.send_response(200)
self.send_header( 'Content-type', 'text/html' )
self.end_headers()
self.wfile.write( open('index.html').read() )
httpd = BaseHTTPServer.HTTPServer( ('127.0.0.1', 8000), Handler )
httpd.serve_forever()
下载并安装CherryPy
创建以下 python 脚本(将其称为
always_index.py
或类似名称),并将“c:\index.html”替换为您要使用的实际文件的路径
import cherrypy
class Root:
def __init__(self, content):
self.content = content
def default(self, *args):
return self.content
default.exposed = True
cherrypy.quickstart(Root(open('c:\index.html', 'r').read()))
python <path\to\always_index.py>
http://localhost:8080
,无论您请求什么网址,您总是会得到相同的内容。这是一个使用 python3 简单 HTTP 服务器和 Linux 的完整解决方案:
spa-server
:
sudo nano /usr/local/bin/spa-server
#!/usr/bin/env python
import os
import sys
from urllib.parse import urlparse
from http.server import SimpleHTTPRequestHandler
from http.server import HTTPServer
class Handler(SimpleHTTPRequestHandler):
def do_GET(self):
url = urlparse(self.path)
request_file_path = url.path.strip('/')
if not os.path.exists(request_file_path):
if os.path.exists('index.html'):
self.path = 'index.html'
elif os.path.exists('index.htm'):
self.path = 'index.htm'
else:
print(f'Not found: {request_file_path}')
return SimpleHTTPRequestHandler.do_GET(self)
try:
param = sys.argv[1]
except IndexError:
param = None
host = '0.0.0.0'
if param is None:
port = 8000
else:
if ':' in param:
host = param.split(':')[0]
port = int(param.split(':')[1])
else:
port = int(param)
httpd = HTTPServer((host, port), Handler)
print(f'Serving HTTP on {host}:{port}')
print(f'Looking for static assets in {os.getcwd()}')
try:
httpd.serve_forever()
except KeyboardInterrupt:
print('Bye bye')
sys.exit(0)
sudo chmod +x /usr/local/bin/spa-server
spa-server
# or
spa-server 8080
# or
spa-server localhost:8080
如果静态文件不存在,服务器将尝试响应
index.html
或 index.htm