Redirect Flash Python to https. The connection was reset

I am a new Flask user and I have a problem. I want to redirect the entire url from http to https, but I have this error:

The connection was reset

This is my jar 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 works, but with http only it doesn’t

Thanks for helping me in advance

+5
source share
1 answer

You cannot do this using ssl_context and Werkzung (the default Flask server). Functionality allowing this was proposed and rejected in 2014: auto http to https redirect ; quoting:

This requires starting another HTTP server. Werkzeug is not capable of this, and IMO it goes beyond that. run_simple should be used only for development.

So what happens, your Flask application calls run_simple under it, passing ssl_context and some other variables. SSLify does not affect your routing as long as you use ssl_context , since the only presence of this variable makes Werkzung a host using only the https scheme. To get a redirect from http to https, you need to either configure another server, listen on HTTP and redirect to https, or transfer it to another, more advanced server, which redirects easily.

I recommend switching to Apache or gunicorn. Flask provides comprehensive deployment instructions: Deployment Options . Keep in mind that the Flask embedded server (Werkzung) is not suitable for production, as the Flask authors write:

While lightweight and easy to use, the Flocks built-in server is suitable for production, as it does not scale well and by default only serves one request at a time.

Using Apache, you can redirect all HTTP requests using the VirtualHost rule by listening to 80:

 <VirtualHost *:80> ServerName mysite.example.com DocumentRoot /usr/local/apache2/htdocs Redirect /secure https://mysite.example.com/secure </VirtualHost> 

For more information, see Redirect the request to SSL on the Apache Wiki.

+1
source

Source: https://habr.com/ru/post/1232484/


All Articles