python设计模式–mvc控制模式

3,758次阅读
没有评论

共计 3246 个字符,预计需要花费 9 分钟才能阅读完成。

从自身的了解来看mvc模式,这个很久以前写GUI的时候用的最多了 model view controller,模型视图控制器,通过这样的方式实现前端视觉与模型分离,视图只要管自己的显示就好了,着重与用户的交互,model负责后台的数据以及相关的业务逻辑处理,中间的controller在模型更改时更新对应的视图,也可以做一些在数据由模型传递给视图之前做一些处理。

python设计模式--mvc控制模式

之前使用过flask写过一个小网站,用的方式也是mvc的方式,model主要来定义后台各种数据模型,controller主要是一些视图函数,用来从数据库查询各种数据并处理,感觉这个其实是控制器与model混合在一起了,视图就是前端各种html页面。

quotes = ('A man is not complete until he is married. Then he is finished.',
          'As I said before, I never repeat myself.',
          'Behind a successful man is an exhausted woman.',
          'Black holes really suck...', 'Facts are stubborn things.')


class QuoteModel:

    def get_quote(self, n):
        try:
            value = quotes[n]
        except IndexError as err:
            value = 'Not found!'
        return value


class QuoteTerminalView:

    def show(self, quote):
        print('And the quote is: "{}"'.format(quote))

    def error(self, msg):
        print('Error: {}'.format(msg))

    def select_quote(self):
        return input('Which quote number would you like to see?')


class QuoteTerminalController:

    def __init__(self):
        self.model = QuoteModel()
        self.view = QuoteTerminalView()

    def run(self):
        valid_input = False
        while not valid_input:
            n = self.view.select_quote()
            try:
                n = int(n)
            except ValueError as err:
                self.view.error("Incorrect index '{}'".format(n))
            else:
                valid_input = True
        quote = self.model.get_quote(n)
        self.view.show(quote)


def main():
    controller = QuoteTerminalController()
    while True:
        controller.run()

if __name__ == '__main__':
    main()

上面这个例子是完全按照mvc的demo,截一段之前写的网站代码片段

class MoUser(UserMixin, db.Model):
    """
    用户基础表
    """
    __tablename__ = 'mo_users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50))
    email = db.Column(db.String(50), unique=True, index=True)
    password_hash = db.Column(db.String(255))
    avatar_hash = db.Column(db.String(32))
    avatar_origin_url=db.Column(db.String(50))
    avatar_thumbnail_url = db.Column(db.String(50))
    create_time = db.Column(db.DATETIME, index=True, default=datetime.utcnow)
    qq_str = db.Column(db.String(15))
    github_str = db.Column(db.String(30))
    weibo_str = db.Column(db.String(30))
    telegram_str = db.Column(db.String(30))
    weixin_str = db.Column(db.String(30))
    about_you = db.Column(db.Text, default=None)
    post_id = db.relationship('MolifePost', backref='user_id', lazy='dynamic')

    def __init__(self, **kwargs):
        super(MoUser, self).__init__(**kwargs)
        if self.email is not None and self.avatar_hash is None:
            self.avatar_hash = hashlib.md5(
                self.email.encode('utf-8')).hexdigest()
#视图函数
@admin.route('/uploads/')
def uploaded_file(filename):
    return send_from_directory(current_app.config['UPLOADED_PHOTOS_DEST'],
                               filename)


@admin.route('/upload', methods=['GET', 'POST'])
@login_required
def upload():
    if request.method == 'POST':
        for file in request.files.getlist('file'):
            _, ext = file.filename.split('.')
            filename_hash = hashlib.md5('molife' + str(time.time())).hexdigest()[:15]
            filename = str(filename_hash) + '.' + ext
            file.save(os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'], filename))
            file_url = url_for('admin.uploaded_file', filename=filename)
            file_thumb_url = create_thumbnail(filename)
            momedia = MolifeMedia(filename=filename, orign_url=file_url, thumbnail_url=file_thumb_url)
            db.session.add(momedia)
        db.session.commit()
        return redirect(url_for('admin.manage_media'))

    return render_template('admin/mo-upload-media.html')


@admin.route('/manage_media', methods=['GET', 'POST'])
@login_required
def manage_media():
    momedia = MolifeMedia.query.all()

    return render_template('admin/mo-manage-media.html', momedia=momedia)

在到前端hitml了,这里就不展示前端代码了,比较长。。。。

总结

mvc实际上实现了前后端分离的思想,各干各的事,模型就做好数据相关的处理,前端view做好与用户的交互就好了,需要更新时通知控制器来实现模型的更新之类 。

正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2018-08-12发表,共计3246字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码