Python:函数的每次调用都包含新对象实例

时间:2019-02-20 15:35:10

标签: python django api celery

我正在尝试使用会话令牌和用户ID更新基类以进行长时间轮询。

每次调用函数时,我都会创建一个新实例,该实例调用我不想发生的登录函数。

我只想在值为login()时调用None方法

将会话令牌设置为与get_balance的函数一起使用后,如何返回apiclient实例?

client.py

from __future__ import absolute_import, unicode_literals
import requests
import os
from matchbook import endpoints
class BaseClient(object):

    def __init__(self, username, password=None, locale=None):

        self.username = username
        self.password = password
        self.locale = locale
        self.url_beta = 'https://beta.matchbook.com'
        self.urn_main = '/bpapi/rest/'
        self.session = requests.Session()
        self.session_token = None
        self.user_id = None  

    def set_session_token(self, session_token, user_id):

        self.session_token = session_token
        self.user_id = user_id

class APIClient(BaseClient):

    def __init__(self, username, password=None):
        super(APIClient, self).__init__(username, password)
        self.login = endpoints.Login(self)
        self.account = endpoints.Account(self)

    def __repr__(self):
        return '<APIClient [%s]>' % self.username

    def __str__(self):
        return 'APIClient' 

get_bal.py

from client import APIClient
from celery import shared_task
def get_client():

    apiclient = APIClient(username, password)
    if apiclient.session_token is None:

        apiclient.login()

        session_token = apiclient.session_token
        user_id = apiclient.user_id
        apiclient.set_session_token(session_token,user_id)

    else:
        print('session token assigned',apiclient.session_token, apiclient.user_id)
    return apiclient

@shared_task
def get_balance():
    apiclient = get_client() *to call instance after login is set*
    r = apiclient.account.get_account()
    print(r)

1 个答案:

答案 0 :(得分:0)

您每次调用APIClient时都会创建一个get_client()的新实例,这就是每次get_balance()被调用时都会发生的情况。

您需要在函数范围之外维护APIClient的实例,以使程序继续执行并更新get_balance(),以免每次都不调用get_client()

def get_balance(apiclient):
    r = apiclient.account.get_account()
    print(r)

def main():
    apiclient = get_client()
    get_balance(apiclient)  # pass instance of APIClient in as an argument

get_client()函数中的另一条注释,由于两个if条件彼此相反,只需将它们包装在if... else块中即可:

def get_client():

    apiclient = APIClient(username, password)

    if apiclient.session_token is None:

        apiclient.login()

        session_token = apiclient.session_token
        user_id = apiclient.user_id
        apiclient.set_session_token(session_token,user_id)

    else:
        print('session token assigned',apiclient.session_token, apiclient.user_id)

    return apiclient

所有这些,更多的OOP方法是将get_balance()烘焙到APIClient中作为实例方法,这样您甚至不必担心实例:

class APIClient(BaseClient):

    ...

    def get_balance(self):
        print(self.account.get_account())

# Then just call the get_balance() anywhere:

apiclient = get_client()
apiclient.get_balance()