使用Python请求重新使用Django中的连接 [英] Reusing connections in Django with Python Requests

查看:168
本文介绍了使用Python请求重新使用Django中的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中多次使用 Python请求连接的正确方法是什么? HTTP请求。这就是我目前正在做的:

What's the correct way of reusing Python Requests connections in Django across multiple HTTP requests. That's what I'm doing currently:

import requests

def do_request(data):
    return requests.get('http://foo.bar/', data=data, timeout=4)

def my_view1(request)
    req = do_request({x: 1})
    ...

def my_view2(request)
    req = do_request({y: 2})
    ...

所以,我有一个发出请求的函数。这个函数在各种Django视图中被调用。用户在单独的HTTP请求中调用视图。我的问题是:Python请求自动重复使用相同的连接< a>(通过urllib3连接池)?

So, I have one function that makes the request. This function is called in various Django views. The views get called in separate HTTP requests by users. My question is: Does Python Requests automatically reuse the same connections (via urllib3 connection pooling)?

或者我必须先创建一个请求会话对象来处理吗?

Or do I have to first create a Requests session object to work with?

s = requests.Session()  

def do_request(data):
    return s.get('http://foo.bar/', data=data, auth=('user', 'pass'), timeout=4).text

如果是,会话对象必须在全局范围内创建,还是应该在函数内?

And if so, does the session object have to be created in global scope or should it be inside the function?

def do_request(data):
    s = requests.Session()  
    return s.get('http://foo.bar/', data=data, auth=('user', 'pass'), timeout=4).text

我可以同时拥有多个HTTP请求,所以解决方案需要线程安全...我是一个新手连接池,所以我真的不是sur e和请求文档在这里不是很广泛。

I can have multiple HTTP requests at the same time, so the solution needs to e thread safe ... I'm a newbie to connection pooling, so I really am not sure and the Requests docs aren't that extensive here.

推荐答案

创建一个会话,通过传递函数来保持会话并返回它,或在全局级别或类级别创建会话对象,因此每当引用最新状态时都会保持最新状态。它将像一个魅力一样工作。

Create a session, keep the session maintained by passing it through functions and returning it, or create the session object at global level or class level, so the latest state is maintained whenever it is referenced. And it will work like a charm.

这篇关于使用Python请求重新使用Django中的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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