CoinbaseWalletAuth.py
from django import template
register = template.Library()
API_KEY = '******************'
API_SECRET = '***************'
class CoinbaseWalletAuth(AuthBase):
def __init__(self, api_key, secret_key):
self.api_key = api_key
self.secret_key = secret_key
def __call__(self, request):
timestamp = str(int(time.time()))
message = timestamp + request.method + request.path_url + (request.body or '')
signature = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest()
request.headers.update({
'CB-ACCESS-SIGN': signature,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': self.api_key,
})
print('hello')
return request
register.tag('CoinbaseWalletAuth', CoinbaseWalletAuth(API_KEY,API_SECRET))
Views.py
def test(request):
if request.method == 'POST':
api_url = 'https://api.coinbase.com/v2/'
auth = CoinbaseWalletAuth # call the class based function in views(This is not working)
r = requests.get(api_url + 'user', auth=auth)
data= r.json()
return HttpResponse(data)
答案 0 :(得分:0)
回答您的问题
from .templatetags.CoinbaseWalletAuth import CoinbaseWalletAuth
def test(request):
if request.method == 'POST':
api_url = 'https://api.coinbase.com/v2/'
auth = CoinbaseWalletAuth # call the class based function in views(This is not working)
r = requests.get(api_url + 'user', auth=auth)
data= r.json()
return HttpResponse(data)
使用templatetags的要点是在渲染模板时运行somelogic ...在您的视图中,您已经可以使用python编写逻辑,如果您必须在应用程序中使用templatetag的某些逻辑,那么您应该将其编写为方法(类,静态或其他方法),并在您的templatetag中调用此方法...,以便您可以在应用之间共享此逻辑
在您项目的某些文件中(可能是模型,也可能是实用程序)
CoinbaseWalletAuth.py
API_KEY = '******************'
API_SECRET = '***************'
class CoinbaseWalletAuth(AuthBase):
def __init__(self, api_key, secret_key):
...
def __call__(self, request):
...
return request
coinbase_templatetag.py
from django import template
from .utils import CoinbaseWalletAuth # utils will the folder that you store that file
register = template.Library()
register.tag('CoinbaseWalletAuth', CoinbaseWalletAuth(API_KEY,API_SECRET))