This tutorial aims to guide you in understanding the basic structure of a Flask application. Flask is a popular lightweight web framework in Python that comes in handy when developing web applications. By the end of this tutorial, you will learn how to structure your Flask application effectively, and this knowledge will aid in maintaining and scaling your projects with ease.
Prerequisites: Basic knowledge of Python and web development concepts.
A Flask application typically consists of the following files and directories:
templates/
and static/
directories for HTML and static files respectively.requirements.txt
file.Consider the following example of a basic Flask application:
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
In the above code snippet:
@app.route('/')
is a decorator in Flask, which tells the application to call the associated function when the specified URL is visited.def home():
defines a function that returns "home.html" file to the user's browser when a request comes from the browser.if __name__ == '__main__':
ensures the server only runs if the script is executed directly from the Python interpreter and not used as an imported module.Expected output: When you navigate to http://localhost:5000/
, you should see the contents of "home.html".
In this tutorial, we covered the basic structure of a Flask application. You've learned about the main components of a Flask application and their purpose. You now know how to structure your Flask application effectively.
For further learning, you can explore Flask documentation, tutorials, and other resources available online.
/about
and a new function about()
that returns an 'about.html' page./user/<username>
that takes username
as input and returns a 'Hello, username
' message.Solutions
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/user/<username>')
def profile(username):
return 'Hello, %s!' % username
style.css
in static/
directory. You can use it in your HTML as follows:<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
Remember to keep practicing and building projects with Flask to get the hang of it!