Tell urllib2 to use custom DNS

前端 未结 3 634
终归单人心
终归单人心 2020-11-30 01:39

I\'d like to tell urllib2.urlopen (or a custom opener) to use 127.0.0.1 (or ::1) to resolve addresses. I wouldn\'t ch

3条回答
  •  广开言路
    2020-11-30 02:14

    Another (dirty) way is monkey-patching socket.getaddrinfo.

    For example this code adds a (unlimited) cache for dns lookups.

    import socket
    prv_getaddrinfo = socket.getaddrinfo
    dns_cache = {}  # or a weakref.WeakValueDictionary()
    def new_getaddrinfo(*args):
        try:
            return dns_cache[args]
        except KeyError:
            res = prv_getaddrinfo(*args)
            dns_cache[args] = res
            return res
    socket.getaddrinfo = new_getaddrinfo
    

提交回复
热议问题