socket请求ip遇到的问题
生活随笔
收集整理的這篇文章主要介紹了
socket请求ip遇到的问题
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
請(qǐng)求ip及歸屬地代碼:
import socket q = QQwry() q.load_file('qqwry.dat') ip = socket.gethostbyname(url) #ip address = list(q.lookup(ip)) #歸屬地及服務(wù)商問(wèn)題匯總:
1、出現(xiàn)第三方包已安裝但是import出錯(cuò)的解決方法:
#注意python版本2和3的區(qū)別 import sys sys.path.append(r'/usr/local/lib/python3.6/site-packages')2、.gethostbyname()的參數(shù)必須是域名,不能帶有http和https:
from urllib.parse import urlparse if url.startswith("http"):url = urlparse(url).netloc3、請(qǐng)求超時(shí)問(wèn)題:如果不加時(shí)間限制,如果網(wǎng)速慢可能會(huì)請(qǐng)求到30s也請(qǐng)求不到,必須設(shè)置時(shí)間限制,超時(shí)跳出。嘗試解決的方法:
(1)eventlet方式:
import eventlet eventlet.monkey_patch() with eventlet.Timeout(1, False):ip = socket.gethostbyname(url)address = list(q.lookup(ip))問(wèn)題:單獨(dú)運(yùn)行腳本可以,但是與項(xiàng)目集成失敗,與gunicorn部署的flask不兼容。
(2)socket.setdefaulttimeout(1)方式:
問(wèn)題:這個(gè)setdefaulttimeout對(duì)socket模塊方法沒(méi)有用處,只是針對(duì)socket.socket對(duì)象設(shè)置超時(shí)。
socket模塊介紹:https://blog.51cto.com/unixman/1656641
socket實(shí)例時(shí)間設(shè)置:https://blog.csdn.net/whatday/article/details/104059531
(3)修改/etc/resolv.conf配置文件:
域名解析優(yōu)化方案;https://www.jianshu.com/p/2c1c081cc521
問(wèn)題:可以限制住時(shí)間,因?yàn)橐呐渲梦募?#xff0c;但是不確定是否會(huì)影響其他的socket模塊如爬蟲(chóng)
(4)用裝飾器 func_timeout 解決函數(shù)超時(shí)問(wèn)題(已使用此方法)
參考:?Python函數(shù)超時(shí),用裝飾器解決 func_timeout - 知乎
#安裝:pip install func_timeout ? #使用:在你的函數(shù)前加上裝飾器,如下: #!/usr/bin/env python # -*- coding: utf-8 -*- import time from func_timeout import func_set_timeout ? @func_set_timeout(1) def task():while True:print('hello world')time.sleep(1) if __name__ == '__main__':try:task()except func_timeout.exceptions.FunctionTimedOut:print('task func_timeout')總結(jié)
以上是生活随笔為你收集整理的socket请求ip遇到的问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: (附源码)php养老院管理系统 毕业设计
- 下一篇: selenium webdriver实现