Serving Flask app with waitress on windows using SSL public/private key - python

How do I run my Flask app which uses SSL keys using waitress. The SSL context is specified in my Flask's run() as in
app.run(ssl_context=('cert.pem', 'key.pem'))
But app.run() is not used when using waitress as in the code below. So, where do I specify the keys? Thanks for the help.
from flask import Flask, request
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
# app.run(ssl_context=('../cert.pem', '../key.pem'))
from waitress import serve
serve(app, host="0.0.0.0", port=5000)

At the current version (1.4.3), Waitress does not natively support TLS.
See TLS support in https://github.com/Pylons/waitress/blob/36240c88b1c292d293de25fecaae1f1d0ad9cc22/docs/reverse-proxy.rst
You either need a reverse proxy in front to handle the tls/ssl part, or use another WSGI server (CherryPy, Tornado...).

Related

Flask app not running on localhost, no error

Similar code to this was working fine, then suddenly not and I have no idea why. Hoping somebody can help. I have the following:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def home():
return "Hi"
if __name__ == "__main__":
app.run(debug=True)
When I run that, the output is the following:
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
There is no error, but also no "Running on http://localhost:5000/" and nothing loads at that URL ("This site can't be reached") etc.
I have tried specifying the host many ways and many other things. Still get the same. Previously it was working fine, said "Running on http://localhost:5000/," was loading fine in my browser, etc.
What am I missing here?
You can explicitly set the host and the port on your script:
# ...
if __name__ == "__main__":
app.run(host='localhost', port=5000, debug=True) # or setting host to '0.0.0.0'

FLASK: curl: (7) Failed to connect to 127.0.0.1 port 5500: Connection refused

I am trying to transition from making Rshiny apps to flask-react apps. Its definitely a steep learning curve so far!
I am sort of following a few tutorials e.g (https://dev.to/arnu515/build-a-fullstack-twitter-clone-using-flask-and-react-1j72) to try and get some basic functionality down .
However some reason curl can't seem to interact with my app. I've tried putting the urls with and without quotes but get the same response. Also I tried the default 5000 port as well. I am running the app in windows:
C:\Users\Marc\flaskTest\backend>curl "http://127.0.0.1:5500"
curl: (7) Failed to connect to 127.0.0.1 port 5500: Connection refused
app.py code
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
#app.route('/')
def index():
return "hello"
#app.route('/message', methods=["GET"])
def message():
message ="my message"
return jsonify({"message": message})
if __name__ == "__main__":
app.run(debug=True, port=5500)
You used jsonify in the view function but haven't imported it before, so there would be error when Flask app runs.
Actually you can just write code like return {"message": message}, it would do the same thing with jsonify does if you are using latest version of flask.
Try:
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, port=5500)
Also in windows cmd type ipconfig IPV4 address. Suppose your IPV4 address is 192.168.X.X, access the website as http://192.168.X.X:5500.
Read what it does: Externally Visible Server

How to serve Tornado with Django on waitress?

I have this tornado application wrapped with django function as WSGI app (using in windows)
from django.core.wsgi import get_wsgi_application
from django.conf import settings
from waitress import serve
settings.configure()
wsgi_app = tornado.wsgi.WSGIContainer(django.core.wsgi.WSGIHandler())
def tornado_app():
url = [(r"/models//predict", PHandler),
(r"/models//explain", EHandler),
('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app))]
return Application(url, db=ELASTIC_URL, debug=options.debug, autoreload=options.debug)
if __name__ == "__main__":
application = tornado_app()
http_server = HTTPServer(application)
http_server.listen(LISTEN_PORT)
IOLoop.current().start()
Not sure how to use waitress,
To serve using waitress I tried http_server = serve(application), server is starting, now sure is it correct, getting error when hitting the endpoint
waitress is a WSGI server; Tornado is not based on or compatible with WSGI. You cannot use waitress to serve the Tornado portions of your application.
To serve both Tornado and WSGI applications in one thread, you need to use Tornado's HTTPServer as you've done in the original example. For better scalability, I'd recommend splitting the Tornado and Django portions of your application into separate processes and putting a proxy like nginx or haproxy in front of them.

Docker and WSGI with a Python Pyramid app?

I am looking at two articles on how to Dockerize a Pyramid app. I am not that familiar with Python, but I am fairly certain with a Pyramid app you need to use WSGI.
This article uses WSGI:
https://medium.com/#greut/minimal-python-deployment-on-docker-with-uwsgi-bc5aa89b3d35
This one just runs the python executable directly:
https://runnable.com/docker/python/dockerize-your-pyramid-application
It seems unlikely to me that you can run python directly and not incorporate WSGI, can anyone provide an explanation for why the runnable.com article's docker solution would work?
Per the scripts in the second link:
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
~snip~
if __name__ == '__main__':
config = Configurator()
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app() # The wsgi server is configured here
server = make_server('0.0.0.0', 6543, app) # and here
This contains an explanation of why the wsgi server is built in the if __name__=="__main__" block

Flask-Python redirection to https The connection was reset

I am a new Flask user and i have a problem. I want to redirect all url from http to https but I am having this error:
The connection was reset
This is my Flask code:
#! /usr/bin/python
# -*- coding:utf-8 -*-
from flask import *
from OpenSSL import SSL
import psycopg2
import os
from datetime import timedelta
import sys
from flask_sslify import SSLify
reload(sys)
sys.setdefaultencoding('utf8')
db_conn = psycopg2.connect("dbname=billjobs host=192.168.42.96 port=50434 user=username password=password")
app = Flask(__name__)
db = db_conn.cursor()
app.permanent_session_lifetime = timedelta(seconds=900)
sslify = SSLify(app)
app.secret_key='\xatYK\x1ba\x1dz\xa6-D\x9d\x97\x83\xfa\xcf\xcbd\xfa\xfb\x1a|\x08\x1af'
context = ('ssl.crt','ssl.key')
#app.route('/')
def pre_log():
return render_template('index.html')
if __name__ == '__main__':
app.run(host="192.168.42.186", ssl_context=context, debug=False)
If I enter directly the address https://192.168.42.186:5000 it work but with http only its not
Thanks for helping me in advance
You cannot do this using ssl_context and Werkzung (default server of Flask) now. A functionality to allow this was proposed and rejected in 2014: auto http to https redirect; citing:
That requires running another HTTP server. Werkzeug is not capable of that and IMO it's out of scope. run_simple should only be used for development anyway.
So what's going on is your Flask application calls run_simple underneath, passing ssl_context and some other variables. SSLify has no impact on your routing as long as you use ssl_context, because sole presence of this variable makes Werkzung host only using https schema. To get redirection from http to https, you need either to set up another server, listening at http and redirecting to https or migrate to other, more advanced server which allows redirection easily.
I recommend to migrate to Apache or gunicorn. Flask provides comprehensive instructions on deployment: Deployment Options. Keep in mind that built-in server of Flask (Werkzung) is not suitable for production, as authors of Flask write:
While lightweight and easy to use, Flask’s built-in server is not
suitable for production as it doesn’t scale well and by default serves
only one request at a time.
Using Apache you could redirect all http requests using VirtualHost rule, listening at 80:
<VirtualHost *:80>
ServerName mysite.example.com
DocumentRoot /usr/local/apache2/htdocs
Redirect /secure https://mysite.example.com/secure
</VirtualHost>
See more on this on Redirect Request to SSL Apache wiki.

Categories

Resources