[Py]flask implements the user CMDB

Source: Internet
Author: User

People most difficult to do is to learn from their own, always learn others, precipitation, after a period of time forget just learned, in the study to others, rather than look at their own precipitation, as everyone knows, the world's closest, the most tacit understanding of the person is their own.

Overview of User CMDB functions

Before learning flask did a CMDB thing. As a learning idea.

Over time, forget, tidy up a delegation up. The visible time is to kill the pig knife, slightly inattentive let you carry the forgotten things, review it, and then in turn waste time. This is the trouble of doing this.

According to the back-end storage can be divided into 3 nodes, this and that TXL project: Python write an Address book step by step V3.0 a bit similar, but that is not flask, this is a simplified front-end version.

    • Support Login
    • CRUD database to enable users to delete and change the search

functions as follows

    • Open Home Let login, enter the correct user name password, the Welcome screen appears
    • Interface can increase the user
    • You can delete users
    • Can update user password
    • Can exit
First stage, back end with file storage fileutils.py
file_dict = {}# file -> dictdef 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 -> filedef 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))

Because the user name password is to correspond, so here consider using Dict. So fix the storage between dict to the file. Note: Only strings can be written to the file.

app.py
#!/usr/bin/env python# coding=utf-8from flask Import flask, render_template, request, redirect, Flash, session, Url_forim Port Fileutilsapp = Flask (__name__) App.secret_key = "1992" @app. Route ("/head") def get_header (): User_agent = Request.hea Ders.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_templat E ("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]: Sessi on[' 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 ("/ad Duser ") 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 Fileut Ils.write_file () return redirect ("/list") @app. Route ("/del") def del_user (): User = Request.args.get ("user") fi Leutils.read_file () fileutils.file_dict.pop (user) Fileutils.write_file () return redirect ("/list") @app. Route ("/upd    Ate ") 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)
Second stage, rear end with pickcle module

Pickle can be processed directly after the dict to write to the file, or directly from the file read into Dict, write convenient, read out also do not need to do extra processing can be used.

Third stage, back end with pickcle module backend using 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-8from flask Import flask, render_template, request, redirect, Flash, Session,url_ Forimport Fileutilsimport pymysql as Mysqlcon = 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 Retu RN Redirect ("/list") Flash ("User or PWD is error") Return Render_template ("login.html") @app. Route ('/logout ') def logo UT (): 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 ("Inse RT 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.execu Te ("Select pwd from Users"Where user= '%s '%user) pwd = Cur.fetchall () [0][0] return render_template ("update.html", User=user, Pwd=pwd) @app. Rout E ("/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=tr Ue
Login.html
<!DOCTYPE html>
List.html
<!doctype html>
Update.html
<!DOCTYPE html>
Source

[Py]flask implements the user CMDB

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.