Simple Online Booking System With Python Flask (Step-By-Step)

Welcome to a tutorial on how to create a simple online booking system with Python Flask. This is for you guys who are looking to create a simple reservation system, without involving any crazy database stuff – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes Python Booking Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Create your own project folder, e.g. D:\booking, unzip the code inside this folder.
  • Open the terminal (or command line), navigate to your project folder cd D:\booking.
  • As usual, create a virtual environment if you don’t want to mess up your other projects.
    • virtualenv venv
    • Windows – venv\scripts\activate
    • Mac/Linux – venv/bin/activate
  • Get all the packages – pip install Flask
  • Launch! python 3-server.py and access http://localhost/.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

PYTHON ONLINE BOOKING

All right, let us now get into the details of building a booking system with Python Flask. Not going to explain line-by-line, but here’s a quick walkthrough.

 

STEP 1) BOOKING PAGE

THE HTML

templates/1-booking.html
<form id="bookForm" onsubmit="return book();">
  <label for="name">Name</label>
  <input type="text" name="name" required/>
 
  <label for="email">Email</label>
  <input type="email" name="email" required/>
 
  <label for="date">Date</label>
  <input type="date" name="date" required/>
 
  <input type="submit" value="Go!" disabled id="bookGo"/>
</form>

This page should be self-explanatory. Just a simple booking form with the name, email, and date fields. Feel free to add more fields as required.

 

THE JAVASCRIPT

static/1-booking.js
// (A) SEND BOOKING REQUEST
function book () {
  // (A1) PREVENT MULTIPLE SUBMIT
  document.getElementById("bookGo").disabled = true;
 
  // (A2) COLLECT FORM DATA
  let data = new FormData(document.getElementById("bookForm"));
 
  // (A3) SEND!
  fetch("/book", { method:"POST", body:data })
  .then((res) => {
    if (res.status==200) { location.href = "/thank"; }
    else { alert("Opps an error has occured."); }
  })
  .catch((err) => { alert("Opps an error has occured."); });
  return false;
} 
 
// (B) ON PAGE LOAD
window.onload = () => {
  // (B1) MIN SELECTABLE DATE IS TODAY
  let datepick = document.getElementsByName("date")[0];
  datepick.min = new Date().toISOString().split("T")[0];
 
  // (B2) ENABLE FORM
  document.getElementById("bookGo").disabled = false;
};

Just a small bit of Javascript for the booking page.

  1. Collect the booking form, and send it to the server-side with fetch post.
  2. On window load, we set the minimum reservation date to today. Feel free to tweak this, even set a max date on it.

 

 

STEP 2) THANK YOU PAGE

templates/2-thank.html
<h1>Thank You</h1>
<p>We have received your reservation request</p>

A dummy “thank you page”.

 

STEP 3) SERVER-SIDE BOOKING

INITIALIZE

3-server.py
# (A) INIT
# (A1) LOAD REQUIRED PACKAGES
from flask import Flask, render_template, request, make_response
from werkzeug.datastructures import ImmutableMultiDict
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
 
# (A2) FLASK INIT
app = Flask(__name__)
# app.debug = True
 
# (B) SETTINGS
HOST_NAME = "localhost"
HOST_PORT = 80
MAIL_FROM = "sys@site.com"
MAIL_TO = "admin@site.com"
MAIL_SUBJECT = "Booking Request"

The first few sections of the server-side should be self-explanatory. We are just loading the required packages, and defining some of the settings stuff. Yes, a gentle reminder here to change the settings to your own.

 

 

ROUTES – HTML PAGES

3-server.py
# (C) ROUTES
# (C1) BOOKING PAGE
@app.route("/")
def index():
  return render_template("1-booking.html")
 
# (C2) THANK YOU PAGE
@app.route("/thank")
def thank():
  return render_template("2-thank.html")

Captain Obvious to the rescue:

  • http://localhost/ to serve the booking page 1-booking.html.
  • http://localhost/thank to serve the “thank you” page 2-thank.html.

 

BOOKING PROCESS

3-server.py
# (C3) BOOKING ENDPOINT
@app.route("/book", methods=["POST"])
def foo():
  # EMAIL HEADERS
  mail = MIMEMultipart("alternative")
  mail["Subject"] = MAIL_SUBJECT
  mail["From"] = MAIL_FROM
  mail["To"] = MAIL_TO
 
  # EMAIL BODY (BOOKING DATA)
  data = dict(request.form)
  msg = "<html><head></head><body>"
  for key, value in data.items():
  msg += key + " : " + value + "<br>"
  msg += "</body></html>"
  mail.attach(MIMEText(msg, "html"))
 
  # SEND MAIL
  mailer = smtplib.SMTP("localhost")
  mailer.sendmail(MAIL_FROM, MAIL_TO, mail.as_string())
  mailer.quit()
 
  # HTTP RESPONSE
  res = make_response("OK", 200)
  return res

Remember the “send booking form via fetch post”? This part handles the submission – Simply collect the form data, and send it to the email address that you have specified.

 

 

START!

3-server.py
# (D) START!
if __name__ == "__main__":
  app.run(HOST_NAME, HOST_PORT)

No explanation is required…

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

EXTRA – MAIL SEND

Take note that we are using mailer = smtplib.SMTP("localhost") to send the email out. You guys who are on Mac/Linux should not have a problem so long as sendmail is in place. But for Windows users, I will recommend using Papercut SMTP for easy testing.

P.S. smtplib is also capable of using a remote SMTP server, just follow up with their documentation.

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *