![]() |
|
[Tut] How I Used the Flask Framework to Create an URL Shortener Application - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How I Used the Flask Framework to Create an URL Shortener Application (/thread-100981.html) |
[Tut] How I Used the Flask Framework to Create an URL Shortener Application - xSicKxBot - 04-14-2023 How I Used the Flask Framework to Create an URL Shortener Application 5/5 – (1 vote) A URL shortener service generates a shorter, more readable version of the URL it was given. Flask, a Python web framework can be used to create a URL shortener app. So, we will create an application allowing users to enter a URL and shorten it. We will use the SQLite database engine to store application data. If you prefer to learn how this is done using the Django framework, you are free to read this article. Set up ![]() Create a new folder for this project. Then, create and activate a virtual environment by running the following commands in your terminal. Code: python3 -m venv venv
source venv/bin/activateInstall Flask and the Code: hashidsCode: pip install flask hashidsThe Code: hashidsCreating a Database Engine ![]() Since we will store application data, we must create a database file. Do it and call the file Code: schema.sqlCode: DROP TABLE IF EXISTS urls;
CREATE TABLE urls( id INTEGER PRIMARY KEY AUTOINCREMENT, created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, original_url TEXT NOT NULL, clicks INTEGER NOT NULL DEFAULT 0
);If the above code seems strange, you may want to familiarize yourself with SQL commands. We want to create a table named Code: urlsCode: DROP TABLE…The table is then created with four columns. The Code: idThe Code: schema.sqlCode: init_db.pyCode: import Sqlite3 connection = Sqlite3.connect('database.db') with open('schema.sql') as sql: connection.executescript(sql.read()) connection.commit()
connection.close()Once you run the script (with Code: python3 init_db.pyCode: database.dbThe Code: connect()Code: schema.sqlIt then calls the Code: executescript()Code: database.db init_db.py schema.sql![]() Let us open a connection to the database file. Create a file and name it Code: db_connection.pyCode: import sqlite3 def get_db_connection(): conn = sqlite3.connect('database.db') conn.row_factory = sqlite3.Row return connNotice that we set the row-factory attribute to Code: sqlite3.RowThe Main File ![]() Next, create another file and name it Code: main.pyCode: from db_connection import get_db_connection
from hashids import Hashids
from flask import Flask, flash, render_template, request, url_for, redirect app = Flask(__name__)
app.config['SECRET_KEY'] = 'Your secret key' hashids = Hashids(min_length=4, salt=app.config['SECRET_KEY']) @app.route('/', methods=('GET', 'POST'))
def index(): conn = get_db_connection() if request.method == 'POST': url = request.form['url'] if not url: flash('The URL is required!') return redirect(url_for('index')) url_data = conn.execute('INSERT INTO urls (original_url) VALUES (?)', (url,)) conn.commit() conn.close() url_id = url_data.lastrowid hashid = hashids.encode(url_id) short_url = request.host_url + hashid return render_template('index.html', short_run=short_url) return render_template('index.html')We create an instance of the Flask class. The Code: __name__![]() The Code: index()Code: @app.routeCode: '/'In the Code: index()Code: render_template()If the request method is POST, we use Code: request.form['url']Code: index.htmlCode: index.htmlIf a URL is given, it will be added to the database by executing the command, Code: INSERT INTO …After closing the database, we select the last row id of the database, which is the current URL added. Remember the AUTOINCREMENT keyword in the id column of the database file. This ensures that the id is incremented with each new entry. With the last row id selected, we use the Code: hashids.encode()Code: request.host_urlPlease check my GitHub page for the template files. Make sure you create a templates folder to keep the HTML files. The local server is opened when you run Code: python3 main.pyCode: nameCode: app.run()Adding Extra Features ![]() Won’t it be nice to know how many times each URL has been clicked and have them displayed on a web page? We are going to add that feature. Update your Code: app.pyCode: @app.route('/stats')
def stats(): conn = get_db_connection() db_urls = conn.execute('SELECT * FROM urls').fetchall() conn.close() urls = [] for url in db_urls: url = dict(url) url['short_url'] = request.host_url + hasids.encode(url['id']) urls.append(url) return render_template('stats.html', urls=urls)We again open a database connection, and fetch all the columns in the urls table (indicated by Code: *Code: fetchall()![]() After closing the database, we loop through the result. In each iteration, we convert the Code: sqlite3.Row Notice we didn’t commit the database as we did previously. This is because we didn’t make changes to the database. We close it after fetching the data we needed.Your folder should now have the following files:
Templates Files ![]() As earlier stated, you should check my GitHub page for the templates files. We created a Code: base.htmlCode: templatesThe other two files have certain things that make rendering dynamic content to our Flask web page possible. It is the Code: {% ... %}Code: { ... }These are Jinja2 templating language that comes together with the Flask library. The Code: render_templates()Code: stats()Code: urlsCode: stats.htmlCode: urlsConclusion ![]() This is one of the ways to create a URL shortener app using the Flask framework. This project has expose us to how Flask works as well as how it interacts with database. If you struggle to understand some of what we did, that should be expected as a beginner. However, as you keep working on projects, it will become second nature to you. Recommended: How I Created an URL Shortener App Using Django
|