Flask is a lightweight web framework for Python that allows you to build web applications. In this tutorial, we will learn how to create a Flask web server step by step. Let’s get started!
Step 1: Install Flask
Before we begin, make sure you have Python installed on your system. You can download the latest version of Python from the official website.
Once you have Python installed, open your command prompt or terminal and run the following command to install Flask:
pip install flask
Step 2: Create a Flask Application
Create a new directory for your project and navigate to it in your command prompt or terminal. Inside the project directory, create a new Python file called “app.py”.
In “app.py”, import the Flask module and create an instance of the Flask class:
from flask import Flask app = Flask(__name__)
Step 3: Create Routes
Routes are URLs that users can visit in your web application. For example, if you want to create a route for the home page, you can define it using the `@app.route` decorator.
Let’s create a simple route that displays “Hello, World!” when visited:
@app.route('/') def hello(): return 'Hello, World!'
Step 4: Run the Web Server
To run the Flask web server, add the following code at the end of “app.py”:
if __name__ == '__main__': app.run()
Now, go back to your command prompt or terminal and navigate to your project directory. Run the following command:
You should see an output similar to this:
* Running on http://127.0.1:5000/ (Press CTRL+C to quit)
Congratulations! You have successfully created a Flask web server.
Now, open your web browser and visit http://127.1:5000/. You should see the “Hello, World!” message displayed.
Step 5: Adding HTML Templates
While returning plain text is great for simple applications, Flask also allows you to return HTML templates for more complex web pages.
First, create a new directory called “templates” inside your project directory. Inside the “templates” directory, create a new HTML file called “index.html”.
In “index.html”, add the following code:
<!DOCTYPE html> <html> <head> <title>Flask Web Server</title> </head> <body> <h1>Welcome to Flask Web Server!</h1> <p>This is a sample HTML page served by Flask.</p> </body> </html>
Now, modify your route in “app.py” to render the HTML template:
from flask import render_template @app.route('/') def hello(): return render_template('index.html')
Run the web server again using the same command as before.
When you visit http://127.1:5000/, you will now see the content of “index.html” rendered by Flask.
In this tutorial, we learned how to create a Flask web server. We covered the installation process, creating routes, running the server, and returning HTML templates. Flask is a powerful framework that allows you to build web applications quickly and efficiently.
Now that you have a basic understanding of Flask, you can explore its other features such as handling form submissions, working with databases, and implementing authentication. Happy coding!