如何通过python扭曲的HTTPClient生成POST和GET请求?

时间:2019-03-18 02:22:15

标签: python http web client twisted

我正在编写一个HTTP客户端。这是一个简单的模拟银行网站。它需要能够发出两种请求:

  1. 用户登录时: 开机自检/登录?user = bob&pass = abc123 HTTP / 1.1 主持人:bank.com
  2. 用户转帐时: GET / transfer?to = badguy&amt = 100 HTTP / 1.1 主持人:bank.com Cookie:login = fde874

我正在通过扭曲的python实现它,我编写了HTTPClient的子类:

class BankClient(HTTPClient):
    def genReq():
       # How to write code to generate and send the Two request?

    def connectionMode(self):
        genReq()



class BankCllientFactory(ClientFactory):
    protocol = BankClient
    def __init__(self):
       self.done = Defered()


def main(reactor):
   factory= BankClientFactory()
   reactor.connectTCP('localhost',8080,factory)
   return factory.done
if __name__ =='__main__':
    task.react(main)

1 个答案:

答案 0 :(得分:0)

您要停止使用HTTPClient。而是使用Agent或第三方treq

使用GET生成POSTAgent

from twisted.web.client import Agent
from twisted.internet import reactor
agent = Agent(reactor)
d_get = agent.request(b"GET", uri)
d_post = agent.request(b"POST", uri)

使用GET生成POSTtreq

import treq
d_get = treq.get(url)
d_post = treq.post(url)