Jack's Studio.

单页面blog全栈完善

字数统计: 1.8k阅读时长: 8 min
2023/07/11
loading

算是前面单页面blog的附属,把后续的路由进行完善的记录。

delete处理

前面进行了blogs的路由设计和前台的页面设计,下面简单设计一下删除blog的设计,如下设计js部分:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>
deleteBlog(blog){
const path='/blog/delete'
const payload={
'id': blog['id'],
'title': blog['title'],
'author': blog['author']
}
console.log(payload)
axios.post(path, payload)
.then(() => {
this.getBlogs()
})
.catch((error) => {
console.error(error)
})
},
</script>

如上设计,设定该函数为[删除]按钮的点击处理函数,按钮点击,构建payload表单,然后对指定/blog/delete的删除路由进行post,提交payload为表单,因此针对删除路由,进行flask的设计:

1
2
3
4
5
6
7
8
9
10
from flask import redirect

@app.route('/blog/delete', methods=['POST'])
def delete_blog():
blog_json = request.get_json()
blog = Blog.query.filter_by(id=blog_json['id'], title=blog_json['title'], author=blog_json['author']).first()
db.session.delete(blog)
db.session.commit()
logger.info(blog)
return redirect('/blogs')

这部分逻辑非常简单,提交blog信息,然后后台flask进行数据库删除操作,在[删除]按钮的点击处理函数中添加整体blog的数据请求,页面会自动渲染。

update处理

这部分最麻烦,因为涉及bootstrap的模态框的处理,因为想复用一下代码,不想再设计多余的页面逻辑了,所以采取添加一个标志位的方案,针对该activeUpdate标志位分出不同操作,如下重新设计一下进行toggle模态逻辑:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
setForm(blog){
this.blogForm.id = blog.id
this.blogForm.title = blog.title
this.blogForm.author = blog.author
this.blogForm.abstract = blog.abstract
},
toggleAddModal(blog){
const body=document.querySelector('body')
this.activeAdditionModal = !this.activeAdditionModal
if (!this.activeUpdate){
this.setForm(blog)
this.activeUpdate = !this.activeUpdate
console.log(this.activeUpdate)
} else {
this.activeUpdate = !this.activeUpdate
console.log(this.activeUpdate)
}

if (this.activeAdditionModal){
body.classList.add('modal-open')
} else {
body.classList.remove('modal-open')
}
},

如上,toggle逻辑主要是针对activeAdditionModal标志位进行操作,bootstrap模态框更多还是css上面的操作,显示和隐藏操作都在这里了:

1
2
3
4
5
6
7
8
9
<div
ref="additionModal"
class="modal fade"
:class="{show: activeAdditionModal, 'd-block': activeAdditionModal}"
tabindex="-1"
role="dialog">
</div>
...
<div v-if="activeAdditionModal" class="modal-backdrop fade show"></div>

如上的页面逻辑已经搞定了添加模态框的隐藏和显示,想要更好的理解可以查看如下菜鸟教程的一个介绍:

bootstrap模态框

在toggle确定操作后,还需要进行[提交]按钮的重新设计,根据activeUpdate标志位进行不同处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
handleSubmit(){
const payload = {
id: this.blogForm.id,
title: this.blogForm.title,
author: this.blogForm.author,
abstract: this.blogForm.abstract
}
console.log(payload)
if (this.activeUpdate) {
this.updateBlog(payload)
} else {
this.addBlog(payload)
}
this.toggleAddModal()
this.initForm()
},

如上切割,具体的请求逻辑如下:

1
2
3
4
5
6
7
8
9
10
11
updateBlog(payload){
const path = '/blog/update'
axios.post(path, payload)
.then((res) => {
console.log(res.data)
this.getBlogs()
})
.catch((error)=>{
console.error(error)
})
},

这样vue部分ok,设计flask的数据库处理:

1
2
3
4
5
6
7
8
9
@app.route('/blog/update', methods=['POST'])
def update_blog():
blog_json = request.get_json()
blog = Blog.query.filter_by(id=blog_json['id']).first()
logger.info(blog)
blog.title, blog.author, blog.abstract = blog_json['title'], blog_json['author'], blog_json['abstract']
logger.info(blog)
db.session.commit()
return jsonify({'msg':'success'})

ok,增删改查完毕,前面已经设计好了添加和列表查询,所以上面的修改和删除完成以后,单页面就已经完成

效果

下面引入一个上传gitee遇到的问题。

