您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何一次在python中发送异步http请求?

5b51 2022/1/14 8:20:30 python 字数 3218 阅读 451 来源 www.jb51.cc/python

我们有一系列工作,工人一次处理这些工作.每个作业都要求我们格式化一些数据并发出HTTP POST请求,并将数据作为请求有效负载. 我们如何让每个工作人员以单线程,非阻塞方式异步发出这些HTTP POST请求?我们不关心请求的响应 – 我们想要的只是请求尽快执行,然后让工作人员立即进入下一个工作. 我们已经探索了使用gevent和grequests库(参见Why does gevent.spawn

概述

我们如何让每个工作人员以单线程,非阻塞方式异步发出这些HTTP POST请求?我们不关心请求的响应 – 我们想要的只是请求尽快执行,然后让工作人员立即进入下一个工作.

我们已经探索了使用gevent和grequests库(参见Why does gevent.spawn not execute the parameterized function until a call to Greenlet.join?).我们的工作代码看起来像这样:

def execute_task(worker,job):

    print "About to spawn request"
    greenlet = gevent.spawn(requests.post,url,params=params)

    print "Request spawned,about to call sleep"
    gevent.sleep()

    print "Greenlet status: ",greenlet.ready()

执行第一个print语句,但第二个和第三个打印语句永远不会打印,并且永远不会命中url.

我们如何才能执行这些异步请求?

2)根据您的喜好制作尽可能多的“工作”线程,从Queue.Queue读取

3)将作业提供给Queue.Queue

工作线程将按照它们放置的顺序读取Queue.Queue

文件中读取行并将它们放入Queue.Queue的示例

import sys
import urllib2
import urllib
from Queue import Queue
import threading
import re

THEEND = "TERMINATION-Now-THE-END"


#read from file into Queue.Queue asynchronously
class QueueFile(threading.Thread):
    def run(self):
        if not(isinstance(self.myq,Queue)):
            print "Queue not set to a Queue"
            sys.exit(1)
        h = open(self.f,'r')
        for l in h:
            self.myq.put(l.strip())  # this will block if the queue is full
        self.myq.put(THEEND)

    def set_queue(self,q):
        self.myq = q

    def set_file(self,f):
        self.f = f

了解工作线程可能是什么样的(仅限示例)

class myWorker(threading.Thread):
    def run(self):
        while(running):           
            try:
                data = self.q.get()  # read from fifo

                req = urllib2.Request("http://192.168.1.10/url/path")
                req.add_data(urllib.urlencode(data))
                h1 = urllib2.urlopen(req,timeout=10)
                res = h1.read()
                assert(len(res) > 80)

            except urllib2.HTTPError,e:
                print e

            except urllib2.URLError,e:
                print "done %d reqs " % n
                print e
                sys.exit()

要使对象基于threading.Thread go,创建对象然后在实例上调用“start”

总结

以上是编程之家为你收集整理的如何一次在python中发送异步http请求?全部内容,希望文章能够帮你解决如何一次在python中发送异步http请求?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