How To Generate URL And Route Dynamically In Flask

We can set route dynamically instead of fixed route.

For example In the pre-determined route links generate like this example.com/users/profile

In the dynamically gendered route will be like this  example.com/users/custom_profile_name


We will use

@app.route('/<username>')

The code will be like this

@app.route('/<username>')
def show_profile(username):
    return username

We can use anything in the <username> here

So if we  load page like example.com/anything_here

It will show the route. This is the complete example. Copy and try and customize the code by yourself.



from flask import Flask, url_for

app = Flask(__name__)

@app.route('/<username>')
def show_profile(username):
    return username

@app.route('/')
def index():
    example_link = url_for('show_profile', username='example')
    return f"You are on index route. Go to <a href='{example_link}'>/example</a> for an example."

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

  
  

How to show html code inside html without rendering

We can show html inside html by using using the html entity
‘<‘ as ‘&lt;’ and the ‘&’ as ‘&amp;’

Normally we use like this in html .

<h1> This is H1 tag </h1>

But it the result renders html and shows like this

This is h1 tag

So will We will use this To prevent the rendering

&lt;h1&gt; This is H1 tag &lt;/h1&gt;

Now there is a full example which the demonstrations this

Copy the code and try by yourself.



<!DOCTYPE html>
<html>
<head>

</head>
<body>

<h1> This is H1 tag </h1>
&lt;h1&gt; This is also H1 tag &lt;/h1&gt;
    

</body>
</html>

    
    
    

Python Flask : Starter Automated Template

When starting new project again, Some common structure needed to be written again and again. So I wrote a program nearly three years (2021) ago to Get Everything ready on one script. Here is the python script that makes everything ready

Here is is the revised version of the code

The Program Automatically generates basic scripts and files and necessary folder.

Copy, run the script And adjust the script on your necessary.


import os

x = os.getcwd()

os.mkdir("templates")
os.mkdir(os.path.join(x, "templates", "layouts"))
os.mkdir("static")
os.mkdir(os.path.join(x, "static", "css"))
os.mkdir(os.path.join(x, "static", "js"))
os.mkdir(os.path.join(x, "static", "img"))

app_w = """from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def home():
	title = "Home"
	return render_template('index.html', title=title)
"""

with open("app.py", "w+") as f:
	f.write(app_w)

css = """
body {
	background-color: #ccebff;
}
a, h1, h2, p {
	color: #3377ba8;
}
"""

with open(os.path.join(x, "static", "css", "main.css"), "w+") as f:
	f.write(css)

main = """<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ title }}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
</head>
<body>
{% block content %}
{% endblock %}
<footer>
<ul>
	<li> <a href="/">Home</a></li>
</ul>
&copy; 2021 Mahid
</footer>
</body>
</html>
"""

with open(os.path.join(x, "templates", "layouts", "main.html"), "w+") as f:
	f.write(main)

index = """{% extends "layouts/main.html" %}
{% block content %}
<h1>{{ title }}</h1>
<p>Hello world</p>
{% endblock %}
"""

with open(os.path.join(x, "templates", "index.html"), "w+") as f:
	f.write(index)
    
    
    

How To Include Full Screen Mode In The Web Application

Full screen mode is useful for video games, editing, and other purpose. So most of these types of applications use Fullscreen API  so the user can switch between full screen mode and the standard default mode.

Also we can program specifically to instruct the browser to switch to full screen.

To apply full screen mode we will use requestFullscreen() method

To set fullscreen document.documentElement.requestFullscreen()

To exit firescreen document.exitFullscreen()

The example Code


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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        #change-display-mode {
            padding: 10px 20px;
            border: 2px solid #333;
            background-color: transparent;
            color: #333;
            font-size: 16px;
            text-transform: uppercase;
            cursor: pointer;
            transition: all 0.3s ease;
            outline: none;
        }

        #change-display-mode:hover {
            background-color: #333;
            color: #fff;
        }


    </style>
</head>

<body>
    <div>
        <button id="change-display-mode">To Fullscreen Mode</button>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var fullscreenButton = document.getElementById('change-display-mode');

            function toggleFullscreen() {
                if (!document.fullscreenElement) {
                    document.documentElement.requestFullscreen();
                    fullscreenButton.textContent = "Exit Fullscreen";
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                        fullscreenButton.textContent = "Go to  Fullscreen Mode";
                    }
                }
            }

            fullscreenButton.addEventListener('click', function () {
                toggleFullscreen();
            });
        });
    </script>
