Python requests send certificate as string
Vasili's answer is technically correct, though per se it doesn't answer your question. The keyfile, truly, must be unencrypted to begin with.
I myself have just resolved a situation like yours. You were on the right path; all you had to do was
1. Pass delete=False
to NamedTemporaryFile()
, so the file wouldn't be deleted after calling close()
2. close()
the tempfile before using it, so it would be saved
Note that this is a very unsafe thing to do. delete=False
, as I understand, causes the file to stay on disk even after deleting the reference to it. So, to delete the file, you should manually call os.unlink(tmpfile.name)
.
Doing this with certificates is a huge security risk: you must ensure that the string with the certificate is secured and hidden and nobody has access to the server.
Nevertheless, it is quite a useful practice in case of, for example, managing your app both on a Heroku server as a test environment and in a Docker image built in the cloud, where COPY
directives are not an option. It is also definitely better than storing the file in your git repository :D
This is an old question, but since I ended up here and the question wasn't answered I figure I'll point to the solution I came up with for a similar question that can be used to solve the OP's problem.
This can be done by monkey patching requests
using this technique.
As per the requests
documentation:
The private key to your local certificate must be unencrypted. Currently, Requests does not support using encrypted keys.
You can [also] specify a local cert to use as client side certificate, as a single file (containing the private key and the certificate) or as a tuple of both file's path:
requests.get('https://kennethreitz.com', cert=('/path/client.cert', '/path/client.key'))
You must include the path for both public and private key... or you can include the path to a single file that contains both.