【Python入门指北】操作数据库

news2024/11/18 21:41:36



在这里插入图片描述


一、

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 pymysql
  Downloading 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]$ 

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 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: 1
     host_name: master1
        kernel: 3.10.0-957.el7.x86_64
            os: CentOS Linux release 7.6.1810 (Core)
  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
      cpu_name: AMD Ryzen 7 5700U with Radeon Graphics
       cpu_pyc: 1
cpu_cores_each: 1
1 row in set (0.16 sec)


2.练手案例

操作数据库

#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 pymysql

import 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)

二、redis数据库

#存放的数据都是一个一个的键值对,数据之间互相没有任何依赖性
[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 database
   Loaded: loaded (/usr/lib/systemd/system/redis.service; disabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/redis.service.d
           └─limit.conf
   Active: active (running) since 六 2023-01-07 12:55:40 CST; 6s ago
 Main PID: 19134 (redis-server)
    Tasks: 3
   CGroup: /system.slice/redis.service
           └─19134 /usr/bin/redis-server 127.0.0.1:6379

1月 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 set

  SET key value [EX seconds] [PX milliseconds] [NX|XX]
  summary: Set the string value of a key
  since: 1.0.0
  group: string

127.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.12

Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]
  -h <hostname>      Server hostname (default: 127.0.0.1).
  -p <port>          Server port (default: 6379).
  -s <socket>        Server socket (overrides hostname and port).
  -a <password>      Password to use when connecting to the server.
  -r <repeat>        Execute specified command N times.
  -i <interval>      When -r is used, waits <interval> seconds per command.
                     It is possible to specify sub-second times like -i 0.1.
  -n <db>            Database number.
  -x                 Read last argument from STDIN.
  -d <delimiter>     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 is
                     not 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 <keys>  Simulate a cache workload with an 80-20 distribution.
  --slave            Simulate a slave showing commands received from the master.
  --rdb <filename>   Transfer an RDB dump from remote server to local file.
  --pipe             Transfer raw Redis protocol from stdin to server.
  --pipe-timeout <n> In --pipe mode, abort with error if after sending all data.
                     no reply is received within <n> 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 <pat>    Useful with --scan to specify a SCAN pattern.
  --intrinsic-latency <sec> Run a test to measure intrinsic system latency.
                     The test will run for the specified amount of seconds.
  --eval <file>      Send an EVAL command using the Lua script at <file>.
  --ldb              Used with --eval enable the Redis Lua debugger.
  --ldb-sync-mode    Like --ldb but uses the synchronous Lua debugger, in
                     this mode the server is blocked and script changes are
                     are 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 mypasswd
  redis-cli get mypasswd
  redis-cli -r 100 lpush mylist x
  redis-cli -r 100 -i 1 info | grep used_memory_human:
  redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3
  redis-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 hashlib

hmd5 = hashlib.md5('hello'.encode())
md5 = hmd5.hexdigest()
print(md5)
#5d41402abc4b2a76b9719d911017c592

import 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,random

import 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 False
    else:
        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_pwd
        else:
            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("用户名密码错误,请重新输入")
            continue

def 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")
            continue
        if ex:
            print("Go go")
        else:
            name,sessid = login()
            save_session(name,sessid,ex=10)
            print(name,sessid)
            print("Go go")


if __name__ == "__main__":
    main()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/148105.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Apache IoTDB PMC 乔嘉林荣获 2022 杰出开源贡献者|开源技术强大,开源文化活跃...

2022 年 12 月 29 日至 30 日&#xff0c;2022 木兰峰会正式召开&#xff0c;会上发布了中国开源云联盟 2022 年度评选名单。本次评审专家包括数十位开源领域专家、社区领袖、科研院所专家&#xff0c;共评选出杰出开源贡献者 3 人。其中&#xff0c;清华大学助理研究员、博士后…

【QT开发笔记-基础篇】| 第五章 绘图QPainter | 5.16 完结和后续:《Qt开发专题-自定义控件》

本节对应的视频讲解&#xff1a;B_站_视_频 https://www.bilibili.com/video/BV1NW4y1K7eL 1. 为什么需要自定义控件 绘图最大的一个应用场景就是自定义控件&#xff0c;Qt 本身提供的一些控件是有限的&#xff0c;并且它提供的一些控件很可能不满足我们的需要 这种情况下&a…

pygame - 图片移动优化

目录 一、优化过程分析 1、pygame - 图片移动中图片移动模式 2、优化过程 二、代码段 1、附注释 2、无注释 三、效果展示 一、优化过程分析 1、pygame - 图片移动中图片移动模式 按一次方向键&#xff0c;图片移动一小步&#xff1b; 若需要一直往某个方向移动&…

【LaTex】LaTex 极简安装教程

文章目录Latex 安装教程1. 下载texlive.iso2. 点击装载3. 运行 install-tl-windows.bat 进行安装4. 验证是否安装成功5. 安装开发工具Latex 安装教程 1. 下载texlive.iso https://mirrors.tuna.tsinghua.edu.cn/ctan/systems/texlive/Images/ 2. 点击装载 下载完成后&#x…

【博客580】内核如何决定数据包的源ip

内核如何决定数据包的源ip 1、Traversing of packets Receive&#xff1a; 某个interface收到数据包 -> PREROUTING (manage, nat) -> routing -> 是发送给本机的数据包? -> INPUT (manage, filter) -> app 不是 -> FORWARD (manage, filter) -> POST…

《Dubbo源码剖析与实战》学习笔记 Day1

流量控制 为了系统的健壮性和稳定性考虑&#xff0c;通常要对访问进行有效的控制&#xff0c;防止流量突然暴增&#xff0c;引发一系列服务雪崩效应。 1.单机限流 大概逻辑就是把每个请求当作一个小朋友&#xff0c;把最细粒度Dubbo服务中的方法当作游乐场&#xff0c;每个方…

Go第 12 章 :1-家庭收支记账软件项目

Go第 12 章 &#xff1a;1-家庭收支记账软件项目 12.1 项目开发流程说明 12.2 项目需求说明 模拟实现基于文本界面的《家庭记账软件》该软件能够记录家庭的收入、支出&#xff0c;并能够打印收支明细表 12.3 项目的界面 12.4 项目代码实现 12.4.1 实现基本功能(先使用面向过…

Windows 10/11 中的快速录屏的 5 种方法

在当今世界&#xff0c;出于各种原因&#xff0c;人们更喜欢录制他们的 PC 屏幕。录制计算机屏幕的功能对于在线学习、录制在线会议的特定亮点或帮助您制作抖音视频至关重要。不管是什么原因&#xff0c;屏幕录制让许多人的生活更轻松。截屏是有效的&#xff0c;但录制有助于您…

聚簇索引,二级索引,MRR,联合索引和自适应哈希索引-详细总结

目录 聚簇索引&#xff0c;二级索引&#xff0c;MRR&#xff0c;联合索引和自适应哈希索引-详细总结 聚簇索引 定义&#xff1a; 问题&#xff1a;为什么不采用B树作为MySQL表数据底层的存储数据结构&#xff1f; 作图&#xff1a; 问题&#xff1a;如果数据库表没有设置…

base64和base64url编解码

文章目录[toc]前言1. Base64编码原理2. 加解密图示3. base64编码Code3. base64url编码Code前言 一个字节可以表示256种数值&#xff0c;但是由于一些字节在网络中有特殊的含义。所以当传输字节内容时就不能传输这些具有控制功能的字符。具体的做法就是将这些字符进行转码。   …

A. Sasha and a Bit of Relax(异或的性质 + 前缀和的性质)

Problem - 1109A - Codeforces Sasha喜欢编程。有一次&#xff0c;在一场很长时间的比赛中&#xff0c;萨沙觉得他有点累了&#xff0c;需要放松一下。他照做了。但由于萨沙不是一个普通人&#xff0c;他更喜欢不同寻常地放松。在闲暇时间&#xff0c;萨沙喜欢解决未解决的问题…

JAVA本科毕业设计家庭财务管理系统源码+数据库,基于springboot + mybatis + mysql5.7

家庭财务管理系统 下载地址&#xff1a;JAVA本科毕业设计家庭财务管理系统源码数据库 介绍 1.cwgl 财务管理系统 提供sql 后面系统在另一个版本修改 此版本功能简单 可能有很多没有完善的地方 仅供参考 2.ffms&#xff08;Family Financial Management System&#xff09; …

linux 编译 c++ 静态库(包含类的实例化)给 c 程序调用

文章目录使用场景代码示例编译运行示例程序参考文章使用场景 c 是面向对象的编程语言&#xff0c;比较方便实现某些第三方库&#xff0c;比如翻译其他面向对象语言的代码&#xff0c;比 c 语言要方便的多。而 c 语言跟 c 很亲和&#xff0c;可以用 c 来实现&#xff0c;编译成…

SAP灵活工作流客制化值帮助

目录 1. 创建值帮助CDS视图 2. 添加值帮助CDS视图对应的ODATA服务 3. 在灵活工作流中设置搜索帮助 4. 效果展示 1. 创建值帮助CDS视图 创建值帮助数据源视图 创建值帮助视图 Dummy表结构如下 2. 注册值帮助CDS视图对应的ODATA服务 事务代码 /N/IWFND/MAINT_SERVICE 选择添加…

【mysql】-【innodb数据存储结构】

文章目录数据库的存储结构&#xff1a;页磁盘与内存交互基本单位&#xff1a;页页结构概述页的大小页的上层结构页的内部结构数据库的存储结构&#xff1a;页 一、索引结构给我们提供了高效的索索隐方式&#xff0c;不过索引信息以及数据记录都是保存在文件上的&#xff0c;确…

MongoDB数据库 | 三分钟学会MongoDB索引,快来看看与MySQL索引有何不同?

目录一、创建索引1、创建索引2、通过索引查询二、复合索引三、索引内嵌文档四、索引基数五、explain六、为何不使用索引七、固定集合一、创建索引 1、创建索引 > db.student.createIndex({"name":1}) {"numIndexesBefore" : 1,"numIndexesAfter&…

【unity3D】Audio Source组件

&#x1f497; 未来的游戏开发程序媛&#xff0c;现在的努力学习菜鸡 &#x1f4a6;本专栏是我关于游戏开发的学习笔记 &#x1f236;本篇是unity的Audio Source组件 Audio Source组件常用的属性解释&#xff1a; AudioClip&#xff1a;在这里指定需要播放的音频片段。Output …

Java面试题每日10问(3)

Core Java - OOPs Concepts: static keyword Interview Questions 1.What if the static modifier is removed from the signature of the main method? Program compiles. However, at runtime, It throws an error “NoSuchMethodError.” 2. What is the difference betw…

2023年会发生什么,一点都不会神秘

文/明道云创始人任向晖我很少写市场预测文章&#xff0c;是因为影响经济活动的要素实在太多了。做任何预测的时候&#xff0c;想明白了一二&#xff0c;但没有预计到三&#xff0c;结果可能就完全不一样。过去三年的疫情就是一个典型的例子。但是这个冬天的预测显得格外重要一些…

Redis+注解实现API接口防刷限流

前言 在开发分布式高并发系统时有三把利器来保护系统&#xff1a;缓存、降级、限流。 缓存: 缓存的目的是提升系统访问速度和增大系统处理容量&#xff1b;降级&#xff1a;降级是当服务出现问题或者影响到核心流程时&#xff0c;需要暂时屏蔽掉&#xff0c;待高峰或者问题解…