Python没有在while循环中捕获404异常

时间:2016-03-18 15:45:40

标签: python flask

当我从API请求信息时,我正在编写一个小函数来捕获404。 的代码

 def film_api():
    number = random.randint(1, 10000)
    film = requests.get('https://api.themoviedb.org/3/movie/{}?api_key=################'.format(number))
    while film.status_code == '404':
        film = requests.get('https://api.themoviedb.org/3/movie/{}?api_key=################'.format(number))
    else:
        return film.json()

404输出

{
    'status_code': 34,
    'status_message': 'The resource you requested could not be found.'
}

正确输出

{
    'spoken_languages': [{
        'name': 'English',
        'iso_639_1': 'en'
    }],
    'genres': [{
        'name': 'Comedy',
        'id': 35
    }, {
        'name': 'Drama',
        'id': 18
    }],
    'popularity': 0.493744,
    'original_title': 'American Splendor',
    'overview': 'An original mix of fiction and reality illuminates the life of comic book hero everyman Harvey Pekar.',
    'runtime': 101,
    'status': 'Released',
    'homepage': 'http://www.newline.com/properties/americansplendor.html',
    'video': False,
    'revenue': 6003587,
    'release_date': '2003-08-15',
    'adult': False,
    'vote_average': 6.4,
    'imdb_id': 'tt0305206',
    'poster_path': '/pcZ08ts1HaxWpUMMMQL2z3pomf1.jpg',
    'production_companies': [],
    'belongs_to_collection': None,
    'title': 'American Splendor',
    'backdrop_path': '/AswDSBB3rbh2auan9tKjETg09H8.jpg',
    'original_language': 'en',
    'budget': 0,
    'vote_count': 43,
    'production_countries': [{
        'iso_3166_1': 'US',
        'name': 'United States of America'
    }],
    'tagline': 'Ordinary life is pretty complicated',
    'id': 2771
}

我一直在文档之间来回弹跳以找到我的答案,并从一个偶数循环移动到一个while循环。我正在使用Python,Flask和Requests来构建一个简单的Web函数,因此它不需要过于复杂。

我有什么特别缺失的吗?

1 个答案:

答案 0 :(得分:1)

requests status_code返回整数而不是字符串。

所以你可以修复if film.status_code == 404:

def film_api():
    number = random.randint(1, 10000)
    film = requests.get('https://api.themoviedb.org/3/movie/{}?api_key=################'.format(number))
    if film.status_code == 404:
        film = requests.get('https://api.themoviedb.org/3/movie/{}?api_key=################'.format(number))
    else:
        return film.json()