首页 > 解决方案 > 线程继续在 python django 服务器中运行

问题描述

当我转到mywebiste/script时,脚本函数运行并在浏览器中呈现 json。

list = []

def script(request):
  
    i = 0
    urls = ["http://www.coden.live", "http://www.hackersvilla.xyz",]
    http = urllib3.PoolManager()
    threads = [threading.Thread(target=fetch_url, args=(url,)) for url in urls]
    for thread in threads:
        
            thread.start()
      
    for thread in threads:
        
            thread.join()
            
    return JsonResponse(list, safe=False)


def fetch_url(url):
    http = urllib3.PoolManager()
    r = http.request('GET', url)
    soup = bs4.BeautifulSoup(r.data, 'html.parser')
    try:
        content =  (soup.find("meta",  {"name":"keywords"})['content'])
        list.append(content)

    except:
        print ("No meta keywords")    

它正在正确显示数据。但是当我刷新页面时,数据显示4次等等 在此处输入图像描述

我认为线程没有终止,它们也在下一个请求中继续运行。

标签: pythonpython-3.xdjangomultithreadingserver

解决方案


推荐阅读