如何使用django运行线程

7d7tgy0s  于 2023-02-17  发布在  Go
关注(0)|答案(1)|浏览(139)

如何用Django运行线程如何在视图文件中发送数据

from django.shortcuts import render
from django.http.response import HttpResponse
from datetime import datetime

from .pnet import Worker1

global value
value = False

def home(request):
 
    global value

    if value == False:
        Worker1.start()
        print(a)

    value = True

    
    today = datetime.today()

  
    return render(request, "home.html")`

pnet.py

import threading

class Worker1(threading.Thread):

    def run(self):
        a = 10`
k3bvogb1

k3bvogb11#

from django.shortcuts import render
from django.http.response import HttpResponse
from .models import WorkAccident,Absenteeism,OverTime,Person,Breakdown,MTTR,MTBF,PredictiveMaintenance,Budget
from datetime import datetime
import asyncio
import threading
import time
import snap7

IP = '192.168.75.220'
RACK = 0
SLOT = 1

DB_NUMBER_1 = 1
DB_NUMBER_2 = 2
START_ADDRESS = 0
SIZE_1 = 2
SIZE_2 = 28
System = False
try:
     plc = snap7.client.Client()
     plc.connect(IP, RACK, SLOT)
     System = True
     print("Baglı")
       
except:
    print("Baglanmadı")


global value
value = False

async def background_task():
    # Do some long-running task

    db1 = plc.db_read(DB_NUMBER_1, START_ADDRESS, SIZE_1)
    

    product_status = bytes(db1[0:2])
    binary_string = "{:016b}".format(int(product_status.hex(),16))
    print(f'PRODUCT BİT: {binary_string}')

    await asyncio.sleep(1)

    return 'Task completed'

class MyThread(threading.Thread):
    def run(self):
        result = asyncio.run(background_task())
        # Do something with the result, such as saving it to a database

# Create your views here.
async def home(request):
    ##u = WorkAccident.objects.all()
    ##for val in u :
    ##    print(val.date)
  

    asyncio.create_task(background_task())

    
    today = datetime.today()

    ##fault = list(filter(lambda item: item is not None, u.values()))

    data = {
        
        "workaccident": WorkAccident.objects.filter(date__month=today.month, date__year=today.year),
        "absenteeism" : Absenteeism.objects.filter(date__month=today.month, date__year=today.year),
        "overtime"    : OverTime.objects.filter(date__month=today.month, date__year=today.year)      

    }
  
    return render(request, "home.html", data)

相关问题