Python Flask+Mysql练习题
#!/usr/bin/python
from flask import Flask,render_template,request,redirect,session
import MySQLdb as mysql
con = mysql.connect(host='59.110.**.**',user='woniu',passwd='123456',db='wangjin')
con.autocommit(True)
cur =con.cursor()
app = Flask(__name__)
import until
# use random
app.secret_key = 'iouasoiduio89127398981273'
@app.route('/')
def index():
if 'user' in session:
cur.execute('select * from user')
res = cur.fetchall()
return render_template('index.html',user=session['user'],users=res)
else:
return redirect('/login')
@app.route('/login',methods=['GET','POST'])
def login():
if request.method=='GET':
return render_template('login.html')
elif request.method=='POST':
user = request.form.get('user')
pwd = request.form.get('pwd')
sql = 'select * from user where (username="%s") and (password="%s")'%(user,pwd)
cur.execute(sql)
if cur.fetchone():
session['user'] = user
return redirect('/')
else:
return 'wrong user. or passwd'
@app.route('/delete')
def deleteuser():
user = request.args.get('user')
sql = 'delete from user where username="%s"'%(user)
cur.execute(sql)
return redirect('/')
@app.route('/changepw',methods=['GET','POST'])
def changepw():
if request.method == 'GET':
user = request.args.get('user')
print user
print '&'*50
return render_template('changepw.html',user=user)
elif request.method == 'POST':
user = request.form.get('user')
user = request.form.get('user')
print '*'*60
print user
oldpwd = request.form.get('oldpwd')
newpwd = request.form.get('newpwd')
confirmpwd = request.form.get('confirmpwd')
if until.user_dict[user]!=oldpwd:
return 'wrong old password'
if newpwd!=confirmpwd:
return 'new pwd not equal to confirmpwd'
until.changepw(user,newpwd)
return redirect('/')
@app.route('/adduser',methods=['GET','POST'])
def adduser():
if request.method == 'GET':
return render_template('adduser.html')
elif request.method =='POST':
user = request.form.get('user')
pwd = request.form.get('pwd')
sql = 'insert into user values ("%s","%s")'%(user,pwd)
cur.execute(sql)
return redirect('/')
@app.route('/logout')
def logout():
del session['user']
return redirect('/login')
if __name__=="__main__":
app.run(host='0.0.0.0',port=22222,debug=True)
cat until.py
#!/usr/bin/python
#from txt to dict
user_dict = {}
def get_data_from_file():
with open('user.txt') as f:
for line in f:
if line == '\n':
continue
(user,pwd) = line.replace('\n','').split(':')
user_dict[user] = pwd
#print user_dict
get_data_from_file()
#from dict to txt
def render_file_from_dict():
user_txt_list = []
for item in user_dict.items():
user_txt_list.append('%s:%s'%item)
with open('user.txt','w') as f:
f.write('\n'.join(user_txt_list))
#user_dict['yy'] = 'yy'
#render_file_from_dict()
def add_user(user,pwd):
if user and pwd:
if user in user_dict:
return 'user already exist'
else:
user_dict[user] = pwd
render_file_from_dict()
return 'ok'
else:
return 'you need a user or passwd'
def del_user(user):
if not user:
return 'you need a username'
if user in user_dict:
del user_dict[user]
render_file_from_dict()
return 'ok'
else:
return 'user not exist'
def login(user,pwd):
pass
def changepw(user,pwd):
user_dict[user] = pwd
render_file_from_dict()
templates目录下:
cat index.html
{% if user=='admin' %}
add user form
{% endif %}
<hr >
{{user}}
<a href="/logout">logout</a>
<a href="/adduser">adduser</a>
<table border="1">
{% for u in users %}
<tr>
<td>{{u[0]}}</td>
<td>{{u[1]}}</td>
<td>
<a href='/changepw?user={{u[0]}}'>changepw</a>
</td>
<td>
{% if user=='admin' %}
<a href='/delete?user={{u[0]}}'>delete</a>
{% endif %}
</td>
</tr>:
{% endfor %}
</table>
cat login.html
<form method='post' >
user:<input type="text" name='user'>
pwd:<input type="text" name='pwd'>
<input type="submit" value="login">
</form>
cat adduser.html
<form method='post' >
user:<input type="text" name='user'>
pwd:<input type="text" name='pwd'>
<input type="submit" value="add">
</form>
cat changepw.html
{{user}}
<form method='post' >
<input type='hidden' name='user' value="{{user}}">
oldpwd:<input type='text' name='oldpwd'>
<br >
newpwd:<input type='text' name='newpwd'>
<br >
confirmpwd:<input type='text' name='confirmpwd'>
<br >
<input type='submit' value='update'>
</form>
===================================================================================>>>>
===================================================================================>>>>
完全是mysql模块化:
分为 config.py 放置mysql的配置信息
until.py 放置模块的信息
flask_web.py 主题程序
templates 目录下放置html文件
cat flask_web.py
#!/usr/bin/python
from flask import Flask,render_template,request,redirect,session
import MySQLdb as mysql
con = mysql.connect(host='59.110.12.72',user='woniu',passwd='123456',db='wangjin')
con.autocommit(True)
cur =con.cursor()
app = Flask(__name__)
import until
from until import app_index,app_login,app_delete,app_adduser,app_updatepw,app_getpw
# use random
app.secret_key = 'iouasoiduio89127398981273'
@app.route('/')
def index():
if 'user' in session:
return render_template('index.html',user=session['user'],users=app_index())
else:
return redirect('/login')
@app.route('/login',methods=['GET','POST'])
def login():
if request.method=='GET':
return render_template('login.html')
elif request.method=='POST':
user = request.form.get('user')
pwd = request.form.get('pwd')
app_user = app_login(user,pwd)
if app_user:
session['user'] = user
return redirect('/')
else:
return 'wrong user. or passwd'
@app.route('/delete')
def deleteuser():
user = request.args.get('user')
app_delete(user)
return redirect('/')
@app.route('/changepw',methods=['GET','POST'])
def changepw():
if request.method == 'GET':
user = request.args.get('user')
return render_template('changepw.html',user=user)
elif request.method == 'POST':
user = request.form.get('user')
oldpwd = request.form.get('oldpwd')
newpwd = request.form.get('newpwd')
confirmpwd = request.form.get('confirmpwd')
pwd = list(app_getpw(user)) #这里获取的是个元组,需要转化为str
pwd = ''.join(pwd)
pwd = pwd.strip()
if pwd!=oldpwd:
return 'wrong old password'
if newpwd!=confirmpwd:
return 'new pwd not equal to confirmpwd'
app_updatepw(newpwd,user)
return redirect('/')
@app.route('/adduser',methods=['GET','POST'])
def adduser():
if request.method == 'GET':
return render_template('adduser.html')
elif request.method =='POST':
user = request.form.get('user')
pwd = request.form.get('pwd')
app_adduser(user,pwd)
return redirect('/')
@app.route('/logout')
def logout():
del session['user']
return redirect('/login')
if __name__=="__main__":
app.run(host='0.0.0.0',port=33333,debug=True)
cat config.py
#!/usr/bin/python
ST = '59.110.**.**'
DB_PORT = 3306
DB_USER = 'woniu'
DB_PASSWD = '123456'
DB_DBNAME = '*******'
DB_CHARSET = 'utf8'
cat until.py
#!/usr/bin/python
import MySQLdb as mysql
from config import ST,DB_PORT,DB_USER,DB_PASSWD,DB_DBNAME,DB_CHARSET
sql_all = 'select * from user'
sql_login = 'select * from user where (username="%s") and (password="%s")'
sql_delete = 'delete from user where username="%s"'
sql_adduser = 'insert into user values ("%s","%s")'
sql_updatepw = 'update user set password="%s" where username="%s"'
sql_getpw = 'select password from user where username="%s"'
#注意%s得加上引号,不然的话会语句报错
Unknown column 'abcd' in 'field list'
def app_index():
con = mysql.connect(host=ST,port=DB_PORT,user=DB_USER,passwd=DB_PASSWD,db=DB_DBNAME,charset=DB_CHARSET)
con.autocommit(True)
cur =con.cursor()
cur.execute(sql_all)
res = cur.fetchall()
cur.close()
con.close()
return res
def app_login(username,passwd):
con = mysql.connect(host=ST,port=DB_PORT,user=DB_USER,passwd=DB_PASSWD,db=DB_DBNAME,charset=DB_CHARSET)
con.autocommit(True)
cur =con.cursor()
cur.execute(sql_login%(username,passwd))
res = cur.fetchone()
cur.close()
con.close()
return res
def app_delete(username):
con = mysql.connect(host=ST,port=DB_PORT,user=DB_USER,passwd=DB_PASSWD,db=DB_DBNAME,charset=DB_CHARSET)
con.autocommit(True)
cur =con.cursor()
cur.execute(sql_delete%(username))
res = cur.fetchone()
cur.close()
con.close()
def app_adduser(username,passwd):
con = mysql.connect(host=ST,port=DB_PORT,user=DB_USER,passwd=DB_PASSWD,db=DB_DBNAME,charset=DB_CHARSET)
con.autocommit(True)
cur =con.cursor()
cur.execute(sql_adduser%(username,passwd))
res = cur.fetchone()
cur.close()
con.close()
def app_updatepw(passwd,username):
con = mysql.connect(host=ST,port=DB_PORT,user=DB_USER,passwd=DB_PASSWD,db=DB_DBNAME,charset=DB_CHARSET)
con.autocommit(True)
cur =con.cursor()
cur.execute(sql_updatepw%(passwd,username))
res = cur.fetchone()
cur.close()
con.close()
def app_getpw(username):
con = mysql.connect(host=ST,port=DB_PORT,user=DB_USER,passwd=DB_PASSWD,db=DB_DBNAME,charset=DB_CHARSET)
con.autocommit(True)
cur =con.cursor()
cur.execute(sql_getpw%(username))
res = cur.fetchone()
cur.close()
con.close()
return res
no pain no gain