久久国产乱子伦精品免费M,亚洲一区二区三区91,欧美国产在线视频,国产精品视频久久

Python入門必備之Django 官方教程(基于Django 1.11)

Python入門非常簡單,但是用好就離不開各種框架和庫——Django就是其中之一,這次帶來的就是Django的官方教程。

一直以來由于英語廢所以極端抵觸看英文文檔。感覺人還是要逼一下自己,所以就有了這篇翻譯。如果有翻譯錯(cuò)誤的地方歡迎在評論中指正。

Let’s learn by example.

Throughout this tutorial, we’ll walk you through the creation of a basic poll application.

讓我們通過樣例來學(xué)習(xí)Django吧。

本教程將通過一個(gè)簡單的投票應(yīng)用來讓您熟悉Django。

It’ll consist of two parts:

  • A public site that lets people view polls and vote in them.
  • An admin site that lets you add, change, and delete polls.

這個(gè)項(xiàng)目包括兩個(gè)部分:

  • 一個(gè)對外顯示的網(wǎng)站,以供人們投票。
  • 一個(gè)管理網(wǎng)站,您可以在其中對結(jié)果增刪改查。

We’ll assume you have?Django installed?already. You can tell Django is installed and which version by running the following command:

我們假定你已經(jīng)?安裝Django?了(如果你已經(jīng)安裝了pip,也可以通過pip install Django來安裝),你可以通過如下命令來查看你是否安裝了Django。

Python入門必備之Django 官方教程(基于Django 1.11)

If Django is installed, you should see the version of your installation. If it isn’t, you’ll get an error telling “No module named django”.

如果你已經(jīng)安裝了Django,那么你應(yīng)該會看到Django的版本號,反之,你將會看到錯(cuò)誤提示“No module named django”。

This tutorial is written for Django 1.11 and Python 3.4 or later. If the Django version doesn’t match, you can refer to the tutorial for your version of Django by using the version switcher at the bottom right corner of this page, or update Django to the newest version. If you are still using Python 2.7, you will need to adjust the code samples slightly, as described in comments.

本教程適用于Django1.11及以上,Python版本要求為Python3.4及以上,如果版本不匹配,你可以嘗試下載更新版本的Django或者尋找之前版本的教程,如果你使用的是Python2.7,那么你可能需要稍微調(diào)整你的代碼,我們會把改動寫在注釋中。

Creating a project

創(chuàng)建項(xiàng)目

If this is your first time using Django, you’ll have to take care of some initial setup. Namely, you’ll need to auto-generate some code that establishes a Django?project?– a collection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings.

如果這是你第一次使用Django,你需要做一些初始化工作,也就是說我們會自動生成一些代碼來幫你建立一個(gè)Django?項(xiàng)目?。主要是一些配置信息,包括數(shù)據(jù)庫配置、Django選項(xiàng)和特定的應(yīng)用程序設(shè)置。

From the command line,?cd?into a directory where you’d like to store your code, then run the following command:

首先,在命令行切換到你想儲存你Django代碼的位置,執(zhí)行接下來的命令:

Python入門必備之Django 官方教程(基于Django 1.11)

This will create a?mysite?directory in your current directory. If it didn’t work, see?Problems running django-admin.

它會在當(dāng)前目錄創(chuàng)建一個(gè)名為mysite的文件夾,如果沒有,請查看?幫助?。

Note

You’ll need to avoid naming projects after built-in Python or Django components. In particular, this means you should avoid using names like?django?(which will conflict with Django itself) or?test?(which conflicts with a built-in Python package).

需要注意的是?,你的項(xiàng)目名稱盡量避免和Python和Django的某些組件重名,例如django(和Django重名)和test(與Python包重名)

Where should this code live?

If your background is in plain old PHP (with no use of modern frameworks), you’re probably used to putting code under the Web server’s document root (in a place such as?/var/www). With Django, you don’t do that. It’s not a good idea to put any of this Python code within your Web server’s document root, because it risks the possibility that people may be able to view your code over the Web. That’s not good for security.

Put your code in some directory?outside?of the document root, such as?/home/mycode.

Django代碼應(yīng)該放在什么地方?

如果你使用的是老式的PHP(沒有現(xiàn)代框架)你可能習(xí)慣于把代碼放在Web服務(wù)器根目錄下(例如/var/www)。而在Django中不建議你這么做,因?yàn)檫@是一個(gè)不好的習(xí)慣,因?yàn)檫@增加了人們通過網(wǎng)絡(luò)直接查看你代碼的可能性,這會降低網(wǎng)站的安全性。

