у меня есть веб-сканер:
import http.client
import time
import threading
class Worker(threading.Thread): # Booting crawler workers
def __init__(self, base, ref, conn, urlKey, url):
threading.Thread.__init__(self)
self.base = base
self.ref = ref
self.conn = conn
self.urlKey = urlKey
self.url = url
def run_aux(self): # Getting web response and do stuff with it
self.conn.request('GET', self.url)
response = self.conn.getresponse()
status = response.status
if status == 200:
data = str(response.read())
if data.find('No he podido entenderte.') != -1:
data = 'Err: Ruta no comprendida'
else:
pos = data.find('>Id: ') + 5
if pos == 4:
data = 'Err: Tag >Id: no encontrado'
else:
data = data[pos:pos+32]
else:
data = 'Err: ' + str(status)
response.close()
self.base.saveRes(self.urlKey, data, self.ref)
def run(self): # Auxiliary function that allows the crawler to continue running if any problem is found while connecting to the web site. It will continue trying to runtill connections are accepted
try:
self.run_aux()
except Exception as e:
self.run()
class MIdCrawler(object): # Boot and instantiate the crawler
def __init__(self, site, nThreads, urlDict):
self.res = {}
self.nThreads = nThreads
self.urlDict = urlDict.copy()
self.urlKeys = list(self.urlDict.keys())
self.conns = [http.client.HTTPSConnection(site) for _ in range(self.nThreads)]
self.threads_launched = 0
self.launch()
def newThread(self, ref): # How the threads are launched
if self.threads_launched < len(self.urlKeys):
urlKey = self.urlKeys[self.threads_launched]
Worker(self, ref, self.conns[ref], urlKey, self.urlDict.get(urlKey)).start()
self.threads_launched += 1
def launch(self): # Create new threads
for i in range(self.nThreads):
self.newThread(i)
def saveRes(self, urlKey, data, ref): # Saving the results into a dict
self.res[urlKey] = data
#print('Dato guardado')
print(urlKey)
self.newThread(ref)
def getRes(self): # Return results
while len(self.res) < len(self.urlKeys):
time.sleep(0.5)
return(self.res)
def close(self): # Close working threads
for i in range(self.nThreads):
self.conns[i].close()
этот сканер восстановит некоторые данные с моего веб-сервера, когда мой сервер получит вызов, он вызовет API Google Maps для восстановления некоторыхданные маршрута.Я должен сделать примерно 3000 звонков, проблема в том, что я заметил, что Google Maps перестает отвечать на звонки, когда определенное количество последовательных звонков делается с одного и того же IP в течение короткого периода времени.Для этого красного флага не установлено фиксированное количество вызовов, но оно всегда между 240 и 300 последовательными вызовами.
Этот сканер позволяет указать количество потоков (вызовов), которые мы хотим загрузитьпараллельно, проблема в том, что когда я получаю вызовы 2xx-300, сервер Google Maps перестает отвечать на мои петиции.
Я новичок в этой утилизации, и мне бы хотелось, чтобы кто-нибудь рассказал мне, как я могу изменить этот сканер, чтобы он выполнял 200 вызовов, подождал десять минут и затем продолжил с того места, где он остановился.
Это некоторые примеры данных, которые получает сканер:
['/testchat?text=quiero%20ir%20desde%20carrer%20cervantes%2C%201%2C%20sant%20andreu%20de%20la%20barca%2C%20hasta%20avinguda%20constituci%C3%B3%2C%2024%2C%20sant%20andreu%20de%20la%20barca',
'/testchat?text=quiero%20ir%20desde%20General%20Mitre%20239%2C%20Barcelona%2C%20hasta%20Plaza%20Artos%2C%20Barcelona',
'/testchat?text=quiero%20ir%20desde%20carrer%20Bon%20viatge%2C%20sant%20Joan%20Desp%C3%AD%2C%20hasta%20mare%20de%20deu%20la%20Merc%C3%A8%2C%20sant%20Joan%20Desp%C3%AD',
'/testchat?text=quiero%20ir%20desde%20no%20recuerdo%2C%20hasta%20no%20recuerdo',
'/testchat?text=quiero%20ir%20desde%20travessera%20de%20les%20corts%2C%20barcelona%2C%20hasta%20Avenida%20diagonal%2050%2C%20barcelona',
'/testchat?text=quiero%20ir%20desde%20Confidencial%2C%20hasta%20Confdencial%2C%20Confidencial',
'/testchat?text=quiero%20ir%20desde%20Paseo%20Zona%20Franca%20241%2C%20Barcelona%2C%20hasta%20Plaza%20Espa%C3%B1a%2C%20Barcelona',
'/testchat?text=quiero%20ir%20desde%20Rbla.%20les%20bobiles%2014%2C%20martorell%2C%20hasta%20plaza%20de%20la%20vila%201%2C%20martorell',
'/testchat?text=quiero%20ir%20desde%20Rambla%20de%20Catalu%C3%B1a%2086%2C%20Barcelona%2C%20hasta%20Padilla%20342%2C%20Barcelona',
'/testchat?text=quiero%20ir%20desde%20Concepci%C3%B3n%2C%20Abrera%2C%20hasta%20Major%2C%20Abrera']
Пример вызова сканера:
site = 'sema-dev-backend.mybluemix.net'
urlDict = df.url.reset_index(drop = True).to_dict()
nThreads = 5
ts1 = time.time()
mIdCrawler = MIdCrawler(site, nThreads, urlDict)
print(mIdCrawler.getRes())
t = time.time() - ts1
print('secs: ' + str(t))
print('mean_time: ' + str(t / len(urlDict)))
Что я должен изменить в этом коде, чтобы сделать его200 звонков на мой веб-сервис, остановка и ожидание 10 минут, а затем продолжить, где он снова остановился 200 звонков и повторить процесс?
Заранее большое спасибо