python - 如何在 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) 的所有打印件?
解决方案
打印不应在 django 应用程序中使用。如果你想打印有用的信息,你必须使用python提供的日志工具和django中的好文档:https ://docs.djangoproject.com/en/2.1/topics/logging/
要实时向您的客户端发送通知,您必须full duplex
在客户端和服务器之间实现一个通道。让你这样做的技术是websocket
,你可以使用包 django-channels 在你的项目中实现 websocket。请记住,对您的基础架构进行一些更改是必要的。
Django-channels 包:https ://github.com/django/channels
一个教程:https ://realpython.com/getting-started-with-django-channels/
推荐阅读
- javascript - Gatsby:“警告有多个模块的名称只是大小写不同。这可能导致意外行为......”
- sql - TSQL Cross Apply 确定要查询的数据库
- mongoose - 代理背后的猫鼬。如何通过代理连接到 mongoDB
- python - 为什么我不能用 fernet [Python] 解密数据库值?
- sharepoint - 如何重置 SharePoint 内容数据库中的缓存?
- php - 在 HTML 表中显示 MySQL 数据库表
- ruby - 将文件读入 Ruby Numo::NArray
- java - 如何在 kotlin 中更改搜索栏的值
- clickhouse - 创建字典权限被拒绝
- javascript - 如何从 Web 应用程序外部找到要监听的事件以与之交互?