一、pickle模块
python的pickle模块实现了基本的数据序列和反序列化。通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储;通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。
1、pickle模块有很多方法,这里主要讲的是dump和load方法:
1.1、pickle.dump():将字典格式的数据以二进制格式保存到文件中
>>> import pickle # 导入pickle模块>>> msg = {'name':'Alice','age':12}
>>> fo = open('test.txt','wb') # 新建一个二进制文件
>>> pickle.dump(msg,fo) # 写入数据
>>> fo.close()
[root@test python]# tail test.txt # 查看写入的数据(dp0S'age'p1I12sS'name'p2S'Alice'p3
1.2、pickle.load():从保存好的数据的文件读取数据
>>> import pickle>>> content = {} # 新建一个字典>>> fo = open('test.txt') >>> content = pickle.load(fo) # 读取数据到字典>>> fo.close()>>> print content{'age': 12, 'name': 'Alice'}
2、通过pickle模块实现增删改查
#!/usr/bin/env python#-*- coding: utf-8 -*-import pickledef create(): # 将字典格式数据以二进制格式写入文件 users = {'pc': '12345', 'wd': '123', 'kkk': '123'} fo = open('test.txt', 'wb') pickle.dump(users,fo) fo.close()def select(): # 从文件获取数据并显示 content = {} f = open('test.txt') content = pickle.load(f) f.close print content for k,v in content1.items(): print ("user info----%s--> %s" %(k,v))def modify(): content = {} f = open('test.txt') content = pickle.load(f) # 获取数据 print content f.close content['pc'] ='467657' # 修改数据 f=open('test.txt','wb') pickle.dump(content,f) # 重新写入文件 f.close()def delete(): content = {} f = open('test.txt') content = pickle.load(f) # 获取数据 f.close content.pop('kkk') # 删除数据 f = open('test.txt','wb') pickle.dump(content,f) # 将处理后的数据重新写入文件 f.close() print contentif __name__ == '__main__': create() select() modify() delete()
3、通过pickle模块,实现一个基于文件存储的web端展示列表,实现用户注册、登录、修改密码,删除用户的功能
[root@test python]# tree test1test1├── templates│ ├── index.html│ ├── user.html│ └── user_modify.html├── user_file2.py├── user.txt└── user_web.py
前端代码
1、index.html
<form action='/login' method='post'><div>用户登录</div>name:<input type='text' name='name'><br>password:<input type='password' name='password'><div><button type='submit'>login</button></div></form><br><form action='/register' method='post'><div>用户注册</div>name:<input type='text' name='name'><br>password:<input type='password' name='password'><br>password again:<input type='password' name='repassword'><div><button type='submit'>register</button></div></form><form action='/showuser'><div>用户管理</div><div><button type='submit'>manage</button></div></form>
2、user.html
<table border='1'> <thead> <tr> <td>User</td> <td>Password</td> <td>Delete</td> <td>Modify</td> </tr> </thead> <tbody> {%for user in users%} {%if user and users[user]%}<tr> <td>{{user}}</td> <td>{{users[user]}}</td> <td><a href='/deluser?username={{user}}'>delete</a></td> <td><a href='/modify'>modify</a></td></tr> {%endif%} {%endfor%} </tbody></table></div><a href='/'>返回首页</a><div>
3、user_modify.html
用户修改<form action='/edit' method='post'>name:<input type='text' name='username'><br>old password:<input type='password' name='old_password'><br>new password:<input type='password' name='new_password'> <br><button type='submit'>修改用户</button></form>
逻辑端
1、user_file2.py
#!/usr/bin/env python#-*- coding: utf-8 -*-import pickledef showuser(): # 从文件获取数据(字典格式) content = {} f = open('user.txt') content = pickle.load(f) f.close return contentdef register(name,pwd): # 注册函数,通过在字典中添加用户名,密码实现 content = {} fo = open('user.txt') content = pickle.load(fo) fo.close() content[name] = pwd fo = open('user.txt','wb') pickle.dump(content,fo) fo.close()def edit(name,pwd,repwd): # 修改密码 content = {} f = open('user.txt') content = pickle.load(f) print (content) f.close for n,p in content.items(): if n == name and p == pwd and pwd != repwd: content[name] = repwd f = open('user.txt','wb') pickle.dump(content,f) f.close()def deluser(name): # 删除用户 content = {} f = open('user.txt') content = pickle.load(f) f.close if name in content.keys(): content.pop(name) f = open('user.txt','wb') pickle.dump(content,f) f.close()
2、user_web.py
from flask import Flask,request,render_template,redirectimport user_file2#new appapp = Flask(__name__)@app.route('/')def index(): return render_template('index.html')@app.route('/register',methods=['POST']) # 注册路由def register(): name = request.form.get('name') pwd = request.form.get('password') repwd = request.form.get('repassword') if name != '' and pwd != '' and pwd==repwd and name not in user_file2.showuser().keys(): # 条件判断 user_file2.register(name,pwd) return redirect('/showuser') else:return 'someting error'@app.route('/showuser') # 表格形式,显示数据端数据def showuser(): users = user_file2.showuser() return render_template('user.html', users = users)@app.route('/deluser') # 删除用户def deluser(): username = request.args.get('username') user_file2.deluser(username) return redirect('/showuser')@app.route('/login',methods=['POST']) # 登录功能def login(): name = request.form.get('name') pwd = request.form.get('password') user_dict = user_file2.showuser() if name not in user_dict.keys(): return "wrong name" elif pwd != user_dict[name]: return "wrong password" else: return "login success"@app.route('/modify',methods=['GET','POST']) # 修改密码def modify(): if request.method=='POST': name = request.form.get('username') old_pwd = request.form.get('old_password') new_pwd = request.form.get('new_password') return render_template('user_modify.html',username=name,old_password=old_pwd,new_password=new_pwd) else: return render_template('user_modify.html') @app.route('/edit',methods=['POST']) # 在数据端修改密码def edit(): name = request.form.get('username') old_pwd = request.form.get('old_password') new_pwd = request.form.get('new_password') if name != '' and old_pwd != '' and new_pwd != '' and old_pwd != new_pwd and name in user_file2.showuser().keys() and old_pwd==user_file2.showuser()[name]: user_file2.edit(name,old_pwd,new_pwd) return redirect('/showuser') else:return 'something error' if __name__ == '__main__': app.run(host='0.0.0.0', port=8888,debug=True)
数据端
[root@test test1]# cat user.txt (dp0Vpcp1V123456p2sV123p3V1234p4sS'yaoliang'p5V123456p6
二、数据库模块MySQL
1、安装并启动数据库(CentOS 7 以上使用的是mariadb)
[root@test python]# yum install -y mariadb-server mariadb # 安装[root@test python]# systemctl start mariadb.service # 启动[root@test python]# mysql_secure_installation # 初始化
2、安装python的数据库模块
[root@test python]# yum install -y python-pip[root@test python]# pip install MySQL-python
3、测试安装是否成功
>>> import MySQLdb as mysql>>> # 无返回,说明安装成功
4、创建数据库和表
MariaDB [(none)]> create database reboot;Query OK, 1 row affected (0.00 sec)MariaDB [(none)]> use reboot;Database changedMariaDB [reboot]> create table users( -> id int AUTO_INCREMENT primary key -> ,name varchar(20) not null -> ,name_cn varchar(50) not null -> ,password varchar(50) not null -> ,email varchar(50) -> ,mobile varchar(11) -> ,role varchar(10) not null -> ,status varchar(10) -> ,create_time timestamp default current_timestamp -> ,last_time timestamp default current_timestamp -> ,unique key name (name) ) engine=innodb;Query OK, 0 rows affected (0.01 sec)MariaDB [reboot]> show tables;+------------------+| Tables_in_reboot |+------------------+| users |+------------------+1 row in set (0.00 sec)MariaDB [reboot]> desc users;+-------------+-------------+------+-----+-------------------+----------------+| Field | Type | Null | Key | Default | Extra |+-------------+-------------+------+-----+-------------------+----------------+| id | int(11) | NO | PRI | NULL | auto_increment || name | varchar(20) | NO | UNI | NULL | || name_cn | varchar(50) | NO | | NULL | || password | varchar(50) | NO | | NULL | || email | varchar(50) | YES | | NULL | || mobile | varchar(11) | YES | | NULL | || role | varchar(10) | NO | | NULL | || status | varchar(10) | YES | | NULL | || create_time | timestamp | NO | | CURRENT_TIMESTAMP | || last_time | timestamp | NO | | CURRENT_TIMESTAMP | |+-------------+-------------+------+-----+-------------------+----------------+10 rows in set (0.00 sec)
5、数据库执行流程
# 导入数据库模块>>> import MySQLdb as mysql# 连接数据库>>> conn = mysql.connect(db='reboot',user='root',passwd='123456',host='localhost')# 创建游标>>> cur = conn.cursor()# 编写sql语句>>> sql = "insert into users(name,name_cn,password,mobile,role,status) values('test','test','123456','12345678901',1,0)"# 执行sql语句>>> cur.execute(sql)1L# 提交结果>>> conn.commit()# 关闭游标和数据库连接>>> cur.close()>>> conn.close()
6、查看数据库是否导入成功
1、连接数据库查看
MariaDB [(none)]> select * from reboot.users;+----+------+----------------+----------+-------+-------------+------+--------+---------------------+---------------------+| id | name | name_cn | password | email | mobile | role | status | create_time | last_time |+----+------+----------------+----------+-------+-------------+------+--------+---------------------+---------------------+| 1 | test | test | 123456 | NULL | 12345678901 | 1 | 0 | 2016-08-08 15:57:28 | 2016-08-08 15:57:28 |+----+------+----------------+----------+-------+-------------+------+--------+---------------------+---------------------+1 row in set (0.00 sec)
2、通过fetchall()和fetchone()查看
>>> import MySQLdb as mysql>>> conn = mysql.connect(db='reboot',user='root',passwd='123456',host='localhost')>>> cur = conn.cursor()>>> cur.execute('select * from users') # 执行select操作>>> cur.fetchall() # fetchall()查找所有数据((1L, 'test', 'test', '123456', None, '12345678901', '1', 0, datetime.datetime(2016, 8, 8, 15, 57, 28), datetime.datetime(2016, 8, 8, 15, 57, 28)), (3L, 'test1', 'test1', '123456', None, '12345678901', '1', 0, datetime.datetime(2016, 8, 8, 16, 5, 55), datetime.datetime(2016, 8, 8, 16, 5, 55)))>>> cur.execute('select * from users')2L>>> cur.fetchone() # fetchone()查找数据中第一个(1L, 'test', 'test', '123456', None, '12345678901', '1', 0, datetime.datetime(2016, 8, 8, 15, 57, 28), datetime.datetime(2016, 8, 8, 15, 57, 28))>>> cur.fetchone() # 第二次则查找第二个(3L, 'test1', 'test1', '123456', None, '12345678901', '1', 0, datetime.datetime(2016, 8, 8, 16, 5, 55), datetime.datetime(2016, 8, 8, 16, 5, 55))
7、结合数据库,实现数据的查询
逻辑端代码
#!/usr/bin/python#coding:utf-8from flask import Flask,render_templateimport MySQLdb as mysqlapp = Flask(__name__)conn = mysql.connect(db='reboot',user='root',passwd='123456',host='localhost')cur = conn.cursor()@app.route('/userlist')def userlist(): sql = "select name,name_cn,email,mobile from users" cur.execute(sql) result = cur.fetchall() # 获取所有数据 return render_template('userlist.html', users = result)if __name__=='__main__': app.run(host='0.0.0.0',port=8888,debug=True)
前端userlist.html代码
<table border='1'> <thead> <tr> <td>用户名</td> <td>中文名</td> <td>邮箱</td> <td>手机号</td> <td>操作</td> </tr> </thead> <tbody> {% if users %} {% for user in users %} <tr> <td>{{user[0]}}</td> <td>{{user[1]}}</td> <td>{{user[2]}}</td> <td>{{user[3]}}</td> <td> <input type='button' name='updata' value='更新''> <input type='button' name='del' value='删除''></td> </tr> {%endfor%} {%endif%} </tbody></table>
运行结果
8、对7中的逻辑端代码进行优化
逻辑端
#!/usr/bin/python#coding:utf-8from flask import Flask,render_templateimport MySQLdb as mysqlapp = Flask(__name__)conn = mysql.connect(db='reboot',user='root',passwd='123456',host='localhost')cur = conn.cursor()@app.route('/userlist')def userlist(): users = [] fields = ['name','name_cn','email','mobile'] sql = "select %s from users"%','.join(fields) cur.execute(sql) result = cur.fetchall() for row in result: user = {} for i,k in enumerate(fields): user[k] = row[i] users.append(user) return render_template('userlist.html', users = result)if __name__=='__main__': app.run(host='0.0.0.0',port=8888,debug=True)
前端代码
<table border='1'> <thead> <tr> <td>用户名</td> <td>中文名</td> <td>邮箱</td> <td>手机号</td> <td>操作</td> </tr> </thead> <tbody> {% if users %} {% for user in users %} <tr> <td>{{user.name}}</td> <td>{{user.name_cn}}</td> <td>{{user.email}}</td> <td>{{user.mobile}}</td> <td> <input type='button' name='updata' value='更新''> <input type='button' name='del' value='删除''></td> </tr> {%endfor%} {%endif%} </tbody></table>