django 最佳实践

by Ofir Chakon

由Ofir Chakon

通过这些最佳实践来改进Django项目 (Improve your Django project with these best practices)

Django is a robust, open-source, Python-based framework for building web applications. Its popularity has increased during the last couple of years, and it is already mature and widely-used with a large community behind it.

Django是一个健壮的,基于Python的开源框架,用于构建Web应用程序。 在过去的几年中,它的受欢迎程度有所增加,并且它已经成熟并且在其背后的大型社区中得到了广泛的使用。

Among other Python-based frameworks for creating web applications (like Flask and Pyramid), Django is by far the most popular. It supports both Python version 2.7 and Python 3.6. But at the time of this article, Python 2.7 is still the more accessible version in terms of community, third party packages, and online documentation. Django is secure when used properly, and provides high dimensions of flexibility. It is the way to go when developing server-side applications using Python.

在其他用于创建Web应用程序的基于Python的框架(例如Flask和Pyramid)中,Django是迄今为止最受欢迎的框架。 它同时支持python版本2.7和Python 3.6。 但是在撰写本文时,就社区,第三方软件包和在线文档而言,Python 2.7仍然是更易于访问的版本。 正确使用Django是安全的,并提供高度的灵活性。 这是使用Python开发服务器端应用程序时要走的路。

As an experienced Python and Django developer, I will share with you some best practices for a Django setup that I’ve learned and collected over the years. Whether you have a few Django projects under your belt, or you’re just about to start your first one from scratch, the best practices described here might help you create better applications down the road.

作为经验丰富的Python和Django开发人员,我将与您分享一些我多年来学习和收集的Django设置最佳实践。 无论您有几个Django项目,还是打算从头开始第一个项目,此处介绍的最佳实践都可以帮助您在将来创建更好的应用程序。

I wrote this article from a very practical mindset so that you can add some tools to your development toolbox immediately. You can even create an advanced custom Django boilerplate for your next projects.

我是从非常实际的心态写这篇文章的,以便您可以立即将一些工具添加到开发工具箱中。 您甚至可以为下一个项目创建高级自定义Django样板。

For the purpose of this article, I assume you’re using a Linux Ubuntu machine. Throughout the article, some code lines start with a $ sign. These are used to emphasize that this line should be inserted into the terminal. Make sure to copy the line without the $ sign.

就本文而言,我假设您使用的是Linux Ubuntu计算机。 在本文中,某些代码行以$符号开头。 这些用于强调应将此线插入终端。 确保复制没有 $符号的行。

虚拟环境 (Virtual Environment)

While developing Python-based applications, using third party packages is an ongoing thing. These packages are updated often, so keeping them organized is essential. When developing more and more projects on the same local machine, it’s challenging to keep track of the current version of each package. It’s impossible to use different versions of the same package for different projects. Moreover, updating a package on one project might break functionality on another, and vice versa.

在开发基于Python的应用程序时,使用第三方程序包是一件持续的事情。 这些软件包经常更新,因此使它们井井有条至关重要。 在同一台本地计算机上开发越来越多的项目时,跟踪每个软件包的当前版本是一项挑战。 对于不同的项目,不可能使用同一软件包的不同版本。 此外,在一个项目上更新程序包可能会破坏另一个项目上的功能,反之亦然。

That’s where Python Virtual Environment comes handy. To install virtual environment use:

这就是Python虚拟环境派上用场的地方。 要安装虚拟环境,请使用:

$ apt-get update
$ apt-get install python-pip python-dev build-essential$ export LC_ALL="en_US.UTF-8" # might be necessary in case you get an error from the next line$ pip install --upgrade pip
$ pip install --upgrade virtualenv
$ mkdir ~/.virtualenvs
$ pip install virtualenvwrapper
$ export WORKON_HOME=~/.virtualenvs
$ nano ~/.bashrc

Add this line to the end of the file:

将此行添加到文件末尾:

. /usr/local/bin/virtualenvwrapper.sh

Then execute:

然后执行:

$ . .bashrc

