paint-brush
Building a Web Server with Python and Flaskby@ajayvallab
518 reads
518 reads

Building a Web Server with Python and Flask

by Ajay Krishnan PrabhakaranJanuary 2nd, 2025
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

This article guides you through building a simple web server using Python and the Flask framework. You'll learn key concepts like routing, templating, and handling HTTP requests, all while creating a functional web application
featured image - Building a Web Server with Python and Flask
Ajay Krishnan Prabhakaran HackerNoon profile picture

The digital age demands dynamic and interactive web experiences. Building a web server is the cornerstone of this digital landscape, enabling you to create applications that go beyond static HTML pages. Python, with its elegant syntax and extensive libraries, provides a powerful foundation for web development. Flask, a lightweight and versatile microframework, further simplifies the process. By combining the flexibility of Python with the streamlined approach of Flask, developers can quickly and efficiently construct robust web servers. This journey delves into the core concepts of web development, from handling HTTP requests and responses to routing and templating, empowering you to build engaging and functional web applications that can connect and inform the world.


"The web is becoming the town square for the global village of tomorrow." - Bill Gates

Prerequisites

  • Python 3.x
  • Flask

Install Flask using pip:

pip install flask

The Code

Below is the complete code for a simple Restaurant reservation system:

from flask import Flask, render_template, request

app = Flask(__name__)

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

@app.route('/submit', methods=['POST'])
def submit():
    # Extract form data
    name = request.form['name']
    phone = request.form['phone']
    email = request.form['email']
    date = request.form['date']
    time = request.form['time']

    # Create a message for the result page
    message = (
        f"Hello, {name.split()[0]}! Your reservation has been booked for {date} at {time}. "
        f"A reminder has been sent to {phone} and {email}"
    )
    return render_template('result.html', message=message)

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


  • Importing Flask Modules: We start by importing the necessary modules from Flask. Flask is the main class for our application, render_template is used to render HTML templates, and request is used to handle incoming form data.
  • Creating the Flask App: We create an instance of the Flask class, which will be our WSGI (Web Server Gateway Interface) application.
  • Defining Routes:
    • Index Route ('/'): This route renders the index.html template, which should contain the form for users to input their reservation details.
    • Submit Route ('/submit'): This route handles the form submission. It extracts the data from the form using request.form and constructs a confirmation message. The message is then passed to the result.html template for rendering.
  • Running the App:
python app.py

Debug Mode: If your app.py includes app.run(debug=True), the server will start in debug mode, which is useful for development. It provides detailed error messages and automatically reloads the server when you make changes to your code.

Port and Host: By default, Flask runs on http://127.0.0.1:5000/. If you need to change the host or port, you can modify the app.run() call in your app.py:

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, debug=True)


Index.html

The index.html file serves as the user interface for the reservation system, featuring a form where users can input their details such as name, phone number, email, date, and time for booking a table. It is styled with CSS to provide a visually appealing and user-friendly experience. Upon submission, the form data is sent to the server for processing.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Restaurant Table Booking</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-image: url('https://img.freepik.com/premium-vector/delicious-food-menu-landing-page-template-homepage-design_631465-116.jpg?w=2000');
            background-size: cover;
            background-position: center;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .form-container {
            background-color: rgba(255, 255, 255, 0.8);
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            max-width: 300px;
            width: 100%;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        label {
            display: block;
            margin-bottom: 8px;
            color: #555;
        }
        input[type="text"],
        input[type="email"],
        input[type="tel"],
        input[type="date"],
        input[type="time"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        input[type="submit"] {
            width: 100%;
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        input[type="submit"]:hover {
            background-color: #45a049;
        }
        </style>
</head>
<body>
    <div class="form-container">
        <h1>Book a Table</h1>
        <form action="/submit" method="POST">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" required>

            <label for="phone">Phone Number:</label>
            <input type="tel" id="phone" name="phone" required>

            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required>

            <label for="date">Date:</label>
            <input type="date" id="date" name="date" required>

            <label for="time">Time:</label>
            <input type="time" id="time" name="time" required>

            <input type="submit" value="Submit">
        </form>
    </div>
</body>
</html>


Restaurant reservation page


Result.html

The result.html file displays a confirmation message to the user after the form is submitted. It dynamically shows the reservation details, confirming the booking and assures that a reminder has been sent to the provided contact information

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reservation Confirmation</title>
    <link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-image: url('https://img.freepik.com/free-vector/minimal-doodle-frame-background-social-story-highlight_53876-97970.jpg?t=st=1735447681~exp=1735451281~hmac=d8f33db86d2b336838279674afb91df8c2089c7e8be13d316dc26982e0b30ac2&w=2000');            
            background-size: cover;
            background-position: center;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            color: #fff;
        }
        .form-container {
            background-color: rgba(0, 0, 0, 0.7);
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            max-width: 400px;
            width: 100%;
            text-align: center;
        }
        h1 {
            font-family: 'Lobster', cursive;
            font-size: 32px;
            margin-bottom: 20px;
        }
        p {
            font-size: 18px;
            line-height: 1.5;
        }
    </style>
</head>
<body>
    <div class="form-container">
        <h1>Reservation Confirmed!</h1>
        <p>{{ message }}</p>
    </div>
</body>
</html>



Reservation confirmation page


Closing Thoughts

We’ve delved into the core principles of web development, from handling HTTP requests to rendering dynamic content, laying a solid foundation for future endeavors. The web is a constantly evolving landscape, brimming with opportunities for innovation and creativity. Embrace this challenge, continue to explore the vast possibilities of web development, and contribute to the ever-growing tapestry of the internet