浙江11选5开奖结果查询今天:Python入門必備之Django 官方教程(基于Django 1.11)

浙江11选5任3遗漏 www.ehxis.com Python入門非常簡單,但是用好就離不開各種框架和庫——Django就是其中之一,這次帶來的就是Django的官方教程。

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

Let’s learn by example.

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

讓我們通過樣例來學習Django吧。

本教程將通過一個簡單的投票應用來讓您熟悉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.

這個項目包括兩個部分:

  • 一個對外顯示的網站,以供人們投票。
  • 一個管理網站,您可以在其中對結果增刪改查。

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

我們假定你已經?安裝Django?了(如果你已經安裝了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”.

如果你已經安裝了Django,那么你應該會看到Django的版本號,反之,你將會看到錯誤提示“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,那么你可能需要稍微調整你的代碼,我們會把改動寫在注釋中。

Creating a project

創建項目

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,你需要做一些初始化工作,也就是說我們會自動生成一些代碼來幫你建立一個Django?項目?。主要是一些配置信息,包括數據庫配置、Django選項和特定的應用程序設置。

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

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

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.

它會在當前目錄創建一個名為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).

需要注意的是?,你的項目名稱盡量避免和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代碼應該放在什么地方?

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

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

Let’s look at what?startproject?created:

我們來看看?startproject?創建了什么:

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僅僅是你項目的容器而已,它的名字不會影響到Django的運行,你可以把它改成你喜歡的名字。

  • 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:是一個供你在命令行使用的管理工具,你可以通過它來管控你的項目,你可以點擊?這里?查看更多細節。

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).

內部的mysite目錄才是你的項目本體,它的名字就是你的包名,如果你需要引用它以及內部的???,你可以直接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:一個空文件,它的作用只是向python表明這是一個python包。如果你還是不太清楚,建議你先閱讀?python文檔中包的部分?。

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

mysite/settings.py:設置/配置這個Django項目,點擊?這里?查看配置是如何工作的。

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:這是這個項目的url聲明,也是你網站的目錄,也可以查看?url調度?獲取更多細節。

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:一個兼容WSGI入口點的Web服務器為您服務。參閱?如何使用WSGI?。

The development server

開發服務器

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

讓我們來驗證你的服務器能否正常運作吧。切換到外層的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 //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.

注意

我們現在暫時忽略數據庫遷移的警告,稍后我們會進行處理。

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.

你已經啟動了一個由Django開發的服務器了,這是一個純python編寫的輕量級服務器,我們將這個服務器內置在Django中,所以你可以快速開發項目而無需花精力去思考如何配置生產服務器(就像Apache那樣),直到你已經準備好生產了為止。

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.)

提前打個預防針:不要將這個服務器用于生產環境中,這僅僅只是一個框架,不是一個Web服務器,所以不要開發環境之外使用這個服務器。

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

現在服務器已經運行,訪問?//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.

默認設置中,runserver命令會在8000端口上啟動服務器。

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:

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

$?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:

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

$?python manage.py runserver 0.0.0.0:8000

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

關于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.

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

Creating the Polls app

創建投票應用

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

現在你的環境已經配置完畢,你已經創建了一個項目,現在你要為這個項目添磚加瓦,使它運作起來。

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中寫的每一個應用都會被看成一個遵守一定規范的python包。Django自帶了一個實用的小程序,它會自動的生成程序的基本目錄結構,所以你可以從目錄地獄中解脫出來,從而專心于代碼的編寫。

Projects vs.?A?pps

項目與應用

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.

項目和應用有什么區別呢?應用會做一些實際的工作,例如一個網絡博客系統、一個公共數據庫或者一個簡單的投票應用。而一個項目則是配置、應用和特定網站的集合,一個項目可以包含多個應用,一個應用也可以被多個項目共享。

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.

你的應用代碼可以放置在?python路徑?下的任何位置,在本教程中,我們會在manage.py文件的旁邊創建我們的投票應用,這樣我們在引入的時候可以將這個應用作為頂級??槎皇莔ysite的子??橐?。

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:

這會創建一個名為polls的目錄,它的結構如下:

polls/

__init__.py

admin.py

apps.py

migrations/

__init__.py

models.py

tests.py

views.py

This directory structure will house the poll application.

這就是我們投票應用的目錄了。

Write your first view

創建你的第一個視圖

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

讓我們開始寫第一個視圖吧。打開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的最簡視圖了,為了調用這個視圖,我們需要把他映射到url中,為此我們需要一個url配置文件

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

在polls目錄下創建urls.py文件。現在你的應用目錄應該是這樣的。

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:

下一步是將項目的url配置指向polls.urls???。在mysite/urls.py中,添加一個django.conf.urls.include?的引用,并且在urlpatterns中插入一個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()函數允許引用其他的url配置文件。需要注意的一點是,include()功能的正則表達式沒有$符號(代表著匹配結尾字符)的,而是以一個斜杠結尾。無論何時Django遇到?include(),它會截取下匹配的部分然后將剩余的字符串送到包含的URL配置文件中做進一步處理。

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()的設計思路是更方便的實現URL的即插即用。由于這個投票應用有它自己的URL配置文件(polls/urls.py),它可以被放置在/polls/下,也可以在/fun_polls/下,或者在/content/polls/下,其他根路徑也是可以的,應用仍然可以正常工作。

When to use??include()

什么時候需要使用include()

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

當你想要包含其他的url路徑時你總是會用到include()的。當然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版本和當前教程的版本不匹配。你可以查閱舊版本的課程或者使用更新的Django版本

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

你現在已經將一個index視圖添加到了url配置文件中,我們來看看他是否能正常工作吧。執行下面的語句:

$?python manage.py runserver

Go to?//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.

現在在瀏覽器中打開?//localhost:8000/polls/?看看結果吧,你應該可以看到你在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()函數傳遞四個參數,兩個是必選的:regex和view,另兩個則是可選的:kwargs和name。我們來回顧一下這些參數吧

url()??argument: regex

url()參?數?: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是正則表達式(regular expression)的常見縮寫,正則表達式是一種字符串匹配模式,在這個函數中被用來匹配url。Django會按順序檢索這個正則表達式的list,匹配請求的url直到某條正則表達式匹配為止。

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/.

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

如果你想看一些正則表達式的相關資料,可以參考?wiki百科的條目?和?re??櫚奈牡?。另外Jeffrey Friedl的書《Mastering Regular Expressions》真的是太棒了。然而在實際工作中,你不需要成為一個正則專家,因為你只需要如何去捕捉簡單的字段就好,事實上,復雜的正則表達式在性能上通常表現不能令人滿意,所以,不建議你完全依賴正則表達式。

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).

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

url()??argument: view

url()參數: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.

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

url()??argument: kwargs

url()參數: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.

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

url()??argument: name

url()參數: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的其他地方簡潔明了的引用它,尤其是從模版中引用,這種強大的功能可以讓你在你的項目中僅僅修改一個文件就能全局的改變url對象

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

當你熟悉了基本的請求和響應流程后,閱讀?第二部分?吧,我們將開始著手處理數據庫相關。

作者:kasora

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

相關新聞

聯系我們

400-080-6560

在線咨詢:點擊這里給我發消息

郵件:[email protected]

工作時間:周一至周日,09:00-18:30

QR code