Welcome to the Flask tutorial for beginners. In this tutorial, our main goal is to create a simple Flask web application from scratch. Flask is a powerful micro-framework for Python that allows for quick and easy web application development.
At the end of this tutorial, you will have a basic understanding of how to:
Prerequisites:
Before we begin, ensure you have the following:
Here is a detailed guide on how to create your first Flask application.
The first thing we need is Flask itself. You can install Flask using pip:
pip install flask
After you've installed Flask, you can create a new Flask application. Start by creating a new folder named "flask_app". Inside this folder, create a new Python file named "app.py". This is where we will write our Flask application.
Here's a simple Flask application:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
Let's dive deeper into the Flask application we just created:
# Import the Flask class from the flask module
from flask import Flask
# Create an instance of the Flask class
app = Flask(__name__)
# Define a route for the URL "/"
@app.route('/')
# Define a function that is triggered when the user visits the URL "/"
def home():
# Return a string to be displayed on the webpage
return "Hello, Flask!"
# Check if the script is running directly
if __name__ == '__main__':
# Run the Flask application with debug mode enabled
app.run(debug=True)
When you run this script and navigate to http://localhost:5000/
in your browser, you should see the text "Hello, Flask!".
In this tutorial, we've learned the basics of Flask including how to set up a Flask project, how to create routes and views, and how to use templates. Flask is a powerful tool for creating web applications, and we've only just scratched the surface of what it can do.
As next steps, consider exploring the following topics:
To solidify your understanding of Flask, try the following exercises:
Solution
@app.route()
decorator:python
@app.route('/name')
def name():
return "Your Name"
@app.route()
decorator:python
@app.route('/greet/<name>')
def greet(name):
return f"Hello, {name}!"
render_template()
function to render this template:```python
from flask import render_template
@app.route('/info')
def info():
return render_template('info.html')
```
In "info.html", you can write HTML code to display whatever information you want. For more complex data, you can pass variables to the template from your route function.