连接到API问题

时间:2018-03-14 20:29:54

标签: python rest api

我是Python的新手,我正在尝试使用它连接到Americommerce API。他们在git上有一个例子。 它似乎不起作用。我将网址添加到STORE_DOMAIN,将密钥添加到ACCESS_TOKEN,将app id添加到STORE_ID。

唯一似乎重要的是网址。如果我误解了它我会得到连接错误,但是我可以输入任何我想要的密钥和ID并得到相同的结果。这是脚本

let group = DispatchGroup()

group.enter()
someLongRunningTask() {
  // completion callback
  group.leave()
}

group.enter()
anotherLongRunningTask() {
  // completion callback
  group.leave()
}

group.wait() // waits synchronously for the submitted work to complete
DispatchQueue.main.async {
  print("all set")
}

运行时我得到了这个结果:

#!/usr/bin/env python3

# The 'requests' module is available via pip: "pip install requests"
# You can find more documentation about requests at http://docs.python-requests.org/en/latest/
import requests
import json
import locale
import sys

STORE_DOMAIN = "http://www.example.com"
ACCESS_TOKEN = "key"
STORE_ID = "app_id"  # This should reflect your store's ID

locale.setlocale(locale.LC_ALL, '')

# Searches for and returns the customer that matches the info passed in,
# if no customer is found a new one is created and returned
def get_customer(firstName, lastName, email):

    # setup headers
    headers = {
        'X-AC-Auth-Token': ACCESS_TOKEN,
        'Content-Type': 'application/json'
    }

    # build API call to check if customer already exists (using email)
    uri = '{}/api/v1/customers?email={}'.format(STORE_DOMAIN, email)

    # include verify=False if using dev certificate
    # r = requests.get(uri, headers = headers, verify=False)
    r = requests.get(uri, headers = headers)

    # see if a customer was found
    customer = r.json()
    if (customer['total_count'] > 0):
        return customer['customers'][0]

    # no customer found, so lets create a new one
    data = {
        'last_name': doe,
        'first_name': john,
        'email': johndoe@email.com,
        'store_id': 4
    }

    # build API call to post a new customer
    uri = '{}/api/v1/customers'.format(STORE_DOMAIN)

    # include verify=False if using dev certificate
    # r = requests.post(uri, headers=headers, data = json.dumps(data), verify=False)
    r = requests.post(uri, headers=headers, data = json.dumps(data))

    # return newly created customer
    return r.json()

if __name__ == '__main__':
    customer = get_customer('John', 'Doe', 'JohnDoe@email.com')
    first_name = customer['first_name'].encode('utf-8')
    last_name = ',{}\n'.format(customer['last_name']).encode('utf-8')
    email = customer['email'].encode('utf-8')
    sys.stdout.buffer.write(first_name + last_name + email)

拜托,请给我一点帮助。我现在已经坚持了一段时间。

1 个答案:

答案 0 :(得分:0)

您收到密钥错误,因为您的字典/ JOSN customer不包含密钥total_count