Shopify API JSON Feed / Limit 250 и Pages / GET извлекает одни и те же записи каждый раз, а не на следующей странице - PullRequest
0 голосов
/ 12 мая 2018

Я пытаюсь получить список всех сборов, и когда я делаю вызов API для их подсчета:

https://[store -username] .myshopify.com / администратор / собирает / count.json

HTTP/1.1 200 OK
{
  "count": 307
}

Я знаю, что ограничение составляет 250, а страница по умолчанию - 1

.

https://[store -username] .myshopify.com / админ / collects.json? Предел = 250 & страница = 1

Получит 250 записей.

Когда я сделаю страницу 2 - я получу те же записи, что и на странице 1

https://[store -username] .myshopify.com / админ / collects.json? Предел = 250 & страница = 2

Так что для любопытства я попробовал страницу 10 - которая выходит за допустимые пределы - это было бы 2500> 307, и она вернула те же 250, что и на странице 1

2-я вещь:

Когда я помещаю это в код / ​​python - и я делаю скрипт для запуска

https://[store -username] .myshopify.com / админ / collects.json? Предел = 250 & страница = 1

Получает 250 записей, а затем я делаю. Page 2

https://[store -username] .myshopify.com / админ / collects.json? Предел = 250 & страница = 2

и возврат НЕТ

Я стаскиваю волосы и не могу заставить всех этих 307 обновить мою базу данных только 250 - поэтому я понятия не имею, почему

в браузере загружает в точности те же записи, что и PAGE 1, и 250 для PAGE 2, это должно быть 307-250 = 57 записей, а в сценарии это NONE.

Можете ли вы помочь?

def handle(self, *args, **options):
    security = urllib2.HTTPPasswordMgrWithDefaultRealm()
    security.add_password(None, "https://[store-username].myshopify.com/admin/collects/count.json",
                          “[credentials]”, "[credentials]")
    auth_handler = urllib2.HTTPBasicAuthHandler(security)
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)

    url = 'https://[store-username].myshopify.com/admin/collects/count.json'

    collect_feed = urllib2.urlopen(url)
    data = collect_feed.read()
    js = json.loads(str(data))
    count = int(js['count'])

    page_size = 250
    pages = int(math.ceil(count / page_size))

    list_of_collects = Collect.objects.all()
    if list_of_collects:
        list_of_collects.delete()

    current_page = 1

    while (current_page <= pages):
        opening_url = "https://[store-username].myshopify.com/admin/collects.json?limit=" + str(page_size) + '&page=' + str(current_page)
        security.add_password(None, opening_url,
                              "[credentials]", "[credentials]")
        auth_handler = urllib2.HTTPBasicAuthHandler(security)
        opener = urllib2.build_opener(auth_handler)
        urllib2.install_opener(opener)

        try:
            collect_feed = urllib2.urlopen(opening_url)
        except:
             collect_feed = None

        if collect_feed != None:
            data = collect_feed.read()
            try:
                js = json.loads(str(data))
            except:
                js = None

                for x in range(0, len(js['collects'])):
                    single_collect = list_of_collects.filter(collect_id=js['collects'][x]["id"]).first()
                    if single_collect == None:
                        # Create the model you want to save the image to
                        collect = Collect(collect_id=js['collects'][x]["id"],
                                  collection_id=js['collects'][x]["collection_id"],
                                  product_id=js['collects'][x]["product_id"])
                        collect.save()
                        print("Product and Collection connection number " + str(x) + " was successfully saved")
        print("NO FEED")
        print("BATCH IS SUCCESSFULLY SAVED, PROCESSING THE NEXT ONE")

        current_page += 1

    self.stdout.write(self.style.SUCCESS(‘Collects Updated.’))

Когда я запускаю скрипт, я получаю:

Product and Collection connection number 0 was successfully saved
Product and Collection connection number 1 was successfully saved
Product and Collection connection number 2 was successfully saved
[…]
Product and Collection connection number 249 was successfully saved
FIRST BATCH IS SUCCESSFULLY SAVED, PROCESSING THE NEXT ONE
sleeping for 20 seconds
NO FEED
SECOND BATCH IS SUCCESSFULLY SAVED, PROCESSING THE NEXT ONE
Collects Updated.

На основании кода PAGE 2 возвращает NONE, но почему счет 307> 250 ...

Ответы [ 2 ]

0 голосов
/ 13 мая 2018

Вот последний сценарий благодаря исправлению Даниэля.

def handle(self, *args, **options):
    security = urllib2.HTTPPasswordMgrWithDefaultRealm()
    security.add_password(None, "https://[store-username].myshopify.com/admin/collects/count.json",
                          “[credentials]”, "[credentials]")
    auth_handler = urllib2.HTTPBasicAuthHandler(security)
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)

    url = 'https://[store-username].myshopify.com/admin/collects/count.json'

    collect_feed = urllib2.urlopen(url)
    data = collect_feed.read()
    js = json.loads(str(data))
    count = int(js['count'])
    print (count)

    page_size = 250
    pages = int(math.ceil(count / 250.0))

    list_of_collects = Collect.objects.all()
    if list_of_collects:
        list_of_collects.delete()

    current_page = 1

    while (current_page <= pages):
        opening_url = "https://[store-username].myshopify.com/admin/collects.json?limit=" + str(
            page_size) + '&page=' + str(current_page)
        security.add_password(None, opening_url,
                              "[credentials]", "[credentials]")
        auth_handler = urllib2.HTTPBasicAuthHandler(security)
        opener = urllib2.build_opener(auth_handler)
        urllib2.install_opener(opener)

        try:
            collect_feed = urllib2.urlopen(opening_url)
        except:
            collect_feed = None

        if collect_feed != None:
            data = collect_feed.read()

            try:
                js = json.loads(str(data))
            except:
                js = None

            if js != None:
                for x in range(0, len(js['collects'])):
                    single_collect = list_of_collects.filter(collect_id=js['collects'][x]["id"]).first()
                    if single_collect == None:
                        # Create the model you want to save the image to
                        collect = Collect(collect_id=js['collects'][x]["id"],
                                          collection_id=js['collects'][x]["collection_id"],
                                          product_id=js['collects'][x]["product_id"])
                        collect.save()
                        print("Product and Collection connection number " + str(x) + " was successfully saved")

                print(str(current_page) + "ST BATCH IS SUCCESSFULLY SAVED, PROCESSING THE NEXT ONE")
            else:
                print ("Feed is empty.")
        current_page += 1
    self.stdout.write(self.style.SUCCESS(‘Collects Updated.'))
0 голосов
/ 12 мая 2018

Вам необходимо использовать & для разделения элементов в строке запроса:

https://[store -username] .myshopify.com / admin / collects.json? Limit = 250 & page = 1

Обратите внимание, вы действительно должны использовать Python-клиент Shopify.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...