把你的代碼放在?別的?地方,例如/home/mycode

Let’s look at what?startproject?created:

我們來看看?startproject?創(chuàng)建了什么:

Python入門必備之Django 官方教程(基于Django 1.11)

These files are:

這些文件的含義如下:

  • The outer?mysite/root directory is just a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.

外部的mysite僅僅是你項(xiàng)目的容器而已,它的名字不會影響到Django的運(yùn)行,你可以把它改成你喜歡的名字。

  • py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details about?manage.pyin?django-admin and manage.py.

manage.py:是一個(gè)供你在命令行使用的管理工具,你可以通過它來管控你的項(xiàng)目,你可以點(diǎn)擊?這里?查看更多細(xì)節(jié)。

The inner?mysite/directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g.?urls).

內(nèi)部的mysite目錄才是你的項(xiàng)目本體,它的名字就是你的包名,如果你需要引用它以及內(nèi)部的模塊,你可以直接import它(例如:mysite.urls)。

mysite/__init__.py: An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, readin the official Python docs.

mysite/__init__.py:一個(gè)空文件,它的作用只是向Python表明這是一個(gè)Python包。如果你還是不太清楚,建議你先閱讀?Python文檔中包的部分?。

mysite/settings.py: Settings/configuration for this Django project.?Django settingswill tell you all about how settings work.

mysite/settings.py:設(shè)置/配置這個(gè)Django項(xiàng)目,點(diǎn)擊?這里?查看配置是如何工作的。

mysite/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site. You can read more about URLs in?URL dispatcher.

mysite/urls.py:這是這個(gè)項(xiàng)目的url聲明,也是你網(wǎng)站的目錄,也可以查看?url調(diào)度?獲取更多細(xì)節(jié)。

mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. See?How to deploy with WSGIfor more details.

mysite/wsgi.py:一個(gè)兼容WSGI入口點(diǎn)的Web服務(wù)器為您服務(wù)。參閱?如何使用WSGI?。

The development server

開發(fā)服務(wù)器

Let’s verify your Django project works. Change into the outer?mysite?directory, if you haven’t already, and run the following commands:

讓我們來驗(yàn)證你的服務(wù)器能否正常運(yùn)作吧。切換到外層的mysite目錄,輸入以下命令:

$?Python manage.py runserver

You’ll see the following output on the command line:

你將會看到如下輸出:

Performing system checks...

System check identified no issues (0 silenced).

You have unapplied migrations; your app may not work properly until they are applied.

Run 'Python manage.py migrate' to apply them.

October 06, 2016 - 15:50:53

Django version 1.11, using settings 'mysite.settings'

Starting development server at http://127.0.0.1:8000/

Quit the server with CONTROL-C.

Note

Ignore the warning about unapplied database migrations for now; we’ll deal with the database shortly.

注意

我們現(xiàn)在暫時(shí)忽略數(shù)據(jù)庫遷移的警告,稍后我們會進(jìn)行處理。

You’ve started the Django development server, a lightweight Web server written purely in Python. We’ve included this with Django so you can develop things rapidly, without having to deal with configuring a production server – such as Apache – until you’re ready for production.

你已經(jīng)啟動了一個(gè)由Django開發(fā)的服務(wù)器了,這是一個(gè)純Python編寫的輕量級服務(wù)器,我們將這個(gè)服務(wù)器內(nèi)置在Django中,所以你可以快速開發(fā)項(xiàng)目而無需花精力去思考如何配置生產(chǎn)服務(wù)器(就像Apache那樣),直到你已經(jīng)準(zhǔn)備好生產(chǎn)了為止。

Now’s a good time to note:?don’t?use this server in anything resembling a production environment. It’s intended only for use while developing. (We’re in the business of making Web frameworks, not Web servers.)

提前打個(gè)預(yù)防針:不要將這個(gè)服務(wù)器用于生產(chǎn)環(huán)境中,這僅僅只是一個(gè)框架,不是一個(gè)Web服務(wù)器,所以不要開發(fā)環(huán)境之外使用這個(gè)服務(wù)器。

Now that the server’s running, visit?http://127.0.0.1:8000/?with your Web browser. You’ll see a “Welcome to Django” page, in pleasant, light-blue pastel. It worked!

現(xiàn)在服務(wù)器已經(jīng)運(yùn)行,訪問?http://127.0.0.1:8000/?你將會看到Django的歡迎界面。

Changing the port

更改端口

By default, the?runserver?command starts the development server on the internal IP at port 8000.

默認(rèn)設(shè)置中,runserver命令會在8000端口上啟動服務(wù)器。

