The strength of WordPress using Python and Redis - (r)

Apr 10, 2024
An illustration with stylized versions of the Redis and Python logos.

-sidebar-toc>

It is possible to bring both worlds together if you alter the WordPress material using Python software.

This video will show how to directly upload files to Redis through the creation of a Python application that utilizes the well-known redis-py library. Additionally, we demonstrate how to publish content through Redis with the WordPress REST API.

What exactly is Redis?

Redis is distinct from other NoSQL databases by the storage system for databases. It's usually called a data structure store because it is able to contain files that are comparable to the kinds of data which are utilized in a variety of programming languages. It includes strings, sets lists, dictionaries, and collections (or hashes). Alongside supporting standard data structures, Redis can also support advanced structures for tasks like geolocation or stream processing.

Python app prerequisites

Prior to making your application it is essential to download the three following items locally.

  • Redis Read Redis's Redis Official Redis installation guidelines to get directions.
  • Python together with pip as of Python 3.4 pip An installer, for the Python installation software is now included as standard.

Once you have the necessary elements installed, it's now time to create the things work. In particular, you're creating a Python program that will take the users' WordPress blog post as a dictionary and then saves it into a Redis cache.

Create the Python app to store an article inside the Redis cache

Redis cache could be described as a fast web-based caching system. It stores frequently requested information to provide faster, easier access. The cache is organized into a key-value data arrangement.

pip Install redis

Install the newly downloaded redis-py library. Set the Redis host and port address:

import redis redis_host = 'localhost' redis_port = 6379

Next, determine the key and value of the WordPress blog post using key/value pairs within an index. Here's an example

post = ID, 'post_author': 1; 'post_date': '2024-02-05 00:00:00', 'post_date_gmt"2024-02-05 00:00,00""post_content": "Test Related blog post to the Post", 'post_title "My first blog post 'post_excerpt': 'In this article, I'll ...',  post a status of "publish", 'comment_status': 'open'  and 'ping_status': open and 'post_password' is'my-post-pwd', 'post_name'  first-post-name'

Include in the code the redis_dict() function that allows you to establish a connection to the Local Redis server, and store the previous post in the Redis cache. You can then send the generated values on 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()

If you haven't launched Redis through Docker as well as Docker by itself, then you may invoke Redis Command Line Interface. Redis Command Line Interface by using these commands:

redis-cli

Run the script in your Python script:

Python main.py

When you execute this script, it should add the script to the Redis value store that stores key values. The script should display this response on the console in your terminal:

Screenshot of the terminal showing data posted via Python to a Redis database.
Console output which shows Python application posts that have been which were added in Redis storage.

The article has been saved to your home Redis database.

Upload a post to WordPress through the REST API. API

WordPress REST API WordPress REST API provides an assortment of endpoints that to call via your application to establish a connection with WordPress. The API we use is post-endpoint to create blogs within WordPress.

Step 1: Create the password to your application within WordPress

The WordPress API needs an application password to grant your app access to the data stored that are stored on the WordPress website. The password consists of a 24-character secret key, which must be provided when you call an API using REST.

Make an application's password by using The user profile page of WordPress's WordPress Dashboard. It is possible to create a user-friendly name for each password you create however, you will not have access to your password until you've constructed it (so take a photocopy immediately):

Screenshot showing the interface for generating an API password in WordPress.
The process of creating the passwords for applications can be done via WordPress Dashboard. WordPress Dashboard.

Second step: Write your post on WordPress with your Python app

The initial step is to install first your Python Requests library for making the HTTP connection to WordPress API. In order to do that, execute this command using the terminal:

Request for installation of pip

Within the Python-redis folder, you can create an app.py file. app.py. After that, you can access the file with your text editor that you've installed.

Begin by installing the request, json and bases64 modules:

request to import JSON Import Base64

Find the API base URL as in addition to your WordPress username and your password. In the variable for passwords choose the password of your application that you generated with WordPress:

url = 'http://localhost/wp-json/wp/v2' user = '' password = ''

Then, sign in with the username and password of username and create password. Once you have created a password then encode it and send it to Request headers:

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

The body of the article:

blog = 'author': 1  Date: '2024-02-05 at 0:00", 'date_gmt '2024-02-05 00:00:00'"content": "Test Blog post related to this title: 'My second post', 'excerpt' in this blog post: I will ...', "status" publish', 'comment_status': 'open' 'ping_status': 'open' password:'my-post-pwd'', 'slug'  my-second-post'

Create your POST request for the API with a command that will display the status of your response

r is requests.post(url + '/posts' headers=header JSON=post) print(r)

It is possible to run your script by using this command inside the terminal

Python app.py
Screenshot of the terminal reporting a 201 response code after posting to WordPress via Python.
A response code of 201 will be provided after an effective submission.

Use Redis cache right from within WordPress

WordPress websites can use Redis cache. Redis cache can be used to temporarily store things like pages, posts or even users. It is accessible from the cache whenever you require it. This helps save time, reduces latency, and improves capacity of the site to cope with more users.

Customers are able to use Redis to buy

Installation of Redis plugin Redis plugin

Let's say, for example that we use the download of Redis Object Cache, for example. Redis Object Cache plugin on your local WordPress site.

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

Begin by opening with the wp-config.php file in an editing program and paste this code in the section that allows you to customize the configuration of variables:

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

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

Go through settings > Redis within Redis within Redis on the WordPress dashboard. You should see something like this:

Screenshot: Settings page for the Redis Object Cache plugin in WordPress.
This is the Redis Object Cache plugin is accessible through the settings tab.

Redis cache has been replaced. Redis cache has now successfully succeeded in replacing the old MySQL database.

Additionally it is true that the front-end WordPress site utilizes the same cache utilized by the backend Python application. You are able to try this by using a different terminal, by running the following command:

Redis-cli Monitor

While you are browsing your site, all queries from your website will result in a prompt

Screenshot showing Redis server requests within the terminal.
You can monitor server requests inside the terminal by using the redis-cli.

When the back and front end are in sync, you'll be able to add a new post to WordPress with the Python application via the REST API.

For this, change the POST object within app.py to include the post you want to add. After that, run the Python app.py to add the post to the cache.

Summary

In this video we'll show you how to connect an Redis database with the Python application by using the Redis Python client. The client is compatible with a range of formats used by Redis data stores including lists, sets dictionary, and various other command data formats.

Also, we saw that it's possible to integrate Redis into the WordPress site via REST API as well as Redis Object Cache. Redis Object Cache plugin.

The possibility of using Redis memory cache for powering your website makes it a potent and flexible software for developing. Redis is extraordinarily effective at making your database queries as well as the performance of your site, as and the general happiness of the users.

Steve Bonisteel

Steve Bonisteel is a Technical Editor of the site. He started his career writing as a print journalist who chased firefighters and ambulances. He has been covering internet-related technologies since the mid 1990s.

This post was first seen on here