首页 > 解决方案 > 如何在 html div 中显示 Python print()

问题描述

我正在使用 Django 编写我的网站。在编写 Python 代码期间,我有许多打印函数。它们都显示在标准控制台中。我想在我的 HTML 代码中显示(无需刷新页面即可实时显示)我在 div 中的所有打印,而不仅仅是在控制台中。怎么做?我的代码是这样的:您按下按钮然后 selenium 开始使用 ajax 而不刷新页面,在此期间我想使用 div 在页面上显示进度。

例如,我的代码:

views.py
bot = Instagram()

class InstabotFormView(AjaxFormMixin, FormView):
    form_class = LoginInstagramForm
    template_name = 'instabot.html'
    success_url = 'runinstabot.html'

    def form_invalid(self, form):
        response = super(InstabotFormView, self).form_invalid(form)
        if self.request.is_ajax():
            return JsonResponse(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        response = super(InstabotFormView, self).form_valid(form)
        login = form.cleaned_data.get('login')
        password = form.cleaned_data.get('password')
        tagi = form.cleaned_data.get('tags')
        func = form.cleaned_data.get('function')
        tags = []
        tagi = tagi.split(',')
        tags.extend(tagi)
        if self.request.is_ajax():
            print('It is AJAX')
            bot.login(login,password)
            bot.search(tags)
            if func == '1':
                bot.downloadPhoto(tags)
            elif func == '2':
                bot.doCalculation(tags)
            print(tags)
            data = {
                'message': "Succesfully  opened Selenium."
            }
            return JsonResponse(data)
        else:
            return response

Instagram()
    def downloadPhoto(self):
        i = 0
        time.sleep(2)
        self.driver.find_element_by_xpath('/html/body/span/section/main/div/header/section/ul/li[2]/a').click()
        print('Start function downloadPhoto')
        print(self.myCurrentList)

        for photo in self.myCurrentList:
            followerPhoto = self.myCurrentList.index(photo) + 1
            print(followerPhoto)

如何在 html div 中显示 def downloadPhoto(self) 的所有打印件?

标签: pythonajaxdjango

解决方案


打印不应在 django 应用程序中使用。如果你想打印有用的信息,你必须使用python提供的日志工具和django中的好文档:https ://docs.djangoproject.com/en/2.1/topics/logging/

要实时向您的客户端发送通知,您必须full duplex在客户端和服务器之间实现一个通道。让你这样做的技术是websocket,你可以使用包 django-channels 在你的项目中实现 websocket。请记住,对您的基础架构进行一些更改是必要的。


推荐阅读