在 Twisted 客户端中生成标头

发布于 2024-09-10 11:43:46 字数 765 浏览 3 评论 0原文

我正在使用 Twisted Web“HTTPClient”协议与 http 服务器对话(使用 Twisted 应用程序作为客户端),问题是我的大多数请求不接受我的标头。是否有某种方法(也许使用某些库)来生成标头? 我将发布一些代码,以便您可以查看

class Local(HTTPClient):
def generateHeaders(self, type=None):
    self.sendHeader('User-Agent', 'Twisted Web Client')
    if type:
        self.sendHeader('Content-Type', 'x-www-form-urlencoded')
    self.sendHeader('Accept', '*/*')
    self.sendHeader('Host', 'localhost')
    self.endHeaders()

def connectionMade(self):
    ## GENERATE ID
    self.userid= self.generateID()
    self.sendCommand('POST', '/chat/action=join&user=pirosb3')
    self.generateHeaders(type=True)

def dataReceived(self, data):
    print data

如您所见,我创建了一个为我生成标头的方法,但我必须说效率不是很高,我总是收到错误响应。

有人知道解决办法吗?

谢谢

i'm using the Twisted web "HTTPClient" protocol to dialogue with a http server (using twisted app as a client), the problem is that most of my request do not accept my header. Is there some sort of way (maybe using certain libraries) to generate header??
I'll post some code so you can have a look

class Local(HTTPClient):
def generateHeaders(self, type=None):
    self.sendHeader('User-Agent', 'Twisted Web Client')
    if type:
        self.sendHeader('Content-Type', 'x-www-form-urlencoded')
    self.sendHeader('Accept', '*/*')
    self.sendHeader('Host', 'localhost')
    self.endHeaders()

def connectionMade(self):
    ## GENERATE ID
    self.userid= self.generateID()
    self.sendCommand('POST', '/chat/action=join&user=pirosb3')
    self.generateHeaders(type=True)

def dataReceived(self, data):
    print data

As you can see, i created a method that generates header for me, but not very efficient i must say, i always get error responses.

Anyone know a solution?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

水水月牙 2024-09-17 11:43:46

我绝对推荐您使用 Twisted 的 Agent 类以及 twisted.web.http_headers 模块中的 Header 类。

此处提供了一个很好的指南。

如果您需要一个现实生活中的 Twisted HTTP 客户端示例,该客户端向请求添加一些标头并可以读取答案的标头,这里是:

from pprint import pformat

from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.client import Agent
from twisted.web.http_headers import Headers

class BeginningPrinter(Protocol):
    def __init__(self, finished):
        self.finished = finished
        self.remaining = 1024 * 10

    def dataReceived(self, bytes):
        if self.remaining:
            display = bytes[:self.remaining]
            print 'Some data received:'
            print display
            self.remaining -= len(display)

    def connectionLost(self, reason):
        print 'Finished receiving body:', reason.getErrorMessage()
        self.finished.callback(None)

agent = Agent(reactor)
d = agent.request(
    'GET',
    'http://example.com/',
    Headers({'User-Agent': ['Twisted Web Client Example']}),
    None)

def cbRequest(response):
    print 'Response version:', response.version
    print 'Response code:', response.code
    print 'Response phrase:', response.phrase
    print 'Response headers:'
    print pformat(list(response.headers.getAllRawHeaders()))
    finished = Deferred()
    response.deliverBody(BeginningPrinter(finished))
    return finished
d.addCallback(cbRequest)

def cbShutdown(ignored):
    reactor.stop()
d.addBoth(cbShutdown)

reactor.run()

I would definitely recommend you to use Twisted's Agent class along with the Header class in the twisted.web.http_headers module.

There is a nice guide available here.

If you need a real life example of a Twisted HTTP client which adds some headers to the request and can read the ones of the answer, here it is:

from pprint import pformat

from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.client import Agent
from twisted.web.http_headers import Headers

class BeginningPrinter(Protocol):
    def __init__(self, finished):
        self.finished = finished
        self.remaining = 1024 * 10

    def dataReceived(self, bytes):
        if self.remaining:
            display = bytes[:self.remaining]
            print 'Some data received:'
            print display
            self.remaining -= len(display)

    def connectionLost(self, reason):
        print 'Finished receiving body:', reason.getErrorMessage()
        self.finished.callback(None)

agent = Agent(reactor)
d = agent.request(
    'GET',
    'http://example.com/',
    Headers({'User-Agent': ['Twisted Web Client Example']}),
    None)

def cbRequest(response):
    print 'Response version:', response.version
    print 'Response code:', response.code
    print 'Response phrase:', response.phrase
    print 'Response headers:'
    print pformat(list(response.headers.getAllRawHeaders()))
    finished = Deferred()
    response.deliverBody(BeginningPrinter(finished))
    return finished
d.addCallback(cbRequest)

def cbShutdown(ignored):
    reactor.stop()
d.addBoth(cbShutdown)

reactor.run()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文