登录
首页 >  Golang >  Go问答

异步通信框架:Go/Python 桥

来源:stackoverflow

时间:2024-02-11 11:45:24 266浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《异步通信框架:Go/Python 桥》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我编写了一个客户端来处理较低级别的 tls 连接参数,例如 clienthellos 等。

我在 go 中做到了这一点,因为它更容易。我的主程序(webscraper)是用python编写的。我通过 ctypes 通过 dll 将 go 源连接到我的 python 文件。到目前为止,我的网络爬虫结构是异步的,可以一次处理多个连接。

不幸的是,我的 go 客户端不是异步的。有没有一种方法可以在python中更改它,以便它异步等待来自ctypes指针的响应,直到它到达为止?现在它正在等待响应,但显然同时会阻止所有其他代码执行。

编辑: 代码示例如下

async def request(self, method, url, headers, body=None, rawBody=None, pseudoHeaderOrder=["method", "authority", "scheme", "path"]):
        global httpLib
        global initFunc
        global requestFunc
        global changeProxyFunc
        global freePointerFunc
        config = {
            "id": self.cid,
            "method": method.upper(),
            "timeout": 20000,
            "url": url,
            "pseudoHeaderOrder": pseudoHeaderOrder,
            "headers": headers
        }
        #Critical
        if body:
            config["body"] = body
        if rawBody:
            rawBody = [b for b in bytes(rawBody, "utf-8")]
            config["rawBody"] = rawBody
        config = json.dumps(config)
        #print(config)
        #THIS PART CASTS THE REQUEST
        ptr = requestFunc(config.encode('utf-8'))
        string = ctypes.cast(ptr, ctypes.c_char_p).value.decode("utf-8")
        #THIS PART CLEARS THE POINTER
        freePointerFunc(ptr)
        #...

正确答案


您可以使用 executor 将阻塞调用移至单独的线程/进程。

像这样的东西应该有效,

async def request(self, method, url, headers, body=None, rawBody=None, pseudoHeaderOrder=["method", "authority", "scheme", "path"]):
        global httpLib
        global initFunc
        global requestFunc
        global changeProxyFunc
        global freePointerFunc
        config = {
            "id": self.cid,
            "method": method.upper(),
            "timeout": 20000,
            "url": url,
            "pseudoHeaderOrder": pseudoHeaderOrder,
            "headers": headers
        }
        #Critical
        if body:
            config["body"] = body
        if rawBody:
            rawBody = [b for b in bytes(rawBody, "utf-8")]
            config["rawBody"] = rawBody
        config = json.dumps(config)
        
        # Move blocking code to separate function
        def blocking_io():
          ptr = requestFunc(config.encode('utf-8'))
          string = ctypes.cast(ptr, ctypes.c_char_p).value.decode("utf-8")
          freePointerFunc(ptr)
          return string

        # Aschronously wait on the result
        loop = asyncio.get_running_loop()
        string = await loop.run_in_executor(None, blocking_io)
        
        #...

今天关于《异步通信框架:Go/Python 桥》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>