Last active
July 5, 2016 08:43
-
-
Save namndev/792446f413acebbd517b3ac631d6faa0 to your computer and use it in GitHub Desktop.
Example Python scrip working with memcached + InnoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import memcache | |
import sys | |
from datetime import datetime, timedelta | |
import pymysql | |
def banner(message): | |
print("=" * len(message)) | |
print(message) | |
print ("=" * len(message)) | |
def connect_memcache(): | |
memc = memcache.Client(['127.0.0.1:11211'], debug=1) | |
print("Connected to memcached.") | |
return memc | |
def switch_table(memc, table): | |
key = '@@' + table | |
print("Switching default table to '" + table + "' by issuing GET for '" + key + "'.") | |
result = memc.get(key) | |
print(result) | |
return result | |
def insert_data(memc, data): | |
banner("Inserting initial data via memcached interface") | |
for item in data: | |
key = str(item[0]) | |
row = item[1] | |
print ("Key: {}".format(key)) | |
print ("Row: {}".format(row)) | |
if memc.add(key,row): | |
print("Added new key, value pair.") | |
else: | |
print("Updating value for existing key.") | |
memc.set(key,row,60) | |
def query_data(memc): | |
banner("Retrieving data for all keys") | |
for item in range(161,180): | |
key = str(item) | |
result = memc.get(key) | |
print (result) | |
print("Here is the result retrieved from the database for key: {}".format(key)) | |
if result is not None: | |
(usr_surveyoff, usr_createdon, usr_gatheringoff) = result.split("|") | |
# print("Unpacked usr_surveyoff value: {}".format(usr_surveyoff)) | |
print("Unpacked usr_createdon value : {}".format(usr_createdon)) | |
# print("Unpacked usr_gatheringoff value: {}".format(usr_gatheringoff)) | |
def init_data(): | |
key = 161 | |
row = "{0}|{1}|{2}" | |
now = datetime.now() | |
data = [] | |
for i in range(0,20): | |
r = row.replace('{0}','0') | |
now = now - timedelta(hours=1) | |
r = r.replace('{1}',str(now)) | |
r = r.replace('{2}', '0') | |
data.append((key+i,r)) | |
return data | |
# query data from view | |
def query_from_view(conn): | |
cursor = conn.cursor() | |
cursor.execute("select * from v_users") | |
print(cursor.description) | |
for row in cursor: | |
print(row) | |
cursor.close() | |
if __name__ == '__main__': | |
data = init_data() | |
memc = connect_memcache() | |
sr = switch_table(memc,"mobience") | |
if sr is not None: | |
insert_data(memc, data) | |
query_data(memc) | |
# query from view | |
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='samvl', db='test') | |
query_from_view(conn) | |
conn.close() | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment