Проблема декодирования JSON при использовании запросов в python 2.7.10 для Zendesk API

У меня есть скрипт Python, который я использую для вызова API Zendesk, чтобы получить возврат JSON. Типичный Data = response.json() работал до тех пор, пока мне не пришлось все перенести на python 2.7. Работало нормально в 3.4. Я попробовал различные стратегии кодирования и декодирования, и я получил его после перерыва, но тогда это в форме, которую я могу использовать. Мне нужно иметь доступ к частям JSON по строке, а не целое число Data['users'] В качестве примера. Вот код, который у меня есть до перерыва.

import datetime
import time
import calendar
import requests
import os.path as path
import json
import logging
import Query2UploadRouter
import sys
from httplib import BadStatusLine
from io import open


def byteify(input):

    if isinstance(input, dict):
        return {byteify(key):byteify(value) for key,value in input.iteritems()}
    elif isinstance(input, list):
        return [byteify(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

def runQuery(endPoint,tableName,topJsonTier,userName,passWord,schema,verticaName,verticaPassword,i):

    if path.isfile('Data_Aquisition_Log_' + str(datetime.date.today()) + '.txt') == True:
        logging.basicConfig(filename='Data_Aquisition_Log_' + str(datetime.date.today()) + '.txt', filemode='a', level=logging.DEBUG)
    else:
        logging.basicConfig(filename='Data_Aquisition_Log_' + str(datetime.date.today()) + '.txt', filemode='w', level=logging.DEBUG)

    startTime = calendar.timegm(datetime.datetime.now().timetuple()) - 3600

    url = "https://myURL.zendesk.com/api/v2/" + str(endPoint) + str(startTime)

    user = userName
    pwd = passWord
    headers = {'content-type': 'application/json'}

    # Create a requests to avoid flooding the server with requests
    # Do all of this stuff and then do it again as long as the response JSON has a next page
    while True:

        # Do the HTTP get request

        for x in xrange(0,9):

            logging.debug('Query Attempt...' + str(x))

            try:

                logging.debug(url)
                response = requests.get(url, auth=(user,passWord))
                break

            except:

                err = sys.exc_info()[0]
                logging.debug('There was an error when attemtping to execute the query!  URL: ' + str(url) + ' Error: ' + str(err))
                time.sleep(5)
                pass

        # Check for HTTP codes other than 200
        if response.status_code != 200 or response.status_code is None:
            if response.status_code == 429:
                logging.debug(unicode(response.status_code) + 'Rate Limited.  Waiting to Retry')
                time.sleep(float(response.headers['retry-after']))
                response = requests.get(url, auth=(user,passWord))
            elif response.status_code == 422:
                logging.debug( 'The last record was reached')
                break
            else:
                logging.debug('Problem with the request. Retrying.')
                response = requests.get(url, auth=(user,passWord))

        # Decode the JSON response into a dictionary and use the data

        data = byteify(response.json())

Использование biteify было решением, которое я нашел в Интернете, и было моей последней попыткой. Вот ответ об ошибке, который я получил:

DEBUG:root:Starting run for ZendeskUsersTest!!
DEBUG:root:Query Attempt... 0 
DEBUG:root:https://myURL.zendesk.com/api/v2/incremental/users.json?start_time=1434444644
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): .zendesk.com
DEBUG:requests.packages.urllib3.connectionpool:"GET /api/v2/incremental/users.json?start_time=1434444644 HTTP/1.1" 200 None 
DEBUG:root:An error caused the run to break! <type 'exceptions.ValueError'>
No JSON object could be decoded
DEBUG:root:All data aquisition was completed!

Итак, как вы можете видеть, я получаю ответ 200. Вставка URL-адреса непосредственно на веб-страницу дает мне возвращение JSON, и я проверил его с помощью JSONlint.

0 ответов

Другие вопросы по тегам