'How to get `self` in http Google Cloud Function
I'm trying to use Firebase authentication in a Python HTTP Google Cloud function.
But the function verify_id_token() requires self as an argument. How do I get self in an HTTP Google Cloud Function? This is my current method:
def main(request):
print(self)
# Handle CORS
if request.method == 'OPTIONS':
# Allows GET requests from any origin with the Content-Type
# header and caches preflight response for an 3600s
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Max-Age': '3600'
}
return '', 204, headers
headers = {
'Access-Control-Allow-Origin': '*'
}
# Validate Firebase session
if 'authorization' not in request.headers:
return f'Unauthorized', 401, headers
authorization = str(request.headers['authorization'])
if not authorization.startswith('Bearer '):
return f'Unauthorized', 401, headers
print(authorization)
id_token = authorization.split('Bearer ')[1]
print(id_token)
decoded_token = auths.verify_id_token(id_token)
uid = str(decoded_token['uid'])
if uid is None or len(uid) == 0:
return f'Unauthorized', 401, headers
I already tried adding self as a parameter to the main function, but that does not work since request has to be the first parameter and no second parameter is set, so neither def main(self, request) nor def main(request, self) work.
Solution 1:[1]
main is a method and not a class. Methods that are not members of a class do not have self.
Solution 2:[2]
self is a reference to object itself. Let's say you have a class with properties (methods, attributes). If you want to access to any one of properties inside the class itself, you'll need self (some languages call it this. Such as JavaScript).
If you create an object from that class and want to access to any one of properties you would use the object name.
Example:
class MyClass:
def __init__(self):
pass
def method1(self):
print("Method 1 is called")
def method2(self):
print("I'll call method 1")
self.method1()
See, if one wants to call method2 from method1 they will need self.
But if you create an object from MyClass you can access any property using the variable name:
mc = MyClass()
mc.method1()
TL;DR
You can't (and you do NOT need to) access self outside the scope of a class.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John Hanley |
| Solution 2 | MSH |
