Django 1.10中文文檔:How to write reusable app

已經(jīng)同步到gitbook雹姊,想閱讀的請轉(zhuǎn)到gitbook: Django 1.10 中文文檔

This advanced tutorial begins where Tutorial 7 left off. We’ll be turning our Web-poll into a standalone Python package you can reuse in new projects and share with other people.

緊接著教程7羊赵,從這只后我們開始高級教程部分。我們將投票應用做成一個單獨的python包盏求,你可以在新項目使用噪漾,或分享給其他人充活。

If you haven’t recently completed Tutorials 1–7, we encourage you to review these so that your example project matches the one described below.

如果你還未完成教程1-7蜂莉,我們建議你完善它們,使你的示例項目與下面描述的一致

Reusability matters?

可重用很重要?

It’s a lot of work to design, build, test and maintain a web application. Many Python and Django projects share common problems. Wouldn’t it be great if we could save some of this repeated work?

設計混卵、構(gòu)建映穗、測試和維護一個網(wǎng)頁應用需要做許多工作。許多Python 和 Django 項目都會遇到一些共性問題幕随。如果我們能不重復的造輪子蚁滋,豈不是很棒。

Reusability is the way of life in Python. The Python Package Index (PyPI) has a vast range of packages you can use in your own Python programs. Check out Django Packages for existing reusable apps you could incorporate in your project. Django itself is also just a Python package. This means that you can take existing Python packages or Django apps and compose them into your own web project. You only need to write the parts that make your project unique.

可重用性在Python 中是一種常見的方式。
Python包索引 (PyPI)網(wǎng)站 具有大量的包辕录,你可以在你自己的Python程序中使用睦霎。
查閱一下Django Packages中已經(jīng)存在的可重用的應用,你可以把它們放到你的項目中走诞。
Django 自身也只是一個Python 包副女。
這意味著你可以獲取已經(jīng)存在的Python包和Django應用并將它們?nèi)诤系侥阕约旱木W(wǎng)頁項目。你只需要編寫你項目的獨有的部分代碼蚣旱。

Let’s say you were starting a new project that needed a polls app like the one we’ve been working on. How do you make this app reusable? Luckily, you’re well on the way already. In Tutorial 3, we saw how we could decouple polls from the project-level URLconf using an include. In this tutorial, we’ll take further steps to make the app easy to use in new projects and ready to publish for others to install and use.

假如說你正在開始一個新的項目碑幅,需要一個像我們正在編寫的投票應用。你如何讓該應用可重用塞绿?幸運的是枕赵,其實你已經(jīng)在這條道路上了。在教程 3中位隶,我們看到我們可以如何使用include將投票應用從項目級別的URLconf 解耦。在本教程中开皿,我們將進一步讓你的應用更容易復用到新的項目中涧黄,而且可以發(fā)布給其它人安裝和使用。

Package? App?

A Python package provides a way of grouping related Python code for easy reuse. A package contains one or more files of Python code (also known as “modules”).

Python package提供了可讓一組相關(guān)性代碼復用的方式赋荆,一個包包含一個或許多python文件(也就是我們常說的模塊)

A package can be imported with import foo.bar or from foo import bar. For a directory (like polls) to form a package, it must contain a special file init.py, even if this file is empty.

一個包可以通過import foo.bar or from foo import bar方法導入笋妥。如果是一個目錄(如polls)要做成一個包,必需要包含一個特殊文件init.py窄潭,即使這個文件是空春宣。

A Django application is just a Python package that is specifically intended for use in a Django project. An application may use common Django conventions, such as having models, tests, urls, and views submodules.

一個Django應用就是僅僅用于Django項目中Python包。一個應用可以遵循常見的Django 約定嫉你,例如具有models月帝、tests、urls和views 子模塊幽污。

Later on we use the term packaging to describe the process of making a Python package easy for others to install. It can be a little confusing, we know.

將python包變的讓其他人更易于安裝的過程嚷辅,我們稱之為打包。目前對于你來說可能有點困惑距误。

Your project and your reusable app?

你的項目以及可復用的app?

After the previous tutorials, our project should look like this:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    polls/
        __init__.py
        admin.py
        migrations/
            __init__.py
            0001_initial.py
        models.py
        static/
            polls/
                images/
                    background.gif
                style.css
        templates/
            polls/
                detail.html
                index.html
                results.html
        tests.py
        urls.py
        views.py
    templates/
        admin/
            base_site.html