After installing, create a new virtual environment for your project by typing:

安装后,通过键入以下内容为项目创建一个新的虚拟环境:

$ mkvirtualenv project_name

While you’re in the context of your virtual environment, you’ll notice that a prefix is added to the terminal, like:

在虚拟环境中时,您会注意到前缀已添加到终端,例如:

(project_name) ofir@playground:~$

In order to deactivate (exit) the virtual environment and get back to the main Python context of your local machine, use:

为了停用(退出)虚拟环境并返回本地计算机的主要Python上下文,请使用:

$ deactivate

In order to activate (start) the virtual environment context, use:

为了激活(启动)虚拟环境上下文,请使用:

$ workon project_name

To list the virtual environments existing in your local machine, use:

要列出本地计算机中现有的虚拟环境,请使用:

$ lsvirtualenv

Holding your project dependencies (packages) in a virtual environment on your machine allows you to keep them in an isolated environment. You only use them for a single (or multiple) projects. When creating a new virtual environment, you’re starting a fresh environment with no packages installed in it. Then you can use, for example:

将项目依赖项(程序包)保存在计算机上的虚拟环境中可以使您将它们保持在隔离的环境中。 您仅将它们用于单个(或多个)项目。 创建新的虚拟环境时,您将启动一个没有安装任何软件包的全新环境。 然后,您可以使用例如:

(project_name) $ pip install Django

for installing Django in your virtual environment, or:

用于在您的虚拟环境中安装Django,或:

(project_name) $ pip install Django==1.11

for installing version 1.11 of Django accessible only from within the environment.

用于安装只能从环境内部访问的Django 1.11版本。

Neither your main Python interpreter nor the other virtual environments on your machine will be able to access the new Django package you’ve just installed.

您的主Python解释器或计算机上的其他虚拟环境都将无法访问您刚安装的新Django软件包。

In order to use the runserver command using your virtual environment, while in the context of the virtual environment, use:

为了在您的虚拟环境中使用runserver命令,请在虚拟环境中使用:

(project_name) $ cd /path/to/django/project
(project_name) $ ./manage.py runserver

Likewise, when entering the Python interpreter from within the virtual environment, type:

同样,在虚拟环境中输入Python解释器时,键入:

(project_name) $ python

It will have access to packages you’ve already installed inside the environment.

它可以访问您已经在环境中安装的软件包。

要求 (Requirements)

Requirements are the list of Python packages (dependencies) your project is using while it runs, including the version for each package. Here’s an example for a requirements.txt file:

要求是您的项目在运行时使用的Python软件包(依赖项)的列表,包括每个软件包的版本。 这是requirements.txt文件的示例:

dicttoxml==1.7.4
Django==1.11.2
h5py==2.7.0
matplotlib==2.0.2
numpy==1.13.0
Pillow==4.1.1
psycopg2==2.7.1
pyparsing==2.2.0
python-dateutil==2.6.0
pytz==2017.2
six==1.10.0
xmltodict==0.11.0

Keeping your requirements.txt file up to date is essential for collaborating properly with other developers. It’s also important for keeping your production environment properly configured. This file, when included in your code repository, enables you to update all the packages installed in your virtual environment by executing a single line in the terminal. Then you can get new developers up and running in no time.

与其他开发人员进行正确协作时,保持您的requirements.txt文件为最新状态至关重要。 这对于保持正确配置生产环境也很重要。 当此文件包含在代码存储库中时,使您可以通过在终端中执行一行来更新虚拟环境中安装的所有软件包。 然后,您可以立即启动新的开发人员并使其运行。

In order to generate a new requirements.txt or to update an existing one, use from within your virtual environment:

为了生成新的requirements.txt或更新现有的requirements.txt ,请在您的虚拟环境中使用:

(project_name) $ pip freeze > requirements.txt

For your convenience, make sure to execute this command in a folder that is being tracked by your Git repository. This allows other instances of the code to have access to the requirements.txt file as well.

为了您的方便,请确保在Git存储库正在跟踪的文件夹中执行此命令。 这样,其他代码实例也可以访问requirements.txt文件。

