禁用python中的nagle:如何正确执行操作? [英] Disabling nagle in python: how to do it the right way?

查看:226
本文介绍了禁用python中的nagle:如何正确执行操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在python2.6中禁用nagle算法. 我发现以这种方式在httplib.py中修补HTTPConnection

I need to disable nagle algorithm in python2.6. I found out that patching HTTPConnection in httplib.py that way

    def connect(self):
        """Connect to the host and port specified in __init__."""
        self.sock = socket.create_connection((self.host,self.port),
                                         self.timeout)
        self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) # added line

起到了作用.

很明显,如果可能的话,我想避免修补系统库.因此,问题是:做这种事情的正确方法是什么? (我是python的新手,在这里很容易错过一些明显的解决方案)

Obviously, I would like to avoid patching system lib if possible. So, the question is: what is right way to do such thing? (I'm pretty new to python and can be easily missing some obvious solution here)

推荐答案

不可能更改httplib指定的套接字选项,也不能传入您自己的套接字对象.在我看来,这种缺乏灵活性是大多数Python HTTP库的最大弱点.例如,在Python 2.6之前,甚至不可能为连接指定超时(除非使用 socket.setdefaulttimeout()全局,这不是很干净).

It's not possible to change the socket options that httplib specifies, and it's not possible to pass in your own socket object either. In my opinion this sort of lack of flexibility is the biggest weakness of most of the Python HTTP libraries. For example, prior to Python 2.6 it wasn't even possible to specify a timeout for the connection (except by using socket.setdefaulttimeout() globally, which wasn't very clean).

如果您不介意外部依赖性,则它看起来像

If you don't mind external dependencies, it looks like httplib2 already has TCP_NODELAY specified.

可以猴子修补该库.由于python是一种动态语言,并且或多或少的所有事情都是在运行时作为名称空间查找完成的,因此您只需在相关类上替换适当的方法即可:

You could monkey-patch the library. Because python is a dynamic language and more or less everything is done as a namespace lookup at runtime, you can simply replace the appropriate method on the relevant class:

:::python
import httplib

def patch_httplib():
    orig_connect = httplib.HTTPConnection.connect
    def my_connect(self):
        orig_connect(self)
        self.sock.setsockopt(...)

但是,这非常容易出错,因为这意味着您的代码变得非常特定于特定的Python版本,因为这些库函数和类的确发生了变化.例如,在2.7中,有一个调用_tunnel()的方法,该方法使用套接字,因此您需要挂在connect()方法的中间-猴子补丁处理非常棘手.

However, this is extremely error-prone as it means that your code becomes quite specific to a particular Python version, as these library functions and classes do change. For example, in 2.7 there's a _tunnel() method called which uses the socket, so you'd want to hook in the middle of the connect() method - monkey-patching makes that extremely tricky.

简而言之,恐怕我不认为有一个简单的答案.

In short, I don't think there's an easy answer, I'm afraid.

这篇关于禁用python中的nagle:如何正确执行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