2
Day 8 homework Karen
Karenzz edited this page 2023-04-14 16:54:09 +02:00
The original graph is shown below.
We can use Flask in python to serve cat pictures as fast as possible, where Flask is used as the web framework to handle incoming HTTP requests.
import os
from flask import Flask, Response
from urllib.parse import urlparse
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello, welcome to the cat picture server!'
@app.route('/<path:path>')
def serve_jpeg(path):
if path.endswith('.jpg'):
file_path = path[1:]
if os.path.isfile(file_path):
with open(file_path, 'rb') as file:
return Response(file.read(), content_type='image/jpeg')
else:
return 'File not found', 404
else:
return 'Only .jpg files are allowed', 403
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)
I also try to use fastapi this morning, and the result turns to be like this:
import os
from fastapi import FastAPI
from fastapi.responses import FileResponse
from urllib.parse import urlparse
app = FastAPI()
@app.get('/')
def index():
return 'Hello, welcome to the cat picture server!'
@app.get('/{path:path}')
async def serve_jpeg(path: str):
if path.endswith('.jpg'):
file_path = path[1:]
if os.path.isfile(file_path):
return FileResponse(file_path, media_type='image/jpeg')
else:
return {'detail': 'File not found'}, 404
else:
return {'detail': 'Only .jpg files are allowed'}, 403
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host='0.0.0.0', port=8000)


