Ask AI Assistant
Download source code
Flask is a micro web framework written in Python. It is classified as a micro-framework because it does not require particular tools or libraries; developers can choose the libraries and tools they want to use. Flask is beginner-friendly and easy to learn, but it is also very powerful and can be used to build complex web applications.
Why We Chose Flask for Our Project?
Flask was chosen for our online store for several reasons:
- Simplicity: Flask is easy to install and use, and it is also easy to learn.
- Flexibility: Flask is flexible and does not force you to use particular tools or libraries. You can choose the tools and libraries you want to use.
- Extensibility: Flask is extensible, and you can add new features to Flask using easy-to-install extensions.
- Active community: Flask has a large and active community, making it one of the most popular Python web frameworks. Because of this, there are many tutorials online, and you can easily find answers if you have any questions.
Flask is a great choice for small and medium-sized projects, and it’s perfect for prototyping. However, it may not be the best fit for asynchronous applications. Additionally, building large and scalable applications with Flask requires a lot of developer experience. Nevertheless, Flask is easy to learn and use, making it a great choice for our online store.
Building a “Hello World” Application
To get started with Flask, you can create a simple “Hello World” web application. This application will display a simple “Hello, World!” message on the screen. This is a common practice when learning a new programming language or framework.
But first let’s talk about pip
Pip is a package manager for Python. It is used to install and manage Python packages. Pip comes pre-installed with Python 3.4 and above. With pip, you can install packages from PyPI (Python Package Index). To install a package, run the pip install package_name command in the terminal. To uninstall a package, run the pip uninstall package_name. You can also list all installed packages by running the pip list in the terminal.
now let’s install Flask. To do this, run the pip install flask in the terminal. This command will install Flask and all its dependencies.
Then we need to create a Python file named app.py and write some code:
from flask import Flask #let's create a new instance of flask application
app = Flask(__name__)
@app.route('/')
def hello_world(): #and handler for this application
return '<b>Hello, World!<b>'
if __name__ == '__main__': # and let's check if the current module is a main module, if it is,
app.run() # we'll run the application with debug mode enabled
This code creates a new Flask application and defines a single route that returns the “Hello, World!” message.
To run this code, you need to start the Flask application. Flask will then start a web server and listen for incoming requests. You can then open a web browser and navigate to http://localhost:5000 to see the “Hello, World!” message displayed on the screen.
When you type a URL in the browser and press enter, the browser sends a request to the web server. The web server then processes the request and sends a response back to the browser. The browser then displays the response on the screen.
introduction to Jinja2
This code in the app.py is correct, but it doesn’t follow best practices because it mixes HTML and Python code. In large applications, it can be hard to maintain such code because it’s difficult to find and understand the Python code when there are large portions of HTML code mixed in. Additionally, if we want to apply CSS to make our website visually appealing, it becomes even harder to maintain the code.
To fix this, we need to use templates. Templates are files that contain static data as well as placeholders for dynamic data. The placeholders are replaced with actual values at runtime.
Jinja2 is a popular template engine for Python. It is a modern and designer-friendly templating language that is fast and widely used. Jinja2 supports many features, such as template inheritance, filters, and macros, making it a great choice for building web applications with Python.
To create our first template, let’s create a new folder named “templates”. Then, inside the “templates” folder, create a new file named “index.html”. This file will contain the HTML code for our template.
Content of the index.html file:
<!-- there is a shortcut in visual studio code
to create basic skeleton for the HTMl file, to use this shortcut -->
<!-- just simply type "!" and hit "Tab" or "enter" -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Online Store
</title>
</head>
<body>
<p>Hello, World!</p>
</body>
</html>
After creating the index.html
file, let’s edit the hello_world
function. To do so, open the app.py file and edit the hello_world
function like this and import render_template
function from flask module. Use quick fix to import the function:
from flask import Flask, render_template
@app.route('/')
def hello_world():
return render_template('index.html')
This code renders the index.html
template and returns it to the browser. The browser then displays the template on the screen.
Passing Data to Templates
Now let’s add variable to our index.html
, we’ll add variable “name” for the web page.
<!DOCTYPE html>
<html lang="en">
<title>
Online Store
</title>
<body>
<p>Hello {{ name }}!</p> <!-- here we'll replace "World!" with new variable "name". It is possible thanks to Jinja2, jinja2 comes with flask framework by default-->
</body>
</html>
After replacing “World” with {{ name }}, let’s modify the hello_world function to display any received name. To do so, you need to modify the function so that it passes the name of the user to the template. To achieve this, you need to add name = request.args.get('name')
to the hello_world
function, and pass it to the render_template
function.
@app.route('/')
def hello_world():
name = request.args.get('name') # Here we'll extract get-parameters sent by the browser to our server. There should be a variable called "name" in the query string
return render_template('index.html', name=name)
The argument from the URL is assigned to the “name” variable and then returned to the template, and subsequently to the browser.
To display the name of the user, you need to use the query string. Simply type in localhost:5000/?name=“your name”.
Note that if there is no name in the query string, the name variable will be None. To avoid this, you can set the default value of the name variable like this:
name = request.args.get('name', 'World')
URLs
Now it’s time to learn what a URL is and how it is formed. URL stands for Uniform Resource Locator. A URL is a string that contains information about how to fetch a resource from a server. Every page you see in your browser is located at a unique URL. For example, the URL of the Google homepage is https://www.google.com/.
In our example, we had the following URL: http://localhost:5000/?name=Joe
.
Here is the structure of a URL:
- Scheme: The scheme is the protocol used to access the resource on the server. The scheme is usually HTTP or HTTPS. In the example above, the scheme is HTTP.
- Host: The host is the domain name or IP address of the server. In the example above, the host is localhost. Localhost is a special domain name that refers to the local computer. When you type localhost in the browser, the browser sends a request to the local computer.
- Port: The port is a number that identifies a specific process on the server. The port is optional, and it is usually omitted. In the example above, the port is 5000. The port is like a jack on a computer. When you plug a device into a jack, you can communicate with the device. Similarly, when you send a request to a port on a server, you can communicate with the process that is listening on that port.
- Path: The path is the location of the resource on the server. In the example above, the path is /.
- Query string: The query string is a string of key-value pairs that are appended to the end of the URL. The query string is separated from the path using a question mark (?). The key-value pairs are separated using an ampersand (&). In the example above, the query string is name=Joe. The query string is used to pass data to the server. Flask provides a request object that contains the data from the query string.
Let’s consider another example: https://www.amazon.com/Apple-2023-MacBook-Laptop-chip/dp/B0C75NTC96/?keywords=macbook&qid=1695751998
.
In this example, the scheme is HTTPS, the host is www.amazon.com, the path is /Apple-2023-MacBook-Laptop-chip/dp/B0C75NTC96/, and the query string is keywords=macbook&qid=1695751998, which represents two variables, keywords and qid (query ID).