首页 > 解决方案 > 如何从 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)

标签: django

解决方案


回答你的问题

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))

推荐阅读