Complete Flask Tutorial for Python

Posted by


Flask is a popular web framework for Python that is lightweight, easy to use, and highly customizable. In this tutorial, we will cover everything you need to know to get started with Flask, including how to set up a basic Flask app, create routes, handle requests, work with templates, and more.

To follow along with this tutorial, you will need to have Python installed on your computer. You can download the latest version of Python from the official website (https://www.python.org/downloads/). Once you have Python installed, you can install Flask by running the following command in your terminal or command prompt:

pip install Flask

Now that you have Flask installed, let’s create a simple Flask app. Create a new directory for your project and navigate to it in your terminal. Inside the directory, create a new Python script (you can name it app.py) and open it in your preferred code editor.

In your app.py file, import the Flask class from the flask module and create an instance of the Flask class:

from flask import Flask

app = Flask(__name__)

Next, you can define a route that will respond to HTTP requests. Routes are functions that you decorate with the @app.route() decorator. The function should return the response that will be sent back to the client. Let’s create a simple route that will return a welcome message when visiting the root URL ("/") of the app:

@app.route('/')
def index():
    return 'Welcome to my Flask app!'

Now that we have defined our route, we can run the Flask development server to see our app in action. Add the following code to the bottom of your app.py file:

if __name__ == '__main__':
    app.run(debug=True)

To start the Flask development server, run the following command in your terminal:

python app.py

You should see output that the Flask development server is now running on http://127.0.0.1:5000/. Open your web browser and navigate to this URL to see your Flask app in action.

Congratulations! You have created a basic Flask app with a single route. In the next section, we will cover more advanced features of Flask, such as handling different types of requests, working with templates, and more.

Handling Different Types of Requests
In addition to handling GET requests, Flask allows you to handle other types of HTTP requests, such as POST, PUT, DELETE, and more. You can specify which HTTP methods a route should respond to by passing the methods argument to the @app.route() decorator. For example, to create a route that only responds to POST requests, you can do the following:

@app.route('/submit', methods=['POST'])
def submit():
    return 'You have submitted a form'

Working with Templates
Flask allows you to render HTML templates to generate dynamic content for your web pages. Templates are stored in a templates directory inside your project directory. You can render a template by using the render_template() function from the flask module. First, create a templates directory inside your project directory and create a new HTML file (you can name it index.html) with the following content:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome to my Flask app!</h1>
</body>
</html>

Next, modify your index route to render the index.html template:

from flask import render_template

@app.route('/')
def index():
    return render_template('index.html')

Now, when you visit the root URL of your app, you should see the content of the index.html template rendered in your browser.

Adding Dynamic Data to Templates
Flask allows you to pass dynamic data to templates by using template variables. You can pass variables to the render_template() function as keyword arguments, which can then be accessed in the template. For example, let’s modify our index route to pass a variable called name to the index.html template:

@app.route('/')
def index():
    name = 'John'
    return render_template('index.html', name=name)

In your index.html template, you can access the name variable using Jinja2 template syntax:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome, {{ name }}!</h1>
</body>
</html>

Now, when you visit the root URL of your app, you should see a personalized welcome message with the name "John" rendered in your browser.

Using Forms
Flask allows you to handle form submissions using the request object. You can access form data submitted by the client through the request.form attribute, which is a dictionary-like object that contains the data sent via POST requests. For example, let’s create a simple form in our index.html template that allows users to submit their name:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome!</h1>
    <form method="POST">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Next, create a new route in your app.py file that handles the form submission:

from flask import request

@app.route('/submit', methods=['POST'])
def submit():
    name = request.form['name']
    return f'Thank you for submitting, {name}!'

Now, when a user submits the form by entering their name and clicking the Submit button, they should see a confirmation message with their name displayed on the screen.

Conclusion
In this tutorial, we covered the basics of Flask, including how to set up a basic Flask app, create routes, handle requests, work with templates, and more. Flask is a versatile web framework that allows you to build web applications quickly and easily. By following the steps in this tutorial, you should now have a good understanding of how to get started with Flask and build your own web applications using Python. Feel free to experiment with different features of Flask and explore the documentation to learn more about what you can do with this powerful web framework. Happy coding!

0 0 votes
Article Rating
32 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@harshakarapureddy2596
2 months ago

I cannot do the import app from db, it just returns ModuleNotFoundError: No module named 'app'

@jubairsami8524
2 months ago

it's stunning that no chatgpt were existing when this tutorial was made

@sambarjunk
2 months ago

Outdated

@sumitapathak2900
2 months ago

Thank you. I finally have a development project in Python now. And ofcourse I am gonna keep learning

@neeharika422
2 months ago

This video is like listening tests when you're learning a new language… and I'm here for it! Especially when if I'm really lost, google or ai can explain it simply so the flow of the vidio isnt lost by the slow explanations.
Especially good because I have very basic knowledge of HTML and python!

@kritigupta1525
2 months ago

If you are a complete beginner to flask, rather read through the basic syntax first and then watch this tutorial to get a sense of what's happening. otherwise its a good short, succinct overview of CRUD application in flask.

@zt9352
2 months ago

Thank you very much!!!

@afahayangha6085
2 months ago

Great content. Very explicit. You nailed it in such a short time Thanks!

@lknryrn
2 months ago

well, this content is really helpfull but i wish istead of you just explain how to write "to do list program" with flask i have learned the basics of flask more so i could try it on my own project

@loicollervides4131
2 months ago

when i try to open the link at the very end it shows me a page with method not allowed. how can i ix that?

@fanBladeOne
2 months ago

Chads for uploading the code

@ColdClock
2 months ago

Thank you, I followed along easily and everything was well explained. I did get a few errors as things have seeminly changed a bit since your tutorial but it was easily enough to google the solutions. I styled the whole thing with Bulma once I was done and it looks great. Thank you again!

@arpitkumar4525
2 months ago

Super Cool. Short and to the point

@ElCuchu
2 months ago

I don't know if this comment will be answered. I'm following this tutorial and I got stuck on minute 8:37. I can create that app and put it to work, but I can't load the app on my browser, it just stays on loading. Anybody of you went through this too?

@crazyboy58
2 months ago

thanks fam finna add u on linked in

@danielius9156
2 months ago

Dude, how are you so bad at writing, this video would've been a lot shorter if you learned to type fast and correctly…

@thomasmuller6005
2 months ago

Hi there – I am stuck at 31:00!! When I open up my local host, I get an Error:

OperationalError
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: todo
[SQL: SELECT todo.id AS todo_id, todo.content AS todo_content, todo.date_created AS todo_date_created
FROM todo ORDER BY todo.date_created]

I have to say – vs code had a problem with line 12 in app.py! I changed 'default=datetime.utcnow' to 'default=datetime.now' because: 'The method "utcnow" in class "datetime" is deprecated
Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.UTC)'. Anyway, could not find any other differences…

would be very thankful for help.🙏

@juanperon2466
2 months ago

This tutorial is not enough for beginners, many concepts are not explained at all

@AhamedThijaniPP
2 months ago

At line:1 char:1

+ from app import db

+ ~~~~

The 'from' keyword is not supported in this version of the language.

+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException

+ FullyQualifiedErrorId : ReservedKeywordNotAllowed

show at 19:43

@madhumitha_1010_
2 months ago

I was following along but i am getting this error again and again
from app import db

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ModuleNotFoundError: No module named 'app'

i opened my virtual environment and then opened my python3 and this happens