โค้ด python ที่ใช้เขียน flask และ fastapi
โค้ด: เลือกทั้งหมด
from fastapi import FastAPI, Body, Request, File, UploadFile, Form
from fastapi.middleware.wsgi import WSGIMiddleware
import uvicorn
from fastapi.staticfiles import StaticFiles
from pathlib import Path
import requests
from flask import Flask, render_template
api = FastAPI() # Init FastAPI App
flask_app = Flask(__name__) # Init Flask App
# Mount Flask on FastAPI
api.mount('/predict', WSGIMiddleware(flask_app))
# Mount static folder on FastAPI
BASE_PATH = Path(__file__).resolve().parent
api.mount(
"/static",
StaticFiles(directory=str(BASE_PATH / "static")),
name="static",
)
# Flask section
# http://127.0.0.1:8000/predict
@flask_app.get('/')
def predict_page():
return render_template('index.html')
# http://127.0.0.1:8000/predict
# def predict_page_result():
# url = 'http://127.0.0.1:8000/submitform'
# response = requests.get(url)
# print(response)
# FastAPI section
# http://127.0.0.1:8000/submitform
@api.post('/submitform')
async def handle_form(model: str = Form(...), file: UploadFile = File(...)):
return {'model': model, 'file': file}
if __name__ == '__main__':
uvicorn.run(api, host='127.0.0.1', port=8000, debug=True)
โค้ด: เลือกทั้งหมด
{% extends "layout.html" %}
{% block title %}
<title>Test ML</title>
{% endblock %}
{% block content %}
<div class="parent">
<header>
<h1>Predict an image</h1>
</header>
<p>
<!-- {% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %} -->
</p>
<main>
{% if filename %}
<div>
<!-- <img src="{{ url_for('display_image', filename=filename) }}"> -->
</div>
{% endif %}
<form action="/submitform" method="post" enctype="multipart/form-data">
<div class="flex-container">
<select class="form-select" name="model" aria-label="select a model">
<option value="1" selected>1st model 224*224</option>
<option value="2">2nd model 90*96</option>
</select>
</div>
<div class="flex-container">
<input type="file" class="form-control" id="inputGroupFile02" name="file" required>
<button type="submit" class="btn btn-primary mb-3">Predict</button>
</div>
</form>
<hr>
<div>
{% if gender_prediction %}
<h3>This's a picture of a {{gender_prediction}}.</h3>
<h4>It was processed by {{model}}</h4>
{% else %}
<h3>Nothing's here</h3>
{% endif %}
</div>
</div>
</main>
{% endblock %}