【问题标题】:Django How to stop the execution of a functionDjango 如何停止函数的执行
【发布时间】:2017-05-23 08:56:21
【问题描述】:

我正在尝试通过 Ajax 调用 python 函数。我想停止执行该功能。我试图刷新页面,但它并没有停止。当我停止 Django 服务器时,它就会停止。

这里有一些代码:This Call call HTTP request

class ScrapData():

    @classmethod
    def search_status(self, urls_list):
      for url in urls_list:
            r = requests.get(url)
            text = r.text
            #...

      return 1

通过 Ajax 调用此视图

class SearchData(View):

    def get(self, request, *args, **kwargs):
        urls_list = [];
        response = ScrapData().search_status(urls_list)

        return HttpResponse(response)

我想停止该功能。我怎样才能做到这一点?谢谢

【问题讨论】:

  • self on classmethod?
  • 什么事件应该停止你的功能?也许,您可以为您的请求设置超时?
  • 抱歉搞错了.. self 将是 cls
  • 点赞按钮点击事件。或者在页面加载时,刷新

标签: python ajax django


【解决方案1】:

这个 django 应用程序是如何提供服务的?有多少进程和线程?您如何知道哪个线程运行特定请求?有几种 Python 方法可以处理这个问题,但并不像“停止特定请求”那么简单。

在我看来,在管理、可扩展性和自我意识方面处理长轮询任务的最佳方法是使用像 Celery 这样的工具。还有一个专用的SO question on how to revoke a Celery task

Django Channels 是解决这个问题的另一种新方法,但它需要更多的开发才能使用,而不是 Celery。

【讨论】:

  • 谢谢,有没有办法通过会话或数据库等来处理?
  • 欢迎。当然,您在发送取消 ajax 时调用的视图中处理那些。
【解决方案2】:

我遇到了同样的问题,我称之为错误且缓慢的请求。我通过重新启动我的 Apache 服务器来停止它。重启服务器就可以解决了。

【讨论】:

    【解决方案3】:

    尝试嵌套函数,它可以让你调用任何你想要的函数,或者结束进程

    代码:

    class ScrapData():
    
        @classmethod
        def func():
            def search_status(self, urls_list):
                  for url in urls_list:
                    r = requests.get(url)
                    text = r.text
                    #...
    
              return 1
            def get(self, request, *args, **kwargs):
                urls_list = [];
                response = ScrapData().search_status(urls_list)
    
                return HttpResponse(response)
            def empty():
                pass
        #call the function you want to be excute further on
        #if you want nothing to happen then call empty function(pass keyword)
    

    【讨论】:

    • 这个答案有帮助吗?请告诉或至少接受
    猜你喜欢
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2021-04-12
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    相关资源
    最近更新 更多