-1

I want to update an empty string value which is declared globally. I want to update that variable from inside a function. Following id the code:

import jwt
import os
from dotenv import load_dotenv
load_dotenv()
from rest_framework.exceptions import APIException
jwtPrivateKey = (os.environ.get('SECRET_KEY'))

# VARIABLE DECALRED HERE
token_value = ""
def authenticate(auth_header_value):
    try:
        
        if auth_header_value is not None:
            if len(auth_header_value.split(" ", 1)) == 2:
                authmeth, auth = auth_header_value.split(
                    " ", 1)
                if authmeth.lower() != "bearer" and authmeth.lower() != "basic":
                    return TokenNotBearer()

                # WANT TO UPDATE THE VALUE OF token_value HERE
                token_value= jwt.decode(
                    jwt=auth, key=jwtPrivateKey, algorithms=['HS256', ])     
               
                return TokenVerified()

            else:

                return TokenNotBearer()
        else:
            return TokenNotProvided()
            
    except (TokenExpiredOrInvalid, jwt.DecodeError):
        return TokenExpiredOrInvalid()

# when token is expired or invalid
class TokenExpiredOrInvalid(APIException):
    status_code = 403
    default_detail = "Invalid/Expired token"
    default_code = "forbidden"

# when token is not provided
class TokenNotProvided(APIException):
    status_code = 401
    default_detail = "Access denied. Authorization token must be provided"
    default_code = "unauthorized"

# when the token is not provided in the bearer
class TokenNotBearer(APIException):
    status_code = 401
    default_detail = "Access denied. Authorization token must be Bearer [token]"
    default_code = "token not bearer"

# when the token is valid
class TokenVerified():
    status_code = 200
    default_detail = "Token verified Successfully"
    default_code = "verified"

    # WANT TO USE THE UPDATED VALUE HERE
    data=token_value
    

I want to update the value of the variable token_value from the function authenticate and access it inside the class TokenVerified.

Ritika
  • 131
  • 1
  • 12
  • 1
    to modify a global variable inside a function you need to put `global` followed by the variable name before you modify the variable. in your case that would be `global token_value`. – Clasherkasten Dec 27 '22 at 12:26
  • Please take a look at [this answer](https://stackoverflow.com/a/71537393/17865804) as well. – Chris Dec 27 '22 at 12:29

1 Answers1

3
# WANT TO UPDATE THE VALUE OF token_value HERE
global token_value # add this line
token_value= jwt.decode(jwt=auth, key=jwtPrivateKey, algorithms=['HS256', ])
Nick
  • 101
  • 3