Calculate time dilation with python

In this example imagine two object one is Earth And another object is traveling in the space

\[ t_0 = t \sqrt{1 – \frac{v^2}{c^2}} \]
  • t0: Represents the dilated time experienced by the object which is traveling or seems traveling from earth
  • t: Time passed on earth
  • v: Velocity of the traveling object.
  • c: Speed of light in the vacuum.

Now back to our example. Here user will enter the time passed on earth and the speed of the traveling object. The program will calculate the time dilation.


from math import sqrt
c=299792458 #speed of light in m/s

t=eval(input("Enter the time passed on earth in year: "))
v=c
while not v<c:
	v=eval(input("Enter the speed of the object in m/s: "))
	if v>c:
		print("Speed of the object must be less than the speed of light:",c)
def time_dilation(c,v,t):
	t_0=t*sqrt(1-(v**2/c**2))
	return t_0
time_passed_to_object=time_dilation(c,v,t)
print("time passed to the object",time_passed_to_object," year")
print("time difference",t-time_passed_to_object," year")


For example if time pass on earth 20 years and the object is traveling in speed 7497924 m/s

The program will print this result based on user input

Enter the time passed on earth in year: 20
Enter the speed of the object in m/s: 7497924
time passed to the object 19.993743829255635  year
time difference 0.006256170744364908  year

How to convert text to sentence with python and nltk

We can easily convert text to sentence in python with nltk by tokenize sentence..

First install nltk

pip install nltk

Download nltk data .

NLTK requires data files for tokenization. run the code in a python program to download the data.


import nltk
nltk.download('punkt')


After download the necessary data


from nltk import tokenize

text="In the symphony of existence, we discover our interconnectedness and the boundless spiritual power within us. Together, we build a world where empathy thrives, sparking hope and lighting the way to a future filled with harmony and peace."

sentence_list=tokenize.sent_tokenize(text)
print(sentence_list)


#for sentence in sentence_list:
#	print(sentence)

for i, sentence in enumerate(sentence_list, start=1):
    print(f"Sentence {i}: {sentence}")


this will print the the result like this

['In the symphony of existence, we discover our interconnectedness and the boundless spiritual power within us.', 'Together, we build a world where empathy thrives, sparking hope and lighting the way to a future filled with harmony and peace.']
Sentence 1: In the symphony of existence, we discover our interconnectedness and the boundless spiritual power within us.
Sentence 2: Together, we build a world where empathy thrives, sparking hope and lighting the way to a future filled with harmony and peace.

How to get all possible combinations with python

Python is rich with wonderful standard library so you do not have to write everything from the very beginning. With permutations from iterators we can get wonderful and useful result with less code

>In this example code we get the user input as string

> Get the user input length

> Then run a for loop based on the user input str length

> get the combinations with permutation with store the combination in a list

Like this

Enter your word or sentence or number: 123
['1', '2', '3', '12', '13', '21', '23', '31', '32', '123', '132', '213', '231', '312', '321']



from itertools import permutations
user_input=str(input("Enter your word or sentence or number: "))
l=len(user_input)+1
combinations=[]
for i in range(1,l):
	a=list(permutations(user_input,i))
	for element in a:
		x=(''.join(element))
		combinations.append(x)
print(combinations)


We can make this more wonderful to print out with pprint. Also print out all combinations from a list.


from itertools import permutations
from pprint import pprint
# flower names
flower_names = ["rose","orchid", "sunflower"]

l=len(flower_names)+1
combinations=[]
for i in range(1,l):
	a=list(permutations(flower_names,i))
	combinations.append(a)
pprint(combinations)


You will get this result on running this code

[[('rose',), ('orchid',), ('sunflower',)],
 [('rose', 'orchid'),
  ('rose', 'sunflower'),
  ('orchid', 'rose'),
  ('orchid', 'sunflower'),
  ('sunflower', 'rose'),
  ('sunflower', 'orchid')],
 [('rose', 'orchid', 'sunflower'),
  ('rose', 'sunflower', 'orchid'),
  ('orchid', 'rose', 'sunflower'),
  ('orchid', 'sunflower', 'rose'),
  ('sunflower', 'rose', 'orchid'),
  ('sunflower', 'orchid', 'rose')]]

