暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Flask留言板教程

原创 flyinsky323 2023-07-26
280

本教程是基于kali系统+Python2+Flask+SQLite3开发的留言板
一、准备工作
1.安装虚拟环境
2.创建项目目录
msg
app
templates
data
__init__.py
routes.py
database.py
msg.py
3.安装Flask
4.创建数据库、数据表
import sqlite3
conn = sqlite3.connect('testdb.db')
curs = conn.cursor()
curs.execute('''
create table msg(
id int primary key,
uname text,
message text,
addtime float
)
''')
conn.commit()
conn.close()

二、先写初始程序并让其运行起来
app/__init__.py
from flask import Flask,render_template,redirect,url_for
app = Flask(__name__)
from app import routes

app/routes.py
from app import app
@app.route('/')
@app.route('/index')
def index():
return "Msg List"

msg.py
from app import app
if __name__=='__main__':
app.run()

运行 python msg.py
在浏览器中输入127.0.0.1:5000 如果看到“Msg List”说明程序是正确的

三、完善程序
1.引入模板render_template
由于网页上头部和底部的信息都是一样的,故使用模板继承机制
1-1.基类模板app/templates/base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>{%block title%}{%endblock%}</title> <!--用子模板的标题替换-->
{{url_for('static',filename='base.css')}} <!--基类模板中使用的样式文件-->
{%block css%}{%endblock%} <!--用子模板的样式文件替换-->
</head>
<body>
<div class='nav'>
<ul>
<li><a href="{{url_for('index')}}">Index</a></li>
<li><a href="{{url_for('add')}}">Add</a></li>
<li><a href="{{url_for('manage')}}">Manage</a></li>
</ul>
</div>
{%block content%}
<!--要显示的子模板的内容-->
{%endblock%}
<div class='foot'>
Welcome To Python's Flask World
</div>
</body>
</html>
1-2.首页模板app/templates/index.html
{%extends 'base.html'%} <!--继承基类模板-->
{%block title%}{{title}}{%endblock%} <!--在路由中定义页面标题-->
{%block css%}{{url_for('static',filename='index.css')}}{%endblock%}
{%block content%}
this is Index List
{%endblock%}
路由app/routes.py
def index():
title='Index List'
return render_template('index.html',title=title)
1-3.添加页模板app/templates/add.html
{%extends 'base.html'%} <!--继承基类模板-->
{%block title%}{{title}}{%endblock%} <!--在路由中定义页面标题-->
{%block css%}{{url_for('static',filename='index.css')}}{%endblock%}
{%block content%}
<h1>Add Message</h1>
<form action='' method='post'>
Username:<input type='text' name='username' /><br>
Theme:<input type='text' name='theme' /><br>
Content:<input type='text' name='Content' /><br>
<input type='submit' value='Sub' />
</form>
{%endblock%}

数据库配置app/database.py
import sqlite3,os.path as oh
base_dir=oh.dirname(oh.abspath(__file__))
db_path=oh.join(base_dir,'data/web.db')
conn=sqlite3.connect(db_path,check_same_thread=False)
global cur
cur=conn.cursor()

路由文件app/routes.py
from flask import request
from app.database import *
@app.route('/')
@app.route('/index') #该行及下面一行表示参数可选
@app.route('/index/<string:info>') #加入参数是和后面添加数据时对应
def index(info=''): #设置一个默认值,添加成功后会用新值替换
title='Index'
info=info
return r('index.html',title=title,info=info)
@app.route('/add',methods=['GET','POST'])
def add():
title='Add message'
if request.method=='POST':
username=request.form['username']
theme=request.form['theme']
content=request.form['content']
sql="insert into `msg`(username,theme,content) values('{}','{}','{}')".format(username,theme,content)
cur.execute(sql)
conn.commit()
conn.close()
info='Add Success'
return redirect(url_for('index',info=info)) #添加成功,将成功提示信息传递给首页
return render_template('add.html',title=title)

然后在首页模板index.html的block content中添加如下内容
{%if info%}
<h2>{{info}}</h2>
{%endif%}
2.显示留言列表
路由文件app/routes.py
@app.route('/')
@app.route('/index/?<string:info>') #加入参数是和后面添加数据时对应
def index(info=''): #设置一个默认值,添加成功后会用新值替换
title='Index'
info=info
sql="select * from msg order by id desc"
cur.execute(sql)
datas=cur.fetchall()
return r('index.html',title=title,info=info,datas=datas)
在模板index.html中循环
{%for row in datas%}
{{row[0]}}-{{row[1]}}-{{row[2]}}
{%endfor%}

3.管理留言
路由、模板和首页的一样,只是在显示列表的地方多了两个"修改"、"删除"的按钮
<a href="{{url_for('edit',id=row[0])}}">Edit</a>
<a href="{{url_for('delInfo',id=row[0])}}">Del</a>
3-1.修改留言
路由文件app/routes.py
(注:模板中使用{{url_for('edit',id=row[0])}})

##################获取参数#################
request.form.get("key", type=str, default=None) 获取表单数据
request.args.get("key") 获取get请求参数
request.values.get("key") 获取所有参数
###########################################

@app.route('/edit',methods=['GET','POST']) #解析成/edit?id=2
def edit():
id=request.args.get('id')
title='Modify one message'
.....

@app.route('/edit/<int:id>/',methods=['GET','POST']) #解析成/edit/2/
def edit(id):
title='Modify one message'
if request.method=='POST':
username=request.form['username']
...
id=request.form['id']
sql="update msg set username='{}',... where id={}".format(username,..,id)
cur.execute(sql)
info="Modify Success"
return redirect(url_for('index',info=info))
sql="select * from msg where id={}".format(id)
cur.execute(sql)
data=cur.fetchone()
return r('edit.html',title=title,data=data)

3-2.删除留言
路由文件app/routes.py
@app.route('/delInfo/<int:id>/')
def delInfo(id):
sql="delete from msg where id={}".format(id)
cur.execute(sql)
info="Delete Success"
return redirect(url_for('index',info=info))

留言板教程至此结束!

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论