首页 > 解决方案 > 在python中用类定义变量时如何使用self

问题描述

我只是在学习使用函数,现在在 python 中使用类。如果我创建的函数不在一个类中,它们将起作用,但现在我的目标是为它们创建一个类。看起来我不明白它是如何self工作的。我已将它添加为每个函数的参数,但是NameError: name 'variable name' is not defined在调用函数时我遇到了消息。我错过了什么?

myTokClassTst.py这是正在进行的脚本代码:

import time
import json
import jwt
import requests
from lib.jwksutils import rsa_pem_from_jwk

class TokenMgr():
    """An attempt to model a Token Manager"""

    def __init__(self):
        """Initialize token attributes as needed"""
        pass

    def get_kid(self, token):
        headers = jwt.get_unverified_header(token)
        if not headers:
            raise InvalidAuthorizationToken('missing headers')
        try:
            return headers['kid']
        except KeyError:
            raise InvalidAuthorizationToken('missing kid')


    def get_jwk(self, kid):
        with open('testkeys/jwks-keys', 'r') as az:
            jwks = json.load(az)
        for jwk in jwks.get('keys'):
            if jwk.get('kid') == kid:
                print ('This is the jwk:', jwk)
                return jwk
        raise InvalidAuthorizationToken('kid not recognized')


    def get_public_key(self, token):
        print ('Response from get_public_token:', rsa_pem_from_jwk(get_jwk(get_kid(token))) )
        return rsa_pem_from_jwk(get_jwk(get_kid(token)))


    def validate_jwt(self, jwt_to_validate):
        public_key = get_public_key(jwt_to_validate)
        #Hard coding these for now
        valid_audiences = ['abc123aa86-1f3a-4774-8bae-2704bff9f797'] 
        issuer = 'https://login.microsoftonline.com/99c77bbe-8598-4b85-9e51-1ca753fa50f2/v2.0'
        decoded = jwt.decode(jwt_to_validate,
                            public_key,
                            verify=True,
                            algorithms=['RS256'],
                            audience=valid_audiences,
                            issuer=issuer)
        print('This is decoded:', decoded)

我在 python shell 中像这样调用函数:

$ python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import myTokClassTst as mytok
>>> idval = mytok.TokenMgr()
>>> idval.validate_jwt('eyJ0eXAiOiJKV1QiLCJhbGciOiJSUA')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\myTokClassTst.py", line 97, in validate_jwt
    public_key = get_public_key(jwt_to_validate)
NameError: name 'get_public_key' is not defined

标签: pythonpython-3.x

解决方案


使用self.get_public_key,因为您试图调用相同的类方法。get_jwk和_get_kid

最终代码:

import time
import json
import jwt
import requests
from lib.jwksutils import rsa_pem_from_jwk

class TokenMgr():
    """An attempt to model a Token Manager"""

    def __init__(self):
        """Initialize token attributes as needed"""
        pass

    def get_kid(self, token):
        headers = jwt.get_unverified_header(token)
        if not headers:
            raise InvalidAuthorizationToken('missing headers')
        try:
            return headers['kid']
        except KeyError:
            raise InvalidAuthorizationToken('missing kid')


    def get_jwk(self, kid):
        with open('testkeys/jwks-keys', 'r') as az:
            jwks = json.load(az)
        for jwk in jwks.get('keys'):
            if jwk.get('kid') == kid:
                print ('This is the jwk:', jwk)
                return jwk
        raise InvalidAuthorizationToken('kid not recognized')


    def get_public_key(self, token):
        print ('Response from get_public_token:', rsa_pem_from_jwk(self.get_jwk(self.get_kid(token))) )
        return rsa_pem_from_jwk(self.get_jwk(self.get_kid(token)))


    def validate_jwt(self, jwt_to_validate):
        public_key = self.get_public_key(jwt_to_validate)
        #Hard coding these for now
        valid_audiences = ['abc123aa86-1f3a-4774-8bae-2704bff9f797'] 
        issuer = 'https://login.microsoftonline.com/99c77bbe-8598-4b85-9e51-1ca753fa50f2/v2.0'
        decoded = jwt.decode(jwt_to_validate,
                            public_key,
                            verify=True,
                            algorithms=['RS256'],
                            audience=valid_audiences,
                            issuer=issuer)
        print('This is decoded:', decoded)

推荐阅读