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
Python Flask+Mysql练习题的更多相关文章
- 前端和后端的数据交互(jquery ajax+python flask+mysql)
上web课的时候老师布置的一个实验,要求省市连动,基本要求如下: 1.用select选中一个省份. 2.省份数据传送到服务器,服务器从数据库中搜索对应城市信息. 3.将城市信息返回客户,客户用sele ...
- 个人学期总结及Python+Flask+MysqL的web建设技术过程
一个学期即将过去,我们也迎来了2018年.这个学期,首次接触了web网站开发建设,不仅是这门课程,还有另外一门用idea的gradle框架来制作网页. 很显然,用python语言的flask框架更加简 ...
- Python+Flask+MysqL的web建设技术过程
一.前言(个人学期总结) 个人总结一下这学期对于Python+Flask+MysqL的web建设技术过程的学习体会,Flask小辣椒框架相对于其他框架而言,更加稳定,不会有莫名其妙的错误,容错性强,运 ...
- 实战接口开发:python + flask + mysql + redis(根据反馈,持续细化更新。。。)
前言 自动化已经成为测试的必备技能之一了,所以,很多想跳槽的测试朋友都在自学,特别是最实用的接口自动化, 但是很多人因为没有可以练手的项目而苦恼,最终导致缺乏实战经验,其实,完全可以自己开发个简单项目 ...
- Python+Flask+MysqL的web技术建站过程
1.个人学期总结 时间过得飞快,转眼间2017年就要过去.这一年,我学习JSP和Python,哪一门都像一样新的东西,之前从来没有学习过. 这里我就用我学习过的Python和大家分享一下,我是怎么从一 ...
- demo项目开发(Python+flask+mysql+redis只包含后端接口)
[demo项目开发需求] 用户信息管理,可以注册.登录.添加用户.删除用户 注册:任何用户可以注册,对用户提交的注册信息进行校验,返回对应的信息,其中: 用户名:必填,唯一 密码:必填,只能6-12位 ...
- Python/ MySQL练习题(一)
Python/ MySQL练习题(一) 查询“生物”课程比“物理”课程成绩高的所有学生的学号 SELECT * FROM ( SELECT * FROM course LEFT JOIN score ...
- python/MySQL练习题(二)
python/MySQL练习题(二) 查询各科成绩前三名的记录:(不考虑成绩并列情况) select score.sid,score.course_id,score.num,T.first_num,T ...
- python操作三大主流数据库(4)python操作mysql④python服务端flask和前端bootstrap框架结合实现新闻展示
python操作mysql④python服务端flask和前端bootstrap框架结合实现新闻展示 参考文档http://flask.pocoo.org/docs/0.11/http://flask ...
随机推荐
- 如何理解linux多用户多任务
Linux 的单用户.多任务: 容易理解. Linux 的多用户.多任务 举个例子,比如LinuxSir.Org 服务器,上面有FTP 用户.系统管理员.web 用户.常规普通用户等.在同一时刻,比如 ...
- Eclipse+Tomcat环境集成
1.下载Eclipse: 我用的Version: Mars.2 Release (4.5.2),直接在官网上下:http://www.eclipse.org/downloads/packages/re ...
- 重置Cacti密码
Cacti登录密码忘记,重置Cacti密码 用root用户进入系统 [root@localhsot]# mysql -u root -p mysql> show databases; mysql ...
- vector容器类型
vector容器是一个模板类,可以存放任何类型的对象(但必须是同一类对象).vector对象可以在运行时高效地添加元素,并且vector中元素是连续存储的. vector的构造 函数原型: tem ...
- github上不了改下host
207.97.227.239 github.com 65.74.177.129 www.github.com 207.97.227.252 nodeload.github.com 207.97.227 ...
- Invalid bound statement (not found): com.ros.dao.LogMapper.insert
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.ros.dao.LogMapp ...
- windows定时任务小注
static class Program { /// <summary> /// 应用程序的主入口点. /// </summary> [STAThread] static vo ...
- RMQ求区间最大最小值
#include<iostream> #include<cmath> #include<cstdio> #define N 50005 using namespac ...
- graphviz layer 教程(非布局)
官方 pdf 上讲解的很少,没有图片. http://www.graphviz.org/wiki/how-use-drawing-layers-overlays 这里有图片,但是又没有说如何生成. 直 ...
- CS193p Lecture 5 - View Controller Lifecycle
1. UITextView @property(nonatomic,readonly,retain) NSTextStorage *textStorage 是 NSMutableAttributedS ...