简体   繁体   中英

how to pass a variable from the Django views.py to another Python file?

views.py

...
    from app.camera import VideoCamera
    from app.camera import VideoCameraImage
...

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield(b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

def video_image(request):
    return StreamingHttpResponse(gen(VideoCameraImage()),content_type='multipart/x-mixed-replace; boundary=frame')

def image(request):
    url = request.GET.get('image_url')
    print(url)
    return render(request,'image.html')

camera.py

class VideoCameraImage(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)

    def __del__(self):
        self.video.release()

    def get_frame(self):

        src2=cv2.imread(os.path.join(settings.BASE_DIR,'img/smile.png'),-1)

        status, frame = self.video.read()

        face, confidence = cv.detect_face(frame)

        ...  
   
        ret,jpeg=cv2.imencode('.jpg',frame)
        return jpeg.tobytes()

When the user clicks the button, the url changes for each button. I would like to receive url from def image of views.py and deliver url to camera.py in the same path. how to pass a variable from the django views.py to another Python file?

The process is the same as passing values between any two python files.

Check this answer for detailed explanation on how to pass values between two scripts

Other workarounds just incase,

  1. You can also save as a seperate model that takes the image with the corresponding url so that you can iterate over them anytime.

If you dont want to put it into db storage,

  1. You can save the image id or name with the image-urls into a text file and then access the text file from another script considering file handling is simple in python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM