简体   繁体   English

将预定功能导入另一个文件 python

[英]Import a scheduled functions to another file python

I am making a tool to post-registration information to an API, using python.我正在制作一个工具,使用 python 将注册信息发布到 API。 I'm having a problem with the token expiring.我在令牌过期时遇到问题。 The token's expiration time is 300 seconds, so I have to constantly refresh the token.令牌的过期时间是 300 秒,所以我必须不断地刷新令牌。 Is there any way I can schedule a token refresh after 300 seconds?有什么办法可以在 300 秒后安排令牌刷新?

I have a python script in a file called logAPI.py containing multiple tasks, processes and functions (and it works).我在一个名为logAPI.py的文件中有一个 python 脚本,其中包含多个任务、进程和函数(它可以工作)。 I have another file called authorization.py containing a function that calls to authorization API and returns a token so I can call other APIs.我有另一个名为authorization.py的文件,其中包含一个 function 调用授权 API 并返回一个令牌,以便我可以调用其他 API。 Since the token expires time is 300 seconds, I intend to return a new token after 300 seconds.由于令牌过期时间是 300 秒,我打算在 300 秒后返回一个新令牌。

I tried while function, schedule module, cron module and import os but I failed with all.我尝试了 function、调度模块、cron 模块和导入操作系统,但我都失败了。

I think this is the most straightforward solution you can do without having a separate thread to refresh the token.我认为这是最直接的解决方案,您无需使用单独的线程来刷新令牌。

AuthToken contains the active token as well as the logic needed to refresh it. AuthToken包含活动令牌以及刷新它所需的逻辑。 When you need a token, you call AuthToken.get() .当你需要一个令牌时,你调用AuthToken.get() This fetches a new token if it's the first time it's being called, or if the token has expired.如果它是第一次被调用,或者令牌已过期,这将获取一个新令牌。 When the new token is fetched, it's stored in the _auth_token singleton.获取新令牌后,它将存储在_auth_token singleton 中。 This caches it for later and also lets us know when it's expired.这会将其缓存以备后用,并让我们知道它何时过期。

It sounds like you're using multithreading, so I added a Lock to prevent a race condition when calling AuthToken.get()听起来您正在使用多线程,所以我添加了一个Lock以防止在调用AuthToken.get()时出现竞争条件

It's important that you always call AuthToken.get() before making a request.在发出请求之前始终调用AuthToken.get()很重要。 Even just making two requests back-to-back, there's a possibility the token might expire before the second request is sent.即使只是连续发出两个请求,令牌也有可能在发送第二个请求之前过期。

You may also want to adjust the TTL to be slightly lower in case there's latency making the request.您可能还希望将 TTL 调整为稍低一些,以防发出请求时存在延迟。

import requests
import time

from threading import Lock
from typing import Optional
from typing_extensions import Self


class AuthToken:
    """Represents an auth token used by the API."""

    # A singleton AuthToken instance
    _auth_token: Optional[Self] = None
    _lock = Lock()

    # The token's TTL (in seconds)
    ttl = 300

    expires: int
    token: str

    def __init__(self, token):
        self.token = token
        self.expires = time.time() + self.ttl

    def is_expired(self):
        """Returns True if the token is expired."""
        return time.time() >= self.expires

    @classmethod
    def get(cls) -> Self:
        """Returns a valid auth token, refreshing the current one if it's expired."""
        cls._lock.acquire()

        if not cls._auth_token or cls._auth_token.is_expired():
            # do API request...
            token = "foo"
            cls._auth_token = AuthToken(token)

        cls._lock.release()

        return cls._auth_token


def request_that_needs_token():
    auth = AuthToken.get()

    # use auth.token in your request
    requests.post(
        "http://example.com", headers={"Authorization": f"Bearer {auth.token}"}
    )

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

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