Easy Temperature Conversions with Python: A Beginner’s Guide (Celsius, Fahrenheit, Kelvin)

Basic Temperature Conversion Program

This program takes a temperature input from the user, identifies the scale (Celsius, Fahrenheit, Kelvin), and converts it to the other two scales. Let’s break down the code step-by-step.

For higher accuracy in the Kelvin scale use 273.15 instead of 273


x = str(input("Enter in which scale you measured temperature (Celsius, Fahrenheit, Kelvin)? Enter C or F or K: "))
# 160 is 5*32  .... equations are simplified
if x=="C" or x=="c":
    c=eval(input("Enter your temperature in Celsius scale: "))
    to_fahrenheit=(9*c+160)/5
    to_kelvin=c+273
    print("Celsius :", c,  "\nFahrenheit :", to_fahrenheit,  "\nKelvin: ", to_kelvin)
    
elif x=="F" or x=="f":
    f=eval(input("Enter your temperature in Fahrenheit scale: "))
    to_celsius=(5*f-160)/9
    to_kelvin=((5*f-160)/9)+273
    print("Celsius :", to_celsius,  "\nFahrenheit :", f,  "\nKelvin: ", to_kelvin)
    

elif x== "K" or x=="k":
    k=eval(input("Enter your temperature in Kalvin scale: "))
    to_celsius=k-273
    to_fahrenheit=(9*(k-273)+160)/5
    print("Celsius :", to_celsius,  "\nFahrenheit :", to_fahrenheit,  "\nKelvin: ", k)



Explanation

>Firstly the this code takes input from user in which scale user measured the temperature

>Then user asked for another input in which scale they want to convert

  • The user is prompted to enter the temperature scale: ‘C’ for Celsius, ‘F’ for Fahrenheit, or ‘K’ for Kelvin.
  • Conversion Calculations:
  • Depending on the input scale, the program calculates the temperature in the other two scales using the following formulas:

Celsius to Fahrenheit:

\[ F = \frac{9}{5}C + 32 \]

Celsius to Kelvin:

\[ K = C + 273 \]

Fahrenheit to Celsius:

\[ C = \frac{5}{9}(F – 32) \]

Fahrenheit to Kelvin:

\[ K = \frac{5}{9}(F – 32) + 273 \]

Kelvin to Celsius:

\[ C = K – 273 \]

Kelvin to Fahrenheit:

\[ F = \frac{9}{5}(K – 273) + 32 \]

Complete code with some added feature


x = str(input("Enter in which scale you measured temperature (Celsius, Fahrenheit, Kelvin)? Enter C or F or K: "))
# 160 is 5*32  .... equations are simplified
if x == "C" or x == "c":
    c = eval(input("Enter your temperature in Celsius scale: "))
    to_fahrenheit = (9 * c + 160) / 5
    to_kelvin = c + 273
    while to_kelvin < 0:
        print("Temperature cannot be less than absolute zero")
        c = eval(input("Enter your temperature in Celsius scale: "))
        to_fahrenheit = (9 * c + 160) / 5
        to_kelvin = c + 273
    print("Celsius:", c, "\nFahrenheit:", to_fahrenheit, "\nKelvin:", to_kelvin)
    
elif x == "F" or x == "f":
    f = eval(input("Enter your temperature in Fahrenheit scale: "))
    to_celsius = (5 * f - 160) / 9
    to_kelvin = ((5 * f - 160) / 9) + 273
    while to_kelvin < 0:
        print("Temperature cannot be less than absolute zero")
        f = eval(input("Enter your temperature in Fahrenheit scale: "))
        to_celsius = (5 * f - 160) / 9
        to_kelvin = ((5 * f - 160) / 9) + 273
    print("Celsius:", to_celsius, "\nFahrenheit:", f, "\nKelvin:", to_kelvin)
    