If you want to change the server’s port, pass it as a command-line argument. For instance, this command starts the server on port 8080:

如果你想改變服務(wù)器的端口,下面的命令會在8080端口啟動服務(wù)器。

$?Python manage.py runserver 8080

If you want to change the server’s IP, pass it along with the port. So to listen on all public IPs (useful if you want to show off your work on other computers on your network), use:

如果你想改變服務(wù)器的IP,從而使該服務(wù)器可以在公網(wǎng)上被訪問(當(dāng)你想要炫耀自己所做的事情時(shí)這就變得很重要了),請使用如下命令:

$?Python manage.py runserver 0.0.0.0:8000

Full docs for the development server can be found in the?runserver?reference.

關(guān)于runserver的全部文檔你可以在這里查閱

Automatic reloading of??runserver

runserver自動重載

The development server automatically reloads Python code for each request as needed. You don’t need to restart the server for code changes to take effect. However, some actions like adding files don’t trigger a restart, so you’ll have to restart the server in these cases.

根據(jù)需要,開發(fā)服務(wù)器會自動為每個(gè)請求重載Python代碼,你不需要為了修改Python代碼而重啟服務(wù)器。然而,某些操作(例如添加文件)不會觸發(fā)重載,所以這些情況下你必須重啟服務(wù)器。

Creating the Polls app

創(chuàng)建投票應(yīng)用

Now that your environment – a “project” – is set up, you’re set to start doing work.

現(xiàn)在你的環(huán)境已經(jīng)配置完畢,你已經(jīng)創(chuàng)建了一個(gè)項(xiàng)目,現(xiàn)在你要為這個(gè)項(xiàng)目添磚加瓦,使它運(yùn)作起來。

Each application you write in Django consists of a Python package that follows a certain convention. Django comes with a utility that automatically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.

你在Django中寫的每一個(gè)應(yīng)用都會被看成一個(gè)遵守一定規(guī)范的Python包。Django自帶了一個(gè)實(shí)用的小程序,它會自動的生成程序的基本目錄結(jié)構(gòu),所以你可以從目錄地獄中解脫出來,從而專心于代碼的編寫。

Projects vs.?A?pps

項(xiàng)目與應(yīng)用

What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

項(xiàng)目和應(yīng)用有什么區(qū)別呢?應(yīng)用會做一些實(shí)際的工作,例如一個(gè)網(wǎng)絡(luò)博客系統(tǒng)、一個(gè)公共數(shù)據(jù)庫或者一個(gè)簡單的投票應(yīng)用。而一個(gè)項(xiàng)目則是配置、應(yīng)用和特定網(wǎng)站的集合,一個(gè)項(xiàng)目可以包含多個(gè)應(yīng)用,一個(gè)應(yīng)用也可以被多個(gè)項(xiàng)目共享。

Your apps can live anywhere on your?Python path. In this tutorial, we’ll create our poll app right next to your?manage.py?file so that it can be imported as its own top-level module, rather than a submodule ofmysite.

你的應(yīng)用代碼可以放置在?Python路徑?下的任何位置,在本教程中,我們會在manage.py文件的旁邊創(chuàng)建我們的投票應(yīng)用,這樣我們在引入的時(shí)候可以將這個(gè)應(yīng)用作為頂級模塊而不是mysite的子模塊引入。

To create your app, make sure you’re in the same directory as?manage.py?and type this command:

我們將目錄切換到manage.py所在的目錄并輸入以下命令:

$?Python manage.py startapp polls

That’ll create a directory?polls, which is laid out like this:

這會創(chuàng)建一個(gè)名為polls的目錄,它的結(jié)構(gòu)如下:

polls/

__init__.py

admin.py

apps.py

migrations/

__init__.py

models.py

tests.py

views.py

This directory structure will house the poll application.

這就是我們投票應(yīng)用的目錄了。

Write your first view

創(chuàng)建你的第一個(gè)視圖

Let’s write the first view. Open the file?polls/views.py?and put the following Python code in it:

讓我們開始寫第一個(gè)視圖吧。打開polls/views.py并在其中寫下如下代碼:

from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, world. You're at the polls index.")

This is the simplest view possible in Django. To call the view, we need to map it to a URL – and for this we need a URLconf.

這是Django的最簡視圖了,為了調(diào)用這個(gè)視圖,我們需要把他映射到url中,為此我們需要一個(gè)url配置文件

To create a URLconf in the polls directory, create a file called?urls.py. Your app directory should now look like:

