Django, requests and..

self signed certificates

Moving from ngrok to nginx proxy manager (upcoming article) put me in the situation where I needed to get requests to accept a self signed certificate to avoid the dreaded SSL: CERTIFICATE_VERIFY_FAILED

verify=False or verify=/path/to/ca.pem is not an option since only the development system is running behind layered firewalls with self signed certificates.

This proved to be quite straight forward.

Update your apps apps.py file

from django.apps import AppConfig
import requests
import certifi
from django.conf import settings

class MyAppConfig(AppConfig):
        name = yourapp

        def ready(self): -> None
            try:
                requests.get(settings.FILESTORE_URL)
            except requests.exceptions.SSLError as err:
                logger.info(
                    f"SSL Error on app init. Adding ca.pem to certificate store. {err}",
                )
                store = certifi.where()
                with open(store, "ab") as outfile:
                    with open("./certs/ca.pem", "rb") as infile:
                        outfile.write(infile.read())

This will ensure that if you need the ca.pem it will be added to the certifi ca store(if using podman/docker, remember to copy the ca.pem file into your container).

NOTE: On a side note - how to get the pem? If you have created, as you should, a local signing authority, create the pem by

$ cat ca.key > ca.pem
$ cat ca.crt >> ca.pem