Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python flask redirect to https from http

Tags:

python

ssl

flask

I have a website build using python3.4 and flask...I have generated my own self-signed certificate and I am currently testing my website through localhost.

I am using the python ssl module along with this flask extension: https://github.com/kennethreitz/flask-sslify

context = ('my-cert.pem', 'my-key.pem') app = Flask(__name__) sslify = SSLify(app)  ...  if __name__ == '__main__':     app.debug = False     app.run(     host="127.0.0.1",     port=int("5000"),     ssl_context=context ) 

This does not seem to be working however. I took a look in the sslify source code and this line does not seem to be working

def init_app(self, app):     """Configures the configured Flask app to enforce SSL."""     app.before_request(self.redirect_to_ssl)     app.after_request(self.set_hsts_header) 

Specifically the function call to redirect_to_ssl (I added my own print statement under the redirect_to_ssl function and my statement was never printed)

def redirect_to_ssl(self):     print("THIS IS WORKING")     """Redirect incoming requests to HTTPS."""     Should we redirect?     criteria = [         request.is_secure,         current_app.debug,         request.headers.get('X-Forwarded-Proto', 'http') == 'https'     ]      if not any(criteria) and not self.skip:         if request.url.startswith('http://'):             url = request.url.replace('http://', 'https://', 1)             code = 302             if self.permanent:                 code = 301             r = redirect(url, code=code)             return r 

I am pretty new to python. Any ideas?

like image 698
David Yuan Avatar asked Aug 26 '15 21:08

David Yuan


1 Answers

To me, it appears you're making it more complicated than it needs to be. Here is the code I use in my views.py script to force user to HTTPS connections:

@app.before_request def before_request():     if not request.is_secure:         url = request.url.replace('http://', 'https://', 1)         code = 301         return redirect(url, code=code) 
like image 196
Kelly Keller-Heikkila Avatar answered Sep 18 '22 15:09

Kelly Keller-Heikkila