python - Mixin 在每次页面加载时返回一个随机对象

标签 python django

我正在尝试编写一个 mixin 来动态生成随机的亚马逊附属广告。我不太确定这是否是解决问题的最佳方式(例如,在模型本身中定义一个返回随机项的方法会更好吗?)...但这就是我所在的位置。

我有两个应用:事件广告。我在 advertisements.views 中的 mixin 看起来像:

class AmazonAdvertisingMixin(object):

    config = {
        # Amazon Config
    }
    api = amazonproduct.API(cfg=config)

    # Get all ads from the database
    ads = Advertisement.objects.filter(network__exact='Amazon')

    if len(ads) > 0:
        ad = random.choice(ads)

        # Get the ASIN from a random ad
        asin = ad.ASIN

        result = api.item_lookup(asin, ResponseGroup='Images, Small')

        advertisement = {
            'product_url': result.Items.Item['DetailPageURL']
        }

        def get_context_data(self, **kwargs):
            context = super(AmazonAdvertisingMixin, self).get_context_data(**kwargs)
            context['advertisement'] = self.advertisement
            return context

然后在我的 events.views 中,我有一个 FormView ,如下所示:

class ContactFormView(AmazonAdvertisingMixin, FormView):

    form_class = ContactForm
    template_name = "contact.html"

    # etc, etc...

这非常适合在联系页面上显示广告。唯一的问题是......当我刷新页面时,广告总是相同的。就好像 mixin 只运行一次。有没有办法让它在每次加载页面时重新运行,以便我可以获取新的 asin

我也愿意接受其他实现最终目标的建议:在每次页面加载时从数据库中选择一个随机广告。想法?

最佳答案

我非常确定广告代码仅在进程启动时运行一次。模型不会为每个页面请求重新加载,而是初始化一次,

如果您将广告逻辑放入 get_context_data 中,它应该在每个请求上加载一个随机广告,因为每个请求都会调用 get_context_data

来自similar我问的问题:

Class attributes are shared across all instances of the class within a process, and since a process lasts across many requests, the data will persist across those requests.

关于python - Mixin 在每次页面加载时返回一个随机对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27215245/

相关文章:

python - 在pycharm中运行nupichelloworld

html - 为什么我的导航栏扩展不正确?

django - 日期和时间合并到日期时间字段

python - 结合不同范围的 Pandas 中的多个箱线图?

新手需要 Python 日志记录帮助

python - Tensorflow 的决策森林如何处理分类数据?

django - Django Admin中多表继承的ValueError

Django 注册/登录不引导用户到 ?next=/my/url

python - Django 保存后无法登录

python - pandas df 中的多列分组和计数总和