I have a question about Python to use SSL two-way authentication, our development environment is Windows 10
We are currently using Git Bash curl for initial testing, and the sample code is as follows
curl -v --cacert CA.pem --cert server.crt --key server.key -X POST -H "Content-Type: application/json" -H "Authorization: Bearer <Token>" -d "{}" https://sample.com/api/Accounts
There was success in getting the data, but we used Python Requests and used the conversion site Convert curl commands (https://curlconverter.com/) to get like this
import requests
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <Token>',
}
cert = ('server.crt', 'server.key')
json_data = {}
response = requests.post('https://sample.com/api/Accounts', headers=headers, json=json_data, cert=cert, verify='CA.pem')
The result is an error
ProtocolError: ('Connection aborted.', ConnectionResetError(10054, '遠端主機已強制關閉一個現存的連線。', None, 10054, None))
I need a way to do the same thing in Python. Is there an alternative to cURL in Python?
CodePudding user response:
to be honest, I never had much success with certificates and requests for Python using windows. If I were you, I would use a subprocess and call Git Bash directly. This might not look that nice, but is easily portable, given that you have Git Bash installed (which is the default under windows I think). Here is a code snippet, that might help you:
import subprocess
p = subprocess.Popen(["C:\Program Files\Git\git-bash.exe","C:/Users/userName/Documents/dev/curl_get_data.sh"],
bufsize=-1,
executable=None,
stdin=None,
stdout=None,
stderr=None,
preexec_fn=None,
close_fds=True,
shell=False,
cwd="C:/Users/userName/Documents/dev",
)
In the shell script curl_get_data.sh you can use your normal curl syntax!