动态路由
@app.route(url路径/<变量名>) def 视图函数(变量名): 代码段 from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "<a href='/hello/666'>点击跳转</a>" # 注册路由:参数与href属性相对应 @app.route("/hello/<userid>") def search(userid): return "<h1>编号是:%s</h1>" % userid app.run()
模板的使用
Templat.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模板H5</title> <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body> <a href="/AddInfo" class="btn btn-primary">添加</a> <table class="table table-hover table-bordered" style="text-align:center"> <tr class="info"> <th>编号</th> <th>创建时间</th> <th>用户名</th> <th>简介</th> </tr> {% for row in showList %} <tr> <td>{{ row[0] }}</td> <td>{{ row[1] }}</td> <td>{{ row[2] }}</td> <td>{{ row[3] }}</td> </tr> {% endfor %} </table> </body> </html>
AddInfo.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加</title> <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body> <form action="/SubmitAddInfo" method="post"> <p> <input type="text" name="userName" placeholder="请输入用户名" class="form-control"/> </p> <p> <input type="text" name="introduce" placeholder="请输入用户简介" class="form-control"/> </p> <p> <input type="submit" value="添加" class="btn btn-primary"/> </p> </form> </body> </html>
DBHelper.py
import pymysql class DBHelper(): """DBHelper""" def NoQuery(self, sql): """DML语句""" conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='test', charset='utf8') cursor = conn.cursor() rows = cursor.execute(sql) conn.commit() cursor.close() conn.close() return rows def Query(self, sql): """查DQL询语句""" conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='test', charset='utf8') cursor = conn.cursor() cursor.execute(sql) info = cursor.fetchall() cursor.close() conn.close() return info
demo.py
from DBHelper import DBHelper # 使用第六章的DBHelper from flask import Flask, render_template, redirect from flask import request import time app = Flask(__name__) # 注册路由 @app.route('/') def index(): db = DBHelper() result = db.Query("select * from userinfo") print(result) return render_template("Template.html", showList=result) @app.route('/AddInfo') def AddInfo(): return render_template("AddInfo.html") def GetNow(localTime): """获取当前时间""" return time.strftime("%y-%m-%d %H:%M:%S", localTime) # 注册路由 @app.route('/SubmitAddInfo', methods=["POST"]) def SubmitAddInfo(): userName = request.form.get("userName") introduce = request.form.get("introduce") sql = str.format("insert into userinfo values(0,'{0}','{1}','{2}')", GetNow(time.localtime()), userName, introduce) db = DBHelper() db.NoQuery(sql) return redirect('/') app.run()
运行效果:
添加俩数据看看:
添加功能