Flask还是Django? 深度比较| 第二部分

本文深入比较了Flask和Django两个流行的Web开发框架,涵盖了数据存储、视图、表单、测试及特色功能等方面,帮助开发者理解两者差异,为项目选择合适的技术栈。

Welcome back to the Flask or Django series. In Part One, we compared the two frameworks on the basis of their popularity, documentation and ease of getting started, routing system, and templating system. In Part Two, we're going to take a look at their:

欢迎回到Flask或Django系列。 在第一部分中 ,我们根据这两个框架的流行程度,文档和入门入门,路由系统和模板系统对它们进行了比较。 在第二部分中,我们将研究它们:

  1. Data Storage

    数据存储
  2. Views

    观看次数
  3. Forms

    形式
  4. Tests

    测验
  5. Interesting Features

    有趣的功能

Ready? Let's dive in!

准备? 让我们潜入吧!

数据存储 ( Data Storage )

Storing data is an essential part of any web application. There are several things for a developer to consider with regards to storing data. Of particular importance is the type of data to be stored, which informs the type of database that is best suited to store that data. Let's see what data storage options Flask and Django have.

存储数据是任何Web应用程序的重要组成部分。 在存储数据方面,开发人员需要考虑几件事。 尤为重要的是要存储的数据类型,它告知最适合存储该数据的数据库类型。 让我们看看Flask和Django有哪些数据存储选项。

烧瓶 (Flask)

连接到数据库 (Connecting to a database)

Flask does not support any particular database out of the box. This allows you to choose what kind of database you'd like to use, be it relational (SQL) or non-relational (NoSQL). The Flask documentation provides an example of how you can use an sqlite database with Flask.

Flask不支持开箱即用的任何特定数据库。 这使您可以选择要使用的数据库类型,无论是关系型(SQL)还是非关系型(NoSQL)。 Flask文档提供了有关如何在Flask中使用sqlite数据库的示例。

