简体   繁体   中英

Python not catching a 404 exception in while loop

I am writing a small Function to catch a 404 when I request information from an API. Code

 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 Output

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

correct output

{
    '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
}

I have been bouncing back and forth between docs to find my answer and moved from an except to a while loop. I am using Python, Flask and Requests to build a simple web function so it does not need to be overly complex.

Is there something I am missing specifically?

requests status_code returns integer not string.

So you can fix like 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM