Hello, world! Today, I would be creating a simple python web application with Flask, a microframework for creating full-fledged web applications. I will be covering this topic with Flask since it is an intermediate + beginner tutorial, where anyone with no prior experience can follow along.
Before we move on...
This tutorial assumes that you have Python installed in your Mac or PC (required) and that you have done object-oriented programming in Python before. These prerequisites (except the former one) are recommended but not required.
What is Flask?
- Flask is a micro web framework written in Python.
- It is classified as a microframework because it does not require particular tools or libraries.
- It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.
(Source: wikipedia)
Installation
It is always recommended to create a new directory as your project folder, and that you have activated a virtual environment (optional).
Via Pip -
pip install Flask
(See this for specifications.)
Via Conda -conda install -c anaconda flask
(See this for specifications.)
To check whether Flask has been successfully installed on your Mac or PC, type in flask --version
.
If getting an error, try using python -m flask --version
or python3 -m flask --version
.
If none of the above commands work for you, you can directly run your app instead of running it from the terminal or command prompt (more on that later).
Hmm...Seems like a handful of configurations, but these are only necessary for the first time when you install flask. (Not meant for people using virtual environment).
Our first Flask app
Now, it's time to create our flask app; create a new file in the project directory and name it "app.py". This file contains the back-end code for our application.
As a starter template, type in this code:
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, world!"
# Omittable
if __name__ == "__main__":
app.run(debug=True)
Code lines explained (for newbies)
from flask import Flask
- seems a bit strange that you have to import Flask, again from flask? What is happening here is that you are importing a class named "Flask" (capitalized) from the actual module that we installed before, named flask.
app = Flask(__name__)
- Here, we are instantiating the Flask class and declaring it in a variable named "app"; this app variable is the main structure of our app that can handle routes, run the app, debug it, etc.
The extra parameter that we give to the Flask class (__name__) just checks whether we are in an application package, or just an individual module. (Learn more here).
@app.route('/')
- Now, this is a Python decorator.
Here, we are defining a route (If you are already familiar with web programming and have used any web frameworks for this purpose, you might be familiar with routes as well).
A route is a simple way of telling the server to create a specific path in the app, so that the users will be able to visit it via a web browser.
For the purpose of demonstration, consider these routes as a pathway where users can walk through.
A web app can contain multiple routes, and each route is prefixed with a forward slash "/". If you visit a URL, most of the times the default route will be "/" (For example, " dev.to/", " google.com/"). Other examples include:
- /search
- /login
- /signup
- /posts/abcd (This is a nested route, having a route inside another route)
- /greet?name=John+Smith (A route with a URL parameter "name" and its value set to "John Smith")
def index(): return "Hello, world!"
- This line of code defines a function named index and the above decorator installs this function to the app instance of Flask class, then this function returns "Hello, world!" which would be displayed in the user's browser as an HttpResponse.
Next lines of code can be omitted if the flask --version
commands worked in your terminal window. These lines just run the app, only if the user is actually running the "app.py" file and not when importing the file from somewhere else.
Running the app
To run our app, just type in flask run
to run it via the terminal window or command prompt (in Windows), or just run the python file to run it directly (python app.py
).
Hurray! Our app has been run, now you can visit localhost:5000 in your favorite browser to see our app up and running!
Note: Try changing the value of "Hello, world!" in the 8th line to see the result being reflected on the browser.
Some HTML, perhaps?
Ok, now it's time to write some HTML and make our app look a bit nicer. Our app only returns "Hello, world!" since, which no one would like to stay with. You can also add inline HTML to the string provided (For example, return "<h1>Hello!</h1>"
), but that isn't the way to do it. The following steps show you how to add an html file to the server and display it to the user to make it an actual web app.
Create a new folder named templates in the project directory; inside of it, create a new file named "index.html". Then, inside "index.html":
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world</h1>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
</body>
</html>
Note: I've added additional Bootstrap CDN to style our web app.
Now, in our Python code, change the from flask import Flask
to something like:
from flask import Flask, render_template
This is done to make sure that we import a function named 'render_template' which returns an HTML template as an HttpResponse.
Then, change the return "Hello, world!"
to something like:
return render_template('index.html')
The above is self-explanatory. It just returns index.html whenever someone visits the "/" route.
Note: if you are using the command
flask run
, you may have to stop the server (Ctr + C) and rerun it to see the changes.
Challenge: More routes
Now, our app is just serving one route, but we can add more routes to make it more sophisticated:
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/greet')
def greet():
return render_template('greet.html')
# Omittable
if __name__ == "__main__":
app.run(debug=True)
This creates another route named "greet", and returns another HTML file "greet.html". Try creating the "greet.html" file in the templates folder and visiting localhost:5000/greet to see the newly created file!
Serving static?
CSS, JS and Assets (like images, video clips, SVG, etc.) files never change dynamically - so these can be called as static files. Create a new folder in the project directory named "static", and inside of it, you can place all your static files. One more tweak in the "app.py" file, and you are ready to go.
from flask import Flask, render_template, url_for
When linking static files, consider adding this way:
<link rel="stylesheet" href="{{url_for('static', filename='style.css')}}">
...
<script src="{{url_for('static', filename='script.js')}}"></script>
{{}}
are Jinja syntaxes. Now, Jinja is a templating language used by Flask to serve dynamic pages.
Dynamic pages?
Pages that can change its content dynamically according to the data entered by the user are called dynamic pages. These can be easily created by passing in the values (to be dynamically displayed) in the render_template
function, like:
return render_template('index.html', name="Brian")
This can be called from the "index.html" like:
<h1>Hello, {{name}}!</h1>
Conclusion
Congrats, you've created and run your first Flask app!
If you are having any queries or suggestions related to this topic, feel free to mention it in the comments below, and I will try my best to reply for the same!
Flask is an amazing platform to get started with web programming. Possibilities are endless with Flask, and you can do a lot more than the details listed in this article.
There are a lot of tutorials on the internet that can provide you with the finest materials for creating more advanced projects, and I too soon will be posting a tutorial for creating advanced apps in Flask; this was just a beginning. I will also post an article on how you can host your web app on Heroku for free. Till then, bye π!
Top comments (0)