django - 如何从 Django 中的views.py 调用基于类的模板标签?
问题描述
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)
解决方案
回答你的问题
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)
使用模板标签的要点是在模板渲染时运行一些逻辑......在您的视图中,您已经可以访问在 python 中编写逻辑,如果您的模板标签中有一些逻辑必须在您的应用程序中使用,那么您应该编写它作为方法(类,静态或任何其他)并在您的模板标签中调用此方法...这样您就可以在您的应用程序之间共享此逻辑
在您项目的某个文件中(也许是模型,也许是实用程序)
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))
推荐阅读
- java - 如何检索 GPO 设置
- python - CSV To headers 和 Exploding results into custom class
- python - 如何将变量设置的范围内的所有数字相加?
- ibm-midrange - JT400向队列发送消息(即SNDMSG)
- python - 如何仅使用内存从从 Internet 下载的存档中提取特定文件
- javascript - 错误或我在 inboxsdk“提交”事件中出错
- python - python简单的loop_.join函数
- node.js - 为什么grpc使用了错误的版本?
- c# - 使用 C# 从 MSSQL 动态创建类和可枚举对象
- excel - 当另一个工作表处于活动状态时,Excel VBA 宏不会删除单元格