curl to python for post request - python

I would like to "translate" my curl request into python using request or urllib.
I try to post a file.
My curl request is :
curl -X POST -H "Content-Type: multipart/form-data" -H "Authorization: Bearer $1" -F "data=#$2;filename=$3" --cert certificateprivate.pem --cacert MyDigiCertSHA2.crt.pem <my_url>
I tried the code below ( doesn't work , response 400)
def upload_file(token,file_path):
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile='MyDigiCertSHA2.crt.pem')
ctx.load_cert_chain(certfile='certificateprivate.pem')
url = <my_url>
hdr = {"Content-Type": "multipart/form-data","Authorization":"Bearer "+token}
data = '{"filterList":[{}]}'
with open(file_path, 'rb') as f:
from urllib import request, parse
data = parse.urlencode( {'filename':file_path,"data": f.read()}).encode()
req = request.Request( url, data = data,headers=hdr)
resp = request.urlopen(req, context=ctx)
content = resp.read()
data = json.loads(content.decode('utf-8'))
print(data)

The curl command has "Content-Type: multipart/form-data", but your python code has "Content-Type": "application/json".

Related

Curl requests in python

I have a curl request like this:
curl -X POST http://mdom-n-plus-1.nonprod.appsight.us:8081/mesmerdom/v3/getByImageAndDom -F "data=$DATA" -F "dom=#$DOM" -F "image=#$IMG"
I am trying to convert it to python by using something like this:
import requests
import json
url = "http://mdom-n-plus-1.nonprod.appsight.us:8081/mesmerdom/v1/getByScreen"
payload = {"data": json.dumps({"screen":["screen-id", "57675"]}), dom:"abc", image:"xyz"}
req = requests.post(url, data=payload)
print (req.text)
but it is not working.

Connecting to oauth2 API - it works with curl, doesn't with requests.get (Python)

I've been trying to connect to an oauth2 API. I've managed to write a code that delivers a token, so the token is not a problem.
I've checked that with curl. The following works:
curl -X GET \
https://api.website.pl/sale/delivery-methods \
-H 'Authorization: Bearer eyJhbGciOiJSUzBmF1BWKBjk3GiA' \
-H 'accept: application/vnd.website.public.v1+json'
<- This returns the data I need.
However, I simply can't make it work in python.
headers = {}
headers['Authorization'] = 'Bearer eyJhbGciOiJSUzBmF1BWKBjk3GiA'
headers['Accept'] = 'application/vnd.website.public.v1+json'
get_url = 'https://api.website.pl/sale/delivery-methods'
requests.get(get_url, headers)
The response is <Response [406]>, incorrect data, which I'm interpreting as a signal I didn't pass all the relevant authorization headers.
Any ideas how to fix that?
try this:
headers = {}
headers['Authorization'] = 'Bearer eyJhbGciOiJSUzBmF1BWKBjk3GiA'
headers['Accept'] = 'application/vnd.website.public.v1+json'
get_url = 'https://api.website.pl/sale/delivery-methods'
response = requests.get(get_url, headers=headers)

How to write python code for the below curl request to send a post request and uploading an image as binary

curl --request POST -H "Content-Type: application/octet-stream" --data-binary "#/C:\\Users\\U6068366\\Downloads\\Koala.jpg" https://c6y09pww43.execute-api.us-east-1.amazonaws.com/p
--
App_Url = "https://p7a0km3l6k.execute-api.us-east-1.amazonaws.com/preprod/v1/images/trademark/metadata/providerPartition/{providerPartition}/providerPartitionId/{providerPartitionId}"
# f = open('C://Users//UX016491//PycharmProjects//DSSApi//data1.json')
# requests_json = json.loads(f.read())
files = {'media' : open('C:\\Users\\UX016491\\Desktop\\images\\image123.jpg','rb') }
response = requests.request("POST", App_Url, files = files, headers={"content-type": 'application/octet-stream'})
print(response)
if __name__ == '__main__':
test_createimage_data()
EDIT: I added url from python example because url in curl was incomplete. But it still need two values providerPartition and providerPartitionId
On https://curl.trillworks.com/ you can convert curl to python code. And mostly it works.
Here code from this page. But I can't test it.
import requests
# incompletet url from curl
#url = 'https://c6y09pww43.execute-api.us-east-1.amazonaws.com/p'
providerPartition = '??'
providerPartitionId = '??'
url = f'https://p7a0km3l6k.execute-api.us-east-1.amazonaws.com/preprod/v1/images/trademark/metadata/providerPartition/{providerPartition}/providerPartitionId/{providerPartitionId}'
headers = {
'Content-Type': 'application/octet-stream',
}
data = open('C:\\Users\\U6068366\\Downloads\\Koala.jpg', 'rb').read()
response = requests.post(url, headers=headers, data=data)
print(response.text)
You can also test both with url https://httpbin.org/post and it will send back what it get from you. And you can compare results from both requests. I tested curl and python code and I go the same information so they should give the same effect.

