Python请求模块多线程

2024-04-20 09:45:25 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有可能的方法来加速我的代码使用多处理接口?问题是这个接口使用map函数,它只对1个函数起作用。但我的代码有三个功能。我试着把我的职能结合起来,但没有成功。我的脚本从文件中读取站点的URL并对其执行3个函数。For循环使它非常慢,因为我有很多url

import requests

def Login(url): #Log in     
    payload = {
        'UserName_Text'     : 'user',
        'UserPW_Password'   : 'pass',
        'submit_ButtonOK'   : 'return buttonClick;'  
      }

    try:
        p = session.post(url+'/login.jsp', data = payload, timeout=10)
    except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
        print "site is DOWN! :", url[8:]
        session.cookies.clear()
        session.close() 
    else:
        print 'OK: ', p.url

def Timer(url): #Measure request time
    try:
        timer = requests.get(url+'/login.jsp').elapsed.total_seconds()
    except (requests.exceptions.ConnectionError):
        print 'Request time: None'
        print '-----------------------------------------------------------------'
    else: 
        print 'Request time:', round(timer, 2), 'sec'

def Logout(url): # Log out
    try:
        logout = requests.get(url+'/logout.jsp', params={'submit_ButtonOK' : 'true'}, cookies = session.cookies)
    except(requests.exceptions.ConnectionError):
        pass
    else:
        print 'Logout '#, logout.url
        print '-----------------------------------------------------------------'
        session.cookies.clear()
        session.close()
for line in open('text.txt').read().splitlines():
    session = requests.session()
    Login(line)
    Timer(line)
    Logout(line)

Tags: 函数urltimesessiondeflinerequestselse
2条回答

是的,您可以使用多处理。

from multiprocessing import Pool

def f(line):
    session = requests.session()
    Login(session, line)
    Timer(session, line)
    Logout(session, line)        

if __name__ == '__main__':
    urls = open('text.txt').read().splitlines()
    p = Pool(5)
    print(p.map(f, urls))

请求session不能是全局的,并且不能在工作进程之间共享,每个工作进程都应该使用自己的会话。

你写道,你已经“试图把我的职能结合在一起,但没有成功”。到底什么不起作用?

有很多方法可以完成你的任务,但是在这个层次上不需要多处理,它只会增加复杂性,imho

看看gevent,greenlets和monkey patching吧!

代码准备好后,可以将主函数包装到gevent循环中,如果应用了monkey补丁,gevent框架将同时运行N个作业(可以创建作业池、设置并发限制等)

这个例子应该有助于:

#!/usr/bin/python
# Copyright (c) 2009 Denis Bilenko. See LICENSE for details.

"""Spawn multiple workers and wait for them to complete"""
from __future__ import print_function
import sys

urls = ['http://www.google.com', 'http://www.yandex.ru', 'http://www.python.org']

import gevent
from gevent import monkey

# patches stdlib (including socket and ssl modules) to cooperate with other greenlets
monkey.patch_all()


if sys.version_info[0] == 3:
    from urllib.request import urlopen
else:
    from urllib2 import urlopen


def print_head(url):
    print('Starting %s' % url)
    data = urlopen(url).read()
    print('%s: %s bytes: %r' % (url, len(data), data[:50]))

jobs = [gevent.spawn(print_head, url) for url in urls]

gevent.wait(jobs)

您可以在hereGithub repository中找到更多信息,本例来自

附则。 greenlet也可以处理请求,您不需要更改代码。

相关问题 更多 >