Python Flask with simple HTML files to server web pages along with API

CK CK 3788 
Created at
Updated at  
933 0 0

Flask allows you to render HTML templates using the Jinja2 templating engine.

 

Step 1: Create HTML Templates

First, create a directory named templates in the same directory as your app.py file. Inside the templates directory, create an HTML file (e.g., index.html).

Directory Structure:

/my_flask_app
    /static
        /css
            style.css
        /js
            script.js
        /images
            logo.png
    /templates
        index.html
    app.py

Note that, by default, Flask looks for static files in a directory named static in the same directory as your app.py file.

 

Step 2: Create Static Files

static/css/style.css

body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
}

h1 {
    color: #333;
}

static/js/script.js

document.addEventListener('DOMContentLoaded', function() {
    console.log('JavaScript loaded');
});

 

Step 3: Create an HTML File

templates/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Flask App</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <h1>Welcome to My Flask App</h1>
    <p>This is a simple HTML page served by Flask.</p>
    <script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>

 

Step 4: Modify the Flask Application

Update your app.py to serve the HTML file.

app.py

from flask import Flask, request, jsonify, render_template

app = Flask(__name__)

# Define a route for the home page
@app.route('/')
def home():
    return render_template('index.html')

# Define a route for a simple GET request
@app.route('/api/hello', methods=['GET'])
def hello_world():
    return jsonify(message="Hello, World!")

# Define a route for a simple POST request
@app.route('/api/data', methods=['POST'])
def get_data():
    data = request.get_json()
    return jsonify(received_data=data)

if __name__ == '__main__':
    app.run(debug=True)

 

Explanation

  1. Import render_template:

    python

    코드 복사

    from flask import Flask, request, jsonify, render_template

  2. Create a route to render the HTML template:

    python

    코드 복사

    @app.route('/') def home():    return render_template('index.html')

 

Running the Server

Run the server as before:

python app.py

 

Accessing the HTML Page

Navigate to http://127.0.0.1:5000/ in your web browser. You should see the HTML page with the styles applied from style.css and the JavaScript loaded from script.js.

 

Explanation

  • Static Files Directory: Flask automatically serves files from the static directory at the /static URL path.
  • Referencing Static Files: Use the url_for function in your templates to reference static files. This function helps Flask generate the correct URL for the static file, ensuring that it works correctly even if your application structure changes.

By following this approach, you can easily manage and serve static files without needing to map them with routes manually.

 

Combining HTML and API

You now have a simple Flask web server that can serve HTML pages and handle API requests. You can extend this setup to include more HTML files and more complex interactions between your frontend (HTML, CSS, JavaScript) and backend (Flask API).

Tags Flask Flask API Static Files Directory Facebook X
Comments 0
Similar posts
  1. Python Flask web server tutorial from the scratch
    626
  2. Dynamic DNS Made Easy: Building a Python-Based Solution
    796
  1. Python code to convert PDF file to Excel Spreadsheet
    705
  2. Python script to list files on your Google Drive and download one of them
    941
  3. Coinbase Python API - Basic Example
    465
  4. AWS Lambda Code Example based on Python
    334
  5. Python code using GPU on CentOS with AWS
    1,258
  6. Video Scence Detection with PySceneDetect
    2,339
  7. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,452
  8. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    914
  9. Deleting a specific user voice from the original audio track with Python
    553
  10. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    443
  11. Creating mp3 audio file based on the text input with Python
    470
  12. Implementing Text To Speech / Audio with Python3 and pyttsx3
    359
  13. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    560
  14. Python Simplified Assignment Operators
    535
  15. Trackback module used for Python Threading debugging
    847
  16. Simple Web Server based in Python
    383
  17. Thread Implementation in Python
    512
  18. A shell script that activates a Python virtual environment and then runs a specific Python script
    747
  19. Learning about Python Multiprocessing Technique
    594
  20. Simple Example to get the total number of records in BigQuery with Python
    668
  21. Using BigQuery in Python
    414
  22. Python Web Programming based on Django from the Scratch
    391
  23. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    193
  24. How do I determine the client IP type in Python - IPv4 or IPv6
    767
  25. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,234
  26. PyTorch example to Forcast Stock Price based on 10 days Dataset
    654
  27. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,078
  28. Milvus & FAISS: Decoding Their ML Synergy
    286
  29. Save clustering result (aka dictionary) in JSON and Reuse loaded result
    382
  30. Forecasting with Linear Regression and KNN Regression in Python
    929
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,256
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    105
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    108
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    154
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    117
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    599
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    231
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    264
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233