Python Forum

Full Version: Web connection delay
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

This link displays the local country data and the server response is immediate:

However, getting the same data from using the below code, takes some time. Why the delay?
TIA

#!/usr/bin/python
import requests as req
from xml.etree import ElementTree as ET
import os, time

def get_tz():
    url = 'http://geoip.ubuntu.com/lookup'
    #read file
    r = req.get(url)
    if(r.status_code == req.codes.ok):
        root = ET.fromstring(r.content)
        # parse an xml file by name
        TZ = "'" + root[12].text + "'"
    t = r.elapsed # returns datetime.timedelta(0, 1, 666890)
    #print('elapsed time: {}'.format(t))
    print(TZ)
    #update time 
    os.environ['TZ'] = TZ
    time.tzset()

get_tz()
How much time? It's virtually instantaneous for me.
whaats your topic
Quote:micseydel writes: How much time? It's virtually instantaneous for me.
I also find it nearly instantaneous.

Are you going through a firewall?
The other thing that might be happening is they detected too many requests from your IP + user agent combo and they're rate-limiting you. The solution to that is either wait (it wouldn't surprise me if it works for you now), change your user agent (kinda evil) or figure out the right policy (do they have an API?) and work from there.
By the way, you can use the find method on an Element.

root = ET.fromstring(r.content)
TZ = resp.find('TimeZone').text
Another trick to make from a flat xml structure a dict:
result = {e.tag: e.text for e in resp}
Output:
{'Ip': 'xxx.xxx.xxx.xxx', 'Status': 'OK', 'CountryCode': 'DE', 'CountryCode3': 'DEU', 'CountryName': 'Germany', 'RegionCode': '07', 'RegionName': 'Nordrhein-Westfalen', 'City': 'Iserlohn', 'ZipPostalCode': '58636', 'Latitude': '51.3800', 'Longitude': '7.7032', 'AreaCode': '0', 'TimeZone': 'Europe/Berlin'}
You should not run your script to often. Otherwise -> RateLimit