在Django中使用for循环遍历另一个URL

时间:2019-05-29 18:20:26

标签: python django loops django-views python-requests

我正在设置一个将API数据保存到我的数据库中的按钮,并且我试图找到一种方法来获取每种产品的描述,但是它们不包含在按城市列出所有产品的主网址中: (https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr),仅当我们使用此链接通过id:(https://www.test-headout.com/api/public/v1/product/get/508)来调用产品时,才包含它们。

因此,建议我首先使用Listing API来获取所有产品。遍历该列表并获得id并点击product/get API以获取描述。

这是我到目前为止尝试过的,但是我不知道如何做迭代部分:

我的Django视图:

def api_data(request):
    response = requests.get("https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr",
      headers={
        "Headout-Auth": HEADOUT_TEST_API_KEY
      }
    ).json()

    if (request.GET.get('mybtn')):
        for item in response['items']:  # for loop
            Product.objects.get_or_create(
                title=item['name'],
                destination=item['city']['name'],
                #description=response['contentListHtml'][0]['html'],
                link=item['canonicalUrl'],
                image=item['image']['url'],
            )

    return render(request, "form.html")

我该怎么做?

基于@ralf的答案,这就是我的想法 :

def api_data(request):
    if (request.GET.get('mybtn')):
        url_1 = requests.get("https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr",
          headers={
            "Headout-Auth": HEADOUT_TEST_API_KEY
          }
        )

        base_url_2 = requests.get("https://www.test-headout.com/api/public/v1/product/get/",
          headers={
            "Headout-Auth": HEADOUT_TEST_API_KEY
          }
        )

        resp_data = url_1.json()

        for item in resp_data['items']:
            url = '{}{}'.format(base_url_2, item['id'])
            resp_data = url.json()

            Product.objects.get_or_create(
                title=item['name'],
                destination=item['city']['name'],
                description=response['contentListHtml'][0]['html'],
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

    return render(request, "form.html")

2 个答案:

答案 0 :(得分:1)

您是否尝试过为每个商品提出GET请求?这可以在您已经拥有的for循环内完成。

也许是这样的:

import requests

url_1 = 'https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr'
base_url_2 = 'https://www.test-headout.com/api/public/v1/product/get/'
resp_data = requests.get(url_1).json()

for item in resp_data['items']:
    url = '{}{}'.format(base_url_2, item['id'])
    resp_data = requests.get(url).json()

    print('item')
    print(item)
    print('resp_data')
    print(resp_data)

    break

    Product.objects.get_or_create(...)

运行第一项的代码(请注意我为此测试放置的break),我得到了正确的输出:

item
{'id': '7324', 'name': 'Billets Accès Rapide pour la Sagrada Familia', 'url': '/tour/7324/spain/barcelona/fast-track-tickets-to-sagrada-familia', 'canonicalUrl': 'https://www.test-headout.com/tour/7324/spain/barcelona/fast-track-tickets-to-sagrada-familia', 'city': {'name': 'Barcelona', 'code': 'BARCELONA'}, 'image': {'url': '//cdn-imgix.headout.com/tour/13376/TOUR-IMAGE/eaeefed3-c87b-4531-82c0-0089dc8d11ec-7324-barcelona-sagrada-familia-skyline-day-01.jpg'}, 'neibhourhood': 'Barcelona', 'primaryCategory': {'id': 327, 'name': 'Sagrada Familia', 'cityCode': 'BARCELONA', 'url': '/category/327'}, 'currency': {'code': 'EUR', 'currencyName': 'Euro', 'symbol': 'EUR', 'localSymbol': '€', 'precision': 2, 'currency': 'EUR'}, 'startGeolocation': {'latitude': 41.403629302978516, 'longitude': 2.1743557453155518}, 'ratingCumulative': {'avg': 4.7, 'count': 2496}, 'pricing': {'type': 'PER_PERSON', 'currencyCode': 'EUR', 'minimumPrice': {'originalPrice': 17, 'finalPrice': 17}, 'bestDiscount': 0}}
resp_data
{'id': 7324, 'name': 'Fast Track Tickets to Sagrada Familia', 'url': '/tour/7324/spain/barcelona/fast-track-tickets-to-sagrada-familia', 'canonicalUrl': 'https://www.test-headout.com/tour/7324/spain/barcelona/fast-track-tickets-to-sagrada-familia', 'neighbourhood': 'La Sagrada Familia', 'city': {'name': 'Barcelona', 'code': 'BARCELONA'}, 'currency': {'code': 'EUR', 'name': 'Euro', 'symbol': 'EUR', 'localSymbol': '€', 'precision': 2}, 'displayTags': ['family friendly', 'sightseeing tours', 'day trips', 'attraction tickets', 'skip the line', 'city passes'], 'images': [{'url': '//cdn-imgix.headout.com/tour/13376/TOUR-IMAGE/eaeefed3-c87b-4531-82c0-0089dc8d11ec-7324-barcelona-sagrada-familia-skyline-day-01.jpg'}, {'url': '//cdn-imgix.headout.com/tour/13376/TOUR-IMAGE/ee6912c4-1f4a-482b-be4e-5c035404da96-7324-barcelona-sagrada-familia-skyline-day-02.jpg'}, {'url': '//cdn-imgix.headout.com/tour/13376/TOUR-IMAGE/d983bcd2-be68-4e0e-9066-82adb95f468c-7324-barcelona-sagrada-familia-skyline-day-03.jpg'}, {'url': '//cdn-imgix.headout.com/tour/13376/TOUR-IMAGE/e8afec3d-acad-4056-b15c-f63f8fda9a22-7324-barcelona-sagrada-familia-skyline-day-04.jpg'}], 'contentListHtml': [{'title': 'Summary', 'type': 'SUMMARY_HTML', 'html': '<h2>What to Expect</h2>\n<p>Purchasing tickets for entry at the venue is not only time consuming but often times, futile. Since each time slot for entry into the basilica has limited capacity, same day entry tickets on site tend to sell out before mid-day, even if you waited in line for several hours, as many visitors must do. Our fast track Sagrada Familia tickets provide you with priority access to this iconic basilica. Once you book your tickets, you will receive them via email which you can then display on your phone to skip the ticketing line entirely and proceed directly to the security check.</p>\n<p>Before you head into the inner sanctum of the church, make sure to explore the outer walls and facades of the Sagrada Familia. Two of the three facades, Nativity, and Passion, have been completed, while the third, the Glory Facade, is still under construction. The Nativity facade tells the story of the birth of Jesus Christ while the Passion Facade is dedicated to his death. Though you can admire the facades and towers from the outside, these tickets do not give you access to the towers themselves. If you wish to gain entry to the towers along with the Basilica, please click <a href="https://www.headout.com/tour/7603/spain/barcelona/sagrada-familia-skip-the-line-tickets-with-tower-access-and-audio-guide">here.</a></p>\n<p>As you move inside, you will come face to face with one of the most enchanting interiors of any church in the world. The vaults of the Basilica are as high as 70 meters in certain places and the beautiful, stained glass windows, constructed as per Gaudi’s plans, as well as the pillars holding up the ceiling,  make the entire space appear as though it were the hollowed out rib cage of some giant celestial beast. The magical natural light filtering through the basilica’s exquisite windows will take your breath away and transport you to a different time.</p>'}, {'title': 'Highlights', 'type': 'HIGHLIGHTS_HTML', 'html': '<ul>\n<li>Get a chance to visit the most iconic monument in Barcelona that has been under construction since 1882, this UNESCO World Heritage Site attracts more visitors each year than any other landmark in Spain.</li>\n<li>With these fast-track tickets that you can book online, you need not worry about the long winding queues and you will also be guaranteed access to an otherwise sold out attraction. </li>\n<li>Marvel at the magnificent inner sanctums of the basilica with its extraordinary vaulted ceilings and stained glass windows, bound to sweep you off your feet.</li>\n</ul>'}, {'title': 'FAQs', 'type': 'FAQ_HTML', 'html': '<h2>Know Before You Go</h2>\n<p><strong>Important Information</strong></p>\n<p>Groups with more than a total of 9 people, either adults or children, will not be allowed to gain entry into the Basilica. Should you wish to visit with a group of more than 9 people, you must book a guided visit as per the rules of the Basilica. You can book this by clicking <a href="https://www.headout.com/tour/3441/spain/barcelona/fast-track-guided-tour-of-sagrada-familia-without-tower-access">here.</a></p>\n<p><strong>Timings</strong></p>\n<p>Entry to the Sagrada Familia is timed. You will have the option to choose the time slot for your entry during the next step of your booking. Please note that you will <strong><em>only be allowed to gain entry at the time chosen during the booking</em></strong> so we recommend arriving 15 minutes in advance in order to ensure a hassle-free entry. Though your entry is timed, you may explore the basilica for as long as you wish. Most visitors spend around an hour and a half inside. </p>\n<p>November to February - 9:00 AM to 6:00 PM<br>\nMarch - 9:00 AM to 7:00 PM<br>\nApril to September - 9:00 AM to 8:00 PM<br>\nOctober - 9:00 AM to 7:00 PM<br>\nDecember 25, 26, January 1 and 6 - 9:00 AM to 2:00 PM<br></p>\n<p><strong>Reduced Price Tickets</strong></p>\n<p>Entry for children aged eleven and below is free, however, they will not receive an audioguide. You will have the option to choose the number of children who require free entry at the time of checkout.</p>\n<p><strong>Getting There</strong></p>\n<p>To get to the Sagrada Familia, you can take any of the following options:<br>\nBy Metro: Line 2 and Line 5 to the Sagrada Familia Station.<br>\nBy Bus: Buses 19, 33, 34, 43, 44, 50, 51, B20 and B24 will stop at the Sagrada Familia.<br></p>\n<p>The main access to the Sagrada Familia is on the Carrer de la Marina (C/Marina).</p>\n<p><strong>Dress Code</strong></p>\n<p>To pay your respects to the Holy family, you must be appropriately covered to enter this sacred monument. No tank tops, strapless shirts, short shorts or sandals will be accepted. You will be denied entry if this dress code is not adhered to.</p>\n<p><strong>Accessibility</strong></p>\n<p>The insides of the Sagrada Familia is wheelchair accessible. \nHowever, due to the narrow stairways leading to the towers, tower access is not suitable for individuals with mobility impairments.</p>\n<p>Only small backpacks and regular-size handbags are allowed inside. Guests with larger bags will not be allowed to enter (as there are no storage facilities).</p>'}, {'title': 'Cancellation Policy', 'type': 'CANCELLATION_HTML', 'html': '<h2>Strict Cancellation Policy</h2>\n<p>These tickets cannot be cancelled, amended or rescheduled.</p>'}, {'title': 'Ticket Delivery Information', 'type': 'TICKET_DELIVERY_INFO_HTML', 'html': '<p>You will receive an email confirmation with your Sagrada Familia mobile tickets instantly. No need to print. You can skip the ticket line and go directly to the security line with your mobile ticket.</p>'}, {'title': 'Inclusions', 'type': 'INCLUSIONS_HTML', 'html': '<ul>\n<li>Skip-the-Line access to the Sagrada Familia.</li>\n</ul>'}, {'title': 'Exclusions', 'type': 'EXCLUSIONS_HTML', 'html': '<ul>\n<li>Tower access.</li>\n</ul>'}], 'content': [{'title': 'Summary', 'type': 'SUMMARY_HTML', 'html': '<h2>What to Expect</h2>\n<p>Purchasing tickets for entry at the venue is not only time consuming but often times, futile. Since each time slot for entry into the basilica has limited capacity, same day entry tickets on site tend to sell out before mid-day, even if you waited in line for several hours, as many visitors must do. Our fast track Sagrada Familia tickets provide you with priority access to this iconic basilica. Once you book your tickets, you will receive them via email which you can then display on your phone to skip the ticketing line entirely and proceed directly to the security check.</p>\n<p>Before you head into the inner sanctum of the church, make sure to explore the outer walls and facades of the Sagrada Familia. Two of the three facades, Nativity, and Passion, have been completed, while the third, the Glory Facade, is still under construction. The Nativity facade tells the story of the birth of Jesus Christ while the Passion Facade is dedicated to his death. Though you can admire the facades and towers from the outside, these tickets do not give you access to the towers themselves. If you wish to gain entry to the towers along with the Basilica, please click <a href="https://www.headout.com/tour/7603/spain/barcelona/sagrada-familia-skip-the-line-tickets-with-tower-access-and-audio-guide">here.</a></p>\n<p>As you move inside, you will come face to face with one of the most enchanting interiors of any church in the world. The vaults of the Basilica are as high as 70 meters in certain places and the beautiful, stained glass windows, constructed as per Gaudi’s plans, as well as the pillars holding up the ceiling,  make the entire space appear as though it were the hollowed out rib cage of some giant celestial beast. The magical natural light filtering through the basilica’s exquisite windows will take your breath away and transport you to a different time.</p>'}, {'title': 'Highlights', 'type': 'HIGHLIGHTS_HTML', 'html': '<ul>\n<li>Get a chance to visit the most iconic monument in Barcelona that has been under construction since 1882, this UNESCO World Heritage Site attracts more visitors each year than any other landmark in Spain.</li>\n<li>With these fast-track tickets that you can book online, you need not worry about the long winding queues and you will also be guaranteed access to an otherwise sold out attraction. </li>\n<li>Marvel at the magnificent inner sanctums of the basilica with its extraordinary vaulted ceilings and stained glass windows, bound to sweep you off your feet.</li>\n</ul>'}, {'title': 'FAQs', 'type': 'FAQ_HTML', 'html': '<h2>Know Before You Go</h2>\n<p><strong>Important Information</strong></p>\n<p>Groups with more than a total of 9 people, either adults or children, will not be allowed to gain entry into the Basilica. Should you wish to visit with a group of more than 9 people, you must book a guided visit as per the rules of the Basilica. You can book this by clicking <a href="https://www.headout.com/tour/3441/spain/barcelona/fast-track-guided-tour-of-sagrada-familia-without-tower-access">here.</a></p>\n<p><strong>Timings</strong></p>\n<p>Entry to the Sagrada Familia is timed. You will have the option to choose the time slot for your entry during the next step of your booking. Please note that you will <strong><em>only be allowed to gain entry at the time chosen during the booking</em></strong> so we recommend arriving 15 minutes in advance in order to ensure a hassle-free entry. Though your entry is timed, you may explore the basilica for as long as you wish. Most visitors spend around an hour and a half inside. </p>\n<p>November to February - 9:00 AM to 6:00 PM<br>\nMarch - 9:00 AM to 7:00 PM<br>\nApril to September - 9:00 AM to 8:00 PM<br>\nOctober - 9:00 AM to 7:00 PM<br>\nDecember 25, 26, January 1 and 6 - 9:00 AM to 2:00 PM<br></p>\n<p><strong>Reduced Price Tickets</strong></p>\n<p>Entry for children aged eleven and below is free, however, they will not receive an audioguide. You will have the option to choose the number of children who require free entry at the time of checkout.</p>\n<p><strong>Getting There</strong></p>\n<p>To get to the Sagrada Familia, you can take any of the following options:<br>\nBy Metro: Line 2 and Line 5 to the Sagrada Familia Station.<br>\nBy Bus: Buses 19, 33, 34, 43, 44, 50, 51, B20 and B24 will stop at the Sagrada Familia.<br></p>\n<p>The main access to the Sagrada Familia is on the Carrer de la Marina (C/Marina).</p>\n<p><strong>Dress Code</strong></p>\n<p>To pay your respects to the Holy family, you must be appropriately covered to enter this sacred monument. No tank tops, strapless shirts, short shorts or sandals will be accepted. You will be denied entry if this dress code is not adhered to.</p>\n<p><strong>Accessibility</strong></p>\n<p>The insides of the Sagrada Familia is wheelchair accessible. \nHowever, due to the narrow stairways leading to the towers, tower access is not suitable for individuals with mobility impairments.</p>\n<p>Only small backpacks and regular-size handbags are allowed inside. Guests with larger bags will not be allowed to enter (as there are no storage facilities).</p>'}, {'title': 'Cancellation Policy', 'type': 'CANCELLATION_HTML', 'html': '<h2>Strict Cancellation Policy</h2>\n<p>These tickets cannot be cancelled, amended or rescheduled.</p>'}, {'title': 'Ticket Delivery Information', 'type': 'TICKET_DELIVERY_INFO_HTML', 'html': '<p>You will receive an email confirmation with your Sagrada Familia mobile tickets instantly. No need to print. You can skip the ticket line and go directly to the security line with your mobile ticket.</p>'}, {'title': 'Inclusions', 'type': 'INCLUSIONS_HTML', 'html': '<ul>\n<li>Skip-the-Line access to the Sagrada Familia.</li>\n</ul>'}, {'title': 'Exclusions', 'type': 'EXCLUSIONS_HTML', 'html': '<ul>\n<li>Tower access.</li>\n</ul>'}], 'startLocation': {'geolocation': {'latitude': 41.403629302978516, 'longitude': 2.1743557453155518}, 'address': {'addressLine1': 'Sagrada Família, Carrer de la marina', 'addressLine2': None, 'cityName': 'Barcelona', 'postalCode': '08013', 'state': 'Catalunya', 'countryName': 'Spain'}}, 'endLocation': {'geolocation': {'latitude': 41.403629302978516, 'longitude': 2.1743557453155518}, 'address': {'addressLine1': 'Sagrada Família, Carrer de la marina', 'addressLine2': None, 'cityName': 'Barcelona', 'postalCode': '08013', 'state': 'Catalunya', 'countryName': 'Spain'}}, 'productType': 'ATTRACTION', 'ratingCumulative': {'avg': 4.7, 'count': 2496}, 'hasInstantConfirmation': True, 'hasMobileTicket': True, 'variants': [{'id': 13376, 'name': 'Fast Track', 'description': '- Get Fast Track Access that lets you bypass the ticket line & directly join the security line\r\n- Get guaranteed timed entry to the basilica\r\n- Mobile vouchers for convenient access', 'duration': 5400000, 'inventoryType': 'FIXED_START_FLEXIBLE_DURATION', 'pax': {'min': 1, 'max': 9}, 'cashback': {'value': 10.0, 'type': 'PERCENTAGE'}, 'ticketDeliveryInfoHtml': '<p>You will receive an email confirmation with your Sagrada Familia mobile tickets within 30 minutes of your purchase. No need to print. You can skip the ticket line and go directly to the security line with your mobile ticket.</p>\n<p>Please note that, in some rare cases, if the requested time slot is unavailable, we will book the next available time slot within 30 minutes of your preferred entry time. Please check the exact entry time on your tickets once you receive them.</p>', 'inputFields': [{'oldId': 42249, 'id': 'NAME', 'name': 'Full Name', 'dataType': 'STRING', 'validation': {'regex': '\\s*[^\\s]+\\s+[^\\s]+.*', 'minLength': 3, 'maxLength': 80, 'minValue': None, 'maxValue': None, 'required': True, 'values': None}, 'level': 'PRIMARY_CUSTOMER'}, {'oldId': 42250, 'id': 'EMAIL', 'name': 'Email', 'dataType': 'STRING', 'validation': {'regex': "(?i)^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~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)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))+)*$", 'minLength': 5, 'maxLength': None, 'minValue': None, 'maxValue': None, 'required': True, 'values': None}, 'level': 'PRIMARY_CUSTOMER'}, {'oldId': 42251, 'id': 'PHONE', 'name': 'Phone', 'dataType': 'STRING', 'validation': {'regex': None, 'minLength': None, 'maxLength': 40, 'minValue': None, 'maxValue': None, 'required': True, 'values': None}, 'level': 'PRIMARY_CUSTOMER'}]}, {'id': 13377, 'name': 'Fast Track + Audioguide', 'description': '- Audioguide (Spanish, Catalan, Chinese, English, French, German, Italian, Japanese, Portuguese, Russian)\r\n- Get Fast Track Access that lets you bypass the ticket line & directly join the security line\r\n- Get guaranteed timed entry to the basilica\r\n- Mobile vouchers for convenient access', 'duration': 5400000, 'inventoryType': 'FIXED_START_FLEXIBLE_DURATION', 'pax': {'min': 1, 'max': 9}, 'cashback': {'value': 10.0, 'type': 'PERCENTAGE'}, 'ticketDeliveryInfoHtml': '<p>You will receive an email confirmation with your Sagrada Familia mobile tickets within 30 minutes of your purchase. No need to print. You can skip the ticket line and go directly to the security line with your mobile ticket.</p>\n<p>Please note that, in some rare cases, if the requested time slot is unavailable, we will book the next available time slot within 30 minutes of your preferred entry time. Please check the exact entry time on your tickets once you receive them.</p>', 'inputFields': [{'oldId': 42252, 'id': 'NAME', 'name': 'Full Name', 'dataType': 'STRING', 'validation': {'regex': '\\s*[^\\s]+\\s+[^\\s]+.*', 'minLength': 3, 'maxLength': 80, 'minValue': None, 'maxValue': None, 'required': True, 'values': None}, 'level': 'PRIMARY_CUSTOMER'}, {'oldId': 42253, 'id': 'EMAIL', 'name': 'Email', 'dataType': 'STRING', 'validation': {'regex': "(?i)^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\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])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))+)*$", 'minLength': 5, 'maxLength': None, 'minValue': None, 'maxValue': None, 'required': True, 'values': None}, 'level': 'PRIMARY_CUSTOMER'}, {'oldId': 42254, 'id': 'PHONE', 'name': 'Phone', 'dataType': 'STRING', 'validation': {'regex': None, 'minLength': None, 'maxLength': 40, 'minValue': None, 'maxValue': None, 'required': True, 'values': None}, 'level': 'PRIMARY_CUSTOMER'}, {'oldId': 51544, 'id': 'CUSTOM_51544', 'name': 'Select Audioguide language', 'dataType': 'ENUM', 'validation': {'regex': None, 'minLength': None, 'maxLength': None, 'minValue': None, 'maxValue': None, 'required': True, 'values': ['English', 'Spanish', 'Catalan', 'Chinese', 'French', 'German', 'Italian', 'Japanese', 'Russian', 'Portuguese']}, 'level': 'PRIMARY_CUSTOMER'}]}, {'id': 18620, 'name': 'English Guided Tour', 'description': '- Get Fast Track Access to Sagrada Familia Basilica\r\n- Expert English Guide\r\n- Small group tour\r\n- Headphones', 'duration': 3600000, 'inventoryType': 'FIXED_START_FIXED_DURATION', 'pax': {'min': 1, 'max': 100}, 'cashback': {'value': 0.0, 'type': 'PERCENTAGE'}, 'ticketDeliveryInfoHtml': '', 'inputFields': [{'oldId': 58972, 'id': 'NAME', 'name': 'Full Name', 'dataType': 'STRING', 'validation': {'regex': '\\s*[^\\s]+\\s+[^\\s]+.*', 'minLength': 3, 'maxLength': 80, 'minValue': None, 'maxValue': None, 'required': True, 'values': None}, 'level': 'PRIMARY_CUSTOMER'}, {'oldId': 58973, 'id': 'EMAIL', 'name': 'Email', 'dataType': 'STRING', 'validation': {'regex': "(?i)^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-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\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))+)*$", 'minLength': 5, 'maxLength': None, 'minValue': None, 'maxValue': None, 'required': True, 'values': None}, 'level': 'PRIMARY_CUSTOMER'}, {'oldId': 58974, 'id': 'PHONE', 'name': 'Phone', 'dataType': 'STRING', 'validation': {'regex': None, 'minLength': None, 'maxLength': 40, 'minValue': None, 'maxValue': None, 'required': True, 'values': None}, 'level': 'PRIMARY_CUSTOMER'}]}], 'pricing': {'type': 'PER_PERSON', 'currencyCode': 'EUR', 'minimumPrice': {'originalPrice': 17, 'finalPrice': 17}, 'bestDiscount': 0}}

答案 1 :(得分:1)

我不想在其他答案中添加更多代码,因此这里有了一个新答案。因此,根据更新后的问题代码,代码可能看起来如下:

def api_data(request):
    if request.GET.get('mybtn'):    # this should probably be compared to something ???
        resp_1 = requests.get(
            "https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr",
            headers={
                "Headout-Auth": HEADOUT_TEST_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.test-headout.com/api/public/v1/product/get/"

        for item in resp_1_data['items']:
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'])

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_TEST_API_KEY
                })
            resp_2_data = resp_2.json()

            Product.objects.get_or_create(
                title=item['name'],
                destination=item['city']['name'],
                description=resp_2_data['contentListHtml'][0]['html'],
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

    return render(request, "form.html")