90abyss 90abyss - 9 months ago 109
Python Question

How to setup nginx + tornado + flask?

These are my fully working tornado and flask files:

Tornado:

from flaskk import app
from tornado.wsgi import WSGIContainer
from tornado.ioloop import IOLoop
from tornado.web import FallbackHandler, RequestHandler, Application

class MainHandler(RequestHandler):
def get(self):
self.write("This message comes from Tornado ^_^")

tr = WSGIContainer(app)

application = Application([
(r"/tornado", MainHandler),
(r".*", FallbackHandler, dict(fallback=tr)),
])

if __name__ == '__main__':
application.listen(5052)
IOLoop.instance().start()


Flask:

from flask import Flask, jsonify
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class Report(Resource):
def get(self):
return 'hello from flask'

api.add_resource(Report, '/report')


Now I'm trying to setup nginx in front of tornado. My nginx config file is:

worker_processes 3;

error_log logs/error.;

events {
worker_connections 1024;
}

http {
# Enumerate all the Tornado servers here
upstream frontends {
server 127.0.0.1:5052;
}

include mime.types;
default_type application/octet-stream;

keepalive_timeout 65;

sendfile on;


server {
listen 5050;
server_name localhost;

location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_pass http://localhost:5050;
}
}
}


When I do a


localhost:5050/


then I get the nginx welcome page. But when I do


localhost:5050/report


then I get a 404. Tornado is running on port 5052. Why is nginx not calling tornado which thereby should get the result from flask?

Am I missing something here?

Answer Source

Firstly, you don't want to proxy to localhost:5050 because that is Nginx itself

You want to proxy to upstream frontends.

proxy_pass http://frontends;

Regarding your Flask issues, I've gotten this to work fine.

@app.route('/report')
def report():
    return 'hello from flask'

$ curl localhost:5052/report
hello from flask

When I added in Flask Restful, that still worked.


You said you see the index page of nginx, so it is running, you just need to correctly hook the other ports together.

The proxy_pass fix seemed to work for me.

$ curl localhost:5050/report
"hello from flask"
$ curl localhost:5050/tornado
This message comes from Tornado ^_^