Flask has a number of great extensions (packages that extend Flask's functionality) that can make database connections much easier. One of the most popular ones is Flask-SQLALchemy, which allows us to use SQLAlchemy with Flask. SQLAlchemy is an Object Relational Mapper (ORM), which means that it connects the objects of an application to tables in a relational database management system.

Flask具有许多出色的扩展(扩展Flask功能的软件包),可以使数据库连接更加容易。 最受欢迎的工具之一是Flask-SQLALchemy ,它使我们可以将SQLAlchemy与Flask一起使用。 SQLAlchemy是一个对象关系映射器(ORM),这意味着它将应用程序的对象连接到关系数据库管理系统中的表。

You can also use Flask with popular NoSQL databases such as MongoDB. Flask-MongoAlchemy is the MongoDB equivalent of Flask-SQLAlchemy, and provides a user-friendly proxy between Flask and MongoDB. An alternative is Flask-PyMongo, which bridges Flask with PyMongo. PyMongo is recommended by MongoDB for Python projects.

您还可以将Flask与流行的NoSQL数据库(例如MongoDB)一起使用Flask-MongoAlchemy与MonskDB等效于Flask-SQLAlchemy,并在Flask和MongoDB之间提供了用户友好的代理。 另一种选择是Flask-PyMongo ,它将Flask与PyMongo桥接 。 MongoDB建议将PyMongo用于Python项目。

楷模 (Models)

Models are classes that represent database tables. It is not always necessary to have models in a Flask app. (However, if going the SQLAlchemy route, models are essential.) Models are convenient because you can include validation for data type, length, required fields, and unique fields. Here's an example based on Flask-SQLAlchemy. First, install the extension:

模型是代表数据库表的类。 在Flask应用中不一定总是有模型。 (但是,如果走SQLAlchemy路线,则模型是必不可少的。)模型很方便,因为您可以包括对数据类型,长度,必填字段和唯一字段的验证。 这是一个基于Flask-SQLAlchemy的示例。 首先,安装扩展:

$ pipinstall flask-sqlalchemy

Then, initialize SQLALchemy. Note that you must provide a database URI:

然后,初始化SQLALchemy。 请注意,您必须提供数据库URI:

# app/__init__.py

from flask_sqlalchemy import SQLAlchemy

# Initialize SQLAlchemy
app.config.update(dict(
    SQLALCHEMY_DATABASE_URI='sqlite:////tmp/database.db' # path to your database
))
db = SQLAlchemy()
db.init_app(app)

Next, create the model:

接下来,创建模型:

# app/models.py

from app import db


class User(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(60), index=True, unique=True)
    username = db.Column(db.String(60), index=True, unique=True)
    first_name = db.Column(db.String(60), index=True)
    last_name = db.Column(db.String(60), index=True)
移居 (Migrations)

When using models, it is important to have a way to manage changes in the code and implement them in the database. This is where migrations come in. If using SQLAlchemy, Alembic is the go-to migration tool as it was created specifically for use with SQLAlchemy. Some extensions which make using Alembic with Flask easier are Flask-Alembic and Flask-Migrate.

使用模型时,重要的是要有一种方法来管理代码中的更改并在数据库中实现它们。 这就是迁移的地方。如果使用SQLAlchemy,则Alembic是专门为与SQLAlchemy一起使用而创建的迁移工具。 使Flask-AlembicFlask-Migrate易于使用Alembic和Flask的一些扩展。

Django的 (Django)

连接到数据库 (Connecting to a database)

Django's default database engine is sqlite, which is automatically defined in the settings.py file. Django also creates a default sqlite database named db.sqlite3, which can be found in the app's root directory.

Django的默认数据库引擎是sqlite,它是在settings.py文件中自动定义的。 Django还创建了一个默认的sqlite数据库,名为db.sqlite3 ,可以在应用程序的根目录中找到。

# mysite/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

This can be changed to any other database backend, such as MySQL or PostgreSQL. You can also specify the user, password, hostname, and port, as seen in this example from the Django documentation:

可以将其更改为任何其他数据库后端,例如MySQL或PostgreSQL。 您还可以指定用户,密码,主机名和端口,如Django文档中的以下示例所示:

DATABASES= {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

You can also use Django with NoSQL databases by making use of third-party packages like Django MongoDB Engine.

您还可以通过使用第三方软件包(例如Django MongoDB Engine)将Django与NoSQL数据库一起使用。

楷模 (Models)

Models are an essential part of a Django app, so much so that one of the files created by the Django startapp command is a models.py file. Here's an example:

模型是Django应用程序的重要组成部分,以至于Django startapp命令创建的文件之一就是models.py文件。 这是一个例子:

# new_app/models.py

from __future__ import unicode_literals

from django.db import models

# Create your models here.


class User(models.Model):

    email = models.EmailField(max_length=60)
    username = models.CharField(max_length=60)
    first_name = models.CharField(max_length=60)
    last_name = models.CharField(max_length=60)

Models in Django allow you to select from various field types ranging from integers to emails and even file fields. You can also specify whether the field can be left blank or whether it must be unique. In Django, there is no need to specify an id field as there is an auto-incrementing primary key by default for each model. However, you can create your own primary key by adding a field with the primary_key=True parameter. To learn more about models in Django, visit the models documentation.

Django中的模型可让您从各种字段类型中进行选择,范围从整数到电子邮件甚至文件字段。 您也可以指定该字段可以保留为空白还是必须唯一。 在Django中,无需指定id字段,因为默认情况下每个模型都有一个自动递增的主键。 但是,您可以通过添加带有primary_key=True参数的字段来创建自己的主键。 要了解有关Django中模型的更多信息,请访问模型文档

移居 (Migrations)

Django handles database migrations out of the box without having to install any packages. If changes have been made to the models (or if your database hasn't been set up with tables yet), simply run the following commands to propagate them to the database:

Django无需开箱即用即可处理数据库迁移。 如果对模型进行了更改(或者尚未使用表设置数据库),只需运行以下命令即可将其传播到数据库:

$ python manage.py makemigrations
$ python manage.py migrate

To learn more aout Django migrations, visit the migrations documentation.

要了解有关Django迁移的更多信息,请访问迁移文档

观看次数 ( Views )

Views hold the logic of a web app, and are most often where the functionality of the app lies. They take in a web request and return a web response. Let's see how the two frameworks handle views.

视图具有Web应用程序的逻辑,并且通常位于应用程序功能所在的位置。 他们接受网络请求并返回网络响应。 让我们看看两个框架如何处理视图。

烧瓶 (Flask)

In Flask, there are two types of views: function-based views, and pluggable (class-based) views. Function-based views work with Flask's routing system, which we explored in Part One of this series under the Routing System section. The hello_world() function we wrote is an example of a function-based view. Another example would be:

在Flask中,有两种类型的视图:基于函数的视图和可插入(基于类)的视图。 基于函数的视图可用于Flask的路由系统,我们在本系列的第一部分“ 路由系统”部分中对此进行了探讨。 我们编写的hello_world()函数是基于函数的视图的示例。 另一个示例是:

# app/views.py

@app.route('/current-time')
def current_time():
    now = datetime.datetime.now()
    day = now.strftime("%B %d, %Y")
    time = now.strftime("%I:%M %p")
    return 'It is now ' + time + ' on ' + day + '.'

This view function displays a string that shows the current date and time:

此视图函数显示一个字符串,该字符串显示当前日期和时间:

Pluggable views were introduced in Flask 0.7, and are based on classes rather than functions. They are generally more flexible than function-based views. The view class must inherit from the flask.views.View class and implement the dispatch_request() method. The class must also include the add_url_rule() method. This method is used instead of the @app.route() decorator that is used in function-based views. The following code snippet converts the current_time() function we wrote earlier to a pluggable view:

可插入视图是在Flask 0.7中引入的,并且基于类而不是函数。 它们通常比基于函数的视图更灵活。 视图类必须从flask.views.View类继承,并实现dispatch_request()方法。 该类还必须包含add_url_rule()方法。 使用此方法代替在基于函数的视图中使用的@app.route()装饰器。 以下代码段将我们先前编写的current_time()函数转换为可插入视图:

# app/views.py

from flask.views import View

class CurrentTimeTwo(View):

    def dispatch_request(self):
        now = datetime.datetime.now()
        day = now.strftime("%B %d, %Y")
        time = now.strftime("%I:%M %p")
        return 'It is now ' + time + ' on ' + day + '.'


app.add_url_rule('/current-time-two', view_func=CurrentTimeTwo.as_view('current_time_two'))

This displays exactly what the previous view did:

这将准确显示上一个视图的操作:

To learn more about pluggable views in Flask, visit the documentation.

要了解有关Flask中可插拔视图的更多信息,请访问文档

Django的 (Django)

Django, too, has both function-based views and class-based views. Here's an example of the view we wrote in Flask, as a function-based Django view:

Django也同时具有基于函数的视图和基于类的视图。 这是我们在Flask中编写的视图的示例,它是基于函数的Django视图:

# new_app/views.py

def current_time(request):
    now = datetime.datetime.now()
    day = now.strftime("%B %d, %Y")
    time = now.strftime("%I:%M %p")
    return HttpResponse("It is now " + time + " on " + day + ".")

Once a view is written, it can then be mapped to a URL by including it in the urls.py file. Add the following to the urlpatterns list:

写入视图后,可以将其包含在urls.py文件中,然后将其映射到URL。 将以下内容添加到urlpatterns列表中:

# mysite/urls.py

from new_app import views

urlpatterns = [
    url(r'^current-time/$', views.current_time)
]

This is displayed as:

显示为:

Class-based views in Django usually include different methods within the class for different HTTP methods, such as GET and POST. They also help make code more reusable by implementing OOP techniques like inheritance. Making the current_time() function a class-based view is quite straighforward. Note that only the get() method is defined here:

Django中基于类的视图通常在类中针对不同的HTTP方法(例如GET和POST)包括不同的方法。 它们还通过实现诸如继承之类的OOP技术来帮助使代码更可重用。 使current_time()函数成为基于类的视图非常简单。 请注意,此处仅定义了get()方法:

# new_app/views.py

from django.views import View

class CurrentTimeTwo(View):

    def get(self, request):
        now = datetime.datetime.now()
        day = now.strftime("%B %d, %Y")
        time = now.strftime("%I:%M %p")
        return HttpResponse("It is now " + time + " on " + day + ".")
# mysite/urls.py

urlpatterns = [
    url(r'^current-time-two/$', views.CurrentTimeTwo.as_view())
]

Django has a few classes that class-based views can inherit from, to make the process of creating views much easier. One of them is, of course, the View class that we've already seen above, inherited by the CurrentTimeTwo class. Others include:

Django有一些可以从基于类的视图继承的类,从而使创建视图的过程变得更加容易。 当然,其中之一是上面已经看到的View类,它是由CurrentTimeTwo类继承的。 其他包括:

  • TemplateView: we saw this class in Part One of this tutorial when displaying a template in Django. Template views render a particular template, which is specified in the template_name attribute. To learn more about this class, visit the documentation.

    TemplateView :在Django中显示模板时,我们在本教程的第一部分中看到了此类。 模板视图呈现特定的模板,该template_nametemplate_name属性中指定。 要了解有关此类的更多信息,请访问文档
  • RedirectView: as the name implies, views that inherit from this class redirect the app to a particular URL, which is specified in the pattern_name attribute. To learn more about this class, visit the documentation.

    RedirectView :顾名思义,从此类继承的视图会将应用程序重定向到特定的URL,该URL在pattern_name属性中指定。 要了解有关此类的更多信息,请访问文档
  • Generic display views: these are Django classes that a view inherits from to display data based on a model. They include DetailView, which presents the details of a particular model object, and ListView, which presents a list of model objects. In both cases, the model is specifed. To learn more about generic display views, visit the documentation.

    通用显示视图:这些是视图继承的Django类,用于显示基于模型的数据。 它们包括提供特定模型对象详细信息的DetailView和提供模型对象列表的ListView 。 在两种情况下,都指定了模型。 要了解有关通用显示视图的更多信息,请访问文档

形式 ( Forms )

Forms allow a web app to accept user input from the front end. In this section, we'll see how both Flask and Django handle forms.

表单允许Web应用程序从前端接受用户输入。 在本节中,我们将看到Flask和Django如何处理表单。

烧瓶 (Flask)

Flask doesn't have any support for forms out of the box. However, as is usually the case, there are extensions that come in to save the day. A fantastic option is Flask-WTF, which makes the process much easier. Flask-WTF integrates Flask with WTForms, a Python package that handles form input handling and validation.

Flask对表单不提供任何支持。 但是,通常情况下,会有一些扩展程序可以节省时间。 Flask-WTF是一个很棒的选择,它使处理过程更加容易。 Flask-WTF将Flask与WTForms集成在一起, WTForms是一个处理表单输入处理和验证的Python包。

To create a form, create a new file, forms.py in your app directory. The following is a sign up form, which we can use to create a new user based on the User model we created earlier:

要创建表单, forms.py在您的应用目录中创建一个新文件forms.py 。 以下是注册表单,我们可以使用该表单基于我们之前创建的User模型来创建新用户:

# app/forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.fields.html5 import EmailField
from wtforms.validators import DataRequired, Email


class SignUp(FlaskForm):
    email = EmailField('Email', validators=[DataRequired(), Email()])
    username = StringField('Username', validators=[DataRequired()])
    first_name = StringField('First Name', validators=[DataRequired()])
    last_name = StringField('Last Name', validators=[DataRequired()])
    submit = SubmitField('Sign In')

Using WTForms allows us to easily handle field validation. Note that there are a variety of field types that you can specify, including EmailField, StringField, and SubmitField, as well as validators. You can find more in the WTForms fields documentation. Once the form is done, you need to add a view to process the user input:

使用WTForms可以使我们轻松地进行现场验证。 请注意,您可以指定多种字段类型,包括EmailFieldStringFieldSubmitField以及验证器。 您可以在WTForms 字段文档中找到更多信息 。 表单完成后,您需要添加一个视图来处理用户输入:

# app/views.py

from app import app, db

from .forms import SignUp
from .models import User

@app.route('/signup', methods=["GET", "POST"])
def signup():
    form = SignUp()
    if form.validate_on_submit():
        user = User(email=form.email.data,
                    username=form.username.data,
                    first_name=form.first_name.data,
                    last_name=form.last_name.data)
        db.session.add(user)
        db.session.commit()
        return 'Success!'
    return render_template('signup.html', form=form)

The view above gets the data from the form and uses it to create a User object which is then added to the database. It then returns a simple success message.

上面的视图从表单获取数据,并使用它来创建User对象,然后将其添加到数据库中。 然后,它返回一条简单的成功消息。

The final step to incorporating the form is including it in a template so users can see it and fill in their data. As you can see in the view above, we specified the template to be signup.html, so let's go ahead and create it:

合并表单的最后一步是将其包含在模板中,以便用户可以看到它并填写其数据。 如您在上面的视图中看到的,我们将模板指定为signup.html ,所以让我们继续创建它:

<!-- app/templates/signup.html -->

<html>
    <head>
        <title>Sign Up Page</title>
    </head>
    <body>
        <h1>Fill out the form below to sign up</h1>
        <br/>
        <form action="{{ url_for('signup') }}" method="post">
            <p>
              {{ form.email.label }}<br>
              {{ form.email }}
            </p>
            <p>
              {{ form.username.label }}<br>
              {{ form.username }}
            </p>
            <p>
              {{ form.first_name.label }}<br>
              {{ form.first_name }}
            </p>
            <p>
              {{ form.last_name.label }}<br>
              {{ form.last_name }}
            </p>
            <p>
              {{ form.submit() }}
            </p>
            {{ form.csrf_token }}
        </form>
    </body>
</html>

And lastly, to make use of Flask-WTF's Cross-Site Request Forgery (CSRF) protection feature, we need to include a secret key in the Flask configuration:

最后,要使用Flask-WTF的跨站请求伪造(CSRF)保护功能,我们需要在Flask配置中包括一个秘密密钥:

# app/__init__.py

app.config.update(dict(
    SQLALCHEMY_DATABASE_URI='sqlite:////tmp/database.db',
    SECRET_KEY="your secret key here" # add this line
))

Now, run the Flask app and navigate to http://127.0.0.1:5000/signup. You should see a simple, but perfectly functional form. If the specified database exists and has the User table and all its fields, then filling the form out should add a new user to the database.

现在,运行Flask应用并导航至http://127.0.0.1:5000/signup 。 您应该看到一个简单但功能完善的表格。 如果指定的数据库存在并且具有User表及其所有字段,则填写表格应将新用户添加到数据库中。

Django的 (Django)

Right out of the box, Django takes care of forms without the need to install any third-party packages. This includes processing submitted data from the front-end. Similar to Flask, working with forms in Django involves writing the form code, creating a view, and displaying the form in a template. To begin, create a forms.py file in the new_app directory.

Django即开即用,无需安装任何第三方软件包即可处理表格。 这包括处理前端提交的数据。 与Flask相似,在Django中使用表单涉及编写表单代码,创建视图以及在模板中显示表单。 首先,在new_app目录中创建一个forms.py文件。

Now, forms in Django can be manually configured, or based on a model. Manually configured forms inherit from Django's form.Form class, and are best used when the data being received is not tied to a model. A good example of this would be a contact form, as seen below:

现在,可以手动配置Django中的表单或基于模型。 手动配置的表单继承自Django的form.Form类,当接收的数据未与模型绑定时,最好使用该表单。 一个很好的例子是联系表格,如下所示:

# new_app/forms.py

from django import forms

class ContactForm(forms.Form):
    email = forms.EmailField(label='Your Email Address', required=True)
    subject = forms.CharField(label='Subject', max_length=100)
    message = forms.CharField(label='Your Message', required=True)

Forms based on Django models inherit from the form.ModelForm class. These are best used when the data received through the form will be inserted into a database table based on a Django model. Here's an example based on our User model:

基于Django模型的表单继承自form.ModelForm类。 当通过表单接收的数据将插入基于Django模型的数据库表中时,最好使用这些方法。 这是一个基于我们的用户模型的示例:

# new_app/forms.py

from .models import User

class SignUpForm(forms.ModelForm):

    class Meta:

        model = User
        fields = ('email', 'username', 'first_name', 'last_name')

As we saw in Flask (courtesy of the WTForms package), Django too allows us to use a variety of field types and validators. More on this can be found in the field classes documentation and the validators documentation.

正如我们在Flask中看到的(由WTForms包提供),Django也允许我们使用多种字段类型和验证器。 有关更多信息,请参见字段类文档验证程序文档

Now, to process our form, we need to create a view. Below I have created a function-based view:

现在,要处理表单,我们需要创建一个视图。 下面,我创建了一个基于函数的视图:

# new_app/views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import SignUpForm


def sign_up(request):
    form = SignUpForm(request.POST)

    if form.is_valid():
        user = form.save(commit=False)
        user.email = request.POST.get('email')
        user.username = request.POST.get('username')
        user.first_name = request.POST.get('first_name')
        user.last_name = request.POST.get('last_name')
        user.save()
        return HttpResponse("Success!")
    context = {'form': form}
    return render(request, 'signup.html', context)

The view takes the form data and uses it to populate a new user object, which is then saved. Again, a simple success message is returned. Now, let's create a simple template to display the form:

该视图采用表单数据,并使用其填充新的用户对象,然后将其保存。 同样,返回一条简单的成功消息。 现在,让我们创建一个简单的模板来显示表单:

<!-- new_app/templates/signup.html -->

<html>
    <head>
        <title>Sign Up Page</title>
    </head>
    <body>
        <h1>Fill out the form below to sign up</h1>
        <br/>
        <form action="{% url 'signup' %}" method="post">
            {% csrf_token %}
            {{ form }}
            <input type="submit" value="Submit" />
    </form>
    </body>
</html>

And lastly, let's create the signup URL to display the template. Add the following to the urlpatterns list:

最后,让我们创建signup URL以显示模板。 将以下内容添加到urlpatterns列表中:

# mysite/urls.py

urlpatterns = [
    url(r'^signup/$', views.sign_up, name='signup')
]

Now, run the Django app and navigate to http://127.0.0.1:8000/signup. Again, you should see a simple, but functional sign up form. If you have properly set up your database by making migrations, then filling the form out should add a new user to the User table.

现在,运行Django应用并导航至http://127.0.0.1:8000/signup 。 同样,您应该看到一个简单但实​​用的注册表单。 如果通过迁移正确地设置了数据库,则填写表格应在User表中添加一个新用户。

测验 ( Tests )

Tests are extremely important in software development. They help you ensure your code works as expected, and also catch any unexpected effects of changes to your code. In this section, I will give a brief overview of testing in both Flask and Django.

测试在软件开发中非常重要。 它们可以帮助您确保您的代码按预期工作,并且还可以捕获代码更改的任何意外影响。 在本节中,我将简要介绍Flask和Django中的测试。

烧瓶 (Flask)

Flask makes use of Werkzeug, a WSGI (protocol that ensures web apps and web servers can communicate effectively) utility library for Python. It's one of the Python packages that is installed when you first install Flask. During testing, Flask exposes the Werkzeug test client. This is useful because it allows you to send virtual requests to the Flask app. For this to work, it's extremely important that the TESTING configuration variable is set to True.

Flask利用了Werkzeug (一种适用于Python的WSGI(确保Web应用程序和Web服务器能够有效通信的协议))实用程序库。 这是您首次安装Flask时安装的Python软件包之一。 在测试过程中,Flask公开了Werkzeug测试客户端。 这很有用,因为它允许您将虚拟请求发送到Flask应用。 为此,将TESTING配置变量设置为True极为重要。

Once that's done, it's up to you to select the tools and frameworks that you'll use to write and run your tests. The choices are many, but personally, I have found much success with the Flask-Testing extension, used in conjuction with nose2 for running the tests. Note that you also need to create a test database. For an example of how I use Flask-Testing and nose2 for my Flask tests, please take a look at this article.

完成后,由您来选择用于编写和运行测试的工具和框架。 选择有很多,但就个人而言,我发现Flask-Testing扩展非常成功,该扩展与鼻子2一起用于运行测试。 请注意,您还需要创建一个测试数据库。 有关如何在Flask测试中使用Flask-Testing和鼻子2的示例,请查看本文

You can also visit the Flask testing documentation for more information and examples of testing in Flask.

您也可以访问Flask 测试文档,以获取更多信息和Flask中的测试示例。

Django的 (Django)

Django has a test class, django.test.TestCase, which inherits from Python's unittest.TestCase class. You should inherit from Django's test class when creating your own test classes. Tests can be created in the pre-generated tests.py file, like so:

Django有一个测试类django.test.TestCase ,它继承自Python的unittest.TestCase类。 创建自己的测试类时,您应该继承Django的测试类。 可以在预先生成的tests.py文件中创建测试,如下所示:

# new_app/tests.py

from django.test import TestCase
from .models import User

# Create your tests here.


class MyTest(TestCase):
    def setUp(self):
        """
        This method is run before each test
        """
        User.objects.create(
            email="test@user.com",
            username="testuser",
            first_name="Test",
            last_name="User")

    def test_user_count(self):
        """
        Test number of users in the database
        """
        self.assertEqual(User.objects.count(), 1)

In Django, tests can be run using this command:

在Django中,可以使用以下命令运行测试:

$ python manage.pytest
Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Destroying test database for alias 'default'...

Any file beginning with test and ending with a .py extension will be detected. The test command will run any test methods contained in the detected test files, as long as the methods also begin with test. You can also specify which tests will be run by module, package, class, or even method. Note that Django automatically creates a blank test database, and then destroys it after running the tests. To learn more about tests in Django, visit the testing documentation.

将检测到任何以test开头并以.py扩展名结尾的文件。 只要test方法也以test开头,那么test命令将运行包含在检测到的测试文件中的所有测试方法。 您还可以指定将由模块,包,类甚至方法运行的测试。 请注意,Django自动创建一个空白测试数据库,然后在运行测试后销毁它。 要了解有关Django中测试的更多信息,请访问测试文档

有趣的功能 ( Interesting Features )

Both Flask and Django have features that are interesting and worth knowing about. Some are also unique to their particular framework. Let's take a look at some of them!

Flask和Django都具有有趣且值得了解的功能。 有些也对于它们的特定框架是唯一的。 让我们来看看其中的一些!

烧瓶 (Flask)

烧瓶壳 (Flask Shell)

You can run an interactive Python shell based on your Flask app. To use it, simply specify the Flask application using the FLASK_APP environment variable, and then run the flask shell command:

您可以基于Flask应用程序运行交互式Python Shell。 要使用它,只需使用FLASK_APP环境变量指定Flask应用程序,然后运行flask shell命令:

$export FLASK_APP = app.py
$ flask shell
Python 3.6.0 (default, Dec 24 2016, 00:01:50)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
App: app [debug]
Instance: /home/user/Projects/flask-app/instance
>>>

Using the Flask shell, you can explore your app via command line, and even add, edit and delete data in the database:

使用Flask Shell,您可以通过命令行浏览应用程序,甚至可以添加,编辑和删除数据库中的数据:

$ flask shell>>> from app.models import User
>>> from app import db
>>> user = User(email="jane.doe@email.com", username="jane.doe", first_name="Jane", last_name="Doe")
>>> db.session.add(user)
>>> db.session.commit()
烧瓶扩展 (Flask Extensions)

We've talked extensively (haha) about various Flask extensions in this tutorial, so by now you know just how useful they are in your Flask journey. Flask has a handy extensions registry, so feel free to peruse it to find new extensions you can make use of in your projects! And if you're so inclined, there's also some guidance on how to develop your very own Flask extension - check it out here!

在本教程中,我们已经广泛讨论(各种)Flask扩展,因此,现在您知道它们在Flask旅程中有多么有用。 Flask有一个方便的扩展程序注册表 ,因此可以细读它以找到可以在您的项目中使用的新扩展程序! 而且,如果您如此愿意,还有一些有关如何开发自己的Flask扩展的指南- 在此处查看

Django的 (Django)

Django管理员 (Django Admin)

Django ships with an admin interface that allows you to manage the data of your app. To access the admin site, start up your Django app and then navigate to http://127.0.0.1:8000/admin. You'll be presented with a login screen.

Django随附了一个管理界面,可让您管理应用程序的数据。 要访问管理站点,请启动Django应用,然后导航至http://127.0.0.1:8000/admin 。 您将看到一个登录屏幕。

You'll need to create a superuser to be able to login to the admin site, which you can do using the createsuperuser command:

您需要创建一个超级用户才能登录到管理站点,您可以使用createsuperuser命令执行此操作:

$ python manage.py createsuperuser

The command willl prompt you to select a username, email, and password which you can then use to login.

该命令将提示您选择用户名,电子邮件和密码,然后可以使用它们来登录。

To add a model to the admin interface, open up the admin.py file in your app folder and register it as follows:

要将模型添加到管理界面,请在您的应用文件夹中打开admin.py文件,并按如下所示进行注册:

from django.contrib import admin
from .models import User

# Register your models here.
admin.site.register(User)

Now we can view the User model in the admin interface and even add a new entry:

现在,我们可以在管理界面中查看用户模型,甚至添加一个新条目:

Django软件包 (Django Packages)

By now you have probably realised that Django comes with a lot more features out of the box than Flask, which is why we haven't talked very much about third party Django packages in this tutorial. However, they do exist and can be quite useful if, like myself, you are averse to reinventing the wheel. Although there is no official Django packages registry, there is a site, https://djangopackages.org/, that lists various packages in various categories. Note that it was created and is run independently of the Django Software Foundation (the organization that develops and maintains Django).

到现在为止,您可能已经意识到Django提供了比Flask更多的功能,这就是为什么我们在本教程中没有过多谈论第三方Django软件包的原因。 但是,它们确实存在,并且如果像我一样反对重新发明轮子,它们可能会非常有用。 尽管没有官方的Django软件包注册中心,但是有一个网站https://djangopackages.org/ ,其中列出了各种类别的各种软件包。 请注意,它是独立于Django软件基金会(开发和维护Django的组织)创建和运行的。

结论 ( Conclusion )

And it's a wrap! Now that you've read both Part One and Part Two of this series, you should know a lot more about both Flask and Django. And of course, you now have a clear and in-depth understanding of how the two frameworks compare, which means you are in a better position to choose one of them for your next web project. I'm looking forward to hearing your comments on this series, so feel free to share your thoughts in the comments below. Thanks for reading!

这是一个包裹! 现在,您已经阅读了本系列的第1部分和第2部分,您应该对Flask和Django都有更多的了解。 当然,您现在对这两个框架的比较有了清晰而深入的了解,这意味着您可以为下一个Web项目选择一个更好的位置。 我很期待听到您对本系列的评论,请随时在下面的评论中分享您的想法。 谢谢阅读!

翻译自: https://scotch.io/tutorials/flask-or-django-an-in-depth-comparison-part-two

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值