在Python的gevent框架下执行异步的Solr查询的教程

yipeiwu_com5年前Python基础

 我经常需要用Python与solr进行异步请求工作。这里有段代码阻塞在Solr http请求上, 直到第一个完成才会执行第二个请求,代码如下:
 

import requests
 
#Search 1
solrResp = requests.get('http://mysolr.com/solr/statedecoded/search?q=law')
 
for doc in solrResp.json()['response']['docs']:
  print doc['catch_line']
 
#Search 2
solrResp = requests.get('http://mysolr.com/solr/statedecoded/search?q=shoplifting')
 
for doc in solrResp.json()['response']['docs']:
  print doc['catch_line']

(我们用Requests库进行http请求)

通过脚本把文档索引到Solr, 进而可以并行工作是很好的。我需要扩展我的工作,因此索引瓶颈是Solr,而不是网络请求。


不幸的是,当进行异步编程时python不像Javascript或Go那样方便。但是,gevent库能给我们带来些帮助。gevent底层用的是libevent库,构建于原生异步调用(select, poll等原始异步调用),libevent很好的协调很多低层的异步功能。

使用gevent很简单,让人纠结的一点就是thegevent.monkey.patch_all(), 为更好的与gevent的异步协作,它修补了很多标准库。听起来很恐怖,但是我还没有在使用这个补丁实现时遇到 问题。


事不宜迟,下面就是你如果用gevents来并行Solr请求:
 

import requests
from gevent import monkey
import gevent
monkey.patch_all()
 
 
class Searcher(object):
  """ Simple wrapper for doing a search and collecting the
    results """
  def __init__(self, searchUrl):
    self.searchUrl = searchUrl
 
  def search(self):
    solrResp = requests.get(self.searchUrl)
    self.docs = solrResp.json()['response']['docs']
 
 
def searchMultiple(urls):
  """ Use gevent to execute the passed in urls;
    dump the results"""
  searchers = [Searcher(url) for url in urls]
 
  # Gather a handle for each task
  handles = []
  for searcher in searchers:
    handles.append(gevent.spawn(searcher.search))
 
  # Block until all work is done
  gevent.joinall(handles)
 
  # Dump the results
  for searcher in searchers:
    print "Search Results for %s" % searcher.searchUrl
    for doc in searcher.docs:
      print doc['catch_line']
 
searchUrls = ['http://mysolr.com/solr/statedecoded/search?q=law',
       'http://mysolr.com/solr/statedecoded/search?q=shoplifting']

 
searchMultiple(searchUrls)
代码增加了,而且不如相同功能的Javascript代码简洁,但是它能完成相应的工作,代码的精髓是下面几行:
 

# Gather a handle for each task
handles = []
for searcher in searchers:
  handles.append(gevent.spawn(searcher.search))
 
# Block until all work is done
gevent.joinall(handles)

我们让gevent产生searcher.search, 我们可以对产生的任务进行操作,然后我们可以随意的等着所有产生的任务完成,最后导出结果。

差不多就这样子.如果你有任何想法请给我们留言。让我们知道我们如何能为你的Solr搜索应用提供帮助。

相关文章

Python中Selenium模拟JQuery滑动解锁实例

Python中Selenium模拟JQuery滑动解锁实例

本文介绍了Python中Selenium模拟JQuery滑动解锁实例,分享给大家,也给自己留个笔记 滑动解锁一直做UI自动化的难点之一,我补一篇滑动解锁的例子,希望能给初做Web UI自...

浅谈pyhton学习中出现的各种问题(新手必看)

目前比较杂乱无章,后续还会有一些添加补充 1、标识符 (1)标识符是区分大小写的。 (2)标示符以字母或下划线开头,可包括字母,下划线和数字。 (3)以下划线开头的标识符是有特殊意义的。...

Python将图片转换为字符画的方法

Python将图片转换为字符画的方法

最近在学习Python,看到网上用Python将图片转换成字符画便来学习一下 题目意思是,程序读入一个图片,以txt格式输出图片对应的字符画,如图所示: 以下是Python代码:...

python获取指定路径下所有指定后缀文件的方法

本文实例讲述了python获取指定路径下所有指定后缀文件的方法。分享给大家供大家参考。具体实现方法如下: # 获取指定路径下所有指定后缀的文件 # dir 指定路径 # ext 指定...

Python读写及备份oracle数据库操作示例

Python读写及备份oracle数据库操作示例

本文实例讲述了Python读写及备份oracle数据库操作。分享给大家供大家参考,具体如下: 最近项目中需要用到Python调用oracle实现读写操作,踩过很多坑,历尽艰辛终于实现了。...