From Script to Web App: Using Flask to Turn Python Code into a Website

andreasPython Code3 weeks ago26 Views

Goal

  • Start with a small “business logic” function (your script).
  • Wrap it in a Flask app with one HTML page and one JSON API.
  • Prepare requirements.txt and a production command (gunicorn).
  • Deploy on Render or Railway with Git.

1) Start with a tiny script (your logic)

Imagine your current script calculates a greeting:

# logic.py
def make_greeting(name: str) -> str:
    return f"Hello, {name or 'world'}!"

What this does: Keeps your core logic in a pure function so it’s easy to test and reuse (CLI, web, cron jobs, etc.).


2) Wrap it with Flask

# app.py
from flask import Flask, request, jsonify, render_template_string
from logic import make_greeting
import os

app = Flask(__name__)

# --- HTML page (GET /) ---
@app.get("/")
def index():
    name = request.args.get("name", "")
    msg = make_greeting(name)
    # tiny inline template for demo
    html = """
    <!doctype html>
    <title>Flask Greeting</title>
    <h1>{{ msg }}</h1>
    <form method="get" action="/">
      <input name="name" placeholder="Your name">
      <button type="submit">Greet</button>
    </form>
    <p>Try the JSON API at <code>/api/greet?name=Alice</code></p>
    """
    return render_template_string(html, msg=msg)

# --- JSON API (GET /api/greet) ---
@app.get("/api/greet")
def api_greet():
    name = request.args.get("name", "")
    return jsonify({"greeting": make_greeting(name)})

# Local run helper (platforms set PORT)
if __name__ == "__main__":
    port = int(os.getenv("PORT", 5000))
    app.run(host="0.0.0.0", port=port, debug=True)

What’s happening:

  • index() reads ?name= from the URL, calls your function, and renders a tiny HTML page.
  • api_greet() exposes the same logic as JSON for programmatic use.
  • Binding to 0.0.0.0 and using PORT from the environment makes it compatible with hosts like Render/Railway. (Flask quickstart basics are here. flask.palletsprojects.com)

3) Add dependencies & production server

Create a requirements.txt:

flask>=3.0
gunicorn>=21.2

Why gunicorn? Production platforms expect a WSGI server to run Flask apps (not flask run). We’ll start it like gunicorn app:app. (Gunicorn + Flask deployment background. Red Hat Developer)


4) Test locally

# optional but recommended
python -m venv venv
# Windows: venv\Scripts\activate
source venv/bin/activate

pip install -r requirements.txt
python app.py
# Visit http://localhost:5000

5) Put it on GitHub

Create a repo with at least:

app.py
logic.py
requirements.txt

(Add .gitignore with venv/ if you used one.)


6) Deploy to Render (clicks + one command)

One-time setup (via dashboard):

  1. In Render dashboard, New → Web Service.
  2. Connect your GitHub repo.
  3. Runtime: Python auto-detected by requirements.txt.
  4. Build command: pip install -r requirements.txt
  5. Start command: gunicorn app:app
  6. Deploy.

Render’s official Flask quickstart mirrors these steps. If you pick their example first, you’ll see the same pattern. Render+1testdriven.io

Tip: If you set the Start Command to python app.py, Render may complain (no open HTTP port) or run with the wrong server. Use Gunicorn for web services. Render


7) Deploy to Railway (template or repo)

Option A — One-click template / guide: Railway provides a Flask guide and templates—pick Flask, connect GitHub, and Railway auto-detects Python with requirements.txt. Railway DocsRailway

Option B — From your GitHub repo:

  1. In Railway, New Project → Deploy from GitHub and choose your repo.
  2. Railway builds your app from requirements.txt.
  3. Set Start Command (if asked) to gunicorn app:app.
  4. Add any Variables (env vars) in the dashboard (e.g., SECRET_KEY). Reddit

Why this works: Railway detects Python automatically, provisions a web service, and sets a PORT environment variable your app binds to. Railway Docs


8) Verifying it works in production

After deploy:

  • Open the service URL and try:
    • https://<your-app>/ (page)
    • https://<your-app>/api/greet?name=Alice (JSON)
  • Check logs if it fails to bind a port or crashes during install.

9) Common gotchas (and fixes)

  • Using flask run on hosts
    Use gunicorn app:app for production web services. Red Hat Developer
  • Not binding to the platform port
    Ensure app.run(host="0.0.0.0", port=int(os.getenv("PORT", 5000))).
  • Missing build/start commands
    On Render, set build & start explicitly in the service settings. Render
  • Native libraries in requirements
    Some packages need extra system libs (e.g., portaudio for PyAudio). Prefer alternatives or deploy in a Docker container if needed. Reddit

10) Optional: Add a Procfile (some hosts)

If your host uses Procfiles (Railway supports Docker/CLI/templates and may not require it), you can include:

web: gunicorn app:app

This is a conventional way to declare your web process; many PaaS recognize it.


11) Next steps / polishing

  • Split real templates into templates/ and use render_template.
  • Add static files (CSS/JS) under static/.
  • Configure env vars for secrets via your platform dashboard.
  • Add a database (Render and Railway both offer managed Postgres). GistStackademic

Reference docs

0 Votes: 0 Upvotes, 0 Downvotes (0 Points)

Leave a reply

Loading Next Post...
Loading

Signing-in 3 seconds...