烧瓶框架:MVC模式 [英] Flask-framework: MVC pattern

查看:77
本文介绍了烧瓶框架:MVC模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Flask框架自然支持MVC模式吗?我应该将应用程序的哪一部分视为模型,将什么视为视图,将什么视为控制器?

Does Flask framework support MVC pattern naturally? What the part of application should I consider as a model, what as a view and what as a controller?

通常(以我的经验),Flask应用程序看起来像这样:

Typically (in my experience) a Flask app looks like this:

main_dir--|
          |
         app1--|
          |    |
          |  __init__.py
          |  api.py
          |  models.py
          |
         static--|
          |      |
          |    all the static stuff
          |
         app.py # with blueprints registering

推荐答案

Flask实际上不是MVC框架.这是一个简约的框架,可为您提供许多自由的应用程序结构,但是MVC模式非常适合Flask提供的功能.

Flask is actually not an MVC framework. It is a minimalistic framework which gives you a lot of freedom in how you structure your application, but MVC pattern is a very good fit for what Flask provides.

基本上,您要编写方法并将其映射到特定的路线,例如:

Essentially you write your methods and map them to specific route, e.g.:

@app.route("/")
def hello():
    return "Hello World!"

如您所见,那里没有视图或模型.但是,它也是基于Jinja2模板库构建的,因此在实际的应用程序中,您的方法(充当控制器)如下所示:

No view or model there, as you can see. However, it is also built on top of Jinja2 template library, so in a realistic app, your method (which acts as a controller) looks like:

@app.route("/")
def hello():
    return render_template('index.html', username="John Doe")

在这里,您使用index.html模板呈现页面.这就是你的看法.

Here, you use index.html template to render the page. That is your view now.

Flask没有规定任何模型.您可以使用任何所需的东西-从复杂的对象模型(通常使用诸如SQLAlchemy之类的ORM)到满足您需求的最简单的东西.

Flask doesn't prescribe any model. You can use whatever you want - from complex object models (typically with using some ORM like SQLAlchemy) to simplest thing which fits your needs.

在那里,您已经拥有了:MVC

And there you have it: MVC

这篇关于烧瓶框架:MVC模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