文件夹结构
python-webapp/
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的前端表现
User Management
{% if message %} {{message}} {% endif %}
Username :{{form.username}}
Password :{{form.password}}
login.html展现
Paste_Image.png
登陆成功后,跳转到我的blog
Paste_Image.png
register.html展现
Paste_Image.png