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 twisted?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With