If a new developer joins the team, or if you want to configure a new environment using the same packages listed in the requirements.txt file, execute in the virtual environment context:

如果有新开发人员加入团队,或者您要使用requirements.txt文件中列出的相同程序包配置新环境,请在虚拟环境上下文中执行:

(project_name) $ cd /path/to/requirements/file
(project_name) $ pip install -r requirements.txt

All requirements listed in the file will immediately be installed in your virtual environment. Older versions will be updated and newer versions will be downgraded to fit the exact list of requirements.txt. Be careful though — there might be differences between environments that you still want to respect.

文件中列出的所有要求将立即安装在您的虚拟环境中。 较旧的版本将被更新,而较新的版本将被降级以符合requirements.txt的确切列表。 但是请小心-您仍然要尊重的环境之间可能存在差异。

I highly recommend integrating these commands to your work flow. Update the requirements.txt file before pushing code to the repository and install requirements.txt file after pulling code from the repository.

我强烈建议将这些命令集成到您的工作流程中。 在将代码推送到存储库之前,先更新requirements.txt文件,然后从存储库中提取代码后再安装requirements.txt文件。

更好的settings.py配置 (Better settings.py configuration)

Django comes out-of-the-box with a very basic yet useful settings.py file. This defines the main and most useful configurations for your project. The settings.py file is very straightforward. But sometimes, as a developer working on a team, or when setting up a production environment, you need more than one basic settings.py file.

Django开箱即用,带有一个非常基本但有用的settings.py文件。 这定义了项目的主要和最有用的配置。 settings.py文件非常简单。 但是有时,作为开发人员在团队中工作或设置生产环境时,您需要多个基本的settings.py文件。

Multiple settings files allow you to easily define tailor-made configurations for each environment separately like:

多个设置文件使您可以轻松地分别为每个环境定义量身定制的配置,例如:

ALLOWED_HOSTS # for production environment
DEBUG
DATABASES # for different developers on the same team

Let me introduce you to an extended approach for configuring your settings.py file. It allows you to maintain different versions and use the one you want at any given time and in any environment.

让我向您介绍一种用于配置settings.py文件的扩展方法。 它允许您维护不同的版本,并在任何给定的时间和任何环境中使用所需的版本。

First, navigate to your settings.py file path:

首先,浏览至settings.py文件路径:

(project_name) $ cd /path/to/settings/file

Then create a new module called settings (module is a folder containing an __init__.py file):

然后创建一个名为设置的新模块(模块是一个包含__init__.py文件的文件夹):

(project_name) $ mkdir settings

Now, rename your settings.py file to base.py and place it inside the new module you created:

现在,将您的settings.py文件重命名为base.py并将其放置在您创建的新模块中:

(project_name) $ mv settings.py settings/base.py

For this example, I assume that you want to configure one settings file for your development environment and one for your production environment. Different developers on the same team can use the exact same approach for defining different settings files.

对于此示例,我假设您要为开发环境配置一个设置文件,为生产环境配置一个设置文件。 同一团队中的不同开发人员可以使用完全相同的方法来定义不同的设置文件。

For your development environment create:

为您的开发环境创建:

(project_name) $ nano settings/development.py

Then type:

然后输入:

from .base import *DEBUG = True

and save the file by hitting Ctrl + O, Enter and then Ctrl + X.

并按Ctrl + O ,按Enter,然后Ctrl + X保存文件。

For your production environment create:

为您的生产环境创建:

(project_name) $ nano settings/production.py

and type:

并输入:

from .base import *DEBUG = False
ALLOWED_HOSTS = [‘app.project_name.com’, ]

Now, whenever you want to add or update the settings of a specific environment, you can easily do it in its own settings file.

现在,无论何时要添加或更新特定环境的设置,都可以在其自己的设置文件中轻松进行。

