Getting Started with Flask: A Beginners Guide

3>What is Flask?
Flask is a lightweight web framework for Python that allows developers to create web applications quickly and efficiently. Designed with simplicity and flexibility in mind, Flask helps you build web applications without the constraints of larger frameworks. Its design philosophy revolves around providing developers with the essential tools they need while allowing them to choose how to implement additional features. This guide will walk you through the steps to get started with Flask and build your first web application.
Prerequisites
To begin using Flask, ensure you have the following installed:
- Python: Flask requires Python 3.6 or later. You can download it from the official Python website.
- Pip: Along with Python, the package manager
pipis typically included. You can verify its installation by runningpip --versionin your command line. - A code editor: Choose a text editor or IDE you are comfortable with. Popular options include Visual Studio Code, PyCharm, and Sublime Text.
Setting Up Your Environment
Create a Virtual Environment: Using a virtual environment is best practice for Python projects to manage dependencies. You can create one using the following commands:
mkdir my_flask_app cd my_flask_app python -m venv venvActivate the Virtual Environment:
On Windows:
venvScriptsactivateOn macOS or Linux:
source venv/bin/activate
Install Flask: Once the virtual environment is activated, install Flask using pip:
pip install Flask
Creating Your First Flask Application
File Structure: Create a new Python file named
app.pyin your project directory. This file will contain your Flask application code.touch app.pyImport Flask: Open
app.pyin your code editor and import Flask:from flask import FlaskInitialize the Flask Application:
app = Flask(__name__)Create a Route: Define a route to display a simple message:
@app.route('/') def home(): return "Hello, Flask!"Run the Application: Add the following code at the end of
app.pyto run your application:if __name__ == '__main__': app.run(debug=True)
Testing Your Application
Start the Server: Run your application with the following command in your terminal:
python app.pyVisit the URL: Open your web browser and navigate to
http://127.0.0.1:5000/. You should see “Hello, Flask!” displayed on the page.
Adding More Routes
One of the best features of Flask is its ability to handle multiple routes easily. Here’s how to add more functionality to your application:
Create Additional Routes:
@app.route('/about') def about(): return "This is the About page." @app.route('/contact') def contact(): return "This is the Contact page."Test the New Routes: After adding these routes, restart your server and visit
http://127.0.0.1:5000/aboutandhttp://127.0.0.1:5000/contactto see the respective content.
Using HTML Templates
Flask integrates seamlessly with HTML templates through the Jinja2 templating engine. It allows you to render HTML pages dynamically.
Create a Templates Directory: In your project directory, create a folder named
templates:mkdir templatesCreate an HTML Template: Inside the
templatesfolder, create a file namedhome.html:Flask App Render the Template in Your Route:
Update your
homeroute inapp.pyto render the HTML template:from flask import render_template @app.route('/') def home(): return render_template('home.html')
Adding Static Files
Static files like CSS and JavaScript can enhance the look and functionality of your application.
Create a Static Folder: In your project directory, create a folder named
static:mkdir staticAdd a CSS File: Create a file named
style.cssin thestaticfolder:body { font-family: Arial, sans-serif; background-color: #f4f4f4; } h1 { color: #333; }Link CSS in Your Template: Update
home.htmlto include the CSS file:
Handling Forms in Flask
Flask makes it easy to handle forms. To add a simple form to your application:
Create a New Template: Create a file named
form.htmlin thetemplatesfolder:Create the Route to Display the Form:
@app.route('/form') def form(): return render_template('form.html')Create a Route to Handle Form Submission:
from flask import request @app.route('/submit', methods=['POST']) def submit(): name = request.form['name'] return f"Hello, {name}!"
Connecting to a Database
Flask can integrate with databases, allowing you to store and retrieve data. Using SQLAlchemy, a popular ORM (Object Relational Mapper) for Python, you can simplify database interactions.
Install SQLAlchemy:
pip install Flask-SQLAlchemyConfigure SQLAlchemy: Update your
app.pyto connect to a SQLite database:from flask_sqlalchemy import SQLAlchemy app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db = SQLAlchemy(app)Create a Database Model:
class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(150), nullable=False)Create the Database:
After defining the model, you can create the database by running the following commands in the Python shell:
from app import db db.create_all()
Debugging and Deployment
When developing your application, enabling debug mode helps you catch errors. To run Flask in debug mode, set debug=True in your app.run() call.
For deployment, consider using platforms like Heroku, AWS, or DigitalOcean. Prepare your application for production by creating a requirements.txt file using:
pip freeze > requirements.txtDeploy the application following the specific guidelines of your chosen platform.
Additional Resources
- Flask Documentation: The official Flask documentation is an invaluable resource to further expand your Flask knowledge.
- Tutorials and Blogs: Numerous websites offer tutorials and tips on Flask development, providing a community of support for learners.
- Books: Consider reading books like “Flask Web Development” by Miguel Grinberg for in-depth learning.
By following the steps in this guide, you will be well on your way to creating your first Flask application and building upon your skills as a web developer.