在polls目錄下創(chuàng)建urls.py文件。現(xiàn)在你的應(yīng)用目錄應(yīng)該是這樣的。

polls/

__init__.py

admin.py

apps.py

migrations/

__init__.py

models.py

tests.py

urls.py

views.py

In the?polls/urls.py?file include the following code:

在polls/urls.py文件中寫下如下代碼:

from django.conf.urls import url

from . import views

urlpatterns = [
url(r'^$', views.index, name='index'),
]

The next step is to point the root URLconf at the?polls.urls?module. In?mysite/urls.py, add an import fordjango.conf.urls.include?and insert an?include()?in the?urlpatterns?list, so you have:

下一步是將項(xiàng)目的url配置指向polls.urls模塊。在mysite/urls.py中,添加一個(gè)django.conf.urls.include?的引用,并且在urlpatterns中插入一個(gè)include(),代碼如下:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]

The?include()?function allows referencing other URLconfs. Note that the regular expressions for theinclude()?function doesn’t have a?$?(end-of-string match character) but rather a trailing slash. Whenever Django encounters?include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

include()函數(shù)允許引用其他的url配置文件。需要注意的一點(diǎn)是,include()功能的正則表達(dá)式?jīng)]有$符號(代表著匹配結(jié)尾字符)的,而是以一個(gè)斜杠結(jié)尾。無論何時(shí)Django遇到?include(),它會截取下匹配的部分然后將剩余的字符串送到包含的URL配置文件中做進(jìn)一步處理。

The idea behind?include()?is to make it easy to plug-and-play URLs. Since polls are in their own URLconf (polls/urls.py), they can be placed under “/polls/”, or under “/fun_polls/”, or under “/content/polls/”, or any other path root, and the app will still work.

include()的設(shè)計(jì)思路是更方便的實(shí)現(xiàn)URL的即插即用。由于這個(gè)投票應(yīng)用有它自己的URL配置文件(polls/urls.py),它可以被放置在/polls/下,也可以在/fun_polls/下,或者在/content/polls/下,其他根路徑也是可以的,應(yīng)用仍然可以正常工作。

When to use??include()

什么時(shí)候需要使用include()

You should always use?include()?when you include other URL patterns.?admin.site.urls?is the only exception to this.

當(dāng)你想要包含其他的url路徑時(shí)你總是會用到include()的。當(dāng)然admin.site.urls例外。

Doesn’t match what you see?

和你看到的不匹配?

If you’re seeing?include(admin.site.urls)?instead of just?admin.site.urls, you’re probably using a version of Django that doesn’t match this tutorial version. You’ll want to either switch to the older tutorial or the newer Django version.

如果你看到的是include(admin.site.urls)而不是admin.site.urls,你可能使用的Django版本和當(dāng)前教程的版本不匹配。你可以查閱舊版本的課程或者使用更新的Django版本

You have now wired an?index?view into the URLconf. Lets verify it’s working, run the following command:

你現(xiàn)在已經(jīng)將一個(gè)index視圖添加到了url配置文件中,我們來看看他是否能正常工作吧。執(zhí)行下面的語句:

$?Python manage.py runserver

Go to?http://localhost:8000/polls/?in your browser, and you should see the text “?Hello, world. You’re at the polls index.?”, which you defined in the?index?view.

現(xiàn)在在瀏覽器中打開?http://localhost:8000/polls/?看看結(jié)果吧,你應(yīng)該可以看到你在index視圖中所寫的“Hello, world. You’re at the polls index.”

The?url()?function is passed four arguments, two required:?regex?and?view, and two optional:?kwargs, andname. At this point, it’s worth reviewing what these arguments are for.

url()函數(shù)傳遞四個(gè)參數(shù),兩個(gè)是必選的:regex和view,另兩個(gè)則是可選的:kwargs和name。我們來回顧一下這些參數(shù)吧

url()??argument: regex

url()參?數(shù)?:regex

The term “regex” is a commonly used short form meaning “regular expression”, which is a syntax for matching patterns in strings, or in this case, url patterns. Django starts at the first regular expression and makes its way down the list, comparing the requested URL against each regular expression until it finds one that matches.

regex是正則表達(dá)式(regular expression)的常見縮寫,正則表達(dá)式是一種字符串匹配模式,在這個(gè)函數(shù)中被用來匹配url。Django會按順序檢索這個(gè)正則表達(dá)式的list,匹配請求的url直到某條正則表達(dá)式匹配為止。

Note that these regular expressions do not search GET and POST parameters, or the domain name. For example, in a request to?https://www.example.com/myapp/, the URLconf will look for?myapp/. In a request tohttps://www.example.com/myapp/?page=3, the URLconf will also look for?myapp/.

