将视图中的函数转换为异步函数。Django/Python

2024-06-25 06:43:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想听听您对如何将下面的函数转换成异步函数的看法。你知道吗

def currency_converter(price, curr1="SEK", curr2="EUR"):  
    c = CurrencyConverter()
    try:
        return c.convert(price, curr1, curr2)
    except ValueError or RateNotFoundError as err:
        return str(err)

此函数接受价格、两种货币代码并将价格转换为所选货币。问题是,当您在循环中使用此函数时,每次迭代都需要一段时间向web主机发送和接收请求(对于20个请求,大约需要2-3秒)

此函数用于DJANGO中的以下视图:


class BlocketView(DetailView):
    model = BoatModel
    template_name = 'blocket.html'

    def get_context_data(self, **kwargs):
        context = DetailView.get_context_data(self, **kwargs)
        context["blocket"], context['pricelist'] = (spider(self.kwargs.get("name")))
        context["pricelist_euro"] = [currency_converter(price) for price in context['pricelist']]
        return context

在这里,它从pricelist获取价格,并用转换后的价格生成新的上下文[“pricelist\u euro”]列表。你知道吗

此函数也可用作模板筛选器:


@register.filter
def currency_converter(price, curr1="SEK", curr2="EUR"):
    c = CurrencyConverter()
    try:
        return c.convert(price, curr1, curr2)
    except ValueError or RateNotFoundError as err:
        return str(err)

有没有可能把这个函数转换成异步函数?你知道吗

谢谢


Tags: 函数selfgetreturndefcontext价格price
1条回答
网友
1楼 · 发布于 2024-06-25 06:43:29

最后我决定计算汇率1倍,然后用它来转换其余的价格。不过还是挺慢的。你知道吗

    def get_context_data(self, **kwargs):
        context = DetailView.get_context_data(self, **kwargs)
        context["blocket"], context['pricelist'] = (spider(self.kwargs.get("name")))
        rate = currency_converter(1000)
        context["pricelist_euro"] = []
        for price in context['pricelist']:
                try:
                    context["pricelist_euro"].append(int(price/rate))
                except TypeError:
                    context["pricelist_euro"].append(None)
        return context

相关问题 更多 >