3

In the flask doco the following description is shown of deploying a flask app under twistd.

twistd web --wsgi myproject.app

I have a foo.py which looks like this

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)

So I expected to be able to run that under twistd like this

twistd web --wsgi foo.app

but twistd doesn't like that (just spits out the help text).

What am I doing wrong ?

BTW in case it matters I'm running this in a virtualenv (in which I have installed both flask and twisted) and the current directory when I issue the twistd command contains foo.py .


EDIT: The version of twistd I am using is 18.7.0

I had failed to notice (until prompted to by Peter Gibson's comment ) that after the help text appears the message "No such WSGI application: 'foo.app'" appears.

glaucon
  • 8,112
  • 9
  • 41
  • 63

1 Answers1

6

You need to add the current directory to the PYTHONPATH environment variable. Try

PYTHONPATH=. twistd web --wsgi foo.app

Or on Windows (untested)

set PYTHONPATH=.
twistd web --wsgi foo.app
Peter Gibson
  • 19,086
  • 7
  • 60
  • 64
  • Thanks. I've never seen a bash command quite like that before - I should just use it exactly as shown here ? – glaucon Aug 24 '18 at 00:46
  • That syntax modifies PYTHONPATH for the current command only. Alternatively you could `export PYTHONPATH=$PYTHONPATH:.` which will persist for that session, and also appends the current directory `.` to PYTHONPATH instead of overwriting it (in case you have other PYTHONPATH customisations in your .bashrc say) – Peter Gibson Aug 24 '18 at 00:51
  • That's excellent thanks. I never knew you could do that thing with modifying PYTHONPATH for that command only. Thanks for your help it is working now. – glaucon Aug 24 '18 at 00:53
  • Your answer is not os-agnostic. So it does not work in windows. It would help to see a way to resolve the OP from within a python program in a way that is agnostic with respect to os. – CodeMed Jan 24 '23 at 23:56
  • @CodeMed thanks I've updated with an example for Windows, let me know if it works for you – Peter Gibson Jan 26 '23 at 10:45
  • 1
    Thank you and +1. We actually solved it in an os-agnostic way yesterday by using python. We set the environment variable with `os.environ['PYTHONPATH'] = '.'` . And then we ran the `twistd web --wsgi foo.app` using python's subprocess module. The python approach does not require you to write separate code for every operating system. – CodeMed Jan 26 '23 at 23:52