redirect http to https in twisted
I'm running a django app using twisted. I moved now from http to https. How can I add redirects from http to https in twist开发者_如何学JAVAed?
To redirect from any given path on HTTP to the same path on the HTTPS (based on Jean-Paul's suggestions in response to my comment):
from twisted.python import urlpath
from twisted.web import resource, util
class RedirectToScheme(resource.Resource):
"""
I redirect to the same path at a given URL scheme
@param newScheme: scheme to redirect to (e.g. https)
"""
isLeaf = 0
def __init__(self, newScheme):
resource.Resource.__init__(self)
self.newScheme = newScheme
def render(self, request):
newURLPath = request.URLPath()
# TODO Double check that == gives the correct behaviour here
if newURLPath.scheme == self.newScheme:
raise ValueError("Redirect loop: we're trying to redirect to the same URL scheme in the request")
newURLPath.scheme = self.newScheme
return util.redirectTo(newURLPath, request)
def getChild(self, name, request):
return self
Then you can use RedirectToScheme("https")
, in place of your Site()
for the HTTP site that you want to redirect from.
Note: If the HTTP that you want to redirect from is on a non-standard port, you will probably have a :<port>
part in the the URLRequest that you'll also need to rewrite.
An easy way to generate redirects in Twisted Web is is with the Redirect resource. Instantiate it with a URL and put it into your resource hierarchy. If it is rendered, it will return a redirect response to that URL:
from twisted.web.util import Redirect
from twisted.web.resource import Resource
from twisted.web.server import Site
from twisted.internet import reactor
root = Resource()
root.putChild("foo", Redirect("https://stackoverflow.com/"))
reactor.listenTCP(8080, Site(root))
reactor.run()
This will run a server which responds to a request for http://localhost:8080/ with a redirect to https://stackoverflow.com/.
If you're running Django in the WSGI container hosted on an HTTPS server, then you might have code that looks something like this:
from twisted.internet import reactor
from twisted.web.wsgi import WSGIResource
from twisted.web.server import Site
from django import some_wsgi_application_object # Not exactly
root = WSGIResource(reactor, reactor.getThreadPool(), some_wsgi_application_object)
reactor.listenSSL(8443, Site(root), contextFactory)
reactor.run()
You can run an additional HTTP server which generates the redirects you want by just adding some of the code from the first example to this second example:
from twisted.internet import reactor
from twisted.web.wsgi import WSGIResource
from twisted.web.util import Redirect
from twisted.web.server import Site
from django import some_wsgi_application_object # Not exactly
root = WSGIResource(reactor, reactor.getThreadPool(), some_wsgi_application_object)
reactor.listenSSL(8443, Site(root), contextFactory)
old = Redirect("https://localhost:8443/")
reactor.listenTCP(8080, Site(old))
reactor.run()
精彩评论