You created mysite/templates
in Tutorial 7, and polls/templates in Tutorial 3. Now perhaps it is clearer why we chose to have separate template directories for the project and application: everything that is part of the polls application is in polls. It makes the application self-contained and easier to drop into a new project.

你在教程 2中創(chuàng)建了mysite/templates
簸搞,在教程 3中創(chuàng)建了polls/templates。
現(xiàn)在你可能更加清晰為什么我們?yōu)轫椖亢蛻眠x擇單獨的模板目錄:屬于投票應用的部分全部在polls目錄中准潭。這使得該應用只含有自己的東西趁俊,而且更加容易放到一個新的項目中。

The polls directory could now be copied into a new Django project and immediately reused. It’s not quite ready to be published though. For that, we need to package the app to make it easy for others to install.

現(xiàn)在可以拷貝polls目錄到一個新的Django項目并立即重用刑然。盡管它還不能充分準備好到可以立即發(fā)布寺擂。所以,我們需要打包這個應用來讓它對其他人易于安裝。

Installing some prerequisites?

安裝一些需要的東西?

The current state of Python packaging is a bit muddled with various tools. For this tutorial, we’re going to use setuptools to build our package. It’s the recommended packaging tool (merged with the distribute
fork). We’ll also be using pip to install and uninstall it. You should install these two packages now. If you need help, you can refer to how to install Django with pip. You can install setuptools the same way.

Python 目前有眾多打包工具沽讹,非嘲惚埃混亂不堪。在本教程中爽雄,我們打算使用setuptools來構(gòu)建我們的包蝠检。它是推薦的打包工具(已經(jīng)與distribute
分支合并)。我們還將使用pip來安裝和卸載它≈课粒現(xiàn)在你應該安裝這兩個包叹谁。如果你需要幫助,你可以參考how to install Django with pip乘盖。你可以使用同樣的方法安裝setuptools

Packaging your app?

打包你的應用?

Python packaging refers to preparing your app in a specific format that can be easily installed and used. Django itself is packaged very much like this. For a small app like polls, this process isn’t too difficult.

Python 打包 會將你的應用按一定規(guī)則進行處理焰檩, 使其更易安裝和使用。Django 也是以非常相似的方式打包起來的订框。對于一個像polls這樣的小應用析苫,這個過程不是太難。

  1. First, create a parent directory for polls, outside of your Django project. Call this directory django-polls.

首先穿扳,創(chuàng)建一個polls的父目錄衩侥,在Django項目目錄外。目錄名為django-polls

Choosing a name for your app

When choosing a name for your package, check resources like PyPI to avoid naming conflicts with existing packages. It’s often useful to prepend django- to your module name when creating a package to distribute. This helps others looking for Django apps identify your app as Django specific.

當為你的包選擇一個名字時矛物,檢查一下PyPI中的資源以避免與已經(jīng)存在的包沖突茫死。當創(chuàng)建一個要發(fā)布的包時,在你的模塊名字前面加上django-通常很有用履羞。 這有助于其他正在查找Django應用的人區(qū)分你的應用是專門用于Django的峦萎。

Application labels (that is, the final part of the dotted path to application packages) must be unique in INSTALLED_APPS
. Avoid using the same label as any of the Django contrib packages, for example auth, admin, or messages.

應用的標簽(應用的包的點分路徑的最后部分)在 INSTALLED_APPS
必須唯一。避免使用與Django的contrib 包 中任何一個使用相同的標簽忆首,例如auth爱榔、admin和messages。

  1. Move the polls directory into the django-polls directory.

將polls目錄移動到django-polls

  1. Create a file django-polls/README.rst with the following contents:

創(chuàng)建一個包含以下內(nèi)容的文件django-polls/README.rst:

django-polls/README.rst

=====
Polls
=====

Polls is a simple Django app to conduct Web-based polls. For each
question, visitors can choose between a fixed number of answers.

Detailed documentation is in the "docs" directory.

Quick start
-----------

1. Add "polls" to your INSTALLED_APPS setting like this::

    INSTALLED_APPS = [
        ...
        'polls',
    ]

2. Include the polls URLconf in your project urls.py like this::

    url(r'^polls/', include('polls.urls')),

3. Run `python manage.py migrate` to create the polls models.

4. Start the development server and visit http://127.0.0.1:8000/admin/
   to create a poll (you'll need the Admin app enabled).

5. Visit http://127.0.0.1:8000/polls/ to participate in the poll.

  1. Create a django-polls/LICENSE file. Choosing a license is beyond the scope of this tutorial, but suffice it to say that code released publicly without a license is useless. Django and many Django-compatible apps are distributed under the BSD license; however, you’re free to pick your own license. Just be aware that your licensing choice will affect who is able to use your code.

創(chuàng)建一個django-polls/LICENSE文件糙及。如何選擇License超出本教程的范圍搓蚪,但值得一說的是, 公開發(fā)布的代碼如果沒有License是毫無用處的。Django和許多與Django兼容的應用以BSD License 發(fā)布丁鹉;然而妒潭,你可以隨便挑選自己的License。只需知道你所選擇的License,將決定誰能使用你的代碼.

  1. Next we’ll create a setup.py file which provides details about how to build and install the app. A full explanation of this file is beyond the scope of this tutorial, but the setuptools docs have a good explanation. Create a file django-polls/setup.py with the following contents:

下一步我們將創(chuàng)建一個setup.py 文件揣钦,它包含了如何構(gòu)建和安裝該應用的詳細信息雳灾。該文件的詳細解說超出了本教程的范圍,setuptools 文檔 已詳細說明冯凹。
創(chuàng)建一個文件django-polls/setup.py谎亩,其內(nèi)容如下:

django-polls/setup.py

import os
from setuptools import setup

with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
    README = readme.read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-polls',
    version='0.1',
    packages=['polls'],
    include_package_data=True,
    license='BSD License',  # example license
    description='A simple Django app to conduct Web-based polls.',
    long_description=README,
    url='http://www.example.com/',
    author='Your Name',
    author_email='yourname@example.com',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License', # example license
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        # Replace these appropriately if you are stuck on Python 2.
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)

  1. Only Python modules and packages are included in the package by default. To include additional files, we’ll need to create a MANIFEST.in file. The setuptools docs referred to in the previous step discuss this file in more details. To include the templates, the README.rst and our LICENSE file, create a file django-polls/MANIFEST.in with the following contents:

默認只有Python模塊和包會包含進包中炒嘲。如果需要包含額外的文件,我們需要創(chuàng)建一個MANIFEST.in文件匈庭。上一步提到的setuptools 文檔對這個文件有更詳細的討論夫凸。如果要包含模板、README.rst和我們的LICENSE 文件阱持,創(chuàng)建一個文件django-polls/MANIFEST.in夭拌,其內(nèi)容如下:

django-polls/MANIFEST.in

include LICENSE
include README.rst
recursive-include polls/static *
recursive-include polls/templates *
  1. It’s optional, but recommended, to include detailed documentation with your app. Create an empty directory django-polls/docs for future documentation. Add an additional line to django-polls/MANIFEST.in:

包含你的應用的詳細文檔,雖然這是可選的衷咽,但是推薦你這樣做鸽扁。創(chuàng)建django-polls/docs目錄用于保存將來的文檔。然后再django-polls/MANIFEST.in增加一行:

recursive-include docs *

Note that the docs directory won’t be included in your package unless you add some files to it. Many Django apps also provide their documentation online through sites like readthedocs.org.

注意docs不會包含進你的包中除非你添加一些文件到它下面镶骗。
許多Django應用還通過類似readthedocs.org這樣的站點提供它們的在線文檔.

  1. Try building your package with python setup.py sdist
    (run from inside django-polls). This creates a directory called dist
    and builds your new package, django-polls-0.1.tar.gz.

通過命令python setup.py sdist(在django-polls目錄內(nèi)執(zhí)行)來打包桶现,這會創(chuàng)建一個dist目錄并構(gòu)建一個新包:django-polls-0.1.tar.gz。

For more information on packaging, see Python’s Tutorial on Packaging and Distributing Projects.

更多打包相關(guān)的信息請看Tutorial on Packaging and Distributing Projects.

Using your own package?

使用你自己的包?

Since we moved the polls directory out of the project, it’s no longer working. We’ll now fix this by installing our new django-polls package.

由于我們將polls目錄移出了項目鼎姊,它已無法正常使用骡和。我們現(xiàn)在通過安裝我們新構(gòu)建的django-polls包來修復這個問題。

Installing as a user library

作為用戶級別的庫安裝

The following steps install django-polls as a user library. Per-user installs have a lot of advantages over installing the package system-wide, such as being usable on systems where you don’t have administrator access as well as preventing the package from affecting system services and other users of the machine.

