首页 > 解决方案 > 将使用 python-shell 的 Node.js 应用程序部署到 Heroku

问题描述

我有一个 node.js 应用程序,它部署到 heroku 并且运行良好(有一个简单的 Procfile,上面写着web: npm start.

我同时设置了 node.js 和 Python buildpacks。

我将PYTHONPATH配置变量设置为/usr/bin/python.

requirements.txt在我的应用程序主目录中有指定我需要的东西(我什至包括了最新版本的gunicorn)。

但是,当需要调用 python shell 时,这就是我得到的:

2019-04-11T02:46:14.680872+00:00 app[web.1]: { Error: ImportError: No module named site
2019-04-11T02:46:14.680933+00:00 app[web.1]: 
2019-04-11T02:46:14.680937+00:00 app[web.1]:     at PythonShell.parseError (/app/node_modules/python-shell/index.js:254:21)
2019-04-11T02:46:14.680939+00:00 app[web.1]:     at terminateIfNeeded (/app/node_modules/python-shell/index.js:129:32)
2019-04-11T02:46:14.680941+00:00 app[web.1]:     at ChildProcess.<anonymous> (/app/node_modules/python-shell/index.js:121:13)
2019-04-11T02:46:14.680942+00:00 app[web.1]:     at ChildProcess.emit (events.js:189:13)
2019-04-11T02:46:14.680944+00:00 app[web.1]:     at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12)
2019-04-11T02:46:14.680945+00:00 app[web.1]:   executable: '/usr/bin/python',
2019-04-11T02:46:14.680947+00:00 app[web.1]:   options: [ '-u' ],
2019-04-11T02:46:14.680949+00:00 app[web.1]:   script: '/app/routes/resgraph.py',
2019-04-11T02:46:14.680950+00:00 app[web.1]:   args: [ '2', 'ribozyme', 'hatchet' ],
2019-04-11T02:46:14.680952+00:00 app[web.1]:   exitCode: 1 }
2019-04-11T02:46:14.681384+00:00 app[web.1]: results: undefined

基本上,我的应用程序的其余部分都会失败,因为我需要results被定义。

为什么会这样?当我使用本地路径时,似乎在我的计算机上工作正常。

这是调用 python shell 的代码部分:

/* returns graph information for a certain query. */
router.get('/', function(req, response, next) {

    // get the query string
    query_string = req.query.query;
    let options = {
      mode: 'text',
      pythonPath: process.env.PYTHONPATH,
      pythonOptions: ['-u'], // get print results in real-time
      scriptPath: '/app/routes',
      args: [req.query.depth].concat(query_string.split(' '))
    };

    PythonShell.run('/resgraph.py', options, function (err, results) {
      if (err) console.log(err);
      // results is an array consisting of messages collected during execution
      console.log('results: %j', results);
      response.json(JSON.parse(results[1]));
    });

});

标签: pythonnode.jsherokudeployment

解决方案


你需要告诉heroku你需要在你的项目中使用python。

  1. 首先,添加 node js & python 的 buildpacks。
    heroku buildpacks:add --index 1 heroku/nodejs
    heroku buildpacks:add --index 2 heroku/python
    
  2. 接下来,编辑您Procfile
    pipinstall: pip install -r requirements.txt
    web: npm start
    
  3. 现在推送到heroku。

推荐阅读