5

I work on a Django based app, and I want to know if there's a way to know if my server uses http connections or https.

I know that using

import socket
if socket.gethostname().startswith('****'):

I can get the hostname, is it possible to do something like that so I can get to know if the hosting uses a ssl certificate?

PD: I'm a rookie here, so I'm asking to see if it's possible and, if it is, how should I do it. Thanks

Sascuash
  • 3,661
  • 10
  • 46
  • 65

3 Answers3

14

it's completely possible:

def some_request_function(request):
    if request.is_secure():
        #You are safe!
    else:
        #You are NOT safe!

More details: https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.HttpRequest.is_secure

math
  • 8,514
  • 10
  • 53
  • 61
Pedro Walter
  • 623
  • 4
  • 11
4

There simply is an is_secure() method on the request object, returning True if the connection is secure.

Depending on your specific server configuration you may also need to set SECURE_PROXY_SSL_HEADER in your settings.

Ludwik Trammer
  • 24,602
  • 6
  • 66
  • 90
3

django requests (HttpRequest) have is_secure method:

https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.is_secure

dm03514
  • 54,664
  • 18
  • 108
  • 145
  • 1
    Just a question. How would it be in settings.py? – Sascuash Feb 07 '14 at 16:50
  • 1
    it's not. By default it checks the server enviorn (`os.environ`) to see if 'https' is the scheme https://github.com/django/django/blob/master/django/http/request.py#L137, It looks like you can define what a secure header is by defining SECURE_PROXY_SSL_HEADER in your settings though. https://docs.djangoproject.com/en/1.4/ref/settings/#secure-proxy-ssl-header – dm03514 Feb 07 '14 at 17:11