</body>

</html>
    

You can test this here

How to Use GPS And Show The User Location In The Map In The Web Browser

For Location we will use geolocation api

Its super simple

In this code we used navigator.geolocation.getCurrentPosition to know the users location

Save and run the html code It will show the latitude and longitude. Which indicates the exact location in the world map.



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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
    <script>

        let userslatitude;
        let userslongitude;


        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                userslatitude = position.coords.latitude;
                userslongitude = position.coords.longitude;
                alert('latitude: ' + userslatitude + ', longitude: ' + userslongitude);

            });
        }
    </script>
</body>

</html>

    
    
    


In the next example we add button to add more control when calling the geolocation API



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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
    <h1>GPS</h1>
    <button onclick="showLocation()">Show Location</button>
    <p id="locationParagraph"></p>

    <script>
        let userslatitude;
        let userslongitude;

        function showLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (position) {
                    userslatitude = position.coords.latitude;
                    userslongitude = position.coords.longitude;

                    document.getElementById('locationParagraph').innerText = 'Latitude: ' + userslatitude + ', Longitude: ' + userslongitude;
                });
            } else {
                alert('Geolocation is not supported by your browser');
            }
        }
    </script>
</body>

</html>

    
    
    


You can also test this code

GPS

If you click on show location. It will show the latitude and longitude. With this information we can get the exact location.


