继前面全栈的环境跑通以后,现在开始blog单页面blog的设计。
前面已经设计好了整个流程,并且跑通,所以这里只需要针对具体代码的设计即可。因为进行改动的只有后台backend框架,所以先来同样的vue前台逻辑的设计。
vue部分
首先设计一个Blog.vue组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <template> <div class="container"> <p>blog</p> </div> </template> <script> export default{ name: 'Blog' } </script> <style> #app{ margin-top: 60px; } </style>
然后为了进行样式的设计,所以引入bootstrap这个css框架:
然后在vue中进行引入bootstrap框架的blog页面设计:
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 38 39 40 41 42 43 44 45 46 47 <template> <div class="container"> <div class="row"> <div class="col-sm-10"> <h1>Blogs</h1> <hr><br><br> <button type="button" class="btn btn-success btn-sm">添加</button> <br><br> <table class="table table-hover"> <thead> <tr> <th scope="col">title</th> <th scope="col">author</th> <th scope="col">details</th> <th></th> </tr> </thead> <tbody> <tr> <td>阿巴阿巴</td> <td>我</td> <td><a href="https://zhuanlan.zhihu.com/p/642004545">文章</a></td> <td> <div class="btn-group" role="group"> <button type="button" class="btn btn-warning btn-sm">更新</button> <button type="button" class="btn btn-danger btn-sm">删除</button> </div> </td> </tr> </tbody> </table> </div> </div> </div> </template> <script> export default{ name: 'Blog' } </script> <style> #app{ margin-top: 60px; } </style>
在vue路由部分进行Blog的使用注册:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 ... import Blog from '@/components/Blog' Vue .use (Router )export default new Router ({ routes : [ { path : '/' , component : Blog } ] })
如上注册,把blog作为唯一路由进行使用,运行看一下效果:
前台效果
flask操作数据库
上面是基础页面,但重要的还是数据,所以需要设计一个存储文章的数据表:
1 2 3 4 5 6 7 create table posts( id int auto_increment primary key , title varchar (100 ) not null , content text not null , created_at datetime not null default current_timestamp , updated_at datetime not null default current_timestamp on update current_timestamp , )
如上,针对上面这个类型的数据库进行ORM数据表类的设计,不过使用ORM框架需要引入flask-sqlalchemy:
1 pip install flask-sqlalchemy
开始数据表设计:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 from flask_sqlalchemy import SQLAlchemyfrom sqlalchemy import Column, String, Text, Integer, DateTimeapp = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI' ] = 'sqlite:///blogs.db' db = SQLAlchemy(app) class Blog (db.Model): __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 = db.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} >'
如上为数据库model的设计,使用的是本地轻量级sqlite数据库,针对这个数据库,需要进行的初始化动作,设计成如下命令来进行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import click... @app.cli.command() @click.option('--drop' , is_flag=True ) def init (drop ): '''初始化数据库''' if drop: db.drop_all() db.create_all() blogs = [Blog(title='哈哈哈哈' , author='a' , abstract='just a' ), Blog(title='嘻嘻嘻嘻' , author='b' , abstract='just b' ), Blog(title='阿巴阿巴' , author='啊巴' , abstract='just 啊巴' )] db.session.add_all(blogs) db.session.commit() else : db.create_all() click.echo('数据表初始化' )
可以使用flask查看help命令看到上面命令信息,注释部分正是命令行的帮助信息,可以通过flask init来进行简单数据库表创建,添加drop参数可以进行所有数据表的删除后重新创表并插入信息。这里用的就是flask init --drop的命令(后来想了想,好像没有不添加drop参数的使用场合),进行数据表生成后,设计一下数据表查询逻辑,和vue进行交互:
1 2 3 4 5 @app.route('/blogs' ) def lists (): blogs = Blog.query.all () logger.info(blogs) return jsonify(blogs)
针对上面的数据表逻辑,vue还需要改改,而且js部分也需要请求后才能进行template的渲染:
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 ... <table class="table table-hover"> <thead> <tr> <th scope="col">id</th> <th scope="col">title</th> <th scope="col">author</th> <th scope="col">abstract</th> <th scope="col">created_at</th> <th scope="col">updated_at</th> <th></th> </tr> </thead> <tbody> <tr v-for="(blog, index) in blogs" :key="index"> <td>{{ blog.id }}</td> <td>{{ blog.title }}</td> <td>{{ blog.author }}</td> <td>{{ blog.content }}</td> <td>{{ blog.created_at}}</td> <td>{{ blog.updated_at }}</td> <td> <div class="btn-group" role="group"> <button type="button" class="btn btn-warning btn-sm">更新</button> <button type="button" class="btn btn-danger btn-sm">删除</button> </div> </td> </tr> </tbody> </table> ... <script> import axios from 'axios' export default{ name: 'Blog', data() { return { blogs: [] } }, methods: { getBlogs() { const path = 'http://localhost:5000/blogs' axios.get(path) .then((res) => { this.blogs = res.data.blogs; }) .catch((error) => { console.error(error) }) } }, created() { this.getBlogs() } } </script>
如上修改了,样式,然后跑一下,需要说明的是,这里需要检测一下后台逻辑的blogs接口,用的postman,所以要开放外部局域网访问(因为postman在windows里面,实验环境在ubuntu):
1 2 3 source /home/blog/backend/bin/activate export FLASK_APP=/home/blog/backend/app.py flask run --host=0.0.0.0
结果不出意外的失败了,这是因为jsonify进行构造响应的数据是三个Blog对象,而这些个并不是可序列化对象,所以还需要转换:
1 2 3 4 5 6 7 8 9 10 11 12 def model_to_dict (object ): return {field.name:getattr (object , field.name) for field in object .__table__.columns} def scalars_to_list (object ): return [model_to_dict(c) for c in object ] @app.route('/blogs' ) def lists (): blogs = Blog.query.all () blogs = scalars_to_list(blogs) logger.info(blogs) return jsonify(blogs)
计划通,结果如下:
postman效果
本来想直接就进行输出的,不过好像还是有点问题,因为Blog.vue中js部分,获取的是flask返回的json数据中的blogs数据,所以要改一改flask构造的数据样式:
1 2 3 4 5 6 @app.route('/blogs' ) def lists (): blogs = Blog.query.all () blogs = scalars_to_list(blogs) logger.info(blogs) return jsonify({'blogs' :blogs})
这样就可以了,效果如下:
blogs渲染效果
OK,继续进行设计,观察过页面的话,应该会留意到主页面的添加按钮,现在就进行添加blog逻辑的设计,首要的就是进行flask的逻辑设计,把前面的blogs路由的查询和列表数据返回结合在一起,根据请求方式进行逻辑切割:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @app.route('/blogs' , methods=['GET' , 'POST' ] ) def lists (): resp_dict = {'status' :'success' } if request.method == 'POST' : data = request.get_json() blog = Blog(title=data['title' ], author=data['author' ], abstract=data['abstract' ]) logger.info(blog) db.session.add(blog) db.session.commit() resp_dict['msg' ] = 'successfully added' blogs = Blog.query.all () blogs = scalars_to_list(blogs) logger.info(blogs) resp_dict['blogs' ] = blogs return jsonify(resp_dict)
如上,简单的get就进行数据库查询,构造json数据库数据给vue进行渲染,另外的post就是把vue构造的新的blog信息进行Blog数据库model对象构造,然后更新数据库,再来在数据库查询部分给添加进去,下面设计一下vue的请求逻辑和处理逻辑:
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 <script> import axios from 'axios' export default { name : 'Blog' , data ( ) { return { activeAdditionModel : false , additionForm : { title : '' , author : '' , abstract : '' }, blogs : [] } }, methods : { addBlog (payload ) { const path='http://localhost:5000/blogs' axios.post (path, payload) .then (() => { this .getBlogs () }) .catch ((error ) => { console .error (error) this .getBlogs () }) }, getBlogs ( ) { const path = 'http://localhost:5000/blogs' axios.get (path) .then ((res ) => { this .blogs = res.data .blogs ; }) .catch ((error ) => { console .error (error) }) }, resetForm ( ){ this .initForm () }, initForm ( ){ this .additionForm .title ='' this .additionForm .author ='' this .additionForm .abstract ='' }, additionSubmit ( ){ this .toggleAddModal () const payload={ title : this .additionForm .title , author : this .additionForm .author , abstract : this .additionForm .abstract , } console .log (payload) this .addBlog (payload) this .initForm () }, toggleAddModal ( ){ const body=document .querySelector ('body' ) this .activeAdditionModel = !this .activeAdditionModel if (this .activeAdditionModel ){ body.classList .add ('modal-open' ) } else { body.classList .remove ('modal-open' ) } }, }, created ( ) { this .getBlogs () } } </script>
如上,关注axios请求,分出get和post请求,关注post请求应用,构造payload作为表单数据,然后指定axios请求url,最后进行post以后,再来一次get请求渲染列表页面,最后重置一下编辑页面。addBlog是post请求的主体逻辑,但这是按钮点击事件的处理逻辑(additionSubmit)的一部分。然后页面设计如下:
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 <template> <div class="container"> <div class="row"> <div class="col-sm-10"> <h1>Blogs</h1> <hr><br><br> <button type="button" class="btn btn-success btn-sm" @click="toggleAddModal" >添加</button> <br><br> <table class="table table-hover"> <thead> <tr> <th scope="col">id</th> <th scope="col">title</th> <th scope="col">author</th> <th scope="col">abstract</th> <th scope="col">created_at</th> <th scope="col">updated_at</th> <th></th> </tr> </thead> <tbody> <tr v-for="(blog, index) in blogs" :key="index"> <td>{{ blog.id }}</td> <td>{{ blog.title }}</td> <td>{{ blog.author }}</td> <td>{{ blog.abstract }}</td> <td>{{ blog.created_at}}</td> <td>{{ blog.updated_at }}</td> <td> <div class="btn-group" role="group"> <button type="button" class="btn btn-warning btn-sm">更新</button> <button type="button" class="btn btn-danger btn-sm">删除</button> </div> </td> </tr> </tbody> </table> </div> </div> <!-- 根据添加button进行页面逻辑添加 --> <div ref="additionModel" class="modal fade" :class="{show: activeAdditionModel, 'd-block': activeAdditionModel}" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">添加</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close" @click="toggleAddModal"> <!-- 关闭按钮 --> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <form> <div class="mb-3"> <label for="addTitle" class="form-label">Title:</label> <input type="text" class="form-control" id="addTitle" v-model="additionForm.title" placeholder="输入标题"> </div> <div class="mb-3"> <label for="addAuthor" class="form-label">Author:</label> <input type="text" class="form-control" id="addAuthor" v-model="additionForm.author" placeholder="输入作者名"> </div> <div class="mb-3"> <label for="addAbstract" class="form-label">Abstract:</label> <input type="text" class="form-control" id="addAbstract" v-model="additionForm.abstract" placeholder="输入摘要"> </div> <div class="btn-group" role="group"> <button type="button" class="btn btn-primary btn-sm" @click="additionSubmit">提交</button> <button type="button" class="btn btn-danger btn-sm" @click="resetForm">重置</button> </div> </form> </div> </div> </div> </div> <div v-if="activeAdditionModel" class="modal-backdrop fade show"></div> </div> </template>
来查看一下效果:
失败访问
如上访问是失败的,为什么?因为axios进行的请求是访问localhost的5000端口web,所以失败了,现在一个比较简单的办法就是进行axios的请求url的指定,并且开放flask的外界请求:
1 2 import axios from 'axios' axios.defaults .baseURL = 'http://192.168.1.7:5000'
如上在main.js中添加指定url,然后修改addBlog方法和getBlogs方法中path,不用添加host了,直接就访问路由就好,还有flask运行:
flask run --host=0.0.0.0
OK,效果有了:
简单效果
除了这个指定办法,还有着webpack的代理使用来解决这个问题,其他的一些路由就比较简单了,时间不够,留待后续。