Posts: 4
Threads: 2
Joined: Jan 2017
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
'Content-Type' : 'application/json' ,
'Ocp-Apim-Subscription-Key' : '{subscription key}' ,
}
params = urllib.parse.urlencode({
'numberOfLanguagesToDetect' : '{integer}' ,
})
body = {
"documents" : [
{
"id" : "string" ,
"text" : "string"
}
]
}
try :
conn = http.client.HTTPSConnection( 'westus.api.cognitive.microsoft.com' )
conn.request( "POST" , "/text/analytics/v2.0/languages?%s" % params, str (body), headers)
response = conn.getresponse()
data = response.read()
print (data)
conn.close()
except Exception as e:
print ( "[Errno {0}] {1}" . format (e.errno, e.strerror)
|
iam new to python and json.I want to know whether body object used in the code is a json object
or a python object.
Posts: 12,030
Threads: 485
Joined: Sep 2016
Jan-21-2017, 05:51 AM
(This post was last modified: Jan-21-2017, 05:51 AM by Larz60+.)
It's neither, rather a dictionary.
It could be saved as a json object, probably would be best choice
Posts: 4
Threads: 2
Joined: Jan 2017
thank you sir.so as i understand "body" is a python dictionary,and in the code the json input is being stored in the python dictionary called "body"..iam i right?..thanks again
Posts: 7,317
Threads: 123
Joined: Sep 2016
You should use Requests.
Data payload to server is a Python dictionary.
Requests has build in json decoder,it will do encoding inn and out of server(can just call json() ).
Eg:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
>>> import requests
>>> data = { "device_name" : "Super-pc" , "Type" : "DevicePort" , "page_size" : 2 }
>>> r.status_code
200
>>> r.json()
{ 'args' : {},
'data' : '{"device_name": "Super-pc", "page_size": 2, "Type": "DevicePort"}' ,
'files' : {},
'form' : {},
'headers' : { 'Accept' : '*/*' ,
'Accept-Encoding' : 'gzip, deflate' ,
'Content-Length' : '65' ,
'Content-Type' : 'application/json' ,
'Host' : 'httpbin.org' ,
'User-Agent' : 'python-requests/2.9.1' },
'json' : { 'Type' : 'DevicePort' , 'device_name' : 'Super-pc' , 'page_size' : 2 },
'origin' : '83.143.86.75' ,
>>> data = r.json()
>>> data[ 'json' ].get( 'device_name' , 'Not on server' )
'Super-pc'
>>> data[ 'json' ].get( 'hello' , 'Not on server' )
'Not on server'
|
Posts: 2,953
Threads: 48
Joined: Sep 2016
Jan-21-2017, 08:27 AM
(This post was last modified: Jan-21-2017, 08:27 AM by wavic.)
You should mask origin key and value from the output :)
Posts: 7,317
Threads: 123
Joined: Sep 2016
Not so important for me,because i am behind VPN( Astrill which i have used for 6-years).
|