Web Development — Flask

buzonliao
Python 101
Published in
2 min readOct 17, 2023
Photo by Anete Lūsiņa on Unsplash

Explore the world of web development with Flask. Learn how to create a virtual environment, install Flask, and set up a local web server. Dive into the web server’s code and discover how to save submitted form data to CSV files. With clear steps and practical examples, this post is a valuable resource for beginners and aspiring web developers. Get ready to embark on your web development journey and bring your project ideas to life with Flask.

  1. Download website template
  2. Create virtual env
python3 -m venv venv

3. Activate virtual env

. venv/bin/activate

4. Install Flask

pip3 install Flask

5. Launch the web server in the localhost

flask --app server run --debug

Web Server Code

  • Save submitted form data to .csv file
from flask import Flask, render_template, request, redirect
import csv

app = Flask(__name__)

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

@app.route("/<string:page_name>")
def html_page(page_name):
return render_template(page_name)

def write_to_file(data):
with open('database.txt', mode='a') as database:
email = data['email']
subject = data['subject']
message = data['message']
file = database.write(f'\n{email}, {subject}, {message}')

def write_to_csv(data):
with open('database.csv', mode='a', newline='') as csvfile:
email = data['email']
subject = data['subject']
message = data['message']
csv_writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow([email, subject, message])

@app.route('/submit_form', methods=['POST', 'GET'])
def submit_form():
if request.method == 'POST':
try:
data = request.form.to_dict()
write_to_csv(data)
return redirect('./thankyou.html')
except:
return 'did not save to db'
else:
return 'something went wrong'

Reference

--

--