1.创建一个数据库
[guan@master1 ~]$ mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 827
Server version: 5.7.40-log MySQL Community Server (GPL)Copyright (c) 2000, 2022, Oracle and/or its affiliates.Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| discuz |
| guanDB |
| master1db |
| mysql |
| performance_schema |
| sys |
| testdb |
| wordpress |
| zabbix |
+--------------------+
10 rows in set (0.07 sec)mysql> drop database guanDB;
Query OK, 1 row affected (0.14 sec)mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| discuz |
| master1db |
| mysql |
| performance_schema |
| sys |
| testdb |
| wordpress |
| zabbix |
+--------------------+
9 rows in set (0.00 sec)mysql> create database GuanDB;
Query OK, 1 row affected (0.05 sec)mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| GuanDB |
| discuz |
| master1db |
| mysql |
| performance_schema |
| sys |
| testdb |
| wordpress |
| zabbix |
+--------------------+
10 rows in set (0.00 sec)
2.给用户进行授权
mysql> grant all on GuanDB.* to guan@'%' identified by '123456';
Query OK, 0 rows affected, 1 warning (0.03 sec)mysql> grant all on GuanDB.* to root@'%' identified by '123456';
Query OK, 0 rows affected, 1 warning (0.00 sec)
3.安装pymysql
[guan@master1 python-code]$ pip3 install pymysql
Defaulting to user installation because normal site-packages is not writeable
Collecting pymysqlDownloading PyMySQL-1.0.2-py3-none-any.whl (43 kB)━━━━━━━━━━━━━━━━ 43.8/43.8 kB 1.4 MB/s eta 0:00:00
Installing collected packages: pymysql
Successfully installed pymysql-1.0.2
[guan@master1 python-code]$
[guan@master1 ~]$ mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 622
Server version: 5.7.40-log MySQL Community Server (GPL)Copyright (c) 2000, 2022, Oracle and/or its affiliates.Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| GuanDB |
| discuz |
| master1db |
| mysql |
| performance_schema |
| sys |
| testdb |
| wordpress |
| zabbix |
+--------------------+
10 rows in set (0.16 sec)mysql> use GuanDB;
Database changed
mysql> show tables;
Empty set (0.00 sec)mysql> show tables;
+------------------+
| Tables_in_GuanDB |
+------------------+
| base_info |
+------------------+
1 row in set (0.01 sec)mysql> select * from base_info;
Empty set (0.09 sec)mysql> show tables;
+------------------+
| Tables_in_GuanDB |
+------------------+
| base_info |
| memory |
+------------------+
2 rows in set (0.19 sec)mysql> select * from memory;
Empty set (0.01 sec)mysql> select * from memory;
Empty set (0.16 sec)mysql> show tables;
+------------------+
| Tables_in_GuanDB |
+------------------+
| base_info |
| memory |
+------------------+
2 rows in set (0.00 sec)mysql> select * from base_info;
+----+-----------+-----------------------+--------------------------------------+--------------+-------------------------+--------------------------------------------------------+----------------------------------------+---------+----------------+
| id | host_name | kernel | os | manufacturer | pod_name | sn | cpu_name | cpu_pyc | cpu_cores_each |
+----+-----------+-----------------------+--------------------------------------+--------------+-------------------------+--------------------------------------------------------+----------------------------------------+---------+----------------+
| 1 | master1 | 3.10.0-957.el7.x86_64 | CentOS Linux release 7.6.1810 (Core) | VMware, Inc. | VMware Virtual Platform | VMware-56 4d 26 13 58 de 6f c1-41 34 b3 2a 30 dc fc bb | AMD Ryzen 7 5700U with Radeon Graphics | 1 | 1 |
+----+-----------+-----------------------+--------------------------------------+--------------+-------------------------+--------------------------------------------------------+----------------------------------------+---------+----------------+
1 row in set (0.00 sec)mysql> select * from base_info;
+----+-----------+-----------------------+--------------------------------------+--------------+-------------------------+--------------------------------------------------------+----------------------------------------+---------+----------------+
| id | host_name | kernel | os | manufacturer | pod_name | sn | cpu_name | cpu_pyc | cpu_cores_each |
+----+-----------+-----------------------+--------------------------------------+--------------+-------------------------+--------------------------------------------------------+----------------------------------------+---------+----------------+
| 1 | master1 | 3.10.0-957.el7.x86_64 | CentOS Linux release 7.6.1810 (Core) | VMware, Inc. | VMware Virtual Platform | VMware-56 4d 26 13 58 de 6f c1-41 34 b3 2a 30 dc fc bb | AMD Ryzen 7 5700U with Radeon Graphics | 1 | 1 |
+----+-----------+-----------------------+--------------------------------------+--------------+-------------------------+--------------------------------------------------------+----------------------------------------+---------+----------------+
1 row in set (0.02 sec)mysql> select * from base_info\G
*************************** 1. row ***************************id: 1host_name: master1kernel: 3.10.0-957.el7.x86_64os: CentOS Linux release 7.6.1810 (Core)manufacturer: VMware, Inc.pod_name: VMware Virtual Platformsn: VMware-56 4d 26 13 58 de 6f c1-41 34 b3 2a 30 dc fc bbcpu_name: AMD Ryzen 7 5700U with Radeon Graphicscpu_pyc: 1
cpu_cores_each: 1
1 row in set (0.16 sec)
操作数据库
#1.pip3 install pymysql
#2.创建一个数据库
#create database GuanDB;
#3.给用户进行授权
#grant all on GuanDB.* to guan@'%' identified by '123456';
#import pymysql#创建连接
conn = pymysql.connect(host='192.168.200.181',port=3306,user='root',passwd='123456',db='GuanDB')#获取游标对象
cursor = conn.cursor(pymysql.cursors.DictCursor)#实例
info = {"base_info": {"manufacturer": "VMware, Inc.","pod_name": "VMware Virtual Platform","sn": "VMware-56 4d 26 13 58 de 6f c1-41 34 b3 2a 30 dc fc bb","host_name": "master1","kernel": "3.10.0-957.el7.x86_64","os": "CentOS Linux release 7.6.1810 (Core)"},"cpu": {"cpu_name": "AMD Ryzen 7 5700U with Radeon Graphics","cpu_pyc": 1,"cpu_cores_each": 1},"memory": [{"capacity": "8192 MB","slot": "DIMM_B2","model": "DDR3","speed": "1333 MT/s","manufacturer": "00CE00B380CE","sn": "82B79F71"},{"capacity": "8192 MB","slot": "DIMM_B3","model": "DDR3","speed": "1333 MT/s","manufacturer": "00CE00B380CE","sn": "32CDDE81"},{"capacity": "No Module Installed","slot": "DIMM_B4","model": "DDR3","speed": "Unknown","manufacturer": "","sn": ""},{"capacity": "8192 MB","slot": "DIMM_B5","model": "DDR3","speed": "1333 MT/s","manufacturer": "00CE04B380CE","sn": "85966B82"},{"capacity": "8192 MB","slot": "DIMM_B6","model": "DDR3","speed": "1333 MT/s","manufacturer": "000000B380CE","sn": "00000000"}]
}base_info = {**info["base_info"],**info["cpu"]}
print(tuple(base_info))#
sql1 = """create table base_info(id int auto_increment primary key,host_name varchar(64) not null,kernel varchar(64),os varchar(64),manufacturer varchar(64),pod_name varchar(64),sn varchar(64),cpu_name varchar(64),cpu_pyc int not null,cpu_cores_each int not null)"""sql2 = """
create table memory(id int auto_increment primary key,capacity varchar(32),slot varchar(16),model varchar(4),speed varchar(32),manufacturer varchar(128),sn varchar(128),server_id int
)
"""
# cursor.execute(sql1)
# cursor.execute(sql2)
conn.commit( )
cursor.close( )
conn.close( )
插入单多数据
import pymysql#创建连接
conn = pymysql.connect(host='192.168.200.181',port=3306,user='root',passwd='123456',db='GuanDB')#获取游标对象
cursor = conn.cursor(pymysql.cursors.DictCursor)#实例
info = {"base_info": {"manufacturer": "VMware, Inc.","pod_name": "VMware Virtual Platform","sn": "VMware-56 4d 26 13 58 de 6f c1-41 34 b3 2a 30 dc fc bb","host_name": "master1","kernel": "3.10.0-957.el7.x86_64","os": "CentOS Linux release 7.6.1810 (Core)"},"cpu": {"cpu_name": "AMD Ryzen 7 5700U with Radeon Graphics","cpu_pyc": 1,"cpu_cores_each": 1},"memory": [{"capacity": "8192 MB","slot": "DIMM_B2","model": "DDR3","speed": "1333 MT/s","manufacturer": "00CE00B380CE","sn": "82B79F71"},{"capacity": "8192 MB","slot": "DIMM_B3","model": "DDR3","speed": "1333 MT/s","manufacturer": "00CE00B380CE","sn": "32CDDE81"},{"capacity": "No Module Installed","slot": "DIMM_B4","model": "DDR3","speed": "Unknown","manufacturer": "","sn": ""},{"capacity": "8192 MB","slot": "DIMM_B5","model": "DDR3","speed": "1333 MT/s","manufacturer": "00CE04B380CE","sn": "85966B82"},{"capacity": "8192 MB","slot": "DIMM_B6","model": "DDR3","speed": "1333 MT/s","manufacturer": "000000B380CE","sn": "00000000"}]
}# base_info = {**info["base_info"],**info["cpu"]}
# print(tuple(base_info))#
# sql1 = """create table base_info
# (id int auto_increment primary key,
# host_name varchar(64) not null,
# kernel varchar(64),
# os varchar(64),
# manufacturer varchar(64),
# pod_name varchar(64),
# sn varchar(64),
# cpu_name varchar(64),
# cpu_pyc int not null,
# cpu_cores_each int not null)"""
# sql2 = """
# create table memory(
# id int auto_increment primary key,
# capacity varchar(32),
# slot varchar(16),
# model varchar(4),
# speed varchar(32),
# manufacturer varchar(128),
# sn varchar(128),
# server_id int
# )
# """
# cursor.execute(sql1)
# cursor.execute(sql2)# keys = base_info.keys()
# values = base_info.values()
# print(keys)
# print(values)#处理数据mem_info = info["memory"]
mem_li = [ ]
server_id = 1
for mem in mem_info:mem["server_id"] = 1# print(tuple(mem.values()))v = tuple(mem.values())mem_li.append(v)mem = mem_info[0]
m_keys = mem.keys()#一次插入一条数据,并且使用 pymysql 定义的变量占位符
sql = """insert into memory({},{},{},{},{},{},{}
) values(%s,%s,%s,%s,%s,%s,%s);"""sql = sql.format(*m_keys)
# print(sql)
#插入多条语句的语法:
#cursor.executemany(many_mysql,[("v1","v2"),("v3","v4")])
cursor.executemany(sql, mem_li)# sql = sql.format(*keys)
# cursor.execute(sql, tuple(values))conn.commit( )
cursor.close( )
conn.close( )
插入单条数据
import pymysql#创建连接
conn = pymysql.connect(host='192.168.200.181',port=3306,user='root',passwd='123456',db='GuanDB')#获取游标对象
cursor = conn.cursor(pymysql.cursors.DictCursor)#实例
info = {"base_info": {"manufacturer": "VMware, Inc.","pod_name": "VMware Virtual Platform","sn": "VMware-56 4d 26 13 58 de 6f c1-41 34 b3 2a 30 dc fc bb","host_name": "master1","kernel": "3.10.0-957.el7.x86_64","os": "CentOS Linux release 7.6.1810 (Core)"},"cpu": {"cpu_name": "AMD Ryzen 7 5700U with Radeon Graphics","cpu_pyc": 1,"cpu_cores_each": 1},"memory": [{"capacity": "8192 MB","slot": "DIMM_B2","model": "DDR3","speed": "1333 MT/s","manufacturer": "00CE00B380CE","sn": "82B79F71"},{"capacity": "8192 MB","slot": "DIMM_B3","model": "DDR3","speed": "1333 MT/s","manufacturer": "00CE00B380CE","sn": "32CDDE81"},{"capacity": "No Module Installed","slot": "DIMM_B4","model": "DDR3","speed": "Unknown","manufacturer": "","sn": ""},{"capacity": "8192 MB","slot": "DIMM_B5","model": "DDR3","speed": "1333 MT/s","manufacturer": "00CE04B380CE","sn": "85966B82"},{"capacity": "8192 MB","slot": "DIMM_B6","model": "DDR3","speed": "1333 MT/s","manufacturer": "000000B380CE","sn": "00000000"}]
}base_info = {**info["base_info"],**info["cpu"]}
print(tuple(base_info))#
sql1 = """create table base_info(id int auto_increment primary key,host_name varchar(64) not null,kernel varchar(64),os varchar(64),manufacturer varchar(64),pod_name varchar(64),sn varchar(64),cpu_name varchar(64),cpu_pyc int not null,cpu_cores_each int not null)"""sql2 = """
create table memory(id int auto_increment primary key,capacity varchar(32),slot varchar(16),model varchar(4),speed varchar(32),manufacturer varchar(128),sn varchar(128),server_id int
)
"""
# cursor.execute(sql1)
# cursor.execute(sql2)keys = base_info.keys()
values = base_info.values()
# print(keys)
# print(values)#一次插入一条数据,并且使用 pymysql 定义的变量占位符
sql = """insert into base_info({},{},{},{},{},{},{},{},{}
) values(%s,%s,%s,%s,%s,%s,%s,%s,%s);"""sql = sql.format(*keys)
cursor.execute(sql, tuple(values))conn.commit( )
cursor.close( )
conn.close( )
查询数据
import pymysqlimport pymysql#创建连接
conn = pymysql.connect(host='192.168.200.181',port=3306,user='root',passwd='123456',db='GuanDB')#获取游标对象
cursor = conn.cursor(pymysql.cursors.DictCursor)# query_sql = "select id, host_name,os from base_info;"# row_nums = cursor.execute(query_sql)
# print(row_nums)query_mem = "select id,slot,model,sn from memory;"
row_nums = cursor.execute(query_mem)
print(row_nums)one_data = cursor.fetchone()
many_data = cursor.fetchmany(2)
all_data = cursor.fetchall()cursor.close()
conn.close()
print(one_data)
print("*"*20)
print(many_data)
print("*"*20)
print(all_data)
#存放的数据都是一个一个的键值对,数据之间互相没有任何依赖性
[root@master1 ~]# yum install epel-release
已加载插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile* base: mirrors.aliyun.com* extras: mirrors.aliyun.com* updates: mirrors.aliyun.com
base | 3.6 kB 00:00:00
code | 3.0 kB 00:00:00
epel | 4.7 kB 00:00:00
extras | 2.9 kB 00:00:00
percona-release-noarch | 1.5 kB 00:00:00
percona-release-x86_64 | 2.9 kB 00:00:00
prel-release-noarch | 1.5 kB 00:00:00
updates | 2.9 kB 00:00:00
zabbix | 2.9 kB 00:00:00
zabbix-frontend | 2.9 kB 00:00:00
zabbix-non-supported | 2.9 kB 00:00:00
(1/3): epel/x86_64/updateinfo | 1.0 MB 00:00:06
(2/3): code/primary_db | 2.8 MB 00:00:07
(3/3): epel/x86_64/primary_db | 7.0 MB 00:00:10
软件包 epel-release-7-14.noarch 已安装并且是最新版本
无须任何处理
[root@master1 ~]# yum install -y redis
已加载插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile* base: mirrors.aliyun.com* extras: mirrors.aliyun.com* updates: mirrors.aliyun.com
正在解决依赖关系
--> 正在检查事务
---> 软件包 redis.x86_64.0.3.2.12-2.el7 将被 安装
--> 正在处理依赖关系 libjemalloc.so.1()(64bit),它被软件包 redis-3.2.12-2.el7.x86_64 需要
--> 正在检查事务
---> 软件包 jemalloc.x86_64.0.3.6.0-1.el7 将被 安装
--> 解决依赖关系完成依赖关系解决=======================================================================================Package 架构 版本 源 大小
=======================================================================================
正在安装:redis x86_64 3.2.12-2.el7 epel 544 k
为依赖而安装:jemalloc x86_64 3.6.0-1.el7 epel 105 k事务概要
=======================================================================================
安装 1 软件包 (+1 依赖软件包)总下载量:648 k
安装大小:1.7 M
Downloading packages:
(1/2): jemalloc-3.6.0-1.el7.x86_64.rpm | 105 kB 00:00:05
(2/2): redis-3.2.12-2.el7.x86_64.rpm | 544 kB 00:00:06
---------------------------------------------------------------------------------------
总计 105 kB/s | 648 kB 00:06
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction正在安装 : jemalloc-3.6.0-1.el7.x86_64 1/2 正在安装 : redis-3.2.12-2.el7.x86_64 2/2 验证中 : redis-3.2.12-2.el7.x86_64 1/2 验证中 : jemalloc-3.6.0-1.el7.x86_64 2/2 已安装:redis.x86_64 0:3.2.12-2.el7 作为依赖被安装:jemalloc.x86_64 0:3.6.0-1.el7 完毕![root@master1 ~]# systemctl start redis
[root@master1 ~]# systemctl status redis
● redis.service - Redis persistent key-value databaseLoaded: loaded (/usr/lib/systemd/system/redis.service; disabled; vendor preset: disabled)Drop-In: /etc/systemd/system/redis.service.d└─limit.confActive: active (running) since 六 2023-01-07 12:55:40 CST; 6s agoMain PID: 19134 (redis-server)Tasks: 3CGroup: /system.slice/redis.service└─19134 /usr/bin/redis-server 127.0.0.1:63791月 07 12:55:40 master1 systemd[1]: Starting Redis persistent key-value database...
1月 07 12:55:40 master1 systemd[1]: Started Redis persistent key-value database.[root@master1 ~]# ss -ntal
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 127.0.0.1:6379 *:* [root@master1 ~]# redis-cli //连接redis客户端
127.0.0.1:6379> exit
[root@master1 ~]# redis-cli
127.0.0.1:6379> help setSET key value [EX seconds] [PX milliseconds] [NX|XX]summary: Set the string value of a keysince: 1.0.0group: string127.0.0.1:6379> set name shark EX 10
OK
127.0.0.1:6379> get name
"shark"
127.0.0.1:6379> ttl name
(integer) -2 //-2表示过期
127.0.0.1:6379> get name
(nil)
127.0.0.1:6379> set name shark EX 10
OK
127.0.0.1:6379> ttl name
(integer) 6
127.0.0.1:6379> ttl name
(integer) 0
127.0.0.1:6379> ttl name
(integer) -2
127.0.0.1:6379> set name shark
OK
127.0.0.1:6379> ttl name
(integer) -1 //-1表示永不过期
127.0.0.1:6379> exit
[root@master1 ~]# redis-cli set name shark
OK
[root@master1 ~]# echo $?
0
[root@master1 ~]# redis-cli del name
(integer) 1
[root@master1 ~]# echo $?
0
[root@master1 ~]# redis-cli get name
(nil)
redis 配置
[root@master1 ~]# vim /etc/redis.conf
#将redis.conf中的bind 127.0.0.1修改为0.0.0.0
requirepass guan //找到#requirepass 然后去掉注释 后跟密码
[root@master1 ~]# systemctl restart redis
[root@master1 ~]# ss -ntal
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:6379 *:* [root@master1 ~]# redis-cli --help
redis-cli 3.2.12Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]-h Server hostname (default: 127.0.0.1).-p Server port (default: 6379).-s Server socket (overrides hostname and port).-a Password to use when connecting to the server.-r Execute specified command N times.-i When -r is used, waits seconds per command.It is possible to specify sub-second times like -i 0.1.-n Database number.-x Read last argument from STDIN.-d Multi-bulk delimiter in for raw formatting (default: \n).-c Enable cluster mode (follow -ASK and -MOVED redirections).--raw Use raw formatting for replies (default when STDOUT isnot a tty).--no-raw Force formatted output even when STDOUT is not a tty.--csv Output in CSV format.--stat Print rolling stats about server: mem, clients, ...--latency Enter a special mode continuously sampling latency.--latency-history Like --latency but tracking latency changes over time.Default time interval is 15 sec. Change it using -i.--latency-dist Shows latency as a spectrum, requires xterm 256 colors.Default time interval is 1 sec. Change it using -i.--lru-test Simulate a cache workload with an 80-20 distribution.--slave Simulate a slave showing commands received from the master.--rdb Transfer an RDB dump from remote server to local file.--pipe Transfer raw Redis protocol from stdin to server.--pipe-timeout In --pipe mode, abort with error if after sending all data.no reply is received within seconds.Default timeout: 30. Use 0 to wait forever.--bigkeys Sample Redis keys looking for big keys.--scan List all keys using the SCAN command.--pattern Useful with --scan to specify a SCAN pattern.--intrinsic-latency Run a test to measure intrinsic system latency.The test will run for the specified amount of seconds.--eval Send an EVAL command using the Lua script at .--ldb Used with --eval enable the Redis Lua debugger.--ldb-sync-mode Like --ldb but uses the synchronous Lua debugger, inthis mode the server is blocked and script changes areare not rolled back from the server memory.--help Output this help and exit.--version Output version and exit.Examples:cat /etc/passwd | redis-cli -x set mypasswdredis-cli get mypasswdredis-cli -r 100 lpush mylist xredis-cli -r 100 -i 1 info | grep used_memory_human:redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3redis-cli --scan --pattern '*:12345*'(Note: when using --eval the comma separates KEYS[] from ARGV[] items)When no command is given, redis-cli starts in interactive mode.
Type "help" in interactive mode for information on available commands
and settings.[root@master1 ~]# redis-cli -h 192.168.200.181
192.168.200.181:6379> keys *
(empty list or set)
192.168.200.181:6379> set name shark
OK
192.168.200.181:6379> keys *
1) "name"
#NOSQL
#存放的数据都是一个一个的键值对,数据之间互相没有任何依赖性
#数据库 0-15 共16个
#pip3 install redis
import redis
rs = redis.StrictRedis(host="192.168.200.181",port=6379,db=0,decode_responses=True)# ret = rs.set("baidu","www.baidu.com")
# print(ret)#
# v = rs.get('baidu')
# print(v)# SET key value [EX seconds] [PX milliseconds] [NX|XX]
# rs.set("name","shark",ex=50)# print(rs.ttl("name"))
# print(rs.get('name'))# rs.setex('login',30,1)# print(rs.ttl("login"))
# print(rs.get("login"))#{"n1:": {"k1": "v2","k2": "v2"}}
user_info = {"name": "shark","age": 18}
rs.hmset("shark", user_info)
print( rs.hget("shark","age"))
"""
比如我们想存储用户的登录信息
一般用户的登录信息有以下几点:
用户名
"""
import hashlibhmd5 = hashlib.md5('hello'.encode())
md5 = hmd5.hexdigest()
print(md5)
#5d41402abc4b2a76b9719d911017c592import string,random# s = string.ascii_letters
# n = string.digits
# print(s,n)
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789
# base_str = f"{string.ascii_letters}"+f"{string.digits}"
base_str = f"{string.ascii_letters}{string.digits}"
# print(base_str)li = random.sample(base_str,6)
sessid = ''.join(li)
print(sessid)#用户名
#密码
#sessid#hash
#"shark",{"name":"shark","pwd":"","sessid":""}#处理是否过期
#"shark_sessid": "session id"import redis
rs = redis.StrictRedis(host="192.168.200.181",port=6379,db=0,decode_responses=True)hmd5 = hashlib.md5("guan123456".encode())
pwd = hmd5.hexdigest()
name = "shark"
rs.hmset(name,{"name": name,"pwd": pwd,"sessid": sessid})
rs.setex(f"{name}_{sessid}",20,sessid)
192.168.200.181:6379> keys *
1) "shark_CL125bsjoyfkiqOQFANg"
2) "baidu"
3) "shark"
192.168.200.181:6379> hget shark sessid
"CL125bsjoyfkiqOQFANg"
192.168.200.181:6379> ttl shark_CL125bsjoyfkiqOQFANg
(integer) -2
192.168.200.181:6379>
1.需求
编写一个脚本,把上面我们的用户信息存入到Redis中。实现一个简单的登录验证功能。
一般用户的每次请求,都会携带自己的会话(session)ID或者用户名密码的。
这里就分成两种情况:
1、用户没有携带 session ID 就说明是第一次登录,拿就必须是携带用户密码的。此时就走验证用户名密码的流程。
2、用户携带了 session ID 就走验证 session 是否过期的流程。
验证用户名密码流程:
1、提示用户输入用户名密码
2、不正确提示重新输入
3、正确,创建用户 session id 和有效时间,并保存到Redis中。显示“GO go”。
由于模拟的原因,需要打印出 session ID
验证 session ID 是否过期流程:
1、过期了,重新走用户登录流程
2、不过期,显示 “Go go!”
2.流程图:
代码
import hashlib,string,randomimport redis
rs = redis.StrictRedis(host="192.168.200.181",port=6379,db=0,decode_responses=True)#生成随机字符串
#return:返回 session id
def generate_sessid():base_str = f"{string.ascii_letters}{string.digits}"sessid = ''.join(random.sample(base_str,20))return sessid#传入一串字符,进行 MD5 计算
#Keyword arguments:
#pwd -- 字符串
#return:md5 加密值
def hash_pwd(pwd):password = hashlib.md5(pwd.encode('utf-8'))return password.hexdigest() #保存会话信息,并存入缓存
#Keyword arguments:
#name -- 用户名
#pwd -- 加密过的密码
#sessid -- 会话 id
#return:
def save_session(name,sessid='',ex=7200):rs.hset(name,"sessid",sessid)#保存会话有效时间rs.setex(f"{name}_{sessid}",ex,sessid) def check_session(name,sessid):if rs.ttl(f"{name}_{sessid}") in (-2,0):return Falseelse:return True#用户名登录,验证,验证成功返回用户名
#return 用户名 和 会话 ID
def login():while True:inp = input("输入用户名和密码,中间用空格隔开,比如:shark 123\n>>:").strip()user_pwd = inp.split()if len(user_pwd) == 2:name,source_pwd = user_pwdelse:print("格式错误,请重新输入")continue#获取加密密文pwd = hash_pwd(source_pwd)#获取缓存中加密密文user = rs.hget(name,"name")redis_pwd = rs.hget(name,"password")#验证用户名和密码if name == user and pwd == redis_pwd:return name,generate_sessid()else:print("用户名密码错误,请重新输入")continuedef main():while True:inp = input("输入 会话 ID\n格式:name sessionid>>:").strip()if len(inp.split()) == 2:name,sessid = inp.split()ex = check_session(name,sessid)else:print("格式错误name session")continueif ex:print("Go go")else:name,sessid = login()save_session(name,sessid,ex=10)print(name,sessid)print("Go go")if __name__ == "__main__":main()