English 中文(简体)
快速API与Picamera2 相比的应对——浏览器复发问题
原标题:FastAPI StreamingResponse with picamera2 - browser refresh problem

I m试图通过Picamera2图书馆从Raspberry Pi向MJPEG输送快车服务器。 它发挥了作用,但当我多次重载浏览器时,它将 st。 但是,。 你们能否发现问题?

服务器Im在出现故障的情况下使用玉米。

感谢!

import io
import os
from threading import Condition
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from picamera2 import Picamera2
from picamera2.encoders import JpegEncoder
from picamera2.outputs import FileOutput
from fastapi.responses import HTMLResponse, StreamingResponse


app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins="http://localhost:8000",
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


class StreamingOutput(io.BufferedIOBase):
    def __init__(self):
        self.frame = None
        self.condition = Condition()

    def write(self, buf):
        with self.condition:
            self.frame = buf
            self.condition.notify_all()


picam2 = Picamera2()
picam2.configure(picam2.create_video_configuration(main={"size": (640, 480)}))
output = StreamingOutput()
picam2.start_recording(JpegEncoder(), FileOutput(output))


def get_frame():
    try:
        while True:
            with output.condition:
                output.condition.wait()
                frame = output.frame
                yield (
                    b"--frame
" b"Content-Type: image/jpeg

" + frame + b"
"
                )
    except Exception as e:
        print("Error! Frames")


@app.get("/mjpeg", response_class=StreamingResponse)
def mjpeg(request: Request):
    try:
        frames = get_frame()
        response = StreamingResponse(
            frames,
            headers={
                "Cache-Control": "no-cache, private",
                "Pragma": "no-cache",
            },
            media_type="multipart/x-mixed-replace; boundary=frame",
        )
        return response
    except Exception as e:
        print("Error! Route")

问题回答

也许你应努力做到以下几点:

def get_frame():
    try:
        while True:
            with output.condition:
                output.condition.wait()
                frame = output.frame

            ret = b --FRAME
 
            ret += b Content-Type: image/jpeg
 
            ret += f Content-Length: {len(frame)}

 .encode()
            ret += frame
            ret += b 
 
            yield ret
    except Exception as e:
        logging.warning( Removed streaming client! )

@app.get( /mjpeg , response_class=StreamingResponse)
def stream():
    response = StreamingResponse(
        get_frame(),
        headers={
             Age :  0 ,
             Cache-Control :  no-cache, private ,
             Pragma :  no-cache ,
             Content-Type :  multipart/x-mixed-replace; boundary=FRAME 
        }
    )
    return response

The above code runs as expected.





相关问题
FastAPI api giving "str type expected" error

I have this code that returns the url of an amazon rds instance: def get_host(instance_name): """This function receives the name of an RDS instance and returns its connection ...

Unable to obtain header values with FastAPI middleware

I have limited knowledge of FastAPI. Thanks for any help you can give me. I want to get a token and process it in the middleware. However, the problem occurs at the link. https://github.com/fujitomo/...

热门标签