当前位置: 移动技术网 > IT编程>脚本编程>Python > 使用MVC编程模型通过flask蓝图实现前端后台新闻发布系统

使用MVC编程模型通过flask蓝图实现前端后台新闻发布系统

2019年06月20日  | 移动技术网IT编程  | 我要评论

重生未来之随身桃源,拘组词,2012年9月思想汇报

相关知识点:

flask:是python开发轻量级框架,也能很好的开发动态网站。

蓝图:flask中蓝图能很好的实现代码分割管理,从而不使代码全部放在app.py杂乱无章,蓝图就像动物管理员一样,把猫和狗分开管理。方便代码维护。

一个完整的新闻发布系统包括前端和后端,为了使前后端分离,各司其职,使用mvc编程模型。做到互不干预。

话不多说,先来看效果。

项目整体目录状况。

 

效果展示

 

 

 下面是详细步骤:

1.新建flask项目

建好项目内容如下:

点击又上角运行,浏览器输入ip地址及端口号显示结果:helloworld!

2.mvc编程模型,简介看我上一篇博文。

(1)新建三个文件夹,model,controller,因view和flask自动原生的templates组件一样,不需要新建,使用其作为视图,存放html前端页面。

  新建文件config.py主要用来存放mysql数据配置参数,如连接的用户名和密码。

  

(2)需要用到mysql数据库,mysql数据库安装,自行百度,注意设置密码:123456,用户名默认root;

 查看是否安装成功:mysql -v

  

登录数据库,输入之前安装设置的用户名:root,密码:123456

  

进入mysql数据库。先查看mysql有哪些数据库。以下是我之前建好的数据库,现需要新建一个数据库。比如新闻数据库news。

  

新闻news数据库创建。

查看数据库是否创建成功:通过:show databases;

可以看出news数据库已经新建成功。

  

(3)配置数据库。config里面设置数据库连接账户。

  app运行文件导入连接数据库相应包:sqlalchemy,pymysql.

  其中app运行文件把之后要写的控制器使用蓝图注册。

config.py

#root:用户,123456密码,localhost:主机名,本地ip127.0.0.1也可以,news刚才建立的数据库
sqlalchemy_database_uri = 'mysql+pymysql://root:123456@localhost/news?charset=utf8'
sqlalchemy_track_modifications=false
secret_key = '123456'

app.py

from flask import flask
from flask_sqlalchemy import sqlalchemy

app = flask(__name__)
app.config.from_object('config')#配置数据库
db=sqlalchemy(app)

from controller.newspublishedcontroller import news_app#导入控制器蓝图
app.register_blueprint(news_app,url_prefix='/news')#注册蓝图、网页浏览器地址多了前缀/news/

@app.route('/')
def hello_world():
    return 'hello world!'

if __name__ == '__main__':
    app.run(debug=true);

3.创建模型类,在model文件夹下新建新闻发布newspublished.py类

from app import db

class newspublished(db.model):
    #表名
    __tablename__ = 'news_published'
    #字段名
    news_id = db.column(db.integer, primary_key=true)
    news_title = db.column(db.string(50))
    news_content = db.column(db.string(255))

    def __repr__(self):
        return 'newspublished:%s %s %d' % (self.news_title, self.news_content, self.news_id)

#创建数据库
#删除所有的数据库
# db.drop_all()
#创建数据库
db.create_all()

注意,先运行newspublished.py创建数据库。查看数据库创建是否成功。可以看到已经生成表:news_published,并有三个字段。

4.创建视图,在templates新建publish_

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>新闻发布系统</title>
</head>
<body>
<h1>新闻发布系统</h1>
<form action="/news/news/" method="post">
    标题:<input type="text" name="news_title">
    <br>
    内容:<textarea style="width: 400px;height:100px" name="news_content"></textarea>
    <input type="submit" value="发布">
</form>
<table>
    {% if news %}
        <tr>
            <th>标题</th>
            <th>内容</th>
            <th>操作</th>
        </tr>
        {% for new in news %}
       <tr>
           <td>{{ new.news_title }}</td>
           <td>{{ new.news_content }}</td>
           <td style="width: 50px"><a href="{{ url_for("news.delete_new",news_id=new.news_id) }}">删除</a></td>
       </tr>
        {% endfor %}
     {% endif %}
</table>
</body>
</html>

5.实现控制器,在controller新建类newpublishedcontroller,让model和view连接,实现业务逻辑。

from flask import blueprint, render_template, redirect,request,url_for,flash
news_app = blueprint('news',__name__)
from app import db
from model.newspublished import newspublished

# 新闻系统发布路由
@news_app.route('/news/',methods=['get','post'])
def news_add():
    if request.method=='post':
        news_title_add=request.form.get('news_title',none)
        news_content_add=request.form.get('news_content',none)
        if not news_title_add or not news_content_add:
            return 'input error2'
        newsobj=newspublished(news_title=news_title_add,news_content=news_content_add)
        db.session.add(newsobj)
        db.session.commit()
        news=newspublished.query.all()
        return render_template('publish_',news=news)
    news = newspublished.query.all()
    return render_template('publish_',news=news)

# 删除新闻内容,需要传入news_id.
@news_app.route('/news/<news_id>')
def delete_new(news_id):
    #1.查询数据库,是否有新闻id,如果有就删除,没有就提示错误
    new=newspublished.query.get(news_id)
    #2.如果有就删除
    if new:
        try:
            #查询之后直接删除
            newspublished.query.filter_by(news_id=news_id).delete()
            db.session.delete(new)
            db.session.commit()
        except exception as e:
            print(e)
            flash('删除新闻出错')
            db.session.rollback()
        else:
            #3.没有就提示错误
            flash('没有新闻')
    return redirect(url_for('news.news_add'))

 

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网