Why do I get 'internal error' from Paypal using this call in Django?

I have a request that gets PayPal authentication. It is written in Curl and it works perfectly. Trying to rewrite it in Python leads to an error response(500000 internal error). Can anyone please direct me on how I would rewrite it or correct my existing code.
CURL
curl -s --insecure -H "X-PAYPAL-SECURITY-USERID: <user_id>" -H "X-PAYPAL-SECURITY-PASSWORD: <user_password>" -H "X-PAYPAL-SECURITY-SIGNATURE: <user_signature>" -H "X-PAYPAL-REQUEST-DATA-FORMAT: JSON" -H "X-PAYPAL-RESPONSE-DATA-FORMAT: JSON" -H "X-PAYPAL-APPLICATION-ID: APP-80W284485P519543T" https://svcs.sandbox.paypal.com/Permissions/RequestPermissions -d "{\"scope\":\"EXPRESS_CHECKOUT\", \"callback\":\"<callback_url>", \"requestEnvelope\": {\"errorLanguage\":\"en_US\"}}"
PYTHON
import settings
import urllib
import urllib2
from django.utils import simplejson
def home(request):
headers = {
"X-PAYPAL-SECURITY-USERID": settings.USERNAME,
"X-PAYPAL-SECURITY-PASSWORD": settings.PASSWORD,
"X-PAYPAL-SECURITY-SIGNATURE": settings.SIGNATURE,
"X-PAYPAL-REQUEST-DATA-FORMAT": "JSON",
"X-PAYPAL-RESPONSE-DATA-FORMAT": "JSON",
"X-PAYPAL-APPLICATION-ID": "APP-80W284485P519543T"
}
data = {"scope":"EXPRESS_CKECKOUT", callback":"http://www.example.com/success.html", "requestEnvelope": {"errorLanguage":"en_US"}}
req = urllib2.Request("https://svcs.sandbox.paypal.com/Permissions/RequestPermissions/", simplejson.dumps(data), urllib.urlencode(data), headers)
res = urllib2.urlopen(req).read()
typo in "EXPRESS_CKECKOUT" instead of "EXPRESS_CHECKOUT" and third argument urllib.urlencode(data) for urllib2.Request is not required.
data = {"scope":"EXPRESS_CHECKOUT", "callback":"http://www.example.com/success.html", "requestEnvelope": {"errorLanguage":"en_US"}}
req = urllib2.Request("https://svcs.sandbox.paypal.com/Permissions/RequestPermissions/", simplejson.dumps(data), headers)
res = urllib2.urlopen(req).read()

How to use https connection in python?

I have this simple working curl command:
curl -k -d X-User=user -d X-Password=password https://12.12.12.21
This is my example:
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('X-User', 'user'),('X-Password', 'password')]
rr = opener.open("https://12.12.12.21")
print rr.read()
It's not working as i expected ( result: wrong password/user name ), can you help me understand why?
Your curl command is using the -d flag which sends the data using POST, not using headers.
If you meant to use headers then you need to use the -H argument:
curl -k -H X-User=user -H X-Password=password https://12.12.12.21
Here is how to do a POST request in case that is what you need:
values = {'X-User' : 'user', 'X-Password' : 'password'}
data = urllib.urlencode(values)
req = urllib2.Request("https://12.12.12.21", data)
rr = urllib2.urlopen(req)

Categories

Resources