Django嵌套请求

时间:2018-12-12 14:57:45

标签: python django python-requests

我有此功能,可以与SWAPI API通讯,我想获取电影的种类名称。 假设我搜索“新希望”,我必须得到['Hutt','Wookiee','Droid','Human','Rodian']。 问题在于,在SWAPI字典中,您没有获得名称,而获得了URL列表。

"species": [
        "https://swapi.co/api/species/5/", 
        "https://swapi.co/api/species/3/", 
        "https://swapi.co/api/species/2/", 
        "https://swapi.co/api/species/1/", 
        "https://swapi.co/api/species/4/"
    ], 

到目前为止,这是我的主张:

@api_view(['GET'])
    def search_films(request,title):
        context = {}
        species = []
        url = "https://swapi.co/api/?search=" + str(title)
        if request.method == "GET":
            r = requests.get(url)
            if r.status_code == 200:
                data = r.json()
                species = data['results'][0]['species']
                if species:
                    for species_url in species:
                        get_request = requests.get(species_url)
                        response_data = get_request.json()
                        species.append(response_data)
                    context['species'] = response_data
                    print(context)
                return Response(data, status=status.HTTP_200_OK)
            else:
                return Response({"error": "Request failed"}, status=r.status_code)
        else:
            return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST)

这时我得到一个错误:

     raise InvalidSchema("No connection adapters were found for '%s'" % url)
requests.exceptions.InvalidSchema: No connection adapters were found for '{'name': 'Hutt', 'classification': 'gastropod', 'designation': 'sentient', 'average_height': '300', 'skin_colors': 'green, brown, tan', 'hair_colors': 'n/a', 'eye_colors': 'yellow, red', 'average_lifespan': '1000', 'homeworld': 'https://swapi.co/api/planets/24/', 'language': 'Huttese', 'people': ['https://swapi.co/api/people/16/'], 'films': ['https://swapi.co/api/films/3/', 'https://swapi.co/api/films/1/'], 'created': '2014-12-10T17:12:50.410000Z', 'edited': '2014-12-20T21:36:42.146000Z', 'url': 'https://swapi.co/api/species/5/'}'

关于如何实现这一点的任何想法?

1 个答案:

答案 0 :(得分:3)

好吧,看看您的行species = [],您希望只有网址,对吗?事实并非如此,因为您要在此列表的后面附加响应数据species.append(response_data)。在脚本执行期间,它变为:

['https://swapi.co/api/species/5/',
 'https://swapi.co/api/species/3/',
 'https://swapi.co/api/species/2/',
 'https://swapi.co/api/species/1/',
 'https://swapi.co/api/species/4/',
 {'name': 'Hutt', ....},
 {'name': 'Wookiee', ....}]

因为列表是可变数据类型。在某些迭代中,您尝试获取的不是网址,而是字典

我已尝试将函数开始处的代码重命名为Spice,并将代码仅用于存储来自api(json response)的响应,以修复代码。 Spice网址仍在species_data变量中。我不确定spices是否适合您,但您应该明白。您需要2个不同变量来获取网址和响应数据。

return Response(species_data, status=status.HTTP_200_OK)