Deploying Node.js app that uses python-shell to He

2019-12-16 17:49发布

问题:

I have a node.js application that deploys to heroku and runs well (has a simple Procfile that says web: npm start.

I have both the node.js and Python buildpacks set.

I have the PYTHONPATH config variable set to /usr/bin/python.

I have the requirements.txt in my app home directory that specifies the stuff I need (I even included the latest version of gunicorn).

However, when it comes time to invoke the python shell, this is what I get:

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

Basically, then the rest of my app fails, since I need results to be defined.

Why is this happening? Seems to work fine on my computer when I use my local paths.

This is the part of the code that invokes the 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]));
    });

});

回答1:

You need to tell heroku that you need to use python in your project.

  1. First, add the buildpacks for node js & python.
    heroku buildpacks:add --index 1 heroku/nodejs
    heroku buildpacks:add --index 2 heroku/python
    
  2. Next, edit your Procfile to
    pipinstall: pip install -r requirements.txt
    web: npm start
    
  3. Now push to heroku.