How to use WSGI to reroute a user from http to https

筅森魡賤 提交于 2019-11-30 14:02:06

Set the URLs in app.yaml, rather than in code. See https://developers.google.com/appengine/docs/python/config/appconfig#Secure_URLs

For example:

handlers:

- url: /foo/.*
  script: accounts.py
  secure: always

This will redirect HTTP to HTTPS.

This is the working code I used in testing for this question.

Note: The development Web Server (as of this writing v1.6.5) doesn't support https so your WSGI routes will need the schemes removed to work in the development environment. You can add them back before deployment or create an variable to set the scheme that checks the environment as I did below.

You can get App Engine Python to reroute the request by defining app.yaml as:
app.yaml

application: cgi-vs-wsgi
version: 1
runtime: python27
api_version: 1
threadsafe: yes

libraries:
- name: webapp2
  version: latest

handlers:

- url: /profile
  script: main.app
  secure: always

- url: /login
  script: main.app
  secure: always

- url: /.*
  script: main.app

Then in main.py you can declare your WSGI Handlers as normal like:

main.py

import webapp2
import os

# Models
from models.Shout import Shout

# Controllers
from controllers.HomeHandler import HomeHandler
from controllers.LoginHandler import LoginHandler
from controllers.ProfileHandler import ProfileHandler

if os.environ['SERVER_SOFTWARE'].startswith('Development'):
    app_scheme = 'http'
else:
    app_scheme = 'https'

app = webapp.WSGIApplication([
    webapp2.Route(r'/login', LoginHandler, name='login', schemes=[app_scheme]),
    webapp2.Route(r'/profile', ProfileHandler, name='profile', schemes=[app_scheme]),
    webapp2.Route(r'/', HomeHandler)
], debug=True)

I have uploaded the code for this app to my AE-BaseApp GitHub please feel free to download and use this in your applications. The code is licensed Apache License 2.0.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!