A Python micro web framework called Flask is used to create web apps. For those learning how to create web apps in Python, Flask is a popular option because of its famed simplicity, adaptability, and ease of usage. You will learn the fundamentals of creating web applications using Flask in this article.
The installation of the Flask framework is the initial step in creating a Flask application. Pip, the Python package manager, can be used for this. Type the following command into your terminal once it is open: install Flask using pip.
Create a Flask Application:
Create a new Python file and import the Flask class to create a Flask application. Then, set the name of the application and create a new instance of the Flask class. For instance:
from flask import Flask app = Flask(name) @app.route("/") def hello(): return "Hello, World!"
This creates a new Flask application with a single route that returns the string “Hello, World!” when accessed.
Routing involves finding a function that matches a URL and produces a response. Using Flask’s @app.route decorator, you may define routes. For instance:
@app.route("/about") def about(): return "About Us"
This creates a new route for the URL “/about” that returns the string “About Us” when accessed.
In Flask, templates are used to build dynamic HTML pages. Jinja2 is one of the template engines that Flask supports. Create a new folder called “templates” in your project directory, and then add your template files to this folder to use templates in Flask. For instance:
from flask import Flask, render_template app = Flask(name) @app.route("/") def index(): return render_template("index.html", name="John")
This code uses the
render_template function to render a template called “index.html” and passes a variable called “name” with the value “John”.
Running the Application:
Run the command flask run in your terminal to launch the Flask application after saving your code to a file with a.py extension.
In conclusion, Flask is a straightforward and adaptable web framework for creating Python online applications. You can construct a Flask application, specify routes, use templates, and run your application by following these simple steps. You can create more complicated and potent web apps with the help of more advanced Flask technologies.