首页 > 解决方案 > heroku 网络组装。运行python服务器

问题描述

我开发了一个 webassembly 应用程序。

我有一个 index.html:

<section id="app"></section>

<script src='/pkg/package.js'></script>

<script>
    const { render } = wasm_bindgen;
    function run() {
        render();
    }
    wasm_bindgen('/pkg/package_bg.wasm')
        .then(run)
        .catch(console.error);
</script>

我通过 python 脚本(serve.py)运行服务器:

import http.server
import os
import socketserver
import urllib

PORT = 8000


class Handler(http.server.SimpleHTTPRequestHandler):
    # Allow SPA routing by redirecting subpaths.
    def do_GET(self):
        urlparts = urllib.parse.urlparse(self.path)
        request_file_path = urlparts.path.strip('/')
        if not os.path.exists(request_file_path):
            self.path = '/'

        return http.server.SimpleHTTPRequestHandler.do_GET(self)


handler = Handler
# Add support for the WASM mime type.
handler.extensions_map.update({
    '.wasm': 'application/wasm',
})

socketserver.TCPServer.allow_reuse_address = True
with socketserver.TCPServer(("", PORT), handler) as httpd:
    httpd.allow_reuse_address = True
    print("Serving at port", PORT)
    httpd.serve_forever()

它在本地成功运行

我的档案:

web: python serve.py

requirements.txt 是空的。

现在,我想将它部署到 Heroku。

我的步骤:

  1. heroku 创建

  2. heroku 配置:设置端口 = 8000

  3. heroku buildpacks: 设置 heroku/python

  4. git push heroku 大师

应用程序构建成功:

2019-02-25T21:47:08.000000+00:00 app[api]: Build succeeded
2019-02-25T21:47:10.931203+00:00 heroku[web.1]: Starting process with command `python serve.py`
2019-02-25T21:47:12.753933+00:00 app[web.1]: Serving at port 8000

但是当我尝试打开网站时,我得到了错误:

2019-02-25T21:47:42.820665+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2019-02-25T21:47:42.820665+00:00 heroku[web.1]: Stopping process with SIGKILL
2019-02-25T21:47:42.916377+00:00 heroku[web.1]: Process exited with status 137
2019-02-25T21:48:11.109110+00:00 heroku[web.1]: State changed from starting to crashed
2019-02-25T21:48:11.017426+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2019-02-25T21:48:11.017426+00:00 heroku[web.1]: Stopping process with SIGKILL
2019-02-25T21:48:11.096343+00:00 heroku[web.1]: Process exited with status 137
2019-02-25T21:48:13.055253+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=whispering-savannah-32017.herokuapp.com request_id=6f484e71-69fc-462e-bd80-6ad9015c8570 fwd="109.110.75.176" dyno= connect= service= status=503 bytes= protocol=https

我做错了什么?

标签: pythonherokuwebassembly

解决方案


绑定到 $PORT 的要点是 Heroku 动态决定使用哪个端口。您不应该尝试将其设置为配置变量,但更重要的是,您应该使用它从脚本添加的 end l 环境中获取值。所以更换

PORT = 8000

PORT = os.environ["PORT"]

并删除config:set PORT呼叫。


推荐阅读