原型设计:带有 URL 路由的最简单 HTTP 服务器(与 Backbone.Router 一起使用)?

问题描述 投票:0回答:3

我们正在开发 Backbone.js 应用程序,事实上我们可以通过输入

python -m SimpleHTTPServer
来启动 HTTP 服务器,这真是太棒了。

我们希望能够将任何 URL(例如

localhost:8000/path/to/something
)路由到我们的
index.html
,以便我们可以使用 HTML5
Backbone.Router
测试
pushState

实现这一目标最轻松的方法是什么? (为了快速原型制作的目的)

backbone.js prototyping httpserver simplehttpserver backbone-routing
3个回答
3
投票

只需使用

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()

1
投票
  1. 下载并安装CherryPy

  2. 创建以下 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()))
    
  3. 奔跑
    python <path\to\always_index.py>
  4. 将浏览器指向
    http://localhost:8080
    ,无论您请求什么网址,您总是会得到相同的内容。

0
投票

这是一个使用 python3 简单 HTTP 服务器和 Linux 的完整解决方案:

  1. 创建新文件
    spa-server
    sudo nano /usr/local/bin/spa-server
    
  2. 粘贴以下内容:
    #!/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)
    
  3. 使文件可运行:
    sudo chmod +x /usr/local/bin/spa-server
    
  4. 运行服务器
    spa-server
    # or
    spa-server 8080
    # or
    spa-server localhost:8080
    

如果静态文件不存在,服务器将尝试响应

index.html
index.htm

© www.soinside.com 2019 - 2024. All rights reserved.