简体   繁体   English

在多种功能中使用身份验证凭据

[英]Using authentication credentials in multiple functions

I'm writing a script that uses the requests library to obtain API data from a website requiring authentication. 我正在编写一个脚本,该脚本使用请求库从需要身份验证的网站获取API数据。 From my understanding and testing, the site doesn't seem to use auth-saving cookies, so authentication is required with each request, such as this: 根据我的理解和测试,该站点似乎未使用可保存身份验证的Cookie,因此每个请求都需要身份验证,例如:

page = requests.get('http://a_url.com', auth=(uname, pword))

This is fine for what I need except , that I have specific tasks split up into separate functions that handle different data in different ways. 我需要的工作 ,这很合适,因为我将特定的任务分解为多个单独的函数,以不同的方式处理不同的数据。 The only commonality is that they all require the username and password (obtained at the command line), so I've ended up with just short of every function taking "uname" and "pword" as their first parameters, followed by any other necessary params: 唯一的共同点是它们需要用户名和密码(在命令行中获得),因此最后我得到的每个函数都以“ uname”和“ pword”为第一个参数,然后再加上其他必需的参数:

def get_all_projects(uname, pword):
    # function

def get_single_project(uname, pword, project_name):
    # function

def get_select_projects(uname, pword, projects):
    for project in projects:
        get_single_project(uname, pword, project)

# Etc...

Aside from turning the script into a class, is there any other way to deliver the credentials to the functions that need them without having to parameterize them? 除了将脚本转换为类之外,还有其他方法可以将凭据传递给需要它们的功能,而不必对其进行参数化吗? Requests.Session() won't work, since as stated above I need to include the auth with each call to get. Requests.Session()无效,因为如上所述,我需要在每次调用get时都包含auth。 I feel like a decorator would fit the situation well, but I don't understand them well enough yet to be able to confirm that belief. 我觉得装饰工很适合这种情况,但是我对它们的理解还不够,无法确认这一信念。

As @barny pointed out, I missed the fact that you can indeed pass authentication to a requests.Session() via the following (from the docs and barny's comment): 正如@barny指出的那样,我错过了一个事实,您确实可以通过以下方式将身份验证传递给request.Session():(来自文档和barny的评论):

s = requests.Session()
s.auth = (uname, pword)

so my url request from the op can now just be: 因此,我从op发出的url请求现在可以是:

page = s.get('http://a_url.com')

with the auth automatically included as long as the session is active. 只要会话处于活动状态,就会自动包含身份验证。

Along with that, my functions can now be condensed to just using the session object as a param instead of the username and password each time: 除此之外,我的功能现在可以简化为仅使用会话对象作为参数,而不是每次使用用户名和密码:

def get_all_projects(s):
    # function

def get_single_project(s, project_name):
    # function

def get_select_projects(s, projects):
    for project in projects:
        get_single_project(s, project)

# Etc...

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

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