How to create a simple server with Python Flask?

How to create a simple server with Python Flask?

Flask is one of the popular and simple-to-learn frameworks of Python to build a full-stack web app.

This tutorial is the first part of the complete full-stack web app, we are going to build using Flask Framework.

Prerequisite:

Python must be installed version greater than 3.7 (i.e requirement of Flask)

This tutorial is created on Ubuntu but you can run similar commands on macOS or Windows OS.

Know some basics of Python language.

Let's Start:

Step 1. Create a folder and open it in VS Code.

mkdir my-flask-app
cd my-flask-app
code .

Step 2. Create a requirements.txt file.

(For Python Beginner: requirements.txt or any txt file we use in Python to write on which package this project is dependent, for example here we are going to depend on the Flask package for this project, and we use this file to download those packages for the first time we start the project)

touch requirements.txt

Now open this file in VS Code and add the below line

flask==2.1.1

Step 3. Now create a file app.py and add the below code.

#app.py

# importing Flask from flask package
from flask import Flask

# creating app from the Flask
app = Flask(__name__)

# creating base route with .route("/") and returning a p tag with Hello World
@app.route("/")
def hello_world()   return "<p>Hello, World!</p>"

# this is to start a server on local host with port 5001
if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True, port=5001)

Step 4: Now open a terminal and run (You can use a virtual environment if you know that already in Python otherwise, a simple command will also do the same thing)

pip install -r requirements.txt
python app.py run

Now open your browser and visit localhost:5001 and you'll see "Hello World!"

This is the first part, in the next part we will see how to create multiple routes and render HTML pages.

Thank you, and see you in the next post.

Let's Connect on:

Tags :
Share :

Related Posts

How to install Apache Spark on Ubuntu?

How to install Apache Spark on Ubuntu?

This tutorial is for Ubuntu Users. For Windows users, you can directly install Apache Spark from the below link and start it directly on Powershell. Download the latest Spark from Apache Website htt

read more
How to open VS Code Live Server Extension web page on Mobile?

How to open VS Code Live Server Extension web page on Mobile?

Hello guys, today I am going to write about a very productive topic if you have started learning as a Web developer and using one of our favorite Code editors as a VS Code. So, if you have ever writ

read more