简体   繁体   English

Python asyncio HTTP请求模块

[英]Python asyncio http request module

Here is how I'm making a request: 这是我发出请求的方式:

    from aiohttp import request
    def make_request(self, request_payload, request_headers, request_method, request_url_path):
        url = self.config["HOST_URL"] + "/" + request_url_path
        response = yield from request(request_method, url=url, params=request_payload, headers=request_headers, allow_redirects=False)
        return response

The expected response in case of successful request here is response status 302 and a Location header in response, which will contain the url on which redirect needs to be done. 在成功请求的情况下,预期的响应是response status 302response status 302Location标头,其中将包含需要在其上进行重定向的url。

The issue is, I'm getting response status as 200, which is response from the final url. 问题是,我的响应状态为200,这是来自最终URL的响应。 How can I achieve what I want? 我怎样才能实现自己想要的?

"allow_redirects=False" should have worked, but it doesn't. “ allow_redirects = False”应该起作用了,但是没有起作用。 I'm not sure how can I get it to work as I need. 我不确定如何使它按需要工作。

Note: if you use old generator-based syntax you should use decorator asyncio.coroutine . 注意:如果使用基于生成器的旧语法,则应使用装饰器asyncio.coroutine If you're using Python 3.5+ use new syntax for coroutines . 如果您使用的是Python 3.5+,请为协程使用新语法

Please provide also minimal code snippet that can be reproduced (including url, other params, your Python version), since I don't get behavior you're talking about: 请提供最少的可复制代码段(包括url,其他参数,您的Python版本),因为我没有得到您正在谈论的行为:

import asyncio
from aiohttp import request


@asyncio.coroutine
def make_request():
    url = 'http://httpbin.org/redirect/1'
    response = yield from request(method='GET', url=url, allow_redirects=False)
    print(response)


loop = asyncio.get_event_loop()
loop.run_until_complete(make_request())

Output: 输出:

<ClientResponse(http://httpbin.org/redirect/1) [302 FOUND]>
<CIMultiDictProxy('Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Wed, 15 Nov 2017 16:28:55 GMT', 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': '215', 'Location': '/get', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000524044036865', 'Via': '1.1 vegur')>

请求支持可选的allow_redirects参数,您可以将其设置为False。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM