Learning Flask: My Simple Approach to Backend
Today, I studied Flask with a tutorial and took my first steps in learning how to build web applications. Flask, a Python-based web framework, is known for its simplicity and flexibility, making it a great choice for beginners like me who are exploring backend development.
Why Flask?
My current project is a basic currency forecast app with just three pages: Login, Register, and Dashboard. Since it's a straightforward project, I didn’t need an advanced backend framework like Django, which can be more complex and better suited for large-scale applications.
Flask, on the other hand, provides just the tools I need to assign which HTML page to show for a given URL while keeping the process simple.
Flask vs. Django Example:
Here’s a comparison of how Flask and Django handle routing.
Routing is the process of directing users' requests to the correct part of a web application or software, often based on the URL or input, to display the appropriate response or action.
Flask:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run()
Django:
In Django, you would need to configure urls.py, views.py, and additional settings to achieve the same result. For my needs, Flask’s minimalistic approach is ideal.
Standard Flask Folder Structure
As a beginner, my first concern was how to organize my files. Fortunately, there’s a standard folder structure that beginners can follow:
project-folder/
│
├── static/ # Contains static files (CSS, JS, images)
│ ├── css/
│ │ └── styles.css # Your CSS file(s)
│ ├── js/
│ │ └── script.js # Your JavaScript file(s)
│ └── images/
│ └── logo.png # Any images for your website
│
├── templates/ # Contains HTML templates
│ ├── base.html # Base layout (if using template inheritance)
│ ├── login.html # Login page template
│ ├── register.html # Register page template
│ └── dashboard.html # Dashboard page template
│
├── app.py # Main application script
└── requirements.txt # List of dependencies
Explanation:
- app.py : the backend logic using Flask.
- templates/ : Stores HTML files. You can dynamically update them with Flask and Jinja2.
- static/ : Stores static files like CSS, JavaScript, and images.
Basic Grammar of Flask
1. Routes with @app.route
Flask routes define which HTML page or content to show for a given URL.
- @app.route('/'): This connects to the home or root URL. In most websites, visiting / means the user has landed on the homepage.
- @app.route('/path'): This specifies a different page at /path.
- @app.route('/path/<variable>'): Dynamic routes, where parts of the URL can act as variables.
Example:
@app.route('/read/<int:id>/')
def read(id):
return f"<h2>Topic {id}</h2>"
Here, when you access /read/3/, the read function will return the string <h2>Topic 3</h2>. In other words, "Topic 3" will be shown when you access page /read/3/.
2. Methods in @app.route
Flask routes can specify which HTTP methods they handle using the methods parameter. By default, Flask routes handle only GET requests.
Recommended by LinkedIn
Why is this important?
- GET requests are for retrieving information (e.g., viewing a page).
- POST requests are for submitting or updating data (e.g., submitting a form).
Restricting methods ensures that users don’t accidentally use the wrong type of request, and it prevents misuse of routes for unintended purposes.
Example:
@app.route('/create/', methods=['GET', 'POST'])
def create():
# Only responds to GET and POST requests
3. Checking the Request Method
Flask lets you check whether a request is a GET (fetching information) or POST (submitting data). This is done using request.method.
Why is it important?
By checking request.method, you can differentiate between serving a page (GET) and processing user-submitted data (POST), ensuring your backend behaves as expected.
Example:
if request.method == 'GET':
# Return the form for user input
elif request.method == 'POST':
# Process the data from the form that user submitted
4. Accessing Form Data
When users submit a form, Flask allows you to access the data using request.form['name'], where name corresponds to the name attribute in the HTML form.
Example:
@app.route('/create/', methods=['GET', 'POST'])
def create():
if request.method == 'POST':
title = request.form['title'] # Gets the value of the 'title' input field
body = request.form['body'] # Gets the value of the 'body' textarea field
return redirect('/')
Here, request.form['title'] will return the value entered by the user in the title field of the form.
5. Redirects
After processing a request, you can redirect users to another page using redirect(). For example, after creating or deleting content, redirecting users to the homepage is common.
Example:
@app.route('/delete/<int:id>/', methods=['POST'])
def delete(id):
# Deletes a topic
return redirect('/') # Redirects to the homepage
References
All of the codes used today are from this tutorial.
For those who don't understand Korean (which I assume most of you), here is another good Flask tutorial in English!
Today, one day closer to being a data scientist. Thank you for following along my journey!
IELTS Coach & Soft Skills Trainer | Aspiring Data Analyst | Python Programmer & Web Developer | Data Storyteller| Empowering People Through Language & Data
6mo"Such a relatable post! I recently started learning Flask too, and I’m amazed at how simple yet powerful it is for web development. The routing and handling forms part was a game-changer for me! Your take on Flask vs. Django has me curious—I’ll definitely check out your article. Keep inspiring beginners like us! 🚀💡"