Python Flask: 实现笔记列表功能
来自CloudWiki
代码
manage.py:
from flask import Flask from flask import Flask, render_template, flash, redirect, url_for, session, request, logging app = Flask(__name__)#创建一个该类的实例,第一个参数是应用模块或者包的名称 @app.route('/')#告诉Flask 什么样的URL能触发函数 def hello_world(): return 'Hello World!' # 控制台 @app.route('/dashboard') @is_logged_in def dashboard(): db = MysqlUtil() # 实例化数据库操作类 sql = "SELECT * FROM articles WHERE author = '%s' ORDER BY create_date DESC" % (session['username']) # 根据用户名查找用户笔记信息 result = db.fetchall(sql) # 查找所有笔记 if result: # 如果笔记存在,赋值给articles变量 return render_template('dashboard.html', articles=result) else: # 如果笔记不存在,提示暂无笔记 msg = '暂无笔记信息' return render_template('dashboard.html', msg=msg) if __name__ == '__main__':#程序入口 #app.run()#让应用运行在本地服务器上。 app.secret_key='secret123' app.run( host='0.0.0.0',port="5006") #允许任意网址访问本站
模板
dashboard.html:
{% extends 'layout.html' %} {% block body %} <h1>控制台 <small> 欢迎 {{session.username}}</small></h1> <a class="btn btn-success" href="/add_article"> 添加笔记 </a> <hr> <table class="table table-striped"> <tr> <th>ID</th> <th>标题</th> <th>作者</th> <th>日期</th> <th></th> <th></th> </tr> {% for article in articles %} <tr> <td>{{article.id}}</td> <td>{{article.title}}</td> <td>{{article.author}}</td> <td>{{article.create_date}}</td> <td><a href="edit_article/{{article.id}}" class="btn btn-default pull-right">Edit</a></td> <td> <form action="{{url_for('delete_article', id=article.id)}}" method="post"> <input type="hidden" name="_method" value="DELETE"> <input type="submit" value="Delete" class="btn btn-danger"> </form> </td> </tr> {% endfor %} </table> {% endblock %}