elif x == "K" or x == "k":
    k = eval(input("Enter your temperature in Kelvin scale: "))
    while k < 0:
        print("Temperature cannot be less than absolute zero")
        k = eval(input("Enter your temperature in Kelvin scale: "))
    to_celsius = k - 273
    to_fahrenheit = (9 * (k - 273) + 160) / 5
    print("Celsius:", to_celsius, "\nFahrenheit:", to_fahrenheit, "\nKelvin:", k)




Expiring Links Tutorial: Python Flask One-Time Link Generator

One time links are essential where users want to share resources with co-worker or friend’s effortlessly but at the same time restrict other from access.

Its works best because the link automatically inactive if some one go to the link for the first time. That means the same link will not work for the second time. or for other user.

Also we can set time so if no one enters the link it will automatically inactive after the specific time.

Now begin our program

  1. first the user will generate the link. and share..
  2. Other user will go to link and get access.
  3. the link(token) will be deleted from the active token list so it will not work anymore
  4. If no one access the link it will automatically remove from the shared link after specific time.

Generate link

we will use python secrets library to generate the unique token for the link

def generate_token():
    return secrets.token_urlsafe(16)

this is existing users list.( its example for the users who have account)


main_user_ids = ['user1', 'user2', 'user3']

So this users will be able to create the link for friends and co-workers

we will store the active token in python dictionary right now. For real world application you can use database like sql, mongodb or whatever you want

active_tokens = {}

This is code what the main users will get in the browser. You can use render template and place hte index.html in the template folder. but for simplicity we applied it directly.

@app.route('/', methods=['GET'])
def index():
    #return render_template('index.html')
    return """
    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Connection Link</title>
</head>
<body>
    <h1>Generate Connection Link</h1>
    <form action="/generate_link" method="post">
        <label for="user_id">Enter User ID:</label><br>
        <input type="text" id="user_id" name="user_id"><br><br>
        <input type="submit" value="Generate Link">
    </form>
</body>
</html>
"""

Here the main users will enter the user name and generate the link on behalf of them

This is the second part of the code where generate the key from the previous code form action generate link

from datetime import datetime, timedelta
TOKEN_EXPIRY_DURATION = timedelta(hours=1)

# Route to generate a connection link
@app.route('/generate_link', methods=['POST'])
def generate_link():
    user_id = request.form.get('user_id') if request.form.get('user_id') in main_user_ids else None
    if user_id:
        token = generate_token()
        expiry_time = datetime.now() + TOKEN_EXPIRY_DURATION
        active_tokens[token] = (user_id, expiry_time)
        return f"Generated link from user {user_id}: <a href='/connect/{token}'>Click here to connect</a>"  # Return the generated token to the user
    else:
        return "Invalid user ID"

Here in the server side get the user name from the user . if user name exists then create an unique token and link on behalf of the user

Next part Verify the users access



# Route to handle the connection link
@app.route('/connect/<token>', methods=['GET'])
def connect(token):
    if token in active_tokens:
        user_id, expiry_time = active_tokens[token]
        if datetime.now() < expiry_time:
            # Connection successful, do something with the user_id
            del active_tokens[token]  # Mark the token as used
            return f"You have grant access by {user_id}"
        else:
            return "Token expired"
    else:
        return "Invalid token"

In this part the link is received from the user and verify if that exist. if exist and have expiration time . It grant the permission to that user and delete link(token) from the active tokens.

The complete code


from flask import Flask, request, redirect, url_for, render_template
from datetime import datetime, timedelta
import secrets

app = Flask(__name__)

# Active tokens and their expiry times
active_tokens = {}

# Duration for the token to remain valid (e.g., 1 hour)
TOKEN_EXPIRY_DURATION = timedelta(hours=1)

# Main user IDs
main_user_ids = ['user1', 'user2', 'user3']

# Function to generate a unique token
def generate_token():
    return secrets.token_urlsafe(16)

# Route to render the form
@app.route('/', methods=['GET'])
def index():
    #return render_template('index.html')
    return """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Connection Link</title>
</head>
<body>
    <h1>Generate Connection Link</h1>
    <form action="/generate_link" method="post">
        <label for="user_id">Enter Your User ID( this represents the main users in the main usrs list. enter a name from the uses list main_user_id for example <b>user1</b> :</label><br>
        <input type="text" id="user_id" name="user_id"><br><br>
        <input type="submit" value="Generate Link">
    </form>
</body>
</html>
"""

# Route to generate a connection link
@app.route('/generate_link', methods=['POST'])
def generate_link():
    user_id = request.form.get('user_id') if request.form.get('user_id') in main_user_ids else None
    if user_id:
        token = generate_token()
        expiry_time = datetime.now() + TOKEN_EXPIRY_DURATION
        active_tokens[token] = (user_id, expiry_time)
        return f"Generated link from user {user_id}: <a href='/connect/{token}'>Click here to connect</a>"  # Return the generated token to the user
    else:
        return "Invalid user ID"



# Route to handle the connection link
@app.route('/connect/<token>', methods=['GET'])
def connect(token):
    if token in active_tokens:
        user_id, expiry_time = active_tokens[token]
        if datetime.now() < expiry_time:
            # Connection successful
            del active_tokens[token]  # Mark the token as used
            return f"You have grant access by {user_id}"
        else:
            return "Token expired"
    else:
        return "Invalid token"

if __name__ == '__main__':
    app.run(debug=True)



Converting Between Python Dictionaries and JSON

We will use json.dums() function to convert to json from python dictionary and json.loads() to convert from json to python dictionary.

In this example code we used flower details data in python dictionary and converted it to json.


import json

# flowers in python dictionary
flowers = {
    "rose": {
        "scientific_name": "Rosa",
        "grows_in": ["gardens", "wild"],
        "colors": ["red", "pink", "white"]
    },
    "sunflower": {
        "scientific_name": "Helianthus annuus",
        "grows_in": ["fields", "gardens"],
        "colors": ["yellow"]
    }
}

# Converting Python dictionary to JSON

flowers_json = json.dumps(flowers)
# converted to json
print(flowers_json)



# we can add indent to make it more readable
flowers_json = json.dumps(flowers, indent=4)
print(flowers_json)





# Now convert json to python dictionary
#fowers_json is alreay in json

flowers_dict = json.loads(flowers_json)
#converted to python dictionary
print(flowers_dict)



Exporting Python Dictionaries to JSON Files

we can also export this python dictionary data to json


import json

# flowers in python dictionary
flowers = {
    "rose": {
        "scientific_name": "Rosa",
        "grows_in": ["gardens", "wild"],
        "colors": ["red", "pink", "white"]
    },
    "sunflower": {
        "scientific_name": "Helianthus annuus",
        "grows_in": ["fields", "gardens"],
        "colors": ["yellow"]
    }
}

# Converting Python dictionary to JSON

flowers_json = json.dumps(flowers)

# Exporting Python dictionary to a JSON file
with open("flowers.json", "w") as json_file:
    json.dump(flowers, json_file, indent=4)


Loading JSON Data from Files into Python Dictionaries


# Loading JSON data from a file into Python dictionary
import json
with open("flowers.json", "r") as json_file:
	#convert to python dictionary with json.load()
    loaded_flowers_dictionary = json.load(json_file)

print(loaded_flowers_dictionary)



Storing and retrieving data from sqlite with python

For making everything simpler we will use peewee orm with python sqlite3….

pip install peewee

First create and connect to our database



from peewee import *

# SQLite database setup with Peewee
db = SqliteDatabase('cv_database.db')

class User(Model):
    username = CharField(unique=True)
    # Add more user details as needed

    class Meta:
        database = db

class CV(Model):
    user = ForeignKeyField(User, backref='cv')
    education = TextField()
    work_experience = TextField()
    skills = TextField()
    # Add more fields as needed

    class Meta:
        database = db

# Connect to the database and create tables if they don't exist
db.connect()
db.create_tables([User, CV], safe=True)



Add and retrieve data from the database

from peewee import *
import random

# SQLite database setup with Peewee
db = SqliteDatabase('cv_database.db')

class User(Model):
    username = CharField(unique=True)

    class Meta:
        database = db

class CV(Model):
    user = ForeignKeyField(User, backref='cv')
    education = TextField()
    work_experience = TextField()
    skills = TextField()

    class Meta:
        database = db

# Connect to the database and create tables if they don't exist
db.connect()
db.create_tables([User, CV], safe=True)

# Function to generate random data for a CV
def generate_cv_data():
    education = "Education details here"
    work_experience = "Work experience details here"
    skills = "Skills details here"
    return education, work_experience, skills

# Generate and add data for 100 users
for i in range(1, 101):
    username = f"user_{i}"
    user = User.create(username=username)
    education, work_experience, skills = generate_cv_data()
    CV.create(user=user, education=education, work_experience=work_experience, skills=skills)

# Retrieve data for all users
for user in User.select():
    print(f"Username: {user.username}")
    # Retrieve CV for the current user
    cv = CV.get(CV.user == user)
    print(f"Education: {cv.education}")
    print(f"Work Experience: {cv.work_experience}")
    print(f"Skills: {cv.skills}")
    print("-------------------")

Fix the issue: If user already exist then update the data

from peewee import *
import random

# SQLite database setup with Peewee
db = SqliteDatabase('cv_database.db')

class User(Model):
    username = CharField(unique=True)

    class Meta:
        database = db

class CV(Model):
    user = ForeignKeyField(User, backref='cv')
    education = TextField()
    work_experience = TextField()
    skills = TextField()

    class Meta:
        database = db

# Connect to the database and create tables if they don't exist
db.connect()
db.create_tables([User, CV], safe=True)

# Function to generate random data for a CV
def generate_cv_data():
    education = "Education details here"
    work_experience = "Work experience details here"
    skills = "Skills details here"
    return education, work_experience, skills

# Generate and add data for 100 users
for i in range(1, 101):
    username = f"user_{i}"
    # Try to retrieve the user. If it doesn't exist, create it.
    user, created = User.get_or_create(username=username)
    education, work_experience, skills = generate_cv_data()
    # If the user already existed, update the CV data
    if not created:
        cv = CV.get(CV.user == user)
        cv.education = education
        cv.work_experience = work_experience
        cv.skills = skills
        cv.save()
    else:
        CV.create(user=user, education=education, work_experience=work_experience, skills=skills)

# Retrieve data for all users
for user in User.select():
    print(f"Username: {user.username}")
    # Retrieve CV for the current user
    cv = CV.get(CV.user == user)
    print(f"Education: {cv.education}")
    print(f"Work Experience: {cv.work_experience}")
    print(f"Skills: {cv.skills}")
    print("-------------------")

Add and remove user And also update user data

from peewee import *
import random

# SQLite database setup with Peewee
db = SqliteDatabase('cv_database.db')

class User(Model):
    username = CharField(unique=True)

    class Meta:
        database = db

class CV(Model):
    user = ForeignKeyField(User, backref='cv')
    education = TextField()
    work_experience = TextField()
    skills = TextField()

    class Meta:
        database = db

# Connect to the database and create tables if they don't exist
db.connect()
db.create_tables([User, CV], safe=True)

# Function to generate random data for a CV
def generate_cv_data():
    education = "Education details here"
    work_experience = "Work experience details here"
    skills = "Skills details here"
    return education, work_experience, skills



# Generate and add data for 100 users
for i in range(1, 101):
    username = f"user_{i}"
    # Try to retrieve the user. If it doesn't exist, create it.
    user, created = User.get_or_create(username=username)
    education, work_experience, skills = generate_cv_data()
    # If the user already existed, update the CV data
    if not created:
        cv = CV.get(CV.user == user)
        cv.education = education
        cv.work_experience = work_experience
        cv.skills = skills
        cv.save()
    else:
        CV.create(user=user, education=education, work_experience=work_experience, skills=skills)






# Function to add a new user
def add_user(username):
    user, created = User.get_or_create(username=username)
    if created:
        education, work_experience, skills = generate_cv_data()
        CV.create(user=user, education=education, work_experience=work_experience, skills=skills)
        print(f"User '{username}' added successfully.")
    else:
        print(f"User '{username}' already exists.")

# Function to delete a user
def delete_user(username):
    try:
        user = User.get(User.username == username)
        user.delete_instance()
        print(f"User '{username}' deleted successfully.")
    except User.DoesNotExist:
        print(f"User '{username}' does not exist.")

# Function to update CV data for a user
def update_cv_data(username, education=None, work_experience=None, skills=None):
    try:
        user = User.get(User.username == username)
        cv = CV.get(CV.user == user)
        if education:
            cv.education = education
        if work_experience:
            cv.work_experience = work_experience
        if skills:
            cv.skills = skills
        cv.save()
        print(f"CV data updated successfully for user '{username}'.")
    except User.DoesNotExist:
        print(f"User '{username}' does not exist.")
    except CV.DoesNotExist:
        print(f"CV data for user '{username}' does not exist.")

# Add a new user
add_user("user_101")

# Delete a user
delete_user("user_101")

# Update CV data for a user
update_cv_data("user_1", education="New education details")

How to create or remove files or folders using python

The easiest way to create or remove file is using python os module

To create file

import os
os.mknod("this_is_file.txt")

To create folder

os.mkdir("this is a folder")

To remove file

os.remove("this_is_file.txt")

To remove folder

os.rmdir("this is a folder")

The consideration.

If file already exist when creating file it will show error

so we can check if the file already exist

import os
if not os.path.exists("this_is_file.txt"):
	os.mknod("this_is_file.txt")

or when deleting folder

import os
if os.path.exists("this is a folder"):
	os.rmdir("this is a folder")

Save wikipedia article in txt format with python and wikipedia API

For focus based study its essential to get rid of all unnecessary context like wonderful design, and other ui effect. Whats necessary only text like the text book.

Wikipedia is one of my most visited website at this time. Though I love the content , i wll love more if its more minimalist..

So there is the solution… I can read the Wikipedia article in the Linux terminal now!… Too minimalist!!!

Also we can save the article as txt format for offline reading. May be I will read it in vs code!!!! Other thing is I recently purchased a mp4 player which supports e-book only in txt format. So I can real article also from here!

Now back to the program..

We will apply wikipedai api. here

We will request through wikipedia api. in response get the json…

And then prepare the text format with BeautifulSoup library . That’s it!

pip install beautifulsoup4

The complete Code



import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse


WIKIPEDIA_API_URL = "https://en.wikipedia.org/w/api.php"

def get_wikipedia_content(title):
    params = {
        "action": "query",
        "format": "json",
        "prop": "extracts",
        "titles": title,
        "explaintext": True  # Fetch plaintext content
    }

    response = requests.get(WIKIPEDIA_API_URL, params=params)
    data = response.json()
    page_id = list(data["query"]["pages"].keys())[0]
    content = data["query"]["pages"][page_id]["extract"]

    return content




# Wikipedia Article URL
url = "https://en.wikipedia.org/wiki/Life"
parsed_url = urlparse(url)
title = parsed_url.path.split('/')[-1]
print(title)



wiki_content = get_wikipedia_content(title)

soup = BeautifulSoup(wiki_content, 'html.parser')
plain_text = soup.get_text()

print(plain_text)
# Save plain text content to a .txt file
with open("wikipedia_content.txt", "w", encoding="utf-8") as file:
    file.write(plain_text)

print("Plain text content saved")



Create your first chat application with Flask and Socketio

We will use socketio for real-time messaging

First install our dependency for this application


pip install flask
pip install flask-socketio


How it will work.

Every user will get an unique key.

If the the other user submit the other users key that will send the message. its like sending message to unique username

Generate Unique Key for every user


import string
import random
def generate_key():
    key_length = 4
    characters = string.digits
    return ''.join(random.choice(characters) for _ in range(key_length))
generated_key=generate_key()
print(generated_key)


Its a 4 digit key for testing purpose. In real application must use long key with other randomness to make sure two key will not be same. Instead of key we can use unique user name. Thas another topic . For simplicity we will use this 4 digit key. Uptate it later on your necessary.

Our application structure….

stept by step Explanation

when the user load the page on borwer they will go to this page

@app.route('/')
def index():
    return render_template('index.html')

After loading the page they will connect with the socketio they will get an uniuqe key

and this key will send to the user by emiting the key to the client

also save the key in the python dictionary with the socketio sid to handle users connection activity later

When the user connected with socketio

@socketio.on('connect')
def on_connect():
    print('User connected')
    key = generate_key()
    active_connections[key] = request.sid
    emit('key_assigned', {'key': key})

When the user disconnected from socketio

If the user diconnected we will remove the user from the python dictionary.( its like active user management)

@socketio.on('disconnect')
def on_disconnect():
    print('User disconnected')
    for key, sid in active_connections.items():
        if sid == request.sid:
            del active_connections[key]
            break

When the user will send menssage to specific user.( the logic handles on serverside socketio)

@socketio.on('send_message')
def send_message(data):
    key = data['key']
    message = data['message']
    if key in active_connections:
        recipient_sid = active_connections[key]
        emit('receive_message', {'message': message}, to=recipient_sid)
    else:
        emit('receive_message', {'message': 'Does not Match'}, to=request.sid)


The Complete Server Side code


from flask import Flask, render_template,request
from flask_socketio import SocketIO, emit
import random
import string

app = Flask(__name__)
socketio = SocketIO(app)
active_connections = {} 


def generate_key():
    key_length = 4
    characters = string.digits
    return ''.join(random.choice(characters) for _ in range(key_length))

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect')
def on_connect():
    print('User connected')
    key = generate_key()
    active_connections[key] = request.sid
    emit('key_assigned', {'key': key})

@socketio.on('disconnect')
def on_disconnect():
    print('User disconnected')
    for key, sid in active_connections.items():
        if sid == request.sid:
            del active_connections[key]
            break

@socketio.on('send_message')
def send_message(data):
    key = data['key']
    message = data['message']
    if key in active_connections:
        recipient_sid = active_connections[key]
        emit('receive_message', {'message': message}, to=recipient_sid)
    else:
        emit('receive_message', {'message': 'Does not Match'}, to=request.sid)

if __name__ == '__main__':
    socketio.run(app, debug=True)


the client side code( the code we will send to browser when load the landing page index.html)

Step by step guide
First add the scoketuio client side library

<!DOCTYPE html>
<html>
<head>
    <title>Private Chat Application Prototype</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    
</head>
<body>

    <script>

    </script>
</body>
</html>

Add html content to show the message and users key

<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <h1>Python Scoketio Chat Prototype</h1>

<!--User unique key will be shows here -->
    <p>Your Unique Key: <span id="uniqueKey"></span></p>

<!--This is where user will enter the friends key to send message to friend -->
    <input type="text" id="friendKey" placeholder="Enter Friend's Key"><br>
    <button onclick="startChat()">Start Chat</button><br>


<!-- This is where the send and received message will shown
    <div id="chat"></div>


<!-- This is where user will write the message
    <div>
        <input type="text" id="messageInput" placeholder="Enter your message">
        <button onclick="sendMessage()">Send</button>
    </div>

    <script>


    </script>
</body>
</html>

The logical part javascript

connect to socket io

const socket = io();

       const socket = io();
        socket.on('key_assigned', (data) => {
            const uniqueKeySpan = document.getElementById('uniqueKey');
            uniqueKeySpan.textContent = data.key;
        });

When key sent by server this code will extract the key from data and place it to the html with the id name ‘uniquekey’

Initiate Chat

        function startChat() {
            friendKey = document.getElementById('friendKey').value;
            const message = "Hello, let's chat!";
            socket.emit('send_message', { key: friendKey, message: message });
        }

this function will get key which user enter to start chat and send it to the another if that user is active

when the pervious user send the message other user will get it from client side with this code

       socket.on('receive_message', (data) => {
            const chatDiv = document.getElementById('chat');
            const messageDiv = document.createElement('div');
            messageDiv.textContent = `Friend: ${data.message}`;
            chatDiv.appendChild(messageDiv);
        });

This will recieve the message from server and set it to the html chat div .

Start continuouis chat

if the user initiate chat . user can send countinous chat as long as the receiver is active

as friend key already stored when the initiate the chat. so user do not have to add the key every time when send message

        function sendMessage() {
            const message = document.getElementById('messageInput').value;
            if (friendKey && message) {
                socket.emit('send_message', { key: friendKey, message: message });
                const chatDiv = document.getElementById('chat');
                const messageDiv = document.createElement('div');
                messageDiv.textContent = `You: ${message}`;
                chatDiv.appendChild(messageDiv);
            }
        }

The complete code javascript code for client side


    <script>
        const socket = io();

        // Store the friend's key for sending messages
        let friendKey = '';

        // Listen for the 'key_assigned' event to display the assigned key
        socket.on('key_assigned', (data) => {
            const uniqueKeySpan = document.getElementById('uniqueKey');
            uniqueKeySpan.textContent = data.key;
            console.log(data.key);
        });


        function startChat() {
            friendKey = document.getElementById('friendKey').value;
            const message = "Hello, let's chat!";
            socket.emit('send_message', { key: friendKey, message: message });
        }

        function sendMessage() {
            const message = document.getElementById('messageInput').value;
            if (friendKey && message) {
                socket.emit('send_message', { key: friendKey, message: message });
                const chatDiv = document.getElementById('chat');
                const messageDiv = document.createElement('div');
                messageDiv.textContent = `You: ${message}`;
                chatDiv.appendChild(messageDiv);
            }
        }

        socket.on('receive_message', (data) => {
            const chatDiv = document.getElementById('chat');
            const messageDiv = document.createElement('div');
            messageDiv.textContent = `Friend: ${data.message}`;
            chatDiv.appendChild(messageDiv);
        });


    </script>

The complete client side code (index.html)


<!DOCTYPE html>
<html>
<head>
    <title>Private Chat Prototype With Socketio and Flask</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
</head>
<body>
    <h1>Private Chat Prototype With socketio and flask</h1>
    <p>Your Unique Key: <span id="uniqueKey"></span></p>
    <input type="text" id="friendKey" placeholder="Enter Friend's Key"><br>
    <button onclick="startChat()">Start Chat</button><br>
    <div id="chat"></div>
    <div>
        <input type="text" id="messageInput" placeholder="Enter your message">
        <button onclick="sendMessage()">Send</button>
    </div>

    <script>
        const socket = io();

        // Store the friend's key for sending messages
        let friendKey = '';

        // Listen for the 'key_assigned' event to display the assigned key
        socket.on('key_assigned', (data) => {
            const uniqueKeySpan = document.getElementById('uniqueKey');
            uniqueKeySpan.textContent = data.key;
            console.log(data.key);
        });


        function startChat() {
            friendKey = document.getElementById('friendKey').value;
            const message = "Hello, let's chat!";
            socket.emit('send_message', { key: friendKey, message: message });
        }

        function sendMessage() {
            const message = document.getElementById('messageInput').value;
            if (friendKey && message) {
                socket.emit('send_message', { key: friendKey, message: message });
                const chatDiv = document.getElementById('chat');
                const messageDiv = document.createElement('div');
                messageDiv.textContent = `You: ${message}`;
                chatDiv.appendChild(messageDiv);
            }
        }

        socket.on('receive_message', (data) => {
            const chatDiv = document.getElementById('chat');
            const messageDiv = document.createElement('div');
            messageDiv.textContent = `Friend: ${data.message}`;
            chatDiv.appendChild(messageDiv);
        });


    </script>
</body>
</html>



Structure

├── app.py
└── templates
    └── index.html

How you will test. it?

First run the code. and open the localhost link http://127.0.0.1:5000/ in the browser. Another one in in new incognito mode

So it will act like two unique user for your testing. Then Enter the other users unique key ( which works like unique username here) Then send message . Thats all. customize the code your necessary. Happy coding!

You can also get this project code from github
https://github.com/01one/flask-socketio-chat-application