Knowing the location just a number, that is not enough. We need to know the place name or the  visualization with map. There is a wonderful free option for this. OpenStreetMap. In the next example we will specifically show the location name.



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <button onclick="getLocation()">Get Location</button>
    <p id="locationName"></p>

    <script>
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(getAddress);
            } else {
                alert('Geolocation is not supported by your browser');
            }
        }

        function getAddress(position) {
            let latitude = position.coords.latitude;
            let longitude = position.coords.longitude;
            let apiUrl = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}&zoom=18&addressdetails=1`;

            fetch(apiUrl)
                .then(response => response.json())
                .then(data => {
                    let locationName = data.display_name;
                    document.getElementById('locationName').innerText = 'Location: ' + locationName;
                })
                .catch(error => {
                    console.log('Error:', error);
                });
        }
    </script>
</body>
</html>

    
    
    

Run the html code locally or here is demonstration with the Get location button That will show the location name from the latitude and longitude.


Location is great. But users will feel more comfortable if we can visualize this in map

In the next example we will use leaflet library and OpenStreetMap api to show the location in the map.



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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
    <style>
        #map {
            height: 400px;
            width:400px;
        } 

        button {
            padding: 10px 20px;
            border: 2px solid #333;
            background-color: transparent;
            color: #333;
            font-size: 16px;
            text-transform: uppercase;
            cursor: pointer;
            transition: all 0.3s ease;
            outline: none;
        }

        button:hover {
            background-color: #333;
            color: #fff;
        }
    </style>
</head>

<body>
    <button onclick="getLocation()">Get Location</button>
    <p id="locationName"></p>
    <div id="map"></div>

    <script>
        let map;

        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(getAddress);
            } else {
                alert('Geolocation is not supported by your browser');
            }
        }

        function getAddress(position) {
            let latitude = position.coords.latitude;
            let longitude = position.coords.longitude;
            let apiUrl = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}&zoom=18&addressdetails=1`;

            fetch(apiUrl)
                .then(response => response.json())
                .then(data => {
                    let locationName = data.display_name;
                    document.getElementById('locationName').innerText = 'Location: ' + locationName;
                    displayMap(latitude, longitude);
                })
                .catch(error => {
                    console.log('Error:', error);
                });
        }

        function displayMap(latitude, longitude) {
            var mapElement = document.getElementById('map');
            var map;

            map = L.map('map', {
                minZoom: 1,
            }).setView([latitude, longitude], 14);

            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

            var url = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`;

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    let locationText = data.display_name;

                    L.circle([latitude, longitude], {
                        color: 'red',
                        fillOpacity: 0.2,
                        radius: 3000
                    }).addTo(map);

                    L.marker([latitude, longitude])
                        .addTo(map)
                        .bindPopup(locationText)
                        .openPopup();

                    var bounds = L.latLngBounds([[latitude, longitude]]);
                    map.fitBounds(bounds);
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                });
        }
    </script>
</body>

</html>

    
    
    

Customize the code on your needs.  I first applied the GPS feature in my video calling project. I hope it will be helpful for you too. 

One thing to consider . Sometimes the map shows inaccurate result.  

Also Open street Map has standard rate limit. (The standard limit is 1 request per second)

You can get the example code from github for practice github



For performance and visual and location information accuracy you may use google maps Embed api.

How to work with python pickle

Python pickle is an essential tool for serializing and de-serializing Python objects, such as lists, dictionaries, and custom objects, offering a seamless method to store and retrieve data with efficiency.

So we can easily store python lists,dictionary and frequently used object which need to be stored.

Pickle is fast is efficient. Evan I have made a super fast efficient CLI dictionary with it and on other projects. I will share the dictionary code later in this post.

Lets dive into an easy example

For using pickle we import pickle, its build in python.




import pickle
my_list=[1,2,3,4,5]

#store in picke file
with open('myList.pickle', 'wb') as f:
	pickle.dump(my_list, f)

# Load the data
with open('myList.pickle', 'rb') as f:
	my_list = pickle.load(f)
print(my_list)




This is another example with time.



import time
import pickle

t=time.ctime()
old_data=[t]

n=True
try:
	with open('datafile.pickle', 'rb') as data:
		old_data= pickle.load(data)
		try:
			old_data.append(t)
		except:
			old_data=list(old_data)
			old_data.append(t)
		data.close()
		n=True	
except:
	with open('datafile.pickle', 'wb') as data:
		pickle.dump(old_data, data)
		data.close()
	print(old_data)
	n=False
if n==True:
	with open('datafile.pickle', 'wb') as data:
		pickle.dump(old_data, data)
		data.close()
	print(old_data)



Test the example code here

If you run this program again again You will notice that Its print the time also adding new time in the list. So its updating and storing the list in the pickle file.

Now Another simple practical project with pickle is the Command Line Interface English dictionary

I am providing the GitHub code link. Try it by yourself. Github Code

You can do wonderful things with pickle. But before going with serious project keep on mind the security issue with pickle

How to get the mouse position in pygame

We can get the mouse position with pygame.mouse.get_pos()



import pygame,sys
from pygame.locals import*
pygame.init()
screen=pygame.display.set_mode((400,400))

game_running=True
while game_running:
	for event in pygame.event.get():
		if event.type==QUIT:            
			pygame.quit()
			sys.exit()
	mouse_position=pygame.mouse.get_pos()
	print(mouse_position)
	pygame.display.update()
    
    
    

Run this code and hover your mouse on the pygame window. This will print mouse position.

We can me this interesting by moving a rectangle based on the mouse position.

We just have to know the mouse position in the coordinate ( x,y)

In the previous program print(mouse_postion) shows the tuble value

so we can get the x, y value by

mouse_position=pygame.mouse.get_pos()
x,y=mouse_position

As we get the x,y value it will be easy to apply in the next example



import pygame,sys
from pygame.locals import*
pygame.init()
screen=pygame.display.set_mode((400,400))

game_running=True
while game_running:
	for event in pygame.event.get():
		if event.type==QUIT:            
			pygame.quit()
			sys.exit()
	mouse_position=pygame.mouse.get_pos()
	x,y=mouse_position
	screen.fill((255,255,255))
	pygame.draw.rect(screen,(100,100,100),(x,y,60,40),5) #rect(surface,color,(x,y,height,width)
	print(mouse_position)
	pygame.display.update()
    
    
    

Run this code you will find that rectangle is attach to the mouse position

How To Add Static Files And Templates Folder In Python Tornado

In this program example we will use template_path=os.path.join(os.path.dirname(__file__), “templates”)

this code to set the templates folder location

In the same way we will set the static path

static_path=os.path.join(os.path.dirname(__file__), “static”)

And we will add this in the tornado application

tornado.web.Application()

This is the full app.py where templates folder and static folder added


import tornado.web
from tornado.options import define, options, parse_command_line
import tornado.ioloop
import os
import logging


define("port", default=5000, help="port number", type=int)
define("debug", default=True, help="debug mode")

class MainHandler(tornado.web.RequestHandler):
    async def get(self):
        return self.render('index.html')

def main():
    parse_command_line()
    app = tornado.web.Application(
        [
            (r"/", MainHandler),
        ],
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        debug=options.debug,
    )
    app.listen(options.port)
    logging.info(f"Server running on port {options.port}, debug mode: {options.debug}")
    
    logging.info(f"http://localhost:{options.port}")
    
    tornado.autoreload.start()
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    main()



Project structure

├── app.py
├── static
│   ├── script.js
│   └── styles.css
└── templates
    └── index.html

In the program The debug mode is true, which is must for development and detecting the performance and issues Also We have used tornado.autoreload.start()

This feature automatically restart the server and updates the changes When code changes. So it’s best for when developing and testing application.

I have create a github repository for this post. You can Get the complete code from github

How To Set Background Color In Pygame

  • For using background color we will use screen.fill(color)
  • In the color we can use rgb or hexadecimal color whatever we want want.
  • In this example we will fill the screen with this color rgb(255, 250, 240)
  • So our code will be screen.fill((255, 250, 240))



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


screen=pygame.display.set_mode((600,400))
game_running=True
while game_running:
    for event in pygame.event.get():
        if event.type==QUIT:            
            pygame.quit()
            sys.exit()



    screen.fill((255,250,240))
    pygame.display.update()


Lets write the step by step full code and explanation

First import necessary library

  • import pygame,sys
    from pygame.locals import*

And then initiate the pygame

  • pygame.init()

Set the our game display resolution

  • screen=pygame.display.set_mode((400,400))

Set the game in a loop so it will continue running until you exit or game finish

  • game_running=True
    while game_running:

    your logic in this loop

In the loop we will fill the display with color

  • screen.fill((r,g,b))
  • r means red ( value from 0 to 255
  • g means green ( value from 0 to 255
  • b means blue ( value from 0 to 255)

when we change the value its creates a color mixture and with rgb value

Each color channel (Red, Green, Blue) can have an intensity value ranging from 0 (no color) to 255 (maximum intensity).

Since each of the three colors (R, G, B) has 256 possible intensity levels, the total number of potential color combinations is:

256 (Red values) * 256 (Green values) * 256 (Blue values) = 16,777,216 colors

  • screen.fill((255, 250, 240))

after adding the color we will update the display so if we update the color later it will also update the display color

we will update the display with pygame.display.update()

Try the code by yourself. Run the code and get the result. You can find 48+ pygame examples on github. You May also have some questions in your mind now. Let’s answer the questions!

How Many Times The Code Will Update The Color?

Answer: In the example we have not set frame rate. So if we do not set the frame rate, it will update based on your device capacity.

How Can I Set The Frame Rate?

You can add the frame rate by using pygame.time.Clock.tick

so if we want to set the frame rate 60fps we just have to add tick inside while loop tick(60)

Then the current code will be



import pygame,sys
from pygame.locals import*
pygame.init()
clock=pygame.time.Clock()

screen=pygame.display.set_mode((600,400))
game_running=True
while game_running:
	clock.tick(60) # we set the frame rate to 60
	for event in pygame.event.get():
		if event.type==QUIT:            
			pygame.quit()
			sys.exit()

	screen.fill((255,250,240))
	pygame.display.update()


How do I know How many frame rate my pygame program is running?

Setting the frame rate set the limit the frame rate the program to refresh the display. But it does not means if you set it 60fps it will run 60fps. If the program has complex calculation or complexity it may run lower frame rate then you set.

So we can get the actual frame rate in pygame by pygame.time.Clock.get_fps

Now our program should be



import pygame,sys
from pygame.locals import*
pygame.init()
clock=pygame.time.Clock()

screen=pygame.display.set_mode((600,400))
game_running=True
while game_running:
	clock.tick(60) # we set the frame rate to 60
	print(clock.get_fps()) # this line will show the actual frame rate
	for event in pygame.event.get():
		if event.type==QUIT:            
			pygame.quit()
			sys.exit()

	screen.fill((155,250,240)) #add or change RGB color background
	pygame.display.update()



This program will print the actual frame rate.

More about setting color in Pygame

  • Pygame has build in color list
  • you can use the color by using pygame.Color(color_name)
  • Check out which color names in the pygame color list
  • for example if your color is lavender
  • pygame.Color(lavender)
  • We can fill the screen with this color screen.fill(pygame.Color(lavender))