Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Pyramid how can I redirect from http to https?

Tags:

python

pyramid

If you don't have access to the webserver, and the only way you have is to intercept the request and then do a redirect from http to https, what is the best approach to redirect?

I tried looking at subscribers using NewRequest. I did something like so:

@subscriber(NewRequest)
def modify_protocol(event):
    if re.search('some string', event.request.host_url):
        event.request.scheme = 'https'

However, this didn't do what I expected. The page is still being rendered. Any ideas would be appreciated.

Thanks in advance.

like image 204
ericg Avatar asked Aug 02 '26 13:08

ericg


1 Answers

Inside a view:

if req.scheme == "http":
        return HTTPFound("https://" + req.host + req.path_qs)

Using an event listener:

@subscriber(NewRequest)
def redirect(event):
    if event.request.scheme == "http":
        raise HTTPFound("https://" + event.request.host + event.request.path_qs)

I looked into approaches using send and get_response, but couldn't find much.

like image 182
imsky Avatar answered Aug 07 '26 13:08

imsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!