```python from flask import Flask, Response from picamera2 import Picamera2 import io # Initialize Flask app app = Flask(__name__) # Initialize and configure the camera camera = Picamera2() camera.configure(camera.create_preview_configuration(main={"size": (640, 480)})) camera.start() # Generator function to capture frames def generate_frames(): while True: # Capture frame to a memory stream stream = io.BytesIO() camera.capture_file(stream, format='jpeg') stream.seek(0) frame = stream.read() # Yield frame in multipart format for streaming yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') # Route for the video feed @app.route('/video_feed') def video_feed(): return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') # Route for the main page @app.route('/') def index(): return ''' <html> <body> <h1>Raspberry Pi Camera Livestream</h1> <img src="/video_feed" width="640" height="480"> </body> </html> ''' # Run the Flask app if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) ``` --- ```python from flask import Flask, Response, request, abort from picamera2 import Picamera2 import io app = Flask(__name__) # Hardcoded credentials (change these!) USERNAME = "x" PASSWORD = "q" # Initialize and configure the camera camera = Picamera2() camera.configure(camera.create_preview_configuration(main={"size": (640, 480)})) camera.start() # Basic authentication check def check_auth(username, password): return username == USERNAME and password == PASSWORD def authenticate(): return Response( 'Login required.', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) def requires_auth(f): def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): return authenticate() return f(*args, **kwargs) return decorated # Generator function to capture frames def generate_frames(): while True: stream = io.BytesIO() camera.capture_file(stream, format='jpeg') stream.seek(0) frame = stream.read() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') # Protected video feed route @app.route('/video_feed') @requires_auth def video_feed(): return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/') @requires_auth def index(): return ''' <html> <head> <title>fish's rat rig livestream</title> <style> body { background-color: black; color: white; text-align: center; } img { display: block; margin: 0 auto; } </style> </head> <body> <h1>fish's rat rig livestream</h1> <img src="/video_feed" width="640" height="480"> </body> </html> ''' if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) ```