Python - Kinsta® https://kinsta.com/topic/python/ Kinsta: Simply better hosting. Wed, 18 Feb 2026 05:53:31 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.5 https://kinsta.com/wp-content/uploads/2024/09/cropped-Kinsta-black-favicon-1-32x32.png Python - Kinsta® https://kinsta.com/topic/python/ 32 32 Power up WordPress with Python and Redis https://kinsta.com/blog/python-redis/ Fri, 26 Jan 2024 16:11:50 +0000 https://kinsta.com/?p=173858&preview=true&preview_id=173858 In the Python world, many developers love the NoSQL database Redis because of its speed and the availability of a robust assortment of client libraries. In ...

The post Power up WordPress with Python and Redis appeared first on Kinsta®.

]]>
In the Python world, many developers love the NoSQL database Redis because of its speed and the availability of a robust assortment of client libraries. In the WordPress world, Redis is often the go-to technology when a persistent object cache is needed to speed up backend data access.

You can bring these two worlds together when you manipulate that WordPress content with a Python application.

In this tutorial, we demonstrate how to post content directly to Redis by building a Python app that uses the popular redis-py library and how to post through the WordPress REST API.

What is Redis?

Redis, or Remote Dictionary Server, is a fast NoSQL database and in-memory cache developed by Salvatore Sanfilippo and maintained by Redis Ltd. (formerly Redi Labs). The open-source releases of Redis are available under Berkeley Source Distribution (BSD) licensing, while Redis Ltd. also provides commercial enterprise and cloud incarnations of the server.

Redis distinguishes itself from other NoSQL databases by its data storage mechanism. It’s usually called a data structure store because it stores data with the same data types found in many programming languages, including strings, sets, lists, and dictionaries (or hashes). In addition to supporting simple structures, Redis supports advanced data structures for tasks like geolocation and stream processing.

Python app prerequisites

Before you start creating your app, you need to install the following three items locally:

Pro tip: You can easily create this development environment within Docker by installing Kinsta’s WordPress-ready DevKinsta package.

With the prerequisites installed, it’s time to make things work together. Specifically, you are creating a Python app that takes a user’s WordPress post in dictionary format and saves it to a Redis cache.

Creating a Python app to store a post in the Redis cache

Redis cache is an efficient caching mechanism for websites. It stores frequently requested information for quicker, more convenient access. The cache stores information in a key-value data structure.

Begin by creating a new folder for your project named python-redis. Afterward, start up your command terminal, cd to python-redis, and install redis-py by running the following command:

pip install redis

When the installation is complete, create a new file named main.py in the python-redis directory. Open the file in your favorite text editor to enter the code blocks below.

Start by importing the newly installed redis-py library and set the Redis host and port address:

import redis
redis_host = 'localhost'
redis_port = 6379

Now, define the values for the WordPress post as key/value pairs in a dictionary. Here’s an example:

post = {
    'ID': 1,
    'post_author': 1,
    'post_date': '2024-02-05 00:00:00',
    'post_date_gmt': '2024-02-05 00:00:00',
    'post_content': 'Test Post <br/><a href="proxy.php?url=http://www.my-site.com/">related blog post</a>',
    'post_title': 'My first post',
    'post_excerpt': 'In this post, I will...',
    'post_status': 'publish',
    'comment_status': 'open',
    'ping_status': 'open',
    'post_password': 'my-post-pwd',
    'post_name': 'my-first-post',    
}

Note: In a real-world application, that post content would likely come from an HTML input form.

Add to the code with a redis_dict() function that will connect with your local Redis server, store the above post to the Redis cache, and print the successfully created values to the console:

def redis_dict():
    try:
        r = redis.StrictRedis(host = redis_host, port = redis_port, decode_responses=True)
        r.hset("newPostOne", mapping=post)
        msg = r.hgetall("newPostOne")
        print(msg)
    except Exception as e:
        print(f"Something went wrong {e}")

# Runs the function:
if __name__ == "__main__":
    redis_dict()

Unless you launched Redis within Docker, invoke the Redis command line interface with the following command:

redis-cli

Now run your Python script:

python main.py

