Redirect http to https in twisted

I am running a django application using twisted. I have now moved from http to https. How to add redirects from http to https in twisted?

+3
source share
2 answers

An easy way to create a redirect on Twisted Web is to use a Redirect resource. Create it using the URL and put it in your resource hierarchy. If it displays, it will return a redirect response to this 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("http://qaru.site/"))

reactor.listenTCP(8080, Site(root))
reactor.run()

This will start the server, which will respond to the request http: // localhost: 8080 / redirected to /fooobar.com / ... .

Django WSGI, HTTPS, , :

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()

HTTP-, , :

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()
+3

HTTP HTTPS ( - ):

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()
        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

RedirectToScheme("https") Site() HTTP-, .

. HTTP, , , , , :<port> URLRequest, .

+4

All Articles