文件夹结构
python-webapp/ <-- 根目录|+- UserConn/
<-- Web目录,存放.py文件| || +- static/
<-- 存放静态文件| || +- templates/
<--db.py
<--main.py
-
Now we must the first to design the db.py
下面是实现数据库的链接类:
import pymysql
conn=pymysql.connect("localhost","root","********","test")
cur=conn.cursor()
def insert(username,password):
sql="insert into user (username,password) values ('%s','%s')"%(username,password)
cur.execute(sql)
conn.commit()
conn.close()
def isExisted(username,password):
sql="select*from user where username ='%s' and password ='%s'"%(username,password)
cur.execute(sql)
result=cur.fetchall()
if(len(result)==0):
return False
else:
return True
- 接下来是实现main模块的组件功能
from flask import Flask
from flask import request
from flask import render_template
from flask import redirect
from db import *
app=Flask(__name__)
from wtforms import Form,TextField,PasswordField,validators
//定义的LoginForm类
class LoginForm(Form):
username = TextField("username",[validators.Required()])
password = PasswordField("password",[validators.Required()])
//对http://127.0.0.1:8080/register的注册
@app.route("/register",methods=['GET','POST'])
def register():
myForm=LoginForm(request.form) //这里是对LoginForm的实例化
if request.method=='POST':
insert(myForm.username.data,myForm.password.data) //insert方法对应的是db.py里面的insert(user,password)方法
return render_template("Welcome.html")
return render_template("login.html", form=myForm)
//对http://127.0.0.1:8080/login的注册
@app.route("/login",methods=['GET','POST'])
def login():
myForm=LoginForm(request.form)
if request.method =='POST':
if (isExisted(myForm.username.data,myForm.password.data)):
return redirect("http://Waynicshine.github.io")
else:
return "Login Failed"
return render_template("login.html", form=myForm)
if __name__=="__main__":
app.run(port=8080,debug=True)
index.html的前端表现
<html>
<head></head>
<body>
<div align="center">
<h1>User Management</h1>
{% if message %} {{message}} {% endif %}
<form method="post">
Username :{{form.username}}
<br/>
Password :{{form.password}}
<br/>
<input type="submit" value="Submit" />
<input type="reset" value="reset" />
</form>
</div>
</body>
</html>
- login.html展现
- 登陆成功后,跳转到我的blog
www.waynicshine.github.io
- register.html展现