[py]flask實現用戶cmdb
阿新 • • 發佈:2018-01-26
htm alt 增刪改查 cti password 方便 step val 浪費時間
人最難做到的就是跟自己學習, 總是學習別人的, 沈澱, 過一段時間忘了剛學到的, 在向別人學習, 而非看看自己的沈澱, 殊不知, 世界上最親近,最默契的人是自己.
用戶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>
源碼
[py]flask實現用戶cmdb