In this Python Flask article we want to learn about Building Flask Web Application with Python, Flask is popular micro web framework for building web applications in Python. it is lightweight and easy to use, and this makes it great choice for building simple web applications quickly. in this article we want to talk how build Flask web application with Python.
Building Flask Web Application with Python
First of all we need to install Flask
1 |
pip install Flask |
For creating Flask web application, we first need to create new Python file. in this example, we want to call it app.py. we can start by importing the Flask module and creating new Flask application instance, in here we are importing Flask class from the Flask module and creating new instance of the Flask class. we are also passing in the special variable __name__, which tells Flask where to find application resources.
1 2 3 |
from flask import Flask app = Flask(__name__) |
Now we need to create our route, in Flask route is a URL pattern that maps to a function. we can define routes using @app.route decorator, for example we can define a route that maps to the root URL of our web application like this, this code defines a route that maps to the root URL (“/”) and a function called index() that returns the string Welcome to geekscoders.com when the root URL is accessed.
1 2 3 |
@app.route("/") def index(): return "Welcome to geekscoders.com" |
We can also define additional routes by creating more functions and decorating them with the @app.route decorator. for example we can define a route that maps to a URL like /about like this.
1 2 3 |
@app.route("/about") def about(): return "This is a sample Flask web application." |
To run our Flask web application, we need to add the following lines of code to the bottom of our app.py file.
1 2 |
if __name__ == "__main__": app.run() |
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "<h1>Welcome to geekscoders.com</h1>" @app.route("/about") def about(): return "This is a sample Flask web application." if __name__ == "__main__": app.run() |
You can run this code and go to this url http://127.0.0.1:5000/