Python入门必备之Django 官方教程(基于Django 1.11)
Python入门非常简单,但是用好就离不开各种框架和库——Django就是其中之一,这次带来的就是Django的官方教程。
一直以来由于英语废所以极端抵触看英文文档。感觉人还是要逼一下自己,所以就有了这篇翻译。如果有翻译错误的地方欢迎在评论中指正。
<blockquote
Let’slearnbyexample.
Throughoutthistutorial,we’llwalkyouthroughthecreationofabasicpollapplication.
</blockquote
让我们通过样例来学习Django吧。
本教程将通过一个简单的投票应用来让您熟悉Django。
<blockquote
It’llconsistoftwoparts:
- Apublicsitethatletspeopleviewpollsandvoteinthem.
- Anadminsitethatletsyouadd,change,anddeletepolls.
</blockquote
这个项目包括两个部分:
- 一个对外显示的网站,以供人们投票。
- 一个管理网站,您可以在其中对结果增删改查。
<blockquote
We’llassumeyouhave Djangoinstalled already.YoucantellDjangoisinstalledandwhichversionbyrunningthefollowingcommand:
</blockquote
我们假定你已经 安装Django 了(如果你已经安装了pip,也可以通过pipinstallDjango来安装),你可以通过如下命令来查看你是否安装了Django。
<img alt="Python入门必备之Django官方教程(基于Django1.11)" src="https://uupeefile.tsov.net/202103/26238877eb86746e9367cd83400c56a8.
</blockquote
如果这是你第一次使用Django,你需要做一些初始化工作,也就是说我们会自动生成一些代码来帮你建立一个Django 项目 。主要是一些配置信息,包括数据库配置、Django选项和特定的应用程序设置。
<blockquote
Fromthecommandline, cd intoadirectorywhereyou’dliketostoreyourcode,thenrunthefollowingcommand:
</blockquote
首先,在命令行切换到你想储存你Django代码的位置,执行接下来的命令:
<blockquote
Thiswillcreatea mysite directoryinyourcurrentdirectory.Ifitdidn’twork,see Problemsrunningdjango-admin.
</blockquote
它会在当前目录创建一个名为mysite的文件夹,如果没有,请查看 帮助 。
Note</h4
You’llneedtoavoidnamingprojectsafterbuilt-inPythonorDjangocomponents.Inparticular,thismeansyoushouldavoidusingnameslike django (whichwillconflictwithDjangoitself)or test (whichconflictswithabuilt-inPythonpackage).
</blockquote
需要注意的是 ,你的项目名称尽量避免和python和Django的某些组件重名,例如django(和Django重名)和test(与python包重名)
Whereshouldthiscodelive?</h4
IfyourbackgroundisinplainoldPHP(withnouseofmodernframeworks),you’reprobablyusedtoputtingcodeundertheWebserver’sdocumentroot(inaplacesuchas /var/www).WithDjango,youdon’tdothat.It’snotagoodideatoputanyofthisPythoncodewithinyourWebserver’sdocumentroot,becauseitrisksthepossibilitythatpeoplemaybeabletoviewyourcodeovertheWeb.That’snotgoodforsecurity.
Putyourcodeinsomedirectory outside ofthedocumentroot,suchas /home/mycode.
Django代码应该放在什么地方?</h4
如果你使用的是老式的PHP(没有现代框架)你可能习惯于把代码放在Web服务器根目录下(例如/var/www)。而在Django中不建议你这么做,因为这是一个不好的习惯,因为这增加了人们通过网络直接查看你代码的可能性,这会降低网站的安全性。
把你的代码放在 别的 地方,例如/home/mycode
<blockquote
Let’slookatwhat startproject created:
</blockquote
我们来看看 startproject 创建了什么:
<blockquote
Thesefilesare:
这些文件的含义如下:
- Theouter mysite/rootdirectoryisjustacontainerforyourproject.Itsnamedoesn’tmattertoDjango;youcanrenameittoanythingyoulike.
</blockquote
外部的mysite仅仅是你项目的容器而已,它的名字不会影响到Django的运行,你可以把它改成你喜欢的名字。
- py:Acommand-lineutilitythatletsyouinteractwiththisDjangoprojectinvariousways.Youcanreadallthedetailsabout manage.pyin django-adminandmanage.py.
</blockquote
manage.py:是一个供你在命令行使用的管理工具,你可以通过它来管控你的项目,你可以点击 这里 查看更多细节。
<blockquote
Theinner mysite/directoryistheactualPythonpackageforyourproject.ItsnameisthePythonpackagenameyou’llneedtousetoimportanythinginsideit(e.g. urls).
</blockquote
内部的mysite目录才是你的项目本体,它的名字就是你的包名,如果你需要引用它以及内部的模块,你可以直接import它(例如:mysite.urls)。
<blockquote
mysite/__init__.py:AnemptyfilethattellsPythonthatthisdirectoryshouldbeconsideredaPythonpackage.Ifyou’reaPythonbeginner,readintheofficialPythondocs.
</blockquote
mysite/__init__.py:一个空文件,它的作用只是向python表明这是一个python包。如果你还是不太清楚,建议你先阅读 python文档中包的部分 。
<blockquote
mysite/settings.py:Settings/configurationforthisDjangoproject. Djangosettingswilltellyouallabouthowsettingswork.
</blockquote
mysite/settings.py:设置/配置这个Django项目,点击 这里 查看配置是如何工作的。
<blockquote
mysite/urls.py:TheURLdeclarationsforthisDjangoproject;a“tableofcontents”ofyourDjango-poweredsite.YoucanreadmoreaboutURLsin URLdispatcher.
</blockquote
mysite/urls.py:这是这个项目的url声明,也是你网站的目录,也可以查看 url调度 获取更多细节。
<blockquote
mysite/wsgi.py:Anentry-pointforWSGI-compatiblewebserverstoserveyourproject.See HowtodeploywithWSGIformoredetails.
</blockquote
mysite/wsgi.py:一个兼容WSGI入口点的Web服务器为您服务。参阅 如何使用WSGI 。
Thedevelopmentserver
开发服务器
<blockquote
Let’sverifyyourDjangoprojectworks.Changeintotheouter mysite directory,ifyouhaven’talready,andrunthefollowingcommands:
</blockquote
让我们来验证你的服务器能否正常运作吧。切换到外层的mysite目录,输入以下命令:
$ pythonmanage.pyrunserver
<blockquote
You’llseethefollowingoutputonthecommandline:
</blockquote
你将会看到如下输出:
Performingsystemchecks…
Systemcheckidentifiednoissues(0silenced).
Youhaveunappliedmigrations;yourappmaynotworkproperlyuntiltheyareapplied.
Run‘pythonmanage.pymigrate’toapplythem.
October06,2016–15:50:53
Djangoversion1.11,usingsettings‘mysite.settings’
Startingdevelopmentserverathttp://127.0.0.1:8000/
QuittheserverwithCONTROL-C.
Note</h4
Ignorethewarningaboutunapplieddatabasemigrationsfornow;we’lldealwiththedatabaseshortly.
注意</h4
我们现在暂时忽略数据库迁移的警告,稍后我们会进行处理。
<blockquote
You’vestartedtheDjangodevelopmentserver,alightweightWebserverwrittenpurelyinPython.We’veincludedthiswithDjangosoyoucandevelopthingsrapidly,withouthavingtodealwithconfiguringaproductionserver–suchasApache–untilyou’rereadyforproduction.
</blockquote
你已经启动了一个由Django开发的服务器了,这是一个纯python编写的轻量级服务器,我们将这个服务器内置在Django中,所以你可以快速开发项目而无需花精力去思考如何配置生产服务器(就像Apache那样),直到你已经准备好生产了为止。
<blockquote
Now’sagoodtimetonote: don’t usethisserverinanythingresemblingaproductionenvironment.It’sintendedonlyforusewhiledeveloping.(We’reinthebusinessofmakingWebframeworks,notWebservers.)
</blockquote
提前打个预防针:不要将这个服务器用于生产环境中,这仅仅只是一个框架,不是一个Web服务器,所以不要开发环境之外使用这个服务器。
<blockquote
Nowthattheserver’srunning,visit http://127.0.0.1:8000/ withyourWebbrowser.You’llseea“WelcometoDjango”page,inpleasant,light-bluepastel.Itworked!
</blockquote
现在服务器已经运行,访问 http://127.0.0.1:8000/ 你将会看到Django的欢迎界面。
Changingtheport
更改端口
<blockquote
Bydefault,the runserver commandstartsthedevelopmentserverontheinternalIPatport8000.
</blockquote
默认设置中,runserver命令会在8000端口上启动服务器。
<blockquote
Ifyouwanttochangetheserver’sport,passitasacommand-lineargument.Forinstance,thiscommandstartstheserveronport8080:
</blockquote
如果你想改变服务器的端口,下面的命令会在8080端口启动服务器。
$ pythonmanage.pyrunserver8080
<blockquote
Ifyouwanttochangetheserver’sIP,passitalongwiththeport.SotolistenonallpublicIPs(usefulifyouwanttoshowoffyourworkonothercomputersonyournetwork),use:
</blockquote
如果你想改变服务器的IP,从而使该服务器可以在公网上被访问(当你想要炫耀自己所做的事情时这就变得很重要了),请使用如下命令:
$ pythonmanage.pyrunserver0.0.0.0:8000
<blockquote
Fulldocsforthedevelopmentservercanbefoundinthe runserver reference.
</blockquote
关于runserver的全部文档你可以在这里查阅
<blockquote
Automaticreloadingof runserver
runserver自动重载
<blockquote
ThedevelopmentserverautomaticallyreloadsPythoncodeforeachrequestasneeded.Youdon’tneedtorestarttheserverforcodechangestotakeeffect.However,someactionslikeaddingfilesdon’ttriggerarestart,soyou’llhavetorestarttheserverinthesecases.
</blockquote
根据需要,开发服务器会自动为每个请求重载python代码,你不需要为了修改python代码而重启服务器。然而,某些操作(例如添加文件)不会触发重载,所以这些情况下你必须重启服务器。
CreatingthePollsapp
创建投票应用
<blockquote
Nowthatyourenvironment–a“project”–issetup,you’resettostartdoingwork.
</blockquote
现在你的环境已经配置完毕,你已经创建了一个项目,现在你要为这个项目添砖加瓦,使它运作起来。
<blockquote
EachapplicationyouwriteinDjangoconsistsofaPythonpackagethatfollowsacertainconvention.Djangocomeswithautilitythatautomaticallygeneratesthebasicdirectorystructureofanapp,soyoucanfocusonwritingcoderatherthancreatingdirectories.
</blockquote
你在Django中写的每一个应用都会被看成一个遵守一定规范的python包。Django自带了一个实用的小程序,它会自动的生成程序的基本目录结构,所以你可以从目录地狱中解脱出来,从而专心于代码的编写。
<blockquote
Projectsvs. A pps
项目与应用
<blockquote
What’sthedifferencebetweenaprojectandanapp?AnappisaWebapplicationthatdoessomething–e.g.,aWeblogsystem,adatabaseofpublicrecordsorasimplepollapp.Aprojectisacollectionofconfigurationandappsforaparticularwebsite.Aprojectcancontainmultipleapps.Anappcanbeinmultipleprojects.
</blockquote
项目和应用有什么区别呢?应用会做一些实际的工作,例如一个网络博客系统、一个公共数据库或者一个简单的投票应用。而一个项目则是配置、应用和特定网站的集合,一个项目可以包含多个应用,一个应用也可以被多个项目共享。
<blockquote
Yourappscanliveanywhereonyour Pythonpath.Inthistutorial,we’llcreateourpollapprightnexttoyour manage.py filesothatitcanbeimportedasitsowntop-levelmodule,ratherthanasubmoduleofmysite.
</blockquote
你的应用代码可以放置在 python路径 下的任何位置,在本教程中,我们会在manage.py文件的旁边创建我们的投票应用,这样我们在引入的时候可以将这个应用作为顶级模块而不是mysite的子模块引入。
<blockquote
Tocreateyourapp,makesureyou’reinthesamedirectoryas manage.py andtypethiscommand:
</blockquote
我们将目录切换到manage.py所在的目录并输入以下命令:
$ pythonmanage.pystartapppolls
<blockquote
That’llcreateadirectory polls,whichislaidoutlikethis:
</blockquote
这会创建一个名为polls的目录,它的结构如下:
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
<blockquote
Thisdirectorystructurewillhousethepollapplication.
</blockquote
这就是我们投票应用的目录了。
Writeyourfirstview
创建你的第一个视图
<blockquote
Let’swritethefirstview.Openthefile polls/views.py andputthefollowingPythoncodeinit:
</blockquote
让我们开始写第一个视图吧。打开polls/views.py并在其中写下如下代码:
fromdjango.httpimportHttpResponse
defindex(request):
returnHttpResponse(“Hello,world.You’reatthepollsindex.”)
<blockquote
ThisisthesimplestviewpossibleinDjango.Tocalltheview,weneedtomapittoaURL–andforthisweneedaURLconf.
</blockquote
这是Django的最简视图了,为了调用这个视图,我们需要把他映射到url中,为此我们需要一个url配置文件
<blockquote
TocreateaURLconfinthepollsdirectory,createafilecalled urls.py.Yourappdirectoryshouldnowlooklike:
</blockquote
在polls目录下创建urls.py文件。现在你的应用目录应该是这样的。
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
urls.py
views.py
<blockquote
Inthe polls/urls.py fileincludethefollowingcode:
</blockquote
在polls/urls.py文件中写下如下代码:
fromdjango.conf.urlsimporturl
from.importviews
urlpatterns=[
url(r’^$’,views.index,name=’index’),
]
<blockquote
ThenextstepistopointtherootURLconfatthe polls.urls module.In mysite/urls.py,addanimportfordjango.conf.urls.include andinsertan include() inthe urlpatterns list,soyouhave:
</blockquote
下一步是将项目的url配置指向polls.urls模块。在mysite/urls.py中,添加一个django.conf.urls.include 的引用,并且在urlpatterns中插入一个include(),代码如下:
fromdjango.conf.urlsimportinclude,url
fromdjango.contribimportadmin
urlpatterns=[
url(r’^polls/’,include(‘polls.urls’)),
url(r’^admin/’,admin.site.urls),
]
<blockquote
The include() functionallowsreferencingotherURLconfs.Notethattheregularexpressionsfortheinclude() functiondoesn’thavea $ (end-of-stringmatchcharacter)butratheratrailingslash.WheneverDjangoencounters include(),itchopsoffwhateverpartoftheURLmatcheduptothatpointandsendstheremainingstringtotheincludedURLconfforfurtherprocessing.
</blockquote
include()函数允许引用其他的url配置文件。需要注意的一点是,include()功能的正则表达式没有$符号(代表着匹配结尾字符)的,而是以一个斜杠结尾。无论何时Django遇到 include(),它会截取下匹配的部分然后将剩余的字符串送到包含的URL配置文件中做进一步处理。
<blockquote
Theideabehind include() istomakeiteasytoplug-and-playURLs.SincepollsareintheirownURLconf(polls/urls.py),theycanbeplacedunder“/polls/”,orunder“/fun_polls/”,orunder“/content/polls/”,oranyotherpathroot,andtheappwillstillwork.
</blockquote
include()的设计思路是更方便的实现URL的即插即用。由于这个投票应用有它自己的URL配置文件(polls/urls.py),它可以被放置在/polls/下,也可以在/fun_polls/下,或者在/content/polls/下,其他根路径也是可以的,应用仍然可以正常工作。
<blockquote
Whentouse include()
什么时候需要使用include()
<blockquote
Youshouldalwaysuse include() whenyouincludeotherURLpatterns. admin.site.urls istheonlyexceptiontothis.
</blockquote
当你想要包含其他的url路径时你总是会用到include()的。当然admin.site.urls例外。
Doesn’tmatchwhatyousee?
和你看到的不匹配?
<blockquote
Ifyou’reseeing include(admin.site.urls) insteadofjust admin.site.urls,you’reprobablyusingaversionofDjangothatdoesn’tmatchthistutorialversion.You’llwanttoeitherswitchtotheoldertutorialorthenewerDjangoversion.
</blockquote
如果你看到的是include(admin.site.urls)而不是admin.site.urls,你可能使用的Django版本和当前教程的版本不匹配。你可以查阅旧版本的课程或者使用更新的Django版本
<blockquote
Youhavenowwiredan index viewintotheURLconf.Letsverifyit’sworking,runthefollowingcommand:
</blockquote
你现在已经将一个index视图添加到了url配置文件中,我们来看看他是否能正常工作吧。执行下面的语句:
$ pythonmanage.pyrunserver
<blockquote
Goto http://localhost:8000/polls/ inyourbrowser,andyoushouldseethetext“ Hello,world.You’reatthepollsindex. ”,whichyoudefinedinthe index view.
</blockquote
现在在浏览器中打开 http://localhost:8000/polls/ 看看结果吧,你应该可以看到你在index视图中所写的“Hello,world.You’reatthepollsindex.”
<blockquote
The url() functionispassedfourarguments,tworequired: regex and view,andtwooptional: kwargs,andname.Atthispoint,it’sworthreviewingwhattheseargumentsarefor.
</blockquote
url()函数传递四个参数,两个是必选的:regex和view,另两个则是可选的:kwargs和name。我们来回顾一下这些参数吧
url() argument:regex
url()参 数 :regex
<blockquote
Theterm“regex”isacommonlyusedshortformmeaning“regularexpression”,whichisasyntaxformatchingpatternsinstrings,orinthiscase,urlpatterns.Djangostartsatthefirstregularexpressionandmakesitswaydownthelist,comparingtherequestedURLagainsteachregularexpressionuntilitfindsonethatmatches.
</blockquote
regex是正则表达式(regularexpression)的常见缩写,正则表达式是一种字符串匹配模式,在这个函数中被用来匹配url。Django会按顺序检索这个正则表达式的list,匹配请求的url直到某条正则表达式匹配为止。
<blockquote
NotethattheseregularexpressionsdonotsearchGETandPOSTparameters,orthedomainname.Forexample,inarequestto https://www.example.com/myapp/,theURLconfwilllookfor myapp/.Inarequesttohttps://www.example.com/myapp/?page=3,theURLconfwillalsolookfor myapp/.
</blockquote
需要注意的是,这些正则表达式不搜索域名和GET和POST的参数。举例来说,对https://www.example.com/myapp/ 的请求,url配置文件只会去搜索myapp/。https://www.example.com/myapp/?page=3这样的请求,配置文件也会过滤掉参数,只检索myapp/
<blockquote
Ifyouneedhelpwithregularexpressions,see Wikipedia’sentry andthedocumentationofthemodule.Also,theO’Reillybook“MasteringRegularExpressions”byJeffreyFriedlisfantastic.Inpractice,however,youdon’tneedtobeanexpertonregularexpressions,asyoureallyonlyneedtoknowhowtocapturesimplepatterns.Infact,complexregexescanhavepoorlookupperformance,soyouprobablyshouldn’trelyonthefullpowerofregexes.
</blockquote
如果你想看一些正则表达式的相关资料,可以参考 wiki百科的条目 和 re模块的文档 。另外JeffreyFriedl的书《MasteringRegularExpressions》真的是太棒了。然而在实际工作中,你不需要成为一个正则专家,因为你只需要如何去捕捉简单的字段就好,事实上,复杂的正则表达式在性能上通常表现不能令人满意,所以,不建议你完全依赖正则表达式。
<blockquote
Finally,aperformancenote:theseregularexpressionsarecompiledthefirsttimetheURLconfmoduleisloaded.They’resuperfast(aslongasthelookupsaren’ttoocomplexasnotedabove).
</blockquote
最后提一下性能相关:这些正则表达式将会在url配置文件加载的同时被编译。所以他们的查找会很快的(除了上面提到的情况)。
url() argument:view
url()参数:view
<blockquote
WhenDjangofindsaregularexpressionmatch,Djangocallsthespecifiedviewfunction,withanHttpRequest objectasthefirstargumentandany“captured”valuesfromtheregularexpressionasotherarguments.Iftheregexusessimplecaptures,valuesarepassedaspositionalarguments;ifitusesnamedcaptures,valuesarepassedaskeywordarguments.We’llgiveanexampleofthisinabit.
</blockquote
当Django找到一个正则匹配时,Django就会将 HttpRequest对象 作为第一个参数,连同其他被正则表达式捕获的值作为参数传递给视图函数。如果正则表达式只用于简单的捕捉,值就会作为位置参数传递进去,如果使用键捕获,则会把值作为关键字传递。我们将在接下来的教程中给出样例。
url() argument:kwargs
url()参数:kwagrs
<blockquote
Arbitrarykeywordargumentscanbepassedinadictionarytothetargetview.Wearen’tgoingtousethisfeatureofDjangointhetutorial.
</blockquote
任何关键字都可以传递到目标视图中,但是在本教程中并不会使用这一特性。
url() argument:name
url()参数:name
<blockquote
NamingyourURLletsyourefertoitunambiguouslyfromelsewhereinDjango,especiallyfromwithintemplates.ThispowerfulfeatureallowsyoutomakeglobalchangestotheURLpatternsofyourprojectwhileonlytouchingasinglefile.
</blockquote
为你的url命名,你可以在Django的其他地方简洁明了的引用它,尤其是从模版中引用,这种强大的功能可以让你在你的项目中仅仅修改一个文件就能全局的改变url对象
<blockquote
Whenyou’recomfortablewiththebasicrequestandresponseflow,read part2ofthistutorial tostartworkingwiththedatabase.
</blockquote
当你熟悉了基本的请求和响应流程后,阅读 第二部分 吧,我们将开始着手处理数据库相关。
<blockquote
作者:kasora
来源:https://blog.kasora.moe
超哥软件库 » Python入门必备之Django 官方教程(基于Django 1.11)