需要注意的是,這些正則表達(dá)式不搜索域名和GET和POST的參數(shù)。舉例來說,對https://www.example.com/myapp/?的請求,url配置文件只會去搜索myapp/。https://www.example.com/myapp/?page=3這樣的請求,配置文件也會過濾掉參數(shù),只檢索myapp/

If you need help with regular expressions, see?Wikipedia’s entry?and the documentation of themodule. Also, the O’Reilly book “Mastering Regular Expressions” by Jeffrey Friedl is fantastic. In practice, however, you don’t need to be an expert on regular expressions, as you really only need to know how to capture simple patterns. In fact, complex regexes can have poor lookup performance, so you probably shouldn’t rely on the full power of regexes.

如果你想看一些正則表達(dá)式的相關(guān)資料,可以參考?wiki百科的條目?和?re模塊的文檔?。另外Jeffrey Friedl的書《Mastering Regular Expressions》真的是太棒了。然而在實(shí)際工作中,你不需要成為一個(gè)正則專家,因?yàn)槟阒恍枰绾稳ゲ蹲胶唵蔚淖侄尉秃茫聦?shí)上,復(fù)雜的正則表達(dá)式在性能上通常表現(xiàn)不能令人滿意,所以,不建議你完全依賴正則表達(dá)式。

Finally, a performance note: these regular expressions are compiled the first time the URLconf module is loaded. They’re super fast (as long as the lookups aren’t too complex as noted above).

最后提一下性能相關(guān):這些正則表達(dá)式將會在url配置文件加載的同時(shí)被編譯。所以他們的查找會很快的(除了上面提到的情況)。

url()??argument: view

url()參數(shù):view

When Django finds a regular expression match, Django calls the specified view function, with anHttpRequest?object as the first argument and any “captured” values from the regular expression as other arguments. If the regex uses simple captures, values are passed as positional arguments; if it uses named captures, values are passed as keyword arguments. We’ll give an example of this in a bit.

當(dāng)Django找到一個(gè)正則匹配時(shí),Django就會將?HttpRequest對象?作為第一個(gè)參數(shù),連同其他被正則表達(dá)式捕獲的值作為參數(shù)傳遞給視圖函數(shù)。如果正則表達(dá)式只用于簡單的捕捉,值就會作為位置參數(shù)傳遞進(jìn)去,如果使用鍵捕獲,則會把值作為關(guān)鍵字傳遞。我們將在接下來的教程中給出樣例。

url()??argument: kwargs

url()參數(shù):kwagrs

Arbitrary keyword arguments can be passed in a dictionary to the target view. We aren’t going to use this feature of Django in the tutorial.

任何關(guān)鍵字都可以傳遞到目標(biāo)視圖中,但是在本教程中并不會使用這一特性。

url()??argument: name

url()參數(shù):name

Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates. This powerful feature allows you to make global changes to the URL patterns of your project while only touching a single file.

為你的url命名,你可以在Django的其他地方簡潔明了的引用它,尤其是從模版中引用,這種強(qiáng)大的功能可以讓你在你的項(xiàng)目中僅僅修改一個(gè)文件就能全局的改變url對象

When you’re comfortable with the basic request and response flow, read?part 2 of this tutorial?to start working with the database.

當(dāng)你熟悉了基本的請求和響應(yīng)流程后,閱讀?第二部分?吧,我們將開始著手處理數(shù)據(jù)庫相關(guān)。

作者:kasora

來源:https://blog.kasora.moe

相關(guān)新聞

歷經(jīng)多年發(fā)展,已成為國內(nèi)好評如潮的Linux云計(jì)算運(yùn)維、SRE、Devops、網(wǎng)絡(luò)安全、云原生、Go、Python開發(fā)專業(yè)人才培訓(xùn)機(jī)構(gòu)!

    1. 主站蜘蛛池模板: 池州市| 土默特左旗| 宜城市| 徐闻县| 曲阜市| 安国市| 武宁县| 即墨市| 多伦县| 乌拉特中旗| 淳安县| 蛟河市| 井研县| 平阴县| 泸水县| 和顺县| 杭州市| 新密市| 小金县| 贡山| 安国市| 朝阳县| 绵阳市| 彩票| 临城县| 京山县| 邵东县| 延津县| 盘山县| 甘孜县| 罗城| 博湖县| 丰都县| 宜州市| 彩票| 定襄县| 柳林县| 海城市| 清徐县| 三江| 施秉县|