Executing the script adds the post to the Redis key-value store. You should see the following response in your terminal’s console:

Screenshot of the terminal showing data posted via Python to a Redis database.
Console output showing Python app post added to Redis storage.

You’ve successfully stored a post in your local Redis database.

Now, let’s upload this post to your WordPress site using the WordPress REST API, storing it in the default MariaDB or MySQL database instead of Redis.

Upload a post to WordPress using the REST API

The WordPress REST API provides a set of endpoints you can call from your app to interact with WordPress. We use the post endpoint to create a post in WordPress.

Step 1: Set the application password in WordPress

The WordPress API requires an application password to permit your app to access data from the WordPress site. The password is a 24-character secret key, which you must include in every request to the REST API.

Generate an application password on the User Profile page of the WordPress Dashboard. You can assign a user-friendly name to each application password, but you won’t be able to view the password itself after generating it (so make a copy now):

Screenshot showing the interface for generating an API password in WordPress.
Generating an application password in the WordPress Dashboard.

Step 2: Post to WordPress with your Python app

First, install the Python requests library for making the HTTP request to the WordPress API. To do this, run the following command on the terminal:

pip install requests

Next, inside your python-redis folder, create a new file named app.py. Then, open the file with your text editor.

Begin by importing the requests, json, and base64 modules:

import requests
import json
import base64

Define the API base URL, as well as your WordPress username and password. For the password variable, use the application password that you generated in WordPress:

url = 'http://localhost/wp-json/wp/v2'
user = '<Your username here>'
password = '<Your application password here>'

Now, join user and password, encode the result, and pass it to the request headers:

creds = user + ":" + password
token = base64.b64encode(creds.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}

And here’s the post body:

post = {    
    'author': 1,
    'date': '2024-02-05 00:00:00',
    'date_gmt': '2024-02-05 00:00:00',
    'content': 'Test Post <br/><a href="proxy.php?url=http://www.my-site.com/">related blog post</a>',
    'title': 'My second post',
    'excerpt': 'In this post, I will...',
    'status': 'publish',
    'comment_status': 'open',
    'ping_status': 'open',
    'password': 'my-post-pwd',
    'slug': 'my-second-post',    
}

Set up the POST request to the API and a command to print the response status:

r = requests.post(url + '/posts', headers=header, json=post)
print(r)

Run your script with the following command in the terminal:

python app.py

If you received a 201 response (“Created”), it means the resource was successfully added.

Screenshot of the terminal reporting a 201 response code after posting to WordPress via Python.
A 201 response code is returned on a successful post.

You can confirm this in your WordPress dashboard or your site’s MySQL/MariaDB database.

Use Redis cache directly in WordPress

WordPress websites can use the Redis cache to temporarily store objects, such as posts, pages, or users. The object can then be accessed from the cache when needed. This approach saves valuable time, reduces latency, and improves the site’s capacity to scale and deal with more traffic.

Redis for Kinsta customers

A fast load time is vital for a pleasant user experience, and there’s little room for underperformance. That’s why Kinsta provides Redis as a premium add-on.

For customers who would like to take advantage of the Redis add-on, simply reach out to Kinsta support, and we’ll take care of the installation process and set it up for you.

Installing a Redis plugin

If you’re not a Kinsta customer, you’ll need to install a dedicated plugin on your WordPress site.

For example, let’s install the Redis Object Cache plugin on your local WordPress website.

Screenshot: Selecting the Redis Object Cache plugin for installation in WordPress.
The Redis Object Cache plugin.

Open the wp-config.php file in a text editor and add the following code in the section for custom configuration variables:

define('WP_REDIS_CLIENT', 'predis');
define('WP_REDIS_HOST', 'localhost');
define('WP_REDIS_PORT', '6379');

Note: The address of your Redis host will depend on your server configuration.

Navigate to Settings > Redis in the WordPress dashboard. You should see something similar to this:

Screenshot: Settings page for the Redis Object Cache plugin in WordPress.
The Redis Object Cache plugin is displayed within the Settings tab.

The Redis cache has now successfully replaced the previous MySQL database.

In addition, the frontend WordPress site uses the same cache as the backend Python application. You can test this by opening a new terminal and running the following command:

