Basic Web Development with Flask
Basic Web Development with Flask
Learning Objectives
In this lesson, you will learn: - What Flask is and why it is used for web development. - How to set up a Flask application. - How to handle routes and create views. - How to use templates to render HTML. - How to manage static files like CSS and JavaScript. - Best practices for building a Flask application.
Introduction to Flask
Flask is a lightweight web framework for Python that allows you to build web applications quickly and efficiently. It is considered a micro-framework because it does not require particular tools or libraries. This makes it a great choice for beginners who want to understand the basics of web development without the complexity of larger frameworks.
Key Terminology: - Framework: A software framework is a platform for developing software applications. It provides a foundation on which software developers can build programs for a specific platform. - Web Application: A web application is a software application that runs on a web server and is accessed via a web browser.
Setting Up Your Flask Environment
To get started with Flask, you need to set up your environment. Here are the steps:
-
Install Flask: You can install Flask using pip, which is the package installer for Python. Open your terminal or command prompt and run the following command:
bash pip install FlaskThis command downloads and installs Flask and its dependencies. -
Create a Project Directory: Create a new directory for your Flask project. You can do this using the terminal:
bash mkdir my_flask_app cd my_flask_app -
Create a Basic Flask Application: Create a new Python file named
app.pyin your project directory. This file will contain your Flask application code.
Writing Your First Flask Application
Now that you have set up your environment, let’s write a simple Flask application. Open app.py in your text editor and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
Explanation:
- from flask import Flask: This line imports the Flask class from the Flask module.
- app = Flask(__name__): This creates a new instance of the Flask class. The __name__ variable helps Flask determine the root path of the application.
- @app.route('/'): This is a decorator that tells Flask what URL should trigger the home function. In this case, it is the root URL.
- def home(): return "Hello, Flask!": This function returns a simple message when the root URL is accessed.
- app.run(debug=True): This runs the application in debug mode, which provides helpful error messages and auto-reloads the server when changes are made.
Running Your Flask Application
To run your Flask application, navigate to your project directory in the terminal and execute:
python app.py
You should see output indicating that the server is running. Open a web browser and go to http://127.0.0.1:5000/. You should see the message "Hello, Flask!" displayed on the page.
Understanding Routes and Views
In Flask, a route is a URL pattern that is associated with a function (called a view). When a user visits a route, Flask calls the associated function and returns the result to the user.
Creating Multiple Routes
You can create multiple routes in your Flask application. For example:
@app.route('/about')
def about():
return "This is the About page."
@app.route('/contact')
def contact():
return "This is the Contact page."
Using Templates
Flask allows you to separate your HTML from your Python code using templates. This makes your code cleaner and easier to manage. Flask uses the Jinja2 template engine.
- Create a Templates Directory: Inside your project directory, create a folder named
templates. - Create an HTML Template: Inside the
templatesfolder, create a file namedhome.htmland add the following code: ```html
Welcome to My Flask App!
This is a simple web application.
3. **Render the Template in Your View**: Update your `home` function to render the `home.html` template:python
from flask import render_template
@app.route('/') def home(): return render_template('home.html') ```
Managing Static Files
Static files are files that do not change, such as CSS, JavaScript, and images. Flask serves static files from a folder named static within your project directory.
- Create a Static Directory: Inside your project directory, create a folder named
static. - Add a CSS File: Inside the
staticfolder, create a file namedstyle.csswith the following content:css body { font-family: Arial, sans-serif; background-color: #f4f4f4; text-align: center; } - Link the CSS File in Your Template: Update your
home.htmlto include the CSS file:html <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
Common Mistakes and How to Avoid Them
- Forgetting to Import Flask: Always ensure that you have imported Flask and any other necessary modules at the top of your file.
- Incorrect Route Definitions: Make sure that your route decorators are correctly defined. A common mistake is to forget the
@symbol beforeapp.route. - Not Using
url_forfor Static Files: Always useurl_forto generate URLs for static files and templates to avoid hardcoding paths.
Best Practices
- Use Virtual Environments: Always create a virtual environment for your projects to manage dependencies effectively. Use
python -m venv venvto create one. - Organize Your Code: As your application grows, consider organizing your code into blueprints to manage different parts of your application more effectively.
- Keep Business Logic Separate: Separate your business logic from your view functions to maintain clean code.
Key Takeaways
- Flask is a lightweight web framework for building web applications in Python.
- Routes in Flask are defined using decorators to map URLs to functions.
- Templates allow you to separate HTML from Python code, making your application cleaner.
- Static files should be stored in a
staticdirectory and accessed usingurl_for. - Following best practices helps maintain clean and manageable code.
Conclusion
In this lesson, you learned how to create a basic web application using Flask. You set up your environment, created routes, rendered templates, and managed static files. This foundational knowledge will serve you well as you continue your journey in web development.
In the next lesson, we will explore unit testing using the unittest framework, which is crucial for ensuring the reliability of your applications.
Exercises
- Exercise 1: Create a new route
/servicesthat returns a simple string message like "This is the Services page." - Exercise 2: Create a new HTML template named
about.htmland render it from a new route/about. - Exercise 3: Add a CSS file in the
staticdirectory and link it in yourabout.htmltemplate. - Exercise 4: Create a new route
/portfoliothat renders a template displaying a list of your projects. - Practical Assignment: Build a simple Flask application that includes at least three different routes, each rendering a different HTML template. Include a navigation bar linking to each page and style it using CSS.
Summary
- Flask is a micro web framework for Python, ideal for beginners.
- Routes map URLs to functions, defining what content to display.
- Templates separate HTML from Python code, improving maintainability.
- Static files should be organized in a
staticdirectory. - Following best practices ensures a clean and efficient codebase.