You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何调用其他模块变量且避免模块重复执行认证逻辑?

解决Python导入认证模块重复执行认证逻辑的方案

问题根源:authfile.py末尾的cookie = auth(url, headers)属于模块顶层可执行代码,Python导入任意模块时都会默认执行模块内所有顶层代码,所以只要导入authfile就会自动触发认证逻辑,生成新的cookie,同时原auth函数定义的self属于多余参数,调用时会直接报错,需要一并修改。

第一步:修改authfile.py,隔离自动执行的认证逻辑

只有直接运行authfile.py时才会执行认证,导入模块时不会触发:

import requests
import hashlib

url = "https://172.16.1.77:8089/api"

headers = {
    'Content-Type': 'application/json;charset=UTF-8',
    'Connection': 'close',
}

# 去掉多余的self参数
def auth(url, headers):
    data = '{"request": {"action":"challenge","user":"apiuser","version":"1.0"}}'
    # 发送challenge请求
    response = requests.post(url, headers=headers, data=data, verify=False)
    # 提取challenge值
    a = response.json()
    b = a['response']
    c = b['challenge']
    print("This is the challenge number: " + c)
    # 拼接密码生成MD5 token
    e = input("Please enter the Password\n")
    user = c+e
    h = hashlib.md5(user.encode())
    md = h.hexdigest()
    print("This is the Token: " + md)
    # 登录获取cookie
    datas = '{"request":{"action":"login", "token":"' + str(md) + '", "url":"' + str(url) + '" , "user": "cdrapi"}}'
    response2 = requests.post(url, headers=headers, data=datas, verify=False)
    f = response2.json()
    g = f['response']
    cookie = g['cookie']
    print("This is the Cookie: " +cookie)
    return cookie

# 仅直接运行本文件时执行,导入时不执行
if __name__ == "__main__":
    cookie = auth(url, headers)

第二步:修改applychanes.py,改为参数传递依赖值

不要直接跨模块导入cookie,改为调用时传入参数,避免不必要的模块导入触发认证:

import requests

# 把需要的url、headers、cookie都改为入参
def changes(url, headers, cookie):
    while True:
        q = input("Are you sure you would like to apply changes?\nPlease enter only Y for Yes and N for No\n").lower()
        if q not in ("y", "n"):
            print("This is not a valid entry")
            continue
        if q == "y":
            postta = '{"request":{"action":"applyChanges", "cookie":"' + str(cookie) + '"}}'
            format_to_json = requests.post(url, headers=headers, data=postta, verify=False)
            jsonresponse = format_to_json.json()
            presponse = jsonresponse['response']
            codestatus = jsonresponse['status']
            print(presponse)
            print(codestatus)
            print("The changes has been applied")
            break
        if q == "n":
            print("NO changes has been made")
            break
    return q

第三步:新增主程序入口,按要求先执行认证

新建main.py作为程序唯一启动入口,统一控制认证逻辑只执行一次:

from authfile import auth, url, headers
from applychanes import changes

if __name__ == "__main__":
    # 最先执行认证逻辑,仅执行一次拿到全局可用的cookie
    current_cookie = auth(url, headers)
    # 多次调用变更逻辑都复用同一个cookie,不会重复生成会话
    changes(url, headers, current_cookie)
    # 后续需要再次调用变更时直接传已经生成的current_cookie即可
    # changes(url, headers, current_cookie)

内容的提问来源于stack exchange,提问作者F3RN4ND

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 22:15:05