Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'while True' while doing http request in Python 2.7

Is there a more Pythonic (2.7) way to check the server for a good status_code (200) that doesn't include using while True? My code snippet is as follows - and it's called many times:

    import time
    import json
    from datetime import datetime
    import requests

    while True:
        response = requests.get('http://example.com')
        if response.status_code != 200:
            print 'sleeping:',str(datetime.now()),response.status_code
            print 'sleeping:',str(datetime.now()),response.headers
            time.sleep(5.0)
        else: break
    if "x-mashery-error-code" in response.headers:
        return None
    return response.json()

edit: I included the 'if' loop with the header errors.

like image 931
philshem Avatar asked Feb 13 '23 16:02

philshem


2 Answers

You can use Event Hooks

requests.get('http://example.com', hooks=dict(response=check_status))
def check_status(response):
    if response.status_code != 200:
        print 'not yet'
like image 72
Richard Ruiter Avatar answered Feb 17 '23 16:02

Richard Ruiter


I would like this solution:

response = requests.get('http://example.com')
while response.status_code != 200:
    print 'sleeping:',str(datetime.now()),response.status_code
    print 'sleeping:',str(datetime.now()),response.headers
    time.sleep(5.0)
    response = requests.get('http://example.com')

Because:

>>> import this
...
Explicit is better than implicit.
Simple is better than complex.
...
Flat is better than nested.
...
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
...
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
...

Because I read it and understand it right away. With event hooks this is not the case. Do they open a thread to retrieve bytes in parallel? When are they called? Do I need to retrieve the data myself?

like image 45
User Avatar answered Feb 17 '23 14:02

User