git碰上virtualenv

在前面的设计中,笔者是使用virtualenv来直接设计的backend环境,所以它自动生成了一个.gitignore文件在backend中,文件内容如下:

1
2
# created by virtualenv automatically
*

如上,该.gitignore文件设定当前backend文件全部忽略提交,因为这个情况,导致前面提交的flask版本的一些后台文件都没有上传,进行百度也是不知道怎么来百度,因为都没想到virtualenv的情况,所以修改backend下.gitignore文件如下:

1
2
3
4
5
6
7
# created by virtualenv automatically
bin
blogs.db
include
lib
__pycache__
pyvenv.cfg

再来提交,就ok了。目前比较完善的代码在如下:

gitee中代码

感兴趣的可以看一看,或者嫌弃上面啰里啰嗦的也可以直接看代码,反正没有引入过多的复杂逻辑。嗯,因为很多逻辑都有进行逐步的修改,所以一些个原定函数或者标志位都进行一下名字更替。

引入操作结果显示

针对一些个实际上的操作,很多时候都会在页面上有显示,比如某条信息删除成功啥的,所以这里就是做一个这个效果,设计一个子组件Alert.vue:

1
2
3
4
5
6
7
8
9
10
11
12
<template>
<div id="alert">
<div class="alert alert-success" role="alert">{{ msg }}</div>
</div>
</template>

<script>
export default{
name: 'Alert',
props: ['msg']
}
</script>

然后在Blog.vue中引入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script>
import Alert from './Alert.vue'
import axios from 'axios'

export default{
name: 'Blog',
data() {
return {
...
message: ''
}
},
components: {
Alert
},
}
</script>

在template标签中进行应用:

1
2
3
4
5
6
7
8
9
<template>
<div class="container">
<div class="row">
<div class="col-sm-10">
<h1>Blogs</h1>
<hr><br><br>
<alert :msg="message"></alert>
...
</template>

再然后就是修改一下一些个增删改查的逻辑发起处理函数中对message的赋值了:

1
2
3
4
5
6
7
8
9
10
11
12
13
addBlog(payload) {
const path='/blogs'
axios.post(path, payload)
.then(() => {
// 发起添加blog请求后进行渲染
this.message = res.data['msg']
this.getBlogs()
})
.catch((error) => {
console.error(error)
this.getBlogs()
})
},

如上是添加一个blog的逻辑,在then中进行处理就行,其他的就不标出来了,因为flask中已经有对应msg的json回应,直接拿来就用就行。

gitee网络仓

引入mysql数据库

这里采用sqlalchemy的ORM,所以新建一个models.py文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from sqlalchemy import Column, String, Text, Integer, DateTime, create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from loguru import logger
from urllib.parse import quote_plus
from datetime import datetime


DIALECT = 'mysql' # 数据库类型
DRIVER = 'pymysql' # 数据库驱动
USER = 'jam' # 用户名
PWD = 'jam123@' # 用户密码
HOST = '192.168.1.7' # 数据库所在主机
PORT = '3306' # 数据库端口
DATABASE = 'somedb' # 所操作的mysql中database
SQL_URI = '''{}+{}://{}:{}@{}:{}/{}?charset=utf8'''.format(
DIALECT, DRIVER, USER, quote_plus(PWD), HOST, PORT, DATABASE
)
logger.info(SQL_URI)


engine = create_engine(SQL_URI)
Session = sessionmaker(bind=engine)
db_session = Session()
Base = declarative_base()


class Blog(Base):
__tablename__ = 'blog'
id = Column('id', Integer, autoincrement=True, primary_key=True)
title = Column('title', String(100), unique=True, nullable=False)
author = Column('author', String(100), nullable=False)
abstract = Column('abstract', Text, nullable=False)
created_at = Column('created_at', DateTime, default=datetime.utcnow)
updated_at = Column('updated_at', DateTime, default=datetime.utcnow)

def __str__(self):
return f'<id: {self.id}, title: {self.title}, author: {self.author}, created_at: {self.created_at}>'

然后在app.py中的应用就不详细介绍了,都在代码仓里了:

代码仓

其实上面的vue还是有点问题,就是在update调用以后,重新调用add逻辑,但调用会跑错地,进行update的操作却跑去add,这个后面再改一下。

CATALOG
  1. delete处理
  2. update处理
  3. git碰上virtualenv
  4. 引入操作结果显示
  5. 引入mysql数据库