以下的步驟將安裝django-polls 成某個用戶的庫相寇。用戶級別的安裝比系統(tǒng)級別的安裝有許多優(yōu)點慰于,例如將包運行在普通用戶級別上不但不會影響系統(tǒng)服務還不會影響其他用戶

Note that per-user installations can still affect the behavior of system tools that run as that user, so virtualenv is a more robust solution (see below).

注意根據(jù)用戶的安裝仍然可以影響以該用戶身份運行的系統(tǒng)工具,所以virtualenv 是更健壯的解決辦法(見下文)裆赵。

  1. To install the package, use pip (you already installed it, right?):

用pip命令來安裝包(你已經(jīng)安裝了,對吧跺嗽?)

pip install --user django-polls/dist/django-polls-0.1.tar.gz
  1. With luck, your Django project should now work correctly again.
    Run the server again to confirm this.
    幸運的是战授,你的Django項目又重新正常工作了。你可以啟動服務器來驗證桨嫁。

  2. To uninstall the package, use pip:

用以下命令卸載這個包:

pip uninstall django-polls

Publishing your app?

發(fā)布你的應用?

Now that we’ve packaged and tested django-polls, it’s ready to share with the world! If this wasn’t just an example, you could now:

現(xiàn)在你已經(jīng)打包并測試了django-polls植兰,它已經(jīng)準備好公開發(fā)布到全世界了!如果這不僅僅是例子璃吧,你現(xiàn)在可以:

提交到一個公開的倉庫源楣导。 the Python Package Index (PyPI). packaging.python.org 有一個非常好的教程 a good tutorial

Installing Python packages with virtualenv?

用virtualenv安裝Python包?

Earlier, we installed the polls app as a user library. This has some disadvantages:

前面,我們以用戶級別安裝了polls應用壶辜。這有一些不利的地方:

  • Modifying the user libraries can affect other Python software on your system.

  • 更改用戶的庫可能會影響到系統(tǒng)里其他Python程序

  • You won’t be able to run multiple versions of this package (or others with the same name).

  • 你不可能同時跑這個包的多個版本(或者其他同名的包)

Typically, these situations only arise once you’re maintaining several Django projects. When they do, the best solution is to use virtualenv. This tool allows you to maintain multiple isolated Python environments, each with its own copy of the libraries and package namespace.

當你維護幾個Django項目時挨约,這種情況會經(jīng)常出現(xiàn)库倘。遇到了這個問題,最好的解決辦法是使用virtualenv毡咏。這個工具允許你維護多個分離的Python環(huán)境,每個都具有它自己的庫和包的命名空間逮刨。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末呕缭,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌恢总,老刑警劉巖迎罗,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異片仿,居然都是意外死亡纹安,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進店門滋戳,熙熙樓的掌柜王于貴愁眉苦臉地迎上來钻蔑,“玉大人,你說我怎么就攤上這事奸鸯∵湫Γ” “怎么了?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵娄涩,是天一觀的道長窗怒。 經(jīng)常有香客問我,道長蓄拣,這世上最難降的妖魔是什么扬虚? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮球恤,結(jié)果婚禮上辜昵,老公的妹妹穿的比我還像新娘。我一直安慰自己咽斧,他們只是感情好堪置,可當我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著张惹,像睡著了一般舀锨。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上宛逗,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天坎匿,我揣著相機與錄音,去河邊找鬼雷激。 笑死替蔬,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的屎暇。 我是一名探鬼主播进栽,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼恭垦!你這毒婦竟也來了快毛?” 一聲冷哼從身側(cè)響起格嗅,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎唠帝,沒想到半個月后屯掖,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡襟衰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年贴铜,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瀑晒。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡绍坝,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出苔悦,到底是詐尸還是另有隱情轩褐,我是刑警寧澤,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布玖详,位于F島的核電站把介,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏蟋座。R本人自食惡果不足惜拗踢,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望向臀。 院中可真熱鬧巢墅,春花似錦、人聲如沸券膀。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽三娩。三九已至庵芭,卻和暖如春妹懒,著一層夾襖步出監(jiān)牢的瞬間雀监,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工眨唬, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留会前,地道東北人。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓匾竿,卻偏偏與公主長得像瓦宜,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子岭妖,可洞房花燭夜當晚...
    茶點故事閱讀 44,611評論 2 353

推薦閱讀更多精彩內(nèi)容