I use the below function to get data from the web , but failed. I wonder whether urllib.quote use incorrect
i have used urllib.urlencode(xx) but it show not a valid non-string sequence or mapping object
and my request data is:
[{"Keys": "SV_cY1tKhYiocNluHb", "Details": [{"id2": "PK_2gl9xtYKX7TJi29"}], "language": "EN", "id": "535985"}]
Anyone can help. Thanks a lot !!!
###This Funcation call API Post Data
def CallApi(apilink, indata):
token = gettoken()
data = json.dumps(indata, ensure_ascii=False)
print(data)
headers = {'content-type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer %s' % (token)}
proxy = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
DataForGet=urllib.quote(data)
NewUrl= apilink + "?" + DataForGet
request = urllib2.Request(NewUrl, headers=headers)
response = urllib2.urlopen(request, timeout=300)
message = response.read()
print(message)
Error:
the err message below: File "/opt/freeware/lib/python2.7/urllib2.py", line 1198, in do_open raise URLError(err)
You could see the comment of urlencode
Encode a dict or sequence of two-element tuples into a URL query string
So you could choose removing the outer []
{"Keys": "SV_cY1tKhYiocNluHb", "Details": [{"id2": "PK_2gl9xtYKX7TJi29"}], "language": "EN", "id": "535985"}
Or use a two-element tuple
(('Keys', 'SV_cY1tKhYiocNluHb'), ('Details', [{...}]...)
Demo
>>> import urllib
>>> s = {"Keys": "SV_cY1tKhYiocNluHb", "Details": [{"id2": "PK_2gl9xtYKX7TJi29"}], "language": "EN", "id": "535985"}
>>> urllib.urlencode(s)
'Keys=SV_cY1tKhYiocNluHb&Details=%5B%7B%27id2%27%3A+%27PK_2gl9xtYKX7TJi29%27%7D%5D&language=EN&id=535985'
>>>
Related
Looks like I'm doing just about everything correct but I keep receiving this error....
Response text error:
response .text {"name":"INVALID_TRACKING_NUMBER","message":"The requested resource ID was not found","debug_id":"12345","details":[{"field":"tracker_id","value":"1234-567890","location":"path","issue":"INVALID_TRACKING_INFO"}],"links":[]}
Response status: <Response [404]>
I'm using a real transaction and a real tracking number.
I'm doing this through python and this is my code:
def paypal_oauth():
url = 'https://api-m.paypal.com/v1/oauth2/token'
headers = {
"Content-Type": "application/json",
"Accept-Language": "en_US",
}
auth = "1234-1234","0987"
data = {"grant_type":"client_credentials"}
response = requests.post(url, headers=headers, data=data, auth=(auth))
return response
def paypal_tracking(paypal_transaction_token, tracking_number, status, carrier):
try:
_paypal_oauth = paypal_oauth()
_paypal_oauth_response = _paypal_oauth.json()
except Exception as e:
print(e)
pass
access_token = _paypal_oauth_response['access_token']
url = 'https://api-m.paypal.com/v1/shipping/trackers/%s-%s/' % (paypal_transaction_token, tracking_number)
# https://api-m.paypal.com/v1/shipping/trackers/1234-567890/
carrier = carrier_code(carrier)
# This grabs carrier from a method and gets back: 'DHL'
headers = {
'Content-Type' : 'application/json',
'Authorization' : 'Bearer %s' % access_token,
}
# {'Content-Type': 'application/json', 'Authorization': 'Bearer 1234'}
data = {
"transaction_id":"%s" % paypal_transaction_token,
"tracking_number":"%s" % tracking_number,
"status": "%s" % status,
"carrier": "%s" % carrier
}
# {'transaction_id': '1234', 'tracking_number': '567890', 'status': 'SHIPPED', 'carrier': 'DHL'}
response = requests.put(url, headers=headers, data=json.dumps(data))
return HttpResponse(status=200)
Anyone with experience in paypal or using API's see my issue?
To add a tracking number (not update), use an HTTP POST request, as documented.
The URL to POST to is https://api-m.sandbox.paypal.com/v1/shipping/trackers-batch , with no additional URL parameters.
The body format is
{
"trackers": [
{
"transaction_id": "8MC585209K746392H",
"tracking_number": "443844607820",
"status": "SHIPPED",
"carrier": "FEDEX"
},
{
"transaction_id": "53Y56775AE587553X",
"tracking_number": "443844607821",
"status": "SHIPPED",
"carrier": "FEDEX"
}
]
}
Note that trackers is an array of JSON object(s).
I have a string like this below
data = '[{"cId": "y02", "name": "Test 02", "description": "My Test"}]'
I am sending this data in a http request like
import requests
headers = {
'Content-Type': 'application/json',
}
response = requests.post('http://localhost:8000/targets', headers=headers,data=data, auth=('user', 'pass'))
Now what i would like to do is e.g. i have a string in a variable like..
id=str('random string')
and i would like to add it in data like this..
data = '[{"cId": id, "name": "Test 02", "description": "My Test"}]'
But i am not able to add it. I have tried to first convert the entry in json and then adding it into the array. But server sends the exception back. How can i do that?
You could convert it to a list of dicts.Then convert it to str.(With json module):
import json
data_before = '[{"cId": "y02", "name": "Test 02", "description": "My Test"}]'
tmp = json.loads(data_before)
tmp[0]["cId"] = str('random string')
data_after = json.dumps(tmp)
Then use data_after it like before:
import requests
headers = {
'Content-Type': 'application/json',
}
response = requests.post('http://localhost:8000/targets', headers=headers, data=data_after, auth=('user', 'pass'))
Or pass it as json parameter directly in requests.post:
import json
data_before = '[{"cId": "y02", "name": "Test 02", "description": "My Test"}]'
data_after = json.loads(data_before)
data_after[0]["cId"] = str('random string')
Then do:
import requests
headers = {
'Content-Type': 'application/json',
}
response = requests.post('http://localhost:8000/targets', headers=headers, json=data_after, auth=('user', 'pass'))
data in request.post() should be a :
Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:Request.
If your data is json formatted, you can load the data and convert the string into a dict using json.load("<str in json format>").
I have the following Python code that makes a POST request to Clarifai's demographics endpoint:
import requests
import pprint
headers = {
"Authorization": "Key MY_KEY",
"Content-Type": "application/json"
}
data = {"inputs": [{"data": {"image": {"url": "https://samples.clarifai.com/demographics.jpg"}}}]}
proxies = {
"http": "MY_HTTP_PROXY",
"https": "MY_HTTPS_PROXY"
}
response = requests.post('https://api.clarifai.com/v2/models/c0c0ac362b03416da06ab3fa36fb58e3/outputs', headers=headers, data=data, proxies=proxies, verify=False)
pprint.pprint(response.json())
Note that I've replaced my real api key and proxies with MY_KEY, MY_HTTP_PROXY, and MY_HTTPS_PROXY respectively.
Does anyone experienced with Clarifai know what I'm doing wrong? I saw an example of working code posted on Clarifai's own forum, but I can't see any major differences between the working code and mine.
Just convert the data passed to json.
import requests
import pprint
import json
headers = {
"Authorization": "Key MY_KEY",
"Content-Type": "application/json"
}
data = {"inputs": [{"data": {"image": {"url": "https://samples.clarifai.com/demographics.jpg"}}}]}
json_data = json.dumps(data)
proxies = {
"http": "MY_HTTP_PROXY",
"https": "MY_HTTPS_PROXY"
}
response = requests.post('https://api.clarifai.com/v2/models/c0c0ac362b03416da06ab3fa36fb58e3/outputs', headers=headers, data=json_data, proxies=proxies, verify=False)
pprint.pprint(response.json())
Needed quotes around the data variable
'data = {"inputs": [{"data": {"image": {"url": "https://samples.clarifai.com/demographics.jpg"}}}]}'
I am trying to send a message via Firebase to a certain client. This is my current (test) code:
import json
import requests
import urllib
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Content-Type': 'application/json', 'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
payload = json.dumps(payload)
res = requests.post(server, headers=headers, json=payload)
return res
which produces the following error, returned by Firebase:
JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0.
The following JSON sent to Firebase seems correct to me:
{
"data": {
"type":"dataUpdate"
},
"to":"xxx"
}
which is in the format described by the Firebase documentation. Any idea why Firebase doesn't accept the given data?
When you use json=payload as a parameter to requests.post() you don't need to specify 'Content-Type': 'application/json' in the header. In addition, you are passing a string when the parameter should be payload as a dict (ie. no need for json.dumps())
Try this:
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
res = requests.post(server, headers=headers, json=payload)
return res
In the following code, when the following data(template_data) is passed in postman app on chrome then there is a response but the same data when posted with urllib2 gives an error, The only difference i notice is the required field i.e, false should not be given in quotes even in postman script else there is no response but the same fails in urllib2
If 'false' is given quotes in template_data even then the result is 400
Edit: In postman false should not be given in quotes if gives gives an error, so not sure how to send this paramater
import urllib
import urllib2
def get_url_data(url, request_method, content_type, data=None,
headers={}):
method = request_method
handler = urllib2.HTTPHandler(debuglevel=1)
opener = urllib2.build_opener(handler)
if data is not None:
data = urllib.urlencode(data)
request = urllib2.Request(url, data=data,headers=headers)
request.add_header("Content-Type", content_type)
request.get_method = lambda: method
try:
connection = opener.open(request)
except urllib2.HTTPError,e:
connection = e
print connection.code
if connection.code == 200:
resp = connection.read()
return resp
return None
form_template_url="https://example.com"
auth='sometokenid'
template_header_param = {'Authorization':auth}
template_data = {
"templateName": "somename",
"category": "Handbook",
"formTemplateDef": [{
"id": "0",
"component": "textInput",
"editable": "true",
"index": "0",
"label": "Handbook",
"description": "",
"placeholder": "TextInput",
"options": [],
"required": 'false'
}]
}
template_response = get_url_data(form_template_url,
'POST', 'application/json',
template_data, template_header_param)
Remove
data = urllib.urlencode(data)
and use
urllib2.urlopen(req, json.dumps(data))
This should work.