You might be wondering — how does Django know which settings file to load on each environment? That’s what the __init__.py file is used for. When Django looks for the settings.py it used to load when running the server, for example, it now finds a settings module rather than a settings.py file. But as long as it’s a module containing an __init__.py file, as far as Django is concerned, it’s the exact same thing. Django will load the __init__.py file and execute whatever is written in it.

您可能想知道-Django如何知道在每个环境中加载哪个设置文件? 这就是__init__.py文件的用途。 例如,当Django查找运行服务器时用于加载的settings.py时,它现在会找到一个设置模块,而不是settings.py文件。 但是,只要它是一个包含__init__.py文件的模块,就Django而言,它是完全一样的。 Django将加载__init__.py文件并执行其中写入的所有内容。

Therefore, we need to define which settings file we want to load inside the __init__.py file by executing:

因此,我们需要通过执行以下操作来定义要在__init__.py文件中加载的设置文件:

(project_name) $ settings/__init__.py

and then, for a production environment, for example, by typing:

然后针对生产环境,例如,键入:

from .production import *

This way, Django will load all the base.py and production.py settings every time it starts. Magic?

这样,Django每次启动时都会加载所有base.py和production.py设置。 魔法?

Now, the only configuration left is to keep the __init__.py in your .gitignore file so it will not be included in pushes and pulls. Once you set up a new environment, don’t forget to create a new __init__.py file inside the settings module. Then import the settings file required exactly like we did before.

现在,剩下的唯一配置是将__init__.py保留在您的.gitignore文件中,这样它就不会包含在push和pulls中。 设置新环境后,不要忘记在settings模块中创建一个新的__init__.py文件。 然后完全像之前一样导入所需的设置文件。

In this article we’ve covered three best practices for better setting up your Django project:

在本文中,我们介绍了三种最佳实践,可以更好地设置Django项目:

  • Working inside a virtual environment在虚拟环境中工作
  • Keeping the requirements.txt file up to date and using it continuously in your work flow

    保持requirements.txt文件为最新并在工作流程中持续使用它

  • Setting up a better project settings array设置更好的项目设置数组

Have you followed these best practices in your last project? Do you have any insights to share? Comments are highly appreciated.

您在上一个项目中是否遵循了这些最佳实践? 您有什么见识可以分享吗? 评论受到高度赞赏。

Did you find this useful? If so, please give me some claps so more people see the article.

你觉得这有用吗? 如果是这样,请给我一些鼓掌,以便更多的人看到这篇文章。

This is part 1 in the series about best practices for Django development. Follow me to get an immediate update once the next parts are available.

这是有关Django开发最佳实践的系列文章的第1部分。 一旦有下一部分可用,请关注我以立即获得更新。

Find more great tips for technological entrepreneurs at CodingStartups.

在CodingStartups中找到技术企业家的更多重要技巧。

翻译自: https://www.freecodecamp.org/news/improve-your-django-project-with-these-best-practices-47fd60a7bff3/

django 最佳实践

