当前位置: 代码迷 >> python >> 如何将数据从Django发送到外部python类,反之亦然?
  详细解决方案

如何将数据从Django发送到外部python类,反之亦然?

热度:25   发布时间:2023-06-19 09:08:20.0

在我的应用文件夹中,我有views.pybot.py bot.py是我的项目的主要大脑,我的所有功能都“执行”主要任务(后端)。 我导入它们并在Django中使用。 现在,我需要以某种方式将数据从django发送到bot.py。 怎么做? 我有:

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')
        tags = []
        tagi = tagi.split(',')
        tags.extend(tagi)
        print(tags)
        if self.request.is_ajax():
            print('It is AJAX')
            bot.login(login,password)
            bot.search(tags)
            print(form.cleaned_data)
            data = {
                'message': "Succesfully  opened Selenium."
            }
            return JsonResponse(data)
        else:
            return response

bot.py:

class Instagram(object):
...

 def search(self,tags):
        time.sleep(1)
        search = self.driver.find_element_by_xpath('/html/body/span/section/nav/div[2]/div/div/div[2]/input')
        search.clear()
        search.send_keys(tags[self.nextTag], Keys.ENTER)
        time.sleep(2)
        self.driver.find_element_by_xpath(
            '/html/body/span/section/nav/div[2]/div/div/div[2]/div[2]/div[2]/div/a[1]/div').click()

    def changeTag(self):
        #if a list gets to the end reset it
        self.nextTag += 1
        tagsNum = len(Instagram.tags)
        if self.nextTag == tagsNum:
            self.nextTag = 0
        else:
            self.tags[0 + self.nextTag]
        return  self.nextTag

运行脚本后,它写道:

AttributeError: 'Instagram' object has no attribute 'tags'

我知道Instagram.tags不存在,但是如何在bot.py使用Django中的数据? 如何从我的Django类中替换Instagram.tagstags=[] 还是有更好的解决方案?(也许在Django中编写changeTag()并将数据返回给bot.py?)

我尝试在bot.py中导入Django类,但不起作用

这与Django无关。 您只是在处理Python类。 类为其实例定义属性和方法。 因此,如果您在另一个对象( InstabotFormView )中初始化Instagram的实例,则可以为其属性分配值/对象。

现在,如果您将tags = []属性添加到Instagram (使用丢失的空值对其进行初始化),则可以在Django类中将bot.tags设置为标签,并在Intagram方法中使用它。