API call for Alibaba cainiao logistics cloud-python and Alibaba-python

Source: Internet
Author: User

API call for Alibaba cainiao logistics cloud-python and Alibaba-python

You need to write a program to call cainiao logistics cloud.Level 5 address query api, Which is implemented in python.

 

 

 

 

Call an instance

 

 

Interface document:

 

ApplyAppkeyAndResourceid:

TheDataset:

 

Read the file and save it to a list:

1 def get_address (): 2 try: 3 with open (OS. getcwd () + R' \ address.txt ', 'R') as f: 4 address = f. readlines () 5 return address6 failed T: 7 print ('file opening failed') 8 return''

 

 

Construct request parameters:

1 def get_raw_input(address):2     raw_input = {3         "address": address,4         "limit": "20"5     }6     return raw_input

 

 

Construct common request parameters:

1 def get_param(sign, content):2     param = {3         'msg_type': 'CNDZK_ADDRESS_QUERY',4         'data_digest': sign,5         'logistic_provider_id': 'd0119848ab......e1df5d8d6dc149',6         'logistics_interface': content7     }8     return param

 

 

Calculate the request signature (MD5 Algorithm and base64 encoding ):

1 def get_data_digest (inputs, keys): 2 m1 = hashlib. md5 () 3 m1.update (inputs + keys ). encode ('utf-8') 4 5 # base64.b64encode (m1.hexdigest () Get the error value !!! 6 return base64.b64encode (m1.digest ())

I have been stepping on several traps for a long time, mainly becauseM1.hexdigest () is different from m1.digest ().As a result, the calculated results are different from those calculated by java and js.

At first, I thought it was str to bytes. Pay attention to the python str. the results of the encode ('utf-8') and java getBytes () are displayed differently (the former returns the bytes type, and the latter returns the byte [] type)

 

 

Request to call the api and write the file:

1 address_list = get_address () 2 3 for x in address_list: 4 # convert unicode to Chinese, remove spaces (otherwise not found) 5 inputs = json. dumps (get_raw_input (x )). encode ('utf-8 '). decode ('unicode _ escape '). replace ('','') 6 7 result = requests. post (url, data = get_param (get_data_digest (inputs, keys), inputs), headers = headers) 8 result = result. content. decode (encoding = 'utf-8') 9 # print (result) 10 results = results + result + '\ r \ n' 11 12 13 try: 14 with open (OS. getcwd () + R' \ result.txt ', 'w') as f: 15 f. write (results) 16 print ("Writing succeeded") 17 bytes T: 18 print ("Writing failed ")

Here, we step on a trap -. -Because Chinese data of the str type of python3.x is used by defaultUnicode encodingDisplay, so the data in Chinese is \ u..., resulting in query failure

Json. dumps ()Converts dict to a json string and returns the result. UTF-8 is first encoded as bytes.

ReuseDecode ('unicode _ escape ')Decoding to display Chinese characters properly

At the same time, the request parameters includeSpaceIt will also cause query failure (the Ali api documentation is too simple to say nothing, the parameters can only be adjusted slowly, negative feedback)

So here we useReplace ('','')Remove Spaces

 

 

 

Result set:

 

 

Complete code:

1 # coding: UTF-8 2 # by NeilShi 11/29/2017 3 import requests 4 import hashlib 5 import base64 6 import json 7 import OS 8 9 9 10 # 'appkey': '123 ', 11 # 'appsecret': 's7ib51kp5 ...... qd10Lt4490QTwpr ', 12 # Resource: d0119848ab5 ...... df5d8d6dc14913 14 url = 'HTTP: // link.cainiao.com/gateway/link.do'15 keys = 's7ib51kp5o ...... d10Lt4490QTwpr '16 17 headers = {18 'content-type': 'application/x-www-form-urlencoded; Charset = UTF-8 '19} 20 21 results = ''# store result set 22 23 24 def get_address (): 25 try: 26 with open (OS. getcwd () + R' \ address.txt ', 'R') as f: 27 address = f. readlines () 28 return address29 print T: 30 print ('file opening failed') 31 return ''32 33 34 def get_raw_input (address): 35 raw_input = {36 "address ": address, 37 "limit": "20" 38} 39 return raw_input40 41 42 def get_param (sign, content): 43 param = {44 'msg _ type': 'cndz K_ADDRESS_QUERY ', 45 'data _ digest': sign, 46 'logistic _ provider_id ': 'd011984 ...... d7ae1df5d8d6dc149 ', 47 'logistics _ interface': content48} 49 return param50 51 52 def get_data_digest (inputs, keys): 53 m1 = hashlib. md5 () 54 m1.update (inputs + keys ). encode ('utf-8') 55 56 # base64.b64encode (m1.hexdigest () Get the error value !!! Unknown cause 57 return base64.b64encode (m1.digest () 58 59 60 address_list = get_address () 61 62 for x in address_list: 63 # convert unicode format to Chinese, remove spaces (otherwise cannot be found) 64 inputs = json. dumps (get_raw_input (x )). encode ('utf-8 '). decode ('unicode _ escape '). replace ('','') 65 66 result = requests. post (url, data = get_param (get_data_digest (inputs, keys), inputs), headers = headers) 67 result = result. content. decode (encoding = 'utf-8') 68 # print (result) 69 results = results + result + '\ r \ n' 70 71 72 try: 73 with open (OS. getcwd () + R' \ result.txt ', 'w') as f: 74 f. write (results) 75 print ("Writing succeeded") 76 failed T: 77 print ("Writing failed ")

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.