Using Python to Operate Memcached
To operate the Memcached database using Python, you can use the pymemcache library. Pymemcache is a Python library that provides the ability to interact with Memcached servers.
Firstly, you need to install the pymemcache library. You can use the pip command to execute the following commands in the terminal for installation:
pip install pymemcache
After installation, you can write Python code to connect, insert, query, modify, and delete data in Memcached.
The following is a complete Python code example that demonstrates how to use the pymemcache library to connect to a Memcached server and perform data insertion, query, modification, and deletion operations:
python
from pymemcache.client import base
#Connect to Memcached server
client = base.Client(('localhost', 11211))
#Insert Data
client.set('key1', 'value1')
client.set('key2', 'value2')
#Query data
value1 = client.get('key1')
Print (value1) # Output: b'value1 '
#Modify data
client.set('key1', 'new_value')
#Delete data
client.delete('key2')
#Disconnect from Memcached server
client.close()
In the above example, first connect to the Memcached server using the 'base. Client()' method` The base. Client() 'method takes a tuple parameter that contains the IP address and port number of the server. In this example, the local host and default Memcached port number (11211) were used. If the connection is successful, a Memcached client object will be returned.
Next, two key value pairs of data were inserted into Memcached using the 'client. set()' method.
Then, the 'client. get()' method was used to query the value of a key.
Modified the value of a key using the 'client. set()' method.
Finally, a key was deleted using the 'client. delete()' method.
Finally, use the 'client. close()' method to close the connection to the Memcached server.
Through these basic operations, you can use Python to connect and operate Memcached databases.