Database Connection and Operate Functions
Utility functions will handle database connections, URL validations, update browser and platform counters, and generating random tokens for short URLs.
Database Connection
First, you'll set up the database connection using pymysql
. This is crucial for enabling your Flask application to interact with the MySQL database.
In utils.py
, add the following Python code:
from urllib.parse import urlparse
import random
import string
import pymysql
db_config = {
"host": "localhost",
"user": "root",
"password": "",
"db": "SHORTY"
}
def get_db_connection() -> pymysql.Connection:
"""Create and return a new database connection."""
return pymysql.connect(**db_config)
- The
pymysql
library is used for connecting to the MySQL database. This library allows Python applications to interact with MySQL databases using a simple API.
- The
db_config
dictionary contains database connection parameters such as host, user, password, and database name. These are imported from a separate config
module, presumably for better security and modularity. Keeping configuration settings separate allows for easier adjustments without modifying the main codebase.
- The
get_db_connection()
function creates and returns a new connection to the database using the pymysql.connect(**db_config)
function. The **db_config
syntax is used to unpack the dictionary into keyword arguments.
Database Operate Functions
After establishing a database connection, the next step involves creating functions that perform operations on the database. These include listing data for a given short URL and updating counters based on browser and platform usage.
In utils.py
, add the following Python code:
def list_data(shorty_url: str) -> tuple:
"""
Takes short_url for input.
Returns counter , browser , platform ticks.
"""
with get_db_connection() as conn, conn.cursor() as cursor:
su = [shorty_url]
info_sql = "SELECT URL , S_URL ,TAG FROM WEB_URL WHERE S_URL= %s; "
counter_sql = "SELECT COUNTER FROM WEB_URL WHERE S_URL= %s; "
browser_sql = "SELECT CHROME , FIREFOX , SAFARI, OTHER_BROWSER FROM WEB_URL WHERE S_URL =%s;"
platform_sql = "SELECT ANDROID , IOS , WINDOWS, LINUX , MAC , OTHER_PLATFORM FROM WEB_URL WHERE S_URL = %s;"
cursor.execute(info_sql, su)
info_fetch = cursor.fetchone()
cursor.execute(counter_sql, su)
counter_fetch = cursor.fetchone()
cursor.execute(browser_sql, su)
browser_fetch = cursor.fetchone()
cursor.execute(platform_sql, su)
platform_fetch = cursor.fetchone()
return info_fetch, counter_fetch, browser_fetch, platform_fetch
def update_counters(cursor: pymysql.Connection, short_url: str, browser_dict: dict, platform_dict: dict) -> None:
"""Update browser and platform counters in the database for the given short_url."""
counter_sql = """UPDATE WEB_URL SET COUNTER = COUNTER + 1,
CHROME = CHROME + %s, FIREFOX = FIREFOX + %s, SAFARI = SAFARI + %s, OTHER_BROWSER = OTHER_BROWSER + %s,
ANDROID = ANDROID + %s, IOS = IOS + %s, WINDOWS = WINDOWS + %s, LINUX = LINUX + %s, MAC = MAC + %s, OTHER_PLATFORM = OTHER_PLATFORM + %s
WHERE S_URL = %s;"""
cursor.execute(counter_sql, (browser_dict['chrome'], browser_dict['firefox'], browser_dict['safari'], browser_dict['other'],
platform_dict['android'], platform_dict['iphone'], platform_dict[
'windows'], platform_dict['linux'], platform_dict['macos'], platform_dict['other'],
short_url))
- The
list_data(shorty_url)
function is designed to retrieve various pieces of information from the WEB_URL
table for a given short URL (shorty_url
). It establishes a connection to the database and executes four SQL queries to fetch the original URL, the associated tag, the access counter, browser, and platform analytics. Each query is executed separately, and the results are fetched and returned.
- The
update_counters(cursor, short_url, browser_dict, platform_dict)
function updates the access counter, browser, and platform counts for a given short URL in the database. This function takes a database cursor, the short URL, and two dictionaries containing counts for each browser and platform as arguments. It constructs an UPDATE
SQL statement to increment the counters for the short URL based on the provided data. The function assumes that the browser and platform information has been determined prior to calling this function, and that this information is passed in as dictionaries (browser_dict
and platform_dict
), with keys corresponding to the columns in the WEB_URL
table.
This setup is a typical pattern for web applications using Flask and MySQL, where utility functions are defined for common database operations. These functions can then be imported and used throughout the application to interact with the database, abstracting away the direct database access and SQL queries from the main application logic.