redis-cli monitor

As you navigate your site, website requests will output into the command prompt:

Screenshot showing Redis server requests within the terminal.
Monitoring server requests in the terminal with redis-cli.

Now that the front and back ends are in sync, you can add a new post to WordPress using your Python app through the REST API.

To do this, modify the POST object in app.py to include your new post, then run python app.py to add the post to the cache.

Summary

In this article, we learned how to connect a Redis database to a Python application using the Redis Python client. This client supports several formats for Redis data stores: lists, sets, dictionaries, and other command data types.

We also saw how you could integrate Redis into a WordPress site via the REST API and the Redis Object Cache plugin.

The ability to use Redis in-memory cache for your site makes it a potent and flexible development tool. Redis is extraordinarily effective at improving your database query speed, site performance, and general user experience.

A bonus: You can have Kinsta handle Redis installation for your WordPress site. Additionally, Redis fans will find their favorite server available as a stand-alone implementation in Kinsta’s Managed Database Hosting service.

The post Power up WordPress with Python and Redis appeared first on Kinsta®.

]]>
Power up WordPress with Python and Redis Featured image for Power up WordPress with Python and Redis
Build and Deploy a Python App in a Jiffy With Flask and Kinsta https://kinsta.com/blog/python-flask-app/ Fri, 12 Jan 2024 17:57:21 +0000 https://kinsta.com/?p=172623&preview=true&preview_id=172623 Python is one of the most popular development languages. Its simple syntax and low barriers to entry make it a good candidate for novice programmers hoping ...

The post Build and Deploy a Python App in a Jiffy With Flask and Kinsta appeared first on Kinsta®.

]]>
Python is one of the most popular development languages. Its simple syntax and low barriers to entry make it a good candidate for novice programmers hoping to make a mark in the software development landscape.

A host of frameworks and libraries make getting a Python application up and running easier. Those include Django, FastAPI, and Flask. The Flask framework attracts Python developers by supporting easy prototyping and customizability.

This hands-on article demonstrates how to develop a simple database-connected Python application using Flask.

Python Apps Made Easier With Flask

Developed in 2010, Flask is well-suited to developing Python web applications thanks to its ease of use and flexibility. Its lean architecture focuses on providing the basics while making it easy to add libraries for the functionality you need. This approach makes Flask ideal for many projects, from simple applications to complex systems.

Flask offers several tools and capabilities to support web app development, including:

  • Libraries and tools to manage HTTP requests and responses
  • The ability to route requests to designated functions
  • Support for rendering templates
  • Support for databases
  • Authentication and authorization systems

How To Create Your Python Flask App

You can explore the benefits of using Flask for web app development by creating a Python web app using Flask. Then, you can build and deploy the application using Kinsta’s Web Application Hosting service and connect it to a Managed Database on the Kinsta platform.

Python Flask App Prerequisites

To follow this tutorial, you’ll need:

Installing Flask for Python

Go to your terminal (Linux or macOS) or Command Prompt (Windows). Start by creating a directory called flask_demo.

Change to the new directory and create a Python virtual environment using the python3 -m venv venv command. In this case, we are also using venv as the name for the directory that will support the virtual environment.

Activate the virtual environment using one of these commands:

  • venv\Scripts\activate in Windows
  • source venv/bin/activate in Linux or macOS

Now, install Flask using pip by running pip install flask.

The work in your terminal so far should look something like this:

Terminal output during creation of a Python virtual environment and installing Flask.
Creating the foundation of a Python Flask application in the terminal.

Building a Base Application

Next, create the base application and review its functionality by rendering content to the browser.

In the flask_demo directory, create a file called demo.py and add the following code:

from flask import Flask

app = Flask(__name__)

# Routes
@app.route('/')
def index():
    return "Happy Coding!"

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

This code imports Flask from the flask module and creates an instance of it called app. The code then creates a route that returns text displaying “Happy Coding!” when users visit the app in a browser. Finally, it executes the development server once the script starts.

Start the application by running flask --app demo run in the terminal. The --app flag specifies the location of the application it’ll execute — here, the demo.py file.

Adding Templates to Your Python Flask App

Adding templates to your app will bolster your content. First, make a directory called templates in your application’s root. Next, move into the templates directory and create a file called index.html containing the following HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HomePage</title>
</head>
<body>
    <h3>Flask Demo Application</h3>
    <p>My name is John Doe - learning about Application Deployment!</p>
</body>
</html>

In demo.py, import render_template from the flask module and render the index.html template in the route function like this:

from flask import Flask, render_template

app = Flask(__name__)

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

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

Next, serve your application by running flask --app demo run in your local environment. Use the local address reported in the terminal to launch the app in your browser. You should see something like this:

Screenshot of a web browser displaying the initial stage of the Flask application.
The beginnings of a Python Flask app in a web browser.

Connecting Your Flask App to a Local Database

You will create a connection to a local database — MySQL — that stores application content.

To connect your Flask application to MySQL, install the following:

  • flask_mysqldb, the MySQL connector for Flask, using pip install flask_mysqldb
  • Python-dotenv, for reading environment variables, using pip install python-dotenv
  • The Python MySQL connector, using pip install mysql-connector-python
  • The MySQL dependency, using pip install mysqlclient

Head to MySQL Workbench to create a database. Make sure you add a database user with permissions to access the database and create tables.

Create a .env file in your application’s root directory to hold the database connection details. You would add your database user credentials and the database name to this template:

DB_HOST="localhost"
DB_USER="your-db-user"
DB_PASSWORD="your-db-password"
DB_NAME="your-db-name"

In a revised demo.py script, we will now import the MySQL connector and use Python-dotenv to read the environment variable keys in the .env file. This new demo.py script also checks for the existence of a table named persons in the database and will create and populate it if it does not exist.

import os
from flask import Flask, render_template
from flask_mysqldb import MySQL

from dotenv import load_dotenv
load_dotenv()

app = Flask(__name__)

app.config['MYSQL_HOST'] = os.getenv("DB_HOST")
app.config['MYSQL_USER'] = os.getenv("DB_USER")
app.config['MYSQL_PASSWORD'] = os.getenv("DB_PASSWORD")
app.config['MYSQL_DB'] = os.getenv("DB_NAME")

mysql = MySQL(app)

@app.route('/')
def index():
    cursor = mysql.connection.cursor()

    cursor.execute("SHOW TABLES LIKE 'persons'")
    result = cursor.fetchone()

    if not result:
        cursor.execute(''' CREATE TABLE persons (id INTEGER, firstname VARCHAR(20), lastname VARCHAR(20)) ''')
        cursor.execute(''' INSERT INTO persons VALUES(1, 'John', 'Doe') ''')
        cursor.execute(''' INSERT INTO persons VALUES(2, 'Milly', 'Winfrerey') ''')
        mysql.connection.commit()

    cursor.execute('SELECT * FROM persons')
    entry = cursor.fetchall()
    cursor.close()
    return render_template('index.html', entry=entry)

After instantiating Flask, the code above uses environment variables to capture the database attributes from the .env file in your application’s root.

Then, the code instantiates MySQL and associates it with Flask. It creates a cursor object in the index route. Next, the code checks for a table named persons in the database. If it is not found, it creates it with the attributes id, firstname, and lastname and inserts two rows of data.

The next three lines execute an SQL command to select all rows from the persons table and fetch the results. The cursor object is closed, and the results of the query are passed as the context variable entry for rendering with the template.

Here’s a revised index.html template file that can process the results of the database query:

<!DOCTYPE html><html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HomePage</title>
</head>
<body>
    <h3>Flask Demo Application</h3>
    {% for e in entry %}
        <p>My name is {{e[1]}} {{e[2]}} - learning about Application Deployment!</p>
    {% endfor %}
</body>
</html>

Execute the application, then return to MySQL Workbench to check the data. It should look like the following:

Screenshot of query results in MySQL Workbench.
Query results for the persons table in MySQL Workbench.

When you query the table, the two entries generated by the app are returned. Your application now renders the following database-derived content in the browser:

Screenshot showing content generated from the database.
Database-generated content in the browser.

How To Deploy Your Python Flask App to Kinsta

Now that your application is up and running locally, you can make it visible to the world by hosting it on Kinsta. You can pair Kinsta’s Web Application Hosting and Managed Database Hosting services to bring this app (and your future efforts) to life in the cloud. And you can try them both for free.

Preparing Your Python Project for Deployment

Kinsta’s Web Application Hosting platform deploys your code from your favorite Git host. Your next step is to configure your application environment to support that pathway and allow Kinsta to deploy your application with all its required dependencies.

Start by creating a new directory within your flask_demo project root. Let’s call it myapp. Then move the templates directory and the demo.py file into myapp.

Inside the myapp directory, create a wsgi.py file with the following content:

from myapp.demo import app as application

if __name__ == "__main__":
    application.run(debug=True)

The build process at Kinsta will also use pip to generate your application. You can pass a list of your app’s dependencies to pip on the production side using a requirements.txt file in the project’s root directory.

While still working in the venv virtual environment and within the flask_demo root directory, you can generate a requirements.txt file that is specific to your project with the following command:

pip freeze > requirements.txt

The contents of the resulting text file will look something like this:

blinker==1.7.0
click==8.1.7
Flask==3.0.0
Flask-MySQLdb==2.0.0
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.3
mysql-connector-python==8.2.0
mysqlclient==2.2.1
protobuf==4.21.12
python-dotenv==1.0.0
Werkzeug==3.0.1

You won’t be sending the .env file with its database secrets to the production server. Since you won’t need the python-dotenv library to read .env in production, you can remove its reference from requirements.txt and remove (or comment out) these lines in demo.py:

from dotenv import load_dotenv
load_dotenv()

Adding a Python WSGI HTTP Server to the Project

One thing missing from the requirements above is a way to serve the application via HTTP in a production environment. The development server used on your local machine won’t do. For this project, you’ll use the Web Server Gateway Interface (WSGI) package Gunicorn between the app and Kinsta’s Nginx web servers.

You can add a Gunicorn requirement to your project by installing it within your virtual environment like this:

pip install gunicorn

After Gunicorn is installed, use pip to generate requirements.txt again.

An alternative to installing Gunicorn locally is to edit requirements.txt and simply add an entry like this:

gunicorn==21.2.0

To wrap up the groundwork for the WSGI server, create a file in the project’s root directory named Procfile and add the following line:

web: gunicorn myapp.wsgi

This will be the basis of the start command for your app in production.

Getting Your Project Ready for Git

The revised directory structure is ready for deployment at Kinsta, but you don’t want all of those files going to production. Create a .gitignore file in the project root with content like this:

/venv
.env

This will keep the files within the venv directory and the local database secrets in .env from uploading to your Git host.

You can now initiate your local Git environment and push the code to your Git host using your preferred tools.

Deploying Your Python Flask App to Kinsta

Login to your MyKinsta dashboard and make sure you have authorized Kinsta to access your Git service provider. Follow the steps to add an application, selecting the repository and branch on the Git host where Kinsta will find this Flask project code.

When configuring the build environment, select Use Buildpacks to set up container image, but leave all other settings at their defaults. (You will not provide a Start command because that is already defined in your Procfile.)

Screenshot of the MyKinsta interface for configuring a build environment.
Choosing Buildpacks to set up the container image for the application.

After reviewing billing information (you can still get started for free!), click the Build now button and watch the progress in the log viewer:

Screenshot of the log entries for a Python Flask app deployment.
Log entries for your Python Flask app deployment.

Adding a Database for Your Python Flask App

Kinsta has four managed database options to meet your needs and application requirements: Redis, PostgreSQL, MariaDB, and MySQL. For this tutorial, we have been building for the MySQL database service.

Follow the official instructions for adding a database, remembering to select the same data center you chose for your Flask application.

After creating the database, select it from the list of your available DB servers and scroll down to the Internal connections / Allowed applications section of the Overview tab. When you click the Add connection button, your Flask application service in the same data center will be available to select:

Screenshot of the dialog for adding an internal database connection in MyKinsta.
Adding an internal connection to an application after creating a database.

Click the Add environment variables to the application checkbox before creating the new connection. This displays the environment variables that will carry your database secrets — all handled securely without the need for the .env file.

Screenshot of the dialog for adding environment variables for database credentials.
Adding environment variables for an internal connection to your database.

At the bottom of the above dialog, the settings Available during runtime and Available during build process will be enabled by default — and that’s exactly what you want.

After finally clicking the Add connection button, the environment variables required for database access will be applied to your project Settings over in MyKinsta’s Applications dashboard:

Screenshot of a MyKinsta dialog showing environment variables passed from the database to an application.
Database environment variables passed to the Python Flask app.

Now, even when you rebuild your application after future enhancements, the database connection particulars will persist.

Screenshot of the Python Flask application live on the Kinsta platform.
The Python Flask application live on the Kinsta platform.

Congratulations! You’ve just created a Python Flask application and deployed it to the Kinsta platform.

Summary

Flask’s customizable framework makes creating a Python application dramatically simpler. Using Kinsta to deploy a Flask application makes things even easier, accelerating application development and deployment.

Here, we learned how to build a simple database-connected application within a local development environment and then make that available to the rest of the world on Kinsta’s Web Application Hosting and Database Hosting platforms.

Explore what else you can build on our platform by browsing our Quick Start Templates.

The post Build and Deploy a Python App in a Jiffy With Flask and Kinsta appeared first on Kinsta®.

]]>
Build and Deploy a Python App in a Jiffy With Flask and Kinsta Featured image for Build and Deploy a Python App in a Jiffy With Flask and Kinsta
Build a Simple URL Shortener With Python https://kinsta.com/blog/url-shortener-with-python/ Wed, 10 Jan 2024 16:35:36 +0000 https://kinsta.com/?p=171124 A uniform resource locator — or, more commonly, URL — is the address of content on the internet. URLs often feature the address of a web page ...

The post Build a Simple URL Shortener With Python appeared first on Kinsta®.

]]>
A uniform resource locator — or, more commonly, URL — is the address of content on the internet. URLs often feature the address of a web page followed by a long string of seemingly random characters. These can be unsightly and unmemorable. Fortunately, there are tools called URL shorteners that can minimize them.

Shortening a URL has several benefits, including making the address easier to share and less likely to be typed inaccurately by users. Even one missing character in a URL can make it completely useless, directing users to the wrong page or to a resource that doesn’t even exist.

Take the example of https://example.com/blog-url-shorteners/48bfefiahl9adik shortened to https://example.com/url-shorteners. It’s not hard to see which a user would be more prone to share, or which might be more likely to lead to mistakes while typing.

A URL shortener’s benefits go beyond tidying up long URLs. They can also help with the following:

  • Improving ranking in search engines: Content creators, businesses, and start-ups all have content on their websites, blogs, or social media. Search engines prefer links with specific keywords so they can be ranked accordingly and generate good results. A short URL generated from a known platform can help rank your URL higher.
  • Tracking traffic on your links: Paid URL shortener services like Bitly help you track the users clicking your links so you can analyze your incoming traffic and customize your content accordingly.

Two Approaches to a URL Shortener: A Python Library and an API

Following the instructions in this tutorial, you’ll build a URL shortener web app with Python using two different methods:

The pyshorteners module is used by developers to generate short URLs, while the Bitly API module generates short URLs and provides more robust functions like clicks per URL, locations of clicked URLs, customization of URLs, and more.

To complete the tutorial, you’ll need a basic knowledge of Python, and Python must be installed on your system.

Setting Up the Project Environment

Before creating your URL shortener web app, you need to set up the environment for the project, including the installation of Flask, a lightweight framework that makes developing Python web apps easier.

Begin with these steps:

  • Create a project folder, perhaps with a name like url-shortener.
  • Create an empty file named main.py within that folder.
  • Create a virtual environment for this project so that any installation of Python libraries remains independent of your system. Use the command python -m venv myenv in your terminal to create that environment. (In this case, the environment files will be placed in the directory myenv.)
  • Activate the virtual environment using the corresponding command for your operating system (and where <myenv> is the name of the directory you created in the previous step).
    • Windows: <myenv>\Scripts\activate.bat
    • Linux/macOS: source <myenv>/bin/activate
  • Install Flask using the command pip install flask.
  • Create a folder named templates in the project folder. (Flask will retrieve the HTML templates from this directory.)

Your work in the terminal so far will look something like this:

Commands entered in the terminal to create the Python project environment.
The Python project so far in a macOS terminal.

Using the pyshorteners Library to Build a URL Shortener Web App

With your project environment set up, you’ll now create your first URL shortener using the pyshorteners library.

Install the pyshorteners library with the following command:

pip install pyshorteners

Creating a Basic User Interface for the Web Application

Next, you’ll create a basic form in HTML with labels and input fields, where you enter a long URL and generate a shorter one.

Create a form.html file in the templates folder, then enter the following code in that file and save it:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>URL Shortener</title>
</head>
<body>
  <h1>URL Shortener</h1>
  <form method="post" action="proxy.php?url=/">
    <label for="url">Enter an https:// URL:</label>
    <input type="url"
      name="url"
      id="url"
      placeholder="https://www.xyz.com"
      pattern="https://.*" size="50"
        value="{{old_url}}"
      required  
    >
    <button type="submit" value="submit">Submit</button>
    <br>
    <label>Generated URL: </label>
    <input name="generated_url" value="{{new_url}}" style="margin-top: 10px; margin-left:35px" size="50"></input>
  </form>
</body>
</html>

The above code creates a form with two labels, two input fields, and one button.

The first input field called url, is for writing the long URL, and the other field is for generating the short URL.

The url input field has the following attributes:

  • name: To identify the element (e.g., URL)
  • placeholder: To show a URL example
  • pattern: To specify the pattern of a URL which is https://.*
  • required: To give a URL input before submitting
  • value: To view the old URL

The second input field has a value attribute set to new_url. The new_url is a short URL generated by the pyshorteners library from the main.py file (shown in the next section).

The entry form is depicted in the following screenshot:

Screenshot of a web form for shortening URLs.
A web form for the URL shortener.

URL Shortening Code Using pyshorteners

Now that you’ve created the form, you can add some functionality to it using Python and pyshorteners.

You’ll add code to process the long URL into a short one and run the web application. Navigate to the main.py file you created earlier, enter the following code, and save it:

from flask import Flask, render_template, request
import pyshorteners
app = Flask(__name__)
 
@app.route("/", methods=['POST', 'GET'])
def home():
  if request.method=="POST":
    url_received = request.form["url"]
    short_url = pyshorteners.Shortener().tinyurl.short(url_received)
    return render_template("form.html", new_url=short_url, old_url=url_received)
  else:
    return render_template('form.html')
 
if __name__ == "__main__":
 app.run() 

The code above imports the pyshorteners library and the following modules from the Flask framework, all of which you’ll need for shortening URLs:

  • Flask: The Flask framework itself, which was previously introduced.
  • render_template: A template rendering package used to generate the output of HTML files from the folder templates.
  • request: An object from the Flask framework that contains all the data that a user sends from the frontend to the backend as a part of an HTTP request.

Next, it creates a function called home() that takes a URL submitted in the form and outputs a short URL. The app.route() decorator is used to bind the function to the specific URL route for running the app, and the POST/GET methods handle the requests.

In the home() function, there’s an if-else conditional statement.

For the if statement, if request.method=="POST", a variable called url_received is set to request.form["url"], which is the URL submitted in the form. Here, url is the name of the input field defined in the HTML form created earlier.

Then, a variable called short_url is set to pyshorteners.Shortener().tinyurl.short(url_received).
Here, two methods are used from the pyshorteners library: .Shortener() and .short(). The .Shortener() function creates a pyshorteners class instance and the .short() function takes in the URL as an argument and shortens it.

The short() function, tinyurl.short(), is one of the pyshorteners library’s many APIs. osdb.short() is another API that can also be used for the same purpose.

The render_template() function is used to render the HTML file template form.html and send URLs back to the form through arguments. The new_url argument is set to short_url and old_url is set to url_received. The if statement’s scope ends here.

For the else statement, if the request method is other than POST, only the form.html HTML template will be rendered.

Demonstration of the URL Shortener Web App Built with the pyshorteners Library

To demonstrate the pyshorteners URL shortener application, navigate to the default route for the application, http://127.0.0.1:5000/, after running the application.

Paste a link of your choice into the first field of the web form:

Screenshot of URL to be shortened pasted into web form.
Testing the URL shortener using the pyshorteners library.

Click the Submit button to output a short URL with tinyurl as the domain in the Generated URL field:

Screenshot showing shortend URL returned in web form.
Result of URL shortening using the pyshorteners library.

Using the Bitly API Module to Build a URL Shortener Web App

In this section, you’ll develop a URL-shortening application using the Bitly API. As mentioned, the Bitly API module is another method for shortening URLs and also provides detailed analytics on clicks, location, and device type used (such as desktop or mobile).

Install the Bitly API using the following command:

pip install bitly-api-py3

You need an access token to use the Bitly API, which you can get by signing up with Bitly.

After completing the signup process, log in to Bitly to view your dashboard:

Screenshot of the Bitly dashboard.

Click Settings on the left sidebar, then click the API section found under Developer settings.

Generate an access token by entering your password in the field above the Generate token button, as shown in the image below, and keep the token to use in the code for your app:

Screenshot of access token generation for the Bitly API/
Generating an access token for the Bitly API.

URL Shortening Code Using the Bitly API

Now that you have the token from Bitly, you can code the web app to shorten the URL using the Bitly API.

You’ll use the same form you created for the pyshorteners section but with some changes to the main.py file:

from flask import Flask, render_template, request
import bitly_api
app = Flask(__name__)
 
bitly_access_token = "37b1xxxxxxxxxxxxxxxxxxxxxxxxxx"
 
@app.route("/", methods=['POST', 'GET'])
def home():
  if request.method=="POST":
    url_received = request.form["url"]
    bitly = bitly_api.Connection(access_token=bitly_access_token)
    short_url = bitly.shorten(url_received)
    return render_template("form.html", new_url=short_url.get('url'), old_url=url_received)
  else:
    return render_template('form.html')
 
if __name__ == "__main__":
 app.run() 

As you can see from the code above, bitly_api is imported using import bitly_api. The access token is then saved in a variable called bity_access_token, as in bitly_access_token = "37b1xxxxxxxxxxxxxxxxxxxxxxxx".

The home() function shortens the URL and contains an if-else conditional statement.

For the if statement, if the method or request is POST, then the URL submitted in the form is set to the url_received variable.

The bitly_api.Connection(access_token=bitly_access_token) function connects to the Bitly API and passes it the access token you saved earlier as an argument.

To shorten the URL, the bitly.shorten() function is used by passing the url_received variable as an argument and saving it in a variable called short_url.

Finally, the created form is rendered, and URLs are sent back to be shown in the form using the render_template() function. The if statement completes here.

For the else statement, the form is rendered using the render_template() function.

Demonstration of the URL Shortener Web App Built with the Bitly API

To demonstrate the Bitly API URL shortener application, navigate to the default route for the application, http://127.0.0.1:5000/, after running the application.

Paste a link of your choice into the first field of the web form:

Screenshot of web form for Bitly URL shortener API.
Testing the URL shortener using the Bitly API.

Click Submit to generate a short URL with bit.ly as the domain in the second field of the web application:

Screenshot of shortened URL returned by the Bitly API.
Result of URL shortening using the Bitly API.

Using the Bitly API to shorten URLs in your Python application is a simple as that.

Summary

URL shorteners give you short URLs that are easy to share, look cleaner, and take up less space. In this article, you learned about URL shorteners and their benefits, as well as how to create a URL shortener web application with Python using pyshorteners and the Bitly API. The pyshorteners library provides short URLs, while the Bitly API provides detailed analytics as well as short URLs.

Since you’ve already made an awesome app, why not take it to the next level and host it on Kinsta’s Wed Application Hosting service? To help you get a Python app like this up and running on our platform, explore our Flask quick start tutorial.

The post Build a Simple URL Shortener With Python appeared first on Kinsta®.

]]>
Build a Simple URL Shortener With Python Featured image for Build a Simple URL Shortener With Python