django 最佳实践_通过这些最佳实践来改进Django项目相关推荐

  1. 6个座位办公室最佳位置_办公室座位最佳位置(讲解)

    在办公室选择办公位置也很重要,办公位置的好坏也会直接影响工作效率和进度,从而影响到个人健康以及公司的财运等问题. 所以办公室座位不得不重视,下面大师为大家讲解关于办公室位置最佳位置. 办公室座位最佳位 ...

  2. 持续集成最佳实践_集成服务性能最佳实践–数据流优化

    持续集成最佳实践 In this article, we'll present a couple of common best practices regarding the performance ...

  3. python第三章上机实践_《机器学习Python实践》读书笔记-第三章

    <机器学习Python实践>,第三章,第一个机器学习项目 以往目录:橘猫吃不胖:<机器学习Python实践>读书笔记-第一章​zhuanlan.zhihu.com 书中介绍了一 ...

  4. python第二章上机实践_第二章上机实践报告

    设计一个平均时间为O(n)的算法,在n(1<=n<=1000)个无序的整数中找出第k小的数. 提示:函数int partition(int a[],int left,int right)的 ...

  5. 一天测血压的最佳时间_测量血压的最佳时间是几点?

    我国成年人中,患高血压的比例超过四分之一,想要控制好血压,除了注意生活调理,该用药时合理用药,做好血压的监控测量也是很重要的方面,做好血压的测量,才能及时的了解血压的控制情况,保证血压控制的平稳,减少 ...

  6. python django异步访问_初试Ajax异步请求(基于Django框架)

    概要: Ajax异步请求数据之前就听朋友提起过,但是之前一直没有什么机会使用这个技术,就没有去了解,后面在做网站评论这一功能时,为了使用户评论之后不用刷新网页就能够看到刚刚评论的数据,所以决定使用Aj ...

  7. Django使用supervisor管理celery和uwsgi实践记录 uwsgi BACKOFF Exited too quickly (process log may have details)

    Django使用supervisor管理celery和uwsgi实践记录 安装下载supervisor不用多说. 直接上配置文件: vir_path标识虚拟环境路径 pro_path标识项目路径 全部 ...

  8. 日常办公会用到的python模块-宝安2020年_商务办公软件应用与实践_高校邦_期末答案...

    宝安2020年_商务办公软件应用与实践_高校邦_期末答案9p9c 宝安2020年_商务办公软件应用与实践_高校邦_期末答案 关注公众号{帅搜}即可查询答案 支持:大学网课,智慧树,知到,超星,尔雅,学 ...

  9. 大学计算机改革PPT,合肥工业大学计算机与信息学院毕业设计改革与实践_..ppt_点石文库dswenku.com...

    合肥工业大学计算机与信息学院毕业设计改革与实践_....ppt 企业资料,1,合肥工业大学计算机与信息学院毕业设计改革与实践,胡学钢 合肥工业大学计算机与信息学院 (J) 2007年12月22日,企业 ...

最新文章

  1. 计算机故障报告怎么写,计算机这样的诊断报告是否正常
  2. IIS 7.0的ASP.NET应用程序生命周期概述
  3. SD-WAN技术解决方案有什么作用?—Vecloud
  4. Codeforces Round #596 (Div. 2)(第三场)
  5. java 修饰符作用_Java关键字修饰符的作用范围
  6. Spring @Async配置4. 基于@Async无返回值调用 使用的方式非常简单,一个标注即可解决所有的问题: 1 @Async //标注使用 2 public void asyncMe
  7. 洛谷P2486 [SDOI2011]染色
  8. layui jquery innerHTML 无效
  9. java 反射 接口_Java 怎么通过反射获取并实现这个类里面的接口,并且实现接口中的方法...
  10. 利用Minst数据集训练原生GAN网络
  11. php c端,tob端和toc端是什么意思
  12. 个人博客项目——登录和注册
  13. 【PPT】幻灯片放映中常用快捷键
  14. 从Netty基础到聊天系统和RPC实战-卷二
  15. 阴阳师服务器维护内容,阴阳师8月1日维护内容介绍_友人帐弈鬼切内容介绍_3DM手游...
  16. 聚合支付和它的可持续发展之路
  17. 学习笔记(5):第01章-互联网的概述(历史发展+技术发展+常见应用)-互联网的接入(手把手教你调试ADSL宽带技术)
  18. linux命令行 teamview,Ubuntu下命令行方安装TeamViewer
  19. (一)什么是Mybatis?Mybatis的优点是什么?
  20. 3D模型读取库:Assimp

热门文章

  1. 字节缓冲流 BufferedInputStream java
  2. 爬虫-古试词网验证码手工打码访问登陆后页面
  3. Laravel Collection 常用方法(1)
  4. Spring Session 2.0.0.M1 发布,分布式解决方案
  5. 2015 年出现的十大流行 Python 库
  6. Office EXCEL 中如何让一个单元格的数据链接到另一个工作表的数据
  7. 十项全能的java大神
  8. 【案例讨论】从案例引发的对缓存设计的思考,干货讨论,绝对不玩虚的
  9. Adding Keyword And Description meta tags to each page by inheritence
  10. Struts原理与实践(2)