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")

Pygame Project: Create the simplest digital clock

We will use python datetime module for our clock;

We get the current time and separate the time into hour minutes and second.

First get the current time

import datetime
current_time = datetime.datetime.now()
print(current_time)

Get the time in hour, minute and second

current_hour = current_time.hour
current_minute = current_time.minute
current_second = current_time.second

Now got our clock time components. It will be like this



import datetime

current_time = datetime.datetime.now()

hour = current_time.hour
minute = current_time.minute
second = current_time.second

clock_time = f"{hour}:{minute}:{second}"

print(clock_time)




The code will print the time

Now if we loop the program in every second it will show the the updated time in every second


import time
import datetime
while True:
	current_time = datetime.datetime.now()

	hour = current_time.hour
	minute = current_time.minute
	second = current_time.second

	clock_time = f"{hour}:{minute}:{second}"
	print(clock_time)
	time.sleep(1)


We have completed the main structure of our digital clock

Now more improvement and applying to pygame

In the program instead of this line

clock_time = f"{hour}:{minute}:{second}"

we will use this

clock_time = f"{hour:02}:{minute:02}:{second:02}"

because it will always show the time in two digit . for example if the current second is 9 it will show 09

Now our complete code


import datetime
import pygame,sys
from pygame.locals import*
pygame.init()


clock=pygame.time.Clock()

screen=pygame.display.set_mode((800,600))

clock_font=pygame.font.Font(pygame.font.get_default_font(), 150)



game_running=True
while game_running:
	# It will run 1 frame per second. So the time will update every second
	clock.tick(1)
	for event in pygame.event.get():
		if event.type==QUIT:
			pygame.quit()
			sys.exit()
	current_time = datetime.datetime.now()

	hour = current_time.hour
	minute = current_time.minute
	second = current_time.second

	clock_time = f"{hour:02}:{minute:02}:{second:02}"
	screen.fill((255,255,255))
	clock_text=clock_font.render(clock_time,True,(0,0,0))
	screen.blit(clock_text,(100,200))
	pygame.display.update()



You can Get this and also more pygame example from github ( 50+ pygame example)

https://github.com/01one/pygameExamples

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")



How to prevent text selection in html


Its necessary to prevent text selection when the text is ui feature, to make the webpage more professional.

We can prevent the text from selecting by using this in css

user-select: none;

You cannot select this text

You can select this text

example code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <p style="user-select: none;">You cannot select this text</p>
    <p>You can select this text</p>
</body>
</html>

How to create tooltip in html

Is essential to add tooltip to make web page more professional and understandable

The simplest way can we add tooltip is use html inline element <span>

We will add the tool in div and tooltip text(tool description) in the span

Toll description will be always hide ( display none in css) until the user hover the tool text , then it will show the tool

A simple example

Tooltip Example
Tooltip Example. This line has tooltip!
This is the tooltip Text!

The example code


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tooltip Example</title>
<style>
  .tooltip-main {
    background-color: blue;
    color: white;
    position: relative;
  }
  
  .tooltip-text {
    position: absolute;
    display: none;
    background-color: wheat;
    padding: 5px;
    border-radius: 3px;
  }
  
  .tooltip-main:hover + .tooltip-text {
    display: inline;
  }
</style>
</head>
<body>
<div>
  <div class="tooltip-main">Tooltip Example. This line has tooltip!</div>
  <span class="tooltip-text">This is the tooltip Text!</span>
</div>
</body>
</html>



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

Ajax example with flask

One of the best ajax applied in real world is username checker. In this example we will check if there is existing username

This is code /project we will

  • use ajax to search username
  • if username exist or does not exist send to message to the user
  • Also create new user with html form and flask if username exists

Our first step: Check if username exists or not

Imagine we have this existing username

# Sample list of existing usernames
existing_usernames = ["user1", "user2", "user3"]

when the user enter a username we will check it from server(Check username)


@app.route('/check_username', methods=['POST'])
def check_username():
	username = request.form['username']
	print(username)
	if username in existing_usernames:
		return jsonify({'message': 'Username already exists! Please choose a different username.'})
	elif not is_valid_username(username):
		return jsonify({'message': 'Username contains special characters. Only letters, numbers, and underscores are allowed.'})
	else:
		return jsonify({'message': 'Username is available!'})


When new account is created username will be added to the username list (Create New User)


@app.route('/create_profile', methods=['POST'])
def create_profile():
	username = request.form['username']
	if username not in existing_usernames:
		existing_usernames.append(username)
		return  jsonify({'message': f"Welcome, {username}! Your profile has been created successfully."})
	else:
		return jsonify({'message': 'Username already exists! Please choose a different username.'})


In the client side we are using jquery to make everything simpler.

When the user will type it will automatically send to server with ajax and return the response

We will also make sure if the username exists the response text will show in green color if not it will show in red color.


$(document).ready(function () {
	$('#username').keyup(function () {
		var username = $(this).val();
		if (username.length === 0) {
			$('#usernameMessage').text("");
			return;
		}
		if (/\s/.test(username)) {
			$('#usernameMessage').text("Username cannot contain spaces.");
			return;
		}
		if (!/^[a-zA-Z0-9]+$/.test(username)) {
			$('#usernameMessage').text("Username cannot contain special characters.");
			return;
		}
		$.ajax({
			type: 'POST',
			url: '/check_username',
			data: { 'username': username },
			success: function (response) {
				$('#usernameMessage').text(response.message);
				if (response.message === 'Username is available!') {
					$('#usernameMessage').css('color', 'green');
				} else {
					$('#usernameMessage').css('color', 'red');
				}
			}
		});
	});




	$('#createProfileForm').submit(function (e) {
		e.preventDefault();
		var username = $('#username').val();
		if (username.length === 0) {
			$('#usernameMessage').text("Username cannot be empty.");
			return;
		}
		if (/\s/.test(username)) {
			$('#usernameMessage').text("Username cannot contain spaces.");
			return;
		}
		if (!/^[a-zA-Z0-9]+$/.test(username)) {
			$('#usernameMessage').text("Username cannot contain special characters.");
			return;
		}
		$.ajax({
			type: 'POST',
			url: '/create_profile',
			data: { 'username': username },
			success: function (response) {
				$('#usernameMessage').text(response.message);
			}
		});
	});
});



The complete code

structure

├── app.py
└── templates
    └── username-id-generate.html

The serverside code


import re
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

# Sample list of existing usernames
existing_usernames = ["user1", "user2", "user3"]


def is_valid_username(username):
	# Double check
	return re.match("^[a-zA-Z0-9_]*$", username) is not None


@app.route('/')
def index():
	return render_template('username-id-generate.html')


@app.route('/check_username', methods=['POST'])
def check_username():
	username = request.form['username']
	print(username)
	if username in existing_usernames:
		return jsonify({'message': 'Username already exists! Please choose a different username.'})
	elif not is_valid_username(username):
		return jsonify({'message': 'Username contains special characters. Only letters, numbers, and underscores are allowed.'})
	else:
		return jsonify({'message': 'Username is available!'})


@app.route('/create_profile', methods=['POST'])
def create_profile():
	username = request.form['username']
	if username not in existing_usernames:
		existing_usernames.append(username)
		return  jsonify({'message': f"Welcome, {username}! Your profile has been created successfully."})
	else:
		return jsonify({'message': 'Username already exists! Please choose a different username.'})



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



The client side code


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Profile</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body {
            font-family: 'Helvetica Neue', sans-serif;
            background-color: #f0f2f5;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        #createProfileForm {
            background: #fff;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            width: 350px;
        }
        h1 {
            text-align: center;
            font-size: 28px;
            margin-bottom: 20px;
            color: #333;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
        }
        input[type="text"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
            font-size: 16px;
        }
        input[type="submit"] {
            width: 100%;
            padding: 12px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            font-size: 18px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        input[type="submit"]:hover {
            background-color: #0056b3;
        }
        #usernameMessage {
            color: red;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <form id="createProfileForm">
        <h1>Create Your Profile</h1>
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" autocomplete="off" required>
        <span id="usernameMessage"></span>
        <input type="submit" value="Create Profile">
    </form>
    <script>
        $(document).ready(function () {
            $('#username').keyup(function () {
                var username = $(this).val();
                if (username.length === 0) {
                    $('#usernameMessage').text("");
                    return;
                }
                if (/\s/.test(username)) {
                    $('#usernameMessage').text("Username cannot contain spaces.");
                    return;
                }
                if (!/^[a-zA-Z0-9]+$/.test(username)) {
                    $('#usernameMessage').text("Username cannot contain special characters.");
                    return;
                }
        $.ajax({
            type: 'POST',
            url: '/check_username',
            data: {'username': username},
            success: function (response) {
                $('#usernameMessage').text(response.message);
                if (response.message === 'Username is available!') {
                    $('#usernameMessage').css('color', 'green');
                } else {
                    $('#usernameMessage').css('color', 'red');
                }
            }
        });
    });

            $('#createProfileForm').submit(function (e) {
                e.preventDefault();
                var username = $('#username').val();
                if (username.length === 0) {
                    $('#usernameMessage').text("Username cannot be empty.");
                    return;
                }
                if (/\s/.test(username)) {
                    $('#usernameMessage').text("Username cannot contain spaces.");
                    return;
                }
                if (!/^[a-zA-Z0-9]+$/.test(username)) {
                    $('#usernameMessage').text("Username cannot contain special characters.");
                    return;
                }
                $.ajax({
                    type: 'POST',
                    url: '/create_profile',
                    data: {'username': username},
                    success: function (response) {
                        $('#usernameMessage').text(response.message);
                    }
                });
            });
        });
    </script>
</body>
</html>



Get the project code from github

https://github.com/01one/flask-ajax-example

Build browser based Qr code generator with html css and javascript

The main features we will apply

User will able to paste link or text and generate the qr code

The dependency

We will use qurcodejs a javascript library for this

QR Code Generator

QR Code Generator

The complete code. Try and customize by yourself.


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>QR Code Generator</title>
  <style>
    input[type="text"] {
      width: 400px;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-radius: 5px;
      font-size: 16px;
      box-sizing: border-box;
    }

    #qr-code-button {
      padding: 10px 20px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 16px;
    }

    #qr-code-button:hover {
      background-color: #45a049;
    }

    #qr-code-image {
      margin-top: 30px;
      width: 200px;
      height: 200px;
      background-color: #fff;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      display: none;
    }
  </style>
</head>

<body>
  <div class="content">
    <h1>QR Code Generator</h1>
    <input type="text" id="qr-code-text-input" placeholder="Enter website URL or text">
    <button id="qr-code-button" onclick="generateQRCode()">Generate QR Code</button>
    <div id="qr-code-image"></div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/qrcode.min.js"></script>
  <script>
    var qrcode = null;
    function generateQRCode() {
      var text = document.getElementById('qr-code-text-input').value;
      if (text === '') return;
      if (qrcode !== null) {
        qrcode.clear();
        qrcode.makeCode(text);
      } else {
        qrcode = new QRCode(document.getElementById('qr-code-image'), { text: text, width: 400, height: 400 });
      }
      document.getElementById('qr-code-image').style.display = 'block';
    }
  </script>
</body>

</html>




Also you can get the code from github

https://github.com/01one/qr-code-generator-with-html-css-javascript

Create a Simple Image Gallery for Your Website (HTML, CSS & JavaScript)

Image Gallery

The essential structure of the gallery

  • The images will automatically fit to the display ( based on the image)
  • Show the image in smaller size first. Then When the user click the image it will show in larger scale

The complete code. Just place your image link in the img tag to show the image




<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Gallery</title>
<style>
  .gallery {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 10px;
  }

  .image-wrapper {
    position: relative;
    overflow: hidden;
  }

  .zoomable {
    width: 100%;
    height: auto;
    object-fit: cover;
    cursor: pointer;
  }

  .full-image {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.9);
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .full-image img {
    max-width: 90%;
    max-height: 90%;
    object-fit: contain;
  }

  .close-button {
    position: absolute;
    top: 10px;
    right: 10px;
    color: white;
    font-size: 24px;
    cursor: pointer;
  }

  .nav-button {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    color: white;
    font-size: 24px;
    cursor: pointer;
  }

  .prev-button {
    left: 10px;
  }

  .next-button {
    right: 10px;
  }
</style>
</head>
<body>

<div class="gallery">
  <div class="image-wrapper">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/Hever_Castle_rose_garden_with_fountain.JPG/1280px-Hever_Castle_rose_garden_with_fountain.JPG" alt="Rose" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Missouri_Botanical_Garden_-_Seiwa-en.JPG/1280px-Missouri_Botanical_Garden_-_Seiwa-en.JPG" alt="Garden" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Singapore_Gardens_by_the_Bay_viewed_from_Marina_Bay_Sands_03.jpg/1280px-Singapore_Gardens_by_the_Bay_viewed_from_Marina_Bay_Sands_03.jpg" alt="Garden" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/Monet_-_Impression%2C_Sunrise.jpg/1280px-Monet_-_Impression%2C_Sunrise.jpg" alt="Sunrise" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Rudolf_Reschreiter_Blick_von_der_H%C3%B6llentalangerh%C3%BCtte_zum_H%C3%B6llentalgletscher_und_den_Riffelwandspitzen_1921.jpg/1280px-Rudolf_Reschreiter_Blick_von_der_H%C3%B6llentalangerh%C3%BCtte_zum_H%C3%B6llentalgletscher_und_den_Riffelwandspitzen_1921.jpg" alt="" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="https://upload.wikimedia.org/wikipedia/commons/e/e3/Kheops-Pyramid.jpg" alt="Great_Pyramid_of_Giza" class="zoomable">
  </div>
</div>


<script>
  document.addEventListener('DOMContentLoaded', function () {
    const zoomableImages = document.querySelectorAll('.zoomable');
    let currentIndex = 0;

    zoomableImages.forEach(function (image, index) {
      image.addEventListener('click', function () {
        currentIndex = index;
        showFullImage(currentIndex);
      });
    });

    function showFullImage(index) {
      const fullImageContainer = document.createElement('div');
      fullImageContainer.classList.add('full-image');

      const fullImage = document.createElement('img');
      fullImage.src = zoomableImages[index].src;

      const closeButton = document.createElement('span');
      closeButton.classList.add('close-button');
      closeButton.innerHTML = '&times;';
      closeButton.addEventListener('click', function () {
        document.body.removeChild(fullImageContainer);
      });

      const prevButton = document.createElement('span');
      prevButton.classList.add('nav-button', 'prev-button');
      prevButton.innerHTML = '&#10094;';
      prevButton.addEventListener('click', function () {
        currentIndex = (currentIndex - 1 + zoomableImages.length) % zoomableImages.length;
        fullImage.src = zoomableImages[currentIndex].src;
      });

      const nextButton = document.createElement('span');
      nextButton.classList.add('nav-button', 'next-button');
      nextButton.innerHTML = '&#10095;';
      nextButton.addEventListener('click', function () {
        currentIndex = (currentIndex + 1) % zoomableImages.length;
        fullImage.src = zoomableImages[currentIndex].src;
      });

      fullImageContainer.appendChild(fullImage);
      fullImageContainer.appendChild(closeButton);
      fullImageContainer.appendChild(prevButton);
      fullImageContainer.appendChild(nextButton);
      document.body.appendChild(fullImageContainer);
    }
  });
</script>

</body>
</html>





You can also add image from the directory



<div class="gallery">
  <div class="image-wrapper">
    <img src="images/autumn.jpg" alt="Autumn" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="images/butterfly.jpg" alt="Butterfly" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="images/horizon.jpg" alt="Horizon" class="zoomable">
  </div>

</div>




Get the Project code from github

https://github.com/01one/image-gallery-html-css-javascript