[py]flask实现用户cmdb
人最难做到的就是跟自己学习, 总是学习别人的, 沉淀, 过一段时间忘了刚学到的, 在向别人学习, 而非看看自己的沉淀, 殊不知, 世界上最亲近,最默契的人是自己.
用户cmdb功能概述
之前学flask做了个cmdb的东西.当初作为学习的一个思路.
久而久之就忘掉了, 整理一下放上来. 可见时间是把杀猪刀, 稍不留神就让你背负着忘掉的东西,回顾它, 然后反过来浪费时间. 这就是搞这些的烦恼.
根据后端存储可分为3个节点, 这点和那个txl项目: python写一个通讯录step by step V3.0有点类似,不过那个没flask, 这个是简化前端版.
- 支持登录
- crud数据库来实现用户的增删改查
功能如下
- 打开首页让登录,输入正确用户名密码后, 出现欢迎界面
- 界面可以增加用户
- 可以删除用户
- 可以更新用户密码
- 可以退出
第一阶段, 后端用文件存储
fileutils.py
file_dict = {}
# file -> dict
def read_file():
with open("users.txt") as f:
for line in f.readlines():
user, pwd = line.split()
file_dict[user] = pwd
return file_dict
# dict -> file
def write_file():
tmp = []
for user, pwd in file_dict.items():
tmp.append("%s %s" % (user, pwd))
with open("users.txt", "w") as f:
f.write("\n".join(tmp))
因为用户名密码是要对应起来, 因此这里考虑用了dict. 所以解决dict到文件之间的存储. 注意: 只有字符串才能写入文件.
app.py
#!/usr/bin/env python
# coding=utf-8
from flask import Flask, render_template, request, redirect, flash, session, url_for
import fileutils
app = Flask(__name__)
app.secret_key = "1992"
@app.route("/head")
def get_header():
user_agent = request.headers.get("User-Agent")
Cookie = request.headers.get("Cookie")
return "{{ session.username }}------- %s" % Cookie
@app.route("/")
def login():
if "username" in session:
return redirect("/list")
else:
return render_template("login.html")
@app.route("/loginaction")
def login_action():
user = request.args.get("user")
pwd = request.args.get("pwd")
fileutils.read_file()
if fileutils.file_dict.has_key(user) and pwd == fileutils.file_dict[user]:
session['username'] = user
session['password'] = pwd
return redirect("/list")
else:
flash("user or pwd is error")
return render_template("login.html")
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect("/")
@app.route("/list")
def show_user():
print session
if "username" in session:
user_list = fileutils.read_file()
return render_template("list.html", user_list=user_list.items())
else:
return redirect("/")
@app.route("/adduser")
def add_user():
user = request.args.get("user")
pwd = request.args.get("pwd")
fileutils.read_file()
if user in fileutils.file_dict:
return redirect("/list")
else:
fileutils.file_dict[user] = pwd
fileutils.write_file()
return redirect("/list")
@app.route("/del")
def del_user():
user = request.args.get("user")
fileutils.read_file()
fileutils.file_dict.pop(user)
fileutils.write_file()
return redirect("/list")
@app.route("/update")
def update_user():
user = request.args.get("user")
fileutils.read_file()
pwd = fileutils.file_dict[user]
return render_template("update.html", user=user, pwd=pwd)
@app.route("/updateaction")
def update_action():
user = request.args.get("user")
pwd = request.args.get("pwd")
print user, pwd
fileutils.read_file()
print fileutils.file_dict
fileutils.file_dict[user] = pwd
print fileutils.file_dict
fileutils.write_file()
return redirect("/list")
app.run(debug=True)
第二阶段, 后端用pickcle模块
pickle可以直接将dict处理后写入文件, 也可以直接从文件读成dict, 写入方便, 读出来也不需要做额外处理就可以用了.
第三阶段, 后端用pickcle模块
后端使用mysql
create database bbs;
use bbs;
create table users(user varchar(40), pwd varchar(80));
insert into users values('admin','123456');
app.py
#!/usr/bin/env python
# coding=utf-8
from flask import Flask, render_template, request, redirect, flash, session,url_for
import fileutils
import pymysql as mysql
con = mysql.connect(host='127.0.0.1',user='root',passwd='',db='bbs')
cur = con.cursor()
sql = "select * from users"
cur.execute(sql)
con.autocommit(True)
print cur.fetchall()
app = Flask(__name__)
app.secret_key = "1992"
@app.route("/")
def login():
if "username" in session:
return redirect("/list")
else:
return render_template("login.html")
@app.route("/loginaction")
def login_action():
user = request.args.get("user")
pwd = request.args.get("pwd")
cur.execute("select * from users")
for line in cur.fetchall():
suser,spwd = line
print suser,spwd
if suser == user and spwd == pwd:
session['username']=user
return redirect("/list")
flash("user or pwd is error")
return render_template("login.html")
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect("/")
@app.route("/list")
def show_user():
cur.execute("select * from users")
if "username" in session:
user_list = fileutils.read_file()
return render_template("list.html", user_list=cur.fetchall())
else:
return redirect("/")
@app.route("/adduser")
def add_user():
user = request.args.get("user")
pwd = request.args.get("pwd")
if user and pwd:
cur.execute("select * from users")
for line in cur.fetchall():
suser,spwd = line
if suser == user:
return redirect("/list")
else:
cur.execute("insert into users values('%s','%s')"%(user,pwd))
return redirect("/list")
else:
return redirect("/list")
@app.route("/del")
def del_user():
user = request.args.get("user")
cur.execute("delete from users where user ='%s';"% user)
return redirect("/list")
@app.route("/update")
def update_user():
user = request.args.get("user")
cur.execute("select pwd from users where user='%s'"%user)
pwd = cur.fetchall()[0][0]
return render_template("update.html", user=user, pwd=pwd)
@app.route("/updateaction")
def update_action():
user = request.args.get("user")
pwd = request.args.get("pwd")
print user, pwd
cur.execute("update users set pwd='%s' where user = '%s'" % (pwd,user))
return redirect("/list")
app.run(debug=True)
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form action="/loginaction">
user: <input type="text" name="user">
pwd: <input type="text" name="pwd">
<input type="submit"> <br>
{{ get_flashed_messages()[0] }}<br>
</form>
</body>
</html>
list.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>list</title>
</head>
<body>
<h2>welcome <span style="color: pink">{{ session.username }}</span>!</h2>
<h1><a href="/logout">logout</a></h1>
<form action="/adduser">
user: <input type="text" name="user">
pwd: <input type="text" name="pwd">
<input type="submit" value="添加用户">
</form>
<hr>
<table border="1">
<tr>
<th>user</th>
<th>pwd</th>
<th>action</th>
</tr>
{% for user in user_list %}
<tr>
<td>{{ user[0] }}</td>
<td>{{ user[1] }}</td>
<td>
<a href="/update?user={{ user[0] }}">update</a>
<a href="/del?user={{ user[0] }}">del</a>
</td>
</tr>
{% endfor %}
</table>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>update user </title>
</head>
<body>
<form action="/updateaction">
user: {{ user }} <input type="text" value="{{ user }}" name="user" hidden="hidden"><br>
pwd: <input type="text" value="{{ pwd }}" name="pwd">
<input type="submit">
</form>
</body>
</html>