Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have one Flask app listen on two different ports?

Tags:

python

flask

Is it possible to have a single flask app with routes on two different ports? My Flask app needs to listen for webhooks and due to some security biz it can't receive foreign POST requests on the default port. Is it possible to do something like this?

@app.route('/hook/<sourcename>', methods=["POST"], port=5051)
def handle_hook(sourcename):
  print 'asdf'
like image 911
Jed Estep Avatar asked Jul 15 '14 14:07

Jed Estep


People also ask

How can I access my Flask app from another network?

Run the myapp.py on a local server or laptop. Using a browser, let's point to http://localhost:3000 to connect to the flask web application. Right now the flask application can be accessed only by you because it runs on your laptop.

How do I run a Flask app with a different IP?

Another thing you can do is use the flask executable to start your server, you can use flask run --host=0.0. 0.0 to change the default IP which is 127.0. 0.1 and open it up to non local connections. So If we summarize then the outcome is you should use the app.

How does Flask handle multiple concurrent requests?

The server component that comes with Flask is really only meant for when you are developing your application; even though it can be configured to handle concurrent requests with app. run(threaded=True) (as of Flask 1.0 this is the default).


2 Answers

If you don't need any socket code inside C plugins, gevent could help, e.g. with

import gevent
from gevent.pywsgi import WSGIServer

app = Flask(__name__)

https_server = WSGIServer((HOST, HTTPS_PORT), app, keyfile=PRIVKEY, certfile=CERT)
https_server.start()

http_server = WSGIServer((HOST, HTTP_PORT), app)
http_server.start()

while True:
    gevent.sleep(60)
like image 145
Eier Kopp Avatar answered Nov 14 '22 21:11

Eier Kopp


A server by default only listens to a single port. Wouldn't it make more sense, since the additional port requires additional functionality, to implement a front-end server on the second port that proxies the POST request locally? There are many well-documented ways to do this such as this one

like image 21
holdenweb Avatar answered Nov 14 '22 21:11

holdenweb