Menu Close

Real-time Chat Application Using Python Flask

real time python chat application

In this tutorial, we will build a real-time chat application using a python microframework flask. I am going to name this application chat.py in this users will be able to register themselves and post their messages in a group where all other members of the group will be able to see them. Users can create their new chatroom where they can add other users. On posting the link, the links will be expanded with a small description about them. This tutorial will be divided into multiple sections with each section containing the code and explanation.

A quick intro to the flask

Flask is a python web application framework, it is used to build microservices, it can also be used to build scalable web applications. It does not come with batteries included in the philosophy of Django, rather it gives the developer freedom to choose their project structure and various third-party modules as and when required. Enough about flask let’s dive into building our real time chat application using python.

Prerequisites

This tutorial assumes no prerequisites in the flask but basic knowledge of Python is preferred you should be familiar with Python syntax, loop constructs, and functions in python, that is all that you need to know. Everything else will be learned as we go along building our application.

Setting up Virtual environment in Python

A virtual environment is a separate python interpreter which will contain all the dependencies required for your project to work. Suppose you are working on multiple projects, one requires Django and the other one required Flask. Now without the concept of the virtual environment, you will be installing all the third-party modules in your main python interpreter which is a bad practice, because the same python interpreter can’t have multiple versions of any package like, you can’t have Django 2 and Django 3 in the same environment, you need to separate them using the concept of the virtual environment.

To set up a virtual environment you need to type the following command in your command line:

python -m venv chat
python3 -m venv chat  (for Linux users since Linux has both versions python2 and python3)
chat application python

Here the name of the virtual environment is “chat”, you can use any name that you prefer. This command is platform-independent however in Linux-based systems if you get any error you need to install python3-venv package then this command will work.  Okay, now you should see a folder created named chat inside the directory from where you executed this command. Okay our work is not done here we have created our virtual environment but we need to activate this to use it. Type:

chat\Scripts\activate.bat

and press Enter. for Linux user, execute the following command:

source  chat/bin/activate 
real-time chat application using python

You should see a (chat) prefixed before your current directory prompt.  Now you have successfully created and activated your venv. Note: I would use venv and virtual environment interchangeably both refer to the same thing.

Installing packages in python

Python comes with a built-in package manager pip which is used to manage packages for our environment. For building our application we are going to need the flask web framework in our venv. So for installing it we need to type:

pip install flask
chat.py

that’s it you would see some installation going on in your terminal. Now you have successfully installed the flask. To verify whether it’s properly installed or not, type

flask --version

In the command prompt, you should see something like Flask 2.0.0, etc. If you’re seeing this output that means the flask is installed correctly. Okay, now we’re ready to start writing our web application.

Coding our web application ( Real-time Chat Application Using Python)

Let’s code our real time chat application using python. Create a new directory named chatapp inside directory again create a new directory chat.py. This folder structure is entirely up to you and all the naming conventions. But having a structured format is good and avoids confusion when you work on multiple apps together. I will paste screenshots of the directory structure and also the code files to help you understand better.

Directory structure:

chat.py directory
  • Create a file named chat.py inside the chat.py folder. Now add the following lines:
  • The first line of the chat.py file imports the Flask class from the flask package. Here Flask( with capital F) is the main class for our application.
  • In line 3, We create an instance of this class by passing (__name__) as a constructor variable.
  • Line 5: We are using @app.route(“/”)  decorator, what this doing is telling our application to call this method whenever a request comes to our page, we will explain this in just a bit.
  • Line 6: We are defining a python function named chat()  which is just returning “My chat application.”  to the caller.
  • Line 9: Well this we need to understand whenever we run our python script from the command line the script is referred to by a special name known as ” __main__”. So what this, if statement is doing, is just checking
  • Whether we are running this file directly or not if we are running this directly and not importing it only then will the below lines execute.
  • Line 10: Now here’s the crux of running the application. Our flask application has a method run which is taking these few parameters like host, port, etc. Now, since this is a web application we need to access it from our web browser but how does our app know, where should I run my self or how should the browser know where to request it. Do we need the internet to run our website? Absolutely not. So there is a special IP

Address provided to run it which is “127.0.0.1” also known as localhost. Now what is the second parameter the port number, again our app needs a specific port to listen on so by default flask takes 5000 and I’ve also explicitly passed it to help you understand better. The third variable is threaded, I’ve set it true by default it’s also true. With every request, the flask server creates a separate thread to handle the request, so if we want multiple people to use our website at once we need to set it as true. Now the debug option, by default, is False which means you need to rerun your application every time so since we’re developing it’s nice to set it to true.

Running our application

  • Type python chat.py and you should see the below output in VScode or your terminal.
running the chat application using python
  • It’s saying Serving Flask app ’chat’  (lazy loading).  Here this name chat is coming from that Flask(__name__)  constructor name contains the name of our python script file.
  • Environment: production we will look at it later, for now, you can ignore it.
  • Debug mode: on again this value we passed in app.run() method where we set debug=True
  • Running on http://127.0.0.1:5000/           this is the actual address which you need to type in the web browser to see whether your app is working.
local host
  • Here, you can see the address bar of the browser I’ve typed http://127.0.0.1:5000/  here and you can see the web page is showing My chat application. But how this is happening.
python real-time chat application
  • You noticed two new lines added here well these are what we called as web server logs, we will talk about these in a later part of our tutorial, but for now you can understand that every time someone will visit that URL our app will record that in logs and display them in the console.
  • Now regarding the output on a webpage what is happening in our chat() function is mapped to the root of the URL whenever anyone visits that URL the chat() function will be called and the value that is returned will be displayed on the webpage. How this is doing is the magic of flask. But what you need to understand is that what the browser did when it went to that URL is it requested our application to return something and our app called that method and returned the response that was “My chat application” which was displayed on the web browser.

Code Files

All code files will be available on this Github repository:  https://github.com/abhinayy0/chat.py

Summary:

In this mini-tutorial, we have created a real time chat application using python. further, we have understand the Flask python web framework and what it is used for after that we dive into virtual environments and the problem they solved. The essence of computer programs is that they are created to solve a particular type of problem. Later we learned how to install Flask using pip and after that, we dived into the development of our minimal application.  In the application, we understood about Flask class and how python scripts are executed, and also about the methods provided by this class. After that starting our application we understood the output of our app and what each line means. In the next part of this tutorial, we will start from here and will start developing the real-time chat application chat.py.