From scripts to simple apps
Paris Dauphine University-PSL
app.run())Save as app.py
Run with Flask CLI (recommended):
Visit: http://127.0.0.1:5000/
<name> appears in the URL, becomes a function argument?excited=1 read via request.argshttp://localhost:5000/greet/Anahttp://localhost:5000/greet/Ana?excited=1/user/<int:user_id>, /price/<float:x>templates/user.html
{ ... } for variables, {% ... %} for control flowfrom flask import request, jsonify, render_template
@app.get("/form")
def show_form():
return render_template("sum_form.html")
@app.post("/sum")
def compute_sum():
a = int(request.form["a"])
b = int(request.form["b"])
total = a + b
return render_template("sum_result.html", total=total)
@app.post("/api/sum")
def api_sum():
data = request.get_json()
a = data["a"]
b = data["b"]
return jsonify({"result": a + b})request.form → form fields sent via POST (Content-Type: application/x-www-form-urlencoded)request.get_json() / request.json → JSON body for APIsjsonify converts dict → JSON response with correct headersServer code (test.py):
Client code (api_test.py):
requests.post() with json= parameter to send JSON datarequest.get_json() to parse the JSON bodyresponse.json()request: current HTTP request (method, headers, body, args…)session: per-user, signed cookie storageg: request-scoped storage (DB connection, current user…)url_for and redirectsfrom flask import url_for, redirect
@app.get("/")
def index():
# Generate URLs by function name (safer than hard-coding strings)
return f'<a href="{url_for("dashboard")}">Go to dashboard</a>'
@app.get("/dashboard")
def dashboard():
return "Dashboard"
@app.get("/old-dashboard")
def old_dashboard():
# Permanent redirect to new endpoint
return redirect(url_for("dashboard"), code=301)url_for("dashboard") builds /dashboard
redirect() sends HTTP 302/301 to the browserapp.config["SECRET_KEY"]streamlit run app.pyimport streamlit as st
st.sidebar.header("Controls")
option = st.selectbox("Model", ["Logit", "Random Forest", "XGBoost"])
threshold = st.slider("Default threshold", 0.0, 1.0, 0.5, 0.01)
upload = st.file_uploader("Upload CSV", type=["csv"])
if upload:
import pandas as pd
df = pd.read_csv(upload)
st.write("Preview:", df.head())
st.write("Selected model:", option)
st.write("Threshold:", threshold)text_input, selectbox, slider, checkbox, file_uploader, date_input, …@st.cache_data:
clear_cache()st.session_state is similar to Flask session, but kept server-sidest.cache_data:
st.cache_resource:
Intro to VBA and Python