Running Tornado in apache

2019-06-02 09:16发布

问题:

My end goal is to implement a WebSocket server using python.

I'm accomplishing this by importing tornado in my python scripts. I've also installed mod_wsgi in apache, and their script outputs Hello World!, so WSGI seems to be working fine. Tornado is also working fine as far as I can tell.

The issue comes when I use tornado's wsgi "Hello, world" script:

import tornado.web
import tornado.wsgi
import wsgiref.simple_server

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

if __name__ == "__main__":
    application = tornado.wsgi.WSGIApplication([
        (r"/", MainHandler),
    ])
    server = wsgiref.simple_server.make_server('', 8888, application)
    server.serve_forever()

First, I get a 500 error and the log tells me WSGI can't find 'application'.

So I remove if __name__ == "__main__", and the page loads infinitely.

I assume this is because of server.serve_forever() so I removed it in an attempt to see Hello, world

But now I just get 404: Not Found. It's not my apache 404 page, and I know that the server can find my main .wsgi file...

回答1:

You can't use websockets with Tornado's WSGIApplication. To use Tornado's websocket support you have to use Tornado's HTTPServer, not apache.



回答2:

The WSGIApplication handlers are relative to the webserver root. If your application url is /myapp, your 'application' must look like this:

application = tornado.wsgi.WSGIApplication([
    (r"/myapp", MainHandler),
    (r"/myapp/login/etc", LoginEtcHandler),
])

Oh, and it seems like the documentation is shit (as usual) and __name__ will look something like this when running under apache: _mod_wsgi_8a447ce1677c71c08069303864e1283e.


So! a correct "Hello World" python script will look like this:

/var/www/wsgi-scripts/myapp.wsgi:

import tornado.web
import tornado.wsgi
import wsgiref.simple_server

class MainHandler(tornado.web.RequestHandler):
    def get(self):
         self.write('Hello World')

application = tornado.wsgi.WSGIApplication([
    (r"/myapp", MainHandler),
])

And in the apache config (not .htaccess):

WSGIScriptAlias /myapp /var/www/wsgi-scripts/myapp.wsgi



回答3:

To use tornado in apache,add a mod-wsgi plugin to apache.

apt-get install libapache2-mod-wsgi

Write a tornado wsgi server with .wsgi NOTE:Dont use__name__

Configure the apache.conf to run your server.To configure use this mod-wsgi guide