-1

Hi i try to request some json, all is ok, but sometimes request goes wrong, may be site stack or closing connection for me, cause i am requesting json every 15 min.

Code here:

def request_coins(config):
    coins = None
    print(str(datetime.now()) + ' - REQUESTING Coins')
    while coins is None:
        try:
            coins = (requests.get(url=str(config['UrlPath']['url']) + str(config['UrlPath']['userrates'])))
        except:
            print(str(datetime.now()) + " - Site didn't respond. Reconnecting in 10 sec")
        time.sleep(10)
     if coins is not None:
        coins = coins.json()['coins']
        print(str(datetime.now()) + ' - Coins received correctly')
return coins

Problems is that try - catch don't work in my case. Request stack in print(str(datetime.now()) + ' - REQUESTING Coins') and i don't recieve any exception and message to cmd

print(str(datetime.now()) + " - Site didn't respond. Reconnecting in 10 sec")

As I understood code stacks at try: coins = (requests.get(url=str(config['UrlPath']['url']) + str(config['UrlPath']['userrates'])))

and don't go even to except:

Any idea how to fix?

Hellbea
  • 289
  • 6
  • 14
  • is your code structure correct for `if coins is not None:` ? Because python code is based on your tab. – Marprin Jul 25 '17 at 06:50
  • yes, sorry miss tab when wrote here in original code all is ok – Hellbea Jul 25 '17 at 07:07
  • I guess your `requests.get` is just busy, without raising an error... So you should look into `requests` combined with `try - except`. Have you seen [this](https://stackoverflow.com/questions/16511337/correct-way-to-try-except-using-python-requests-module)? Maybe the second part of the accepted answer with the `Response.raise_for_status` could be helpful? – nostradamus Jul 25 '17 at 07:21
  • Sorry for double-posting, but I just found [this](https://stackoverflow.com/questions/16206062/requests-httperror-uncaught-after-a-requests-get-404-response/16206247#16206247), where @gatto writes "Also notice that by default `requests` doesn't raise exception if status is not 200". You need the `(whatever).raise_for_status()`. – nostradamus Jul 25 '17 at 07:24

1 Answers1

0

Just need to add timeout to get request

Hellbea
  • 289
  • 6
  • 14