CopyrightIBMCorporation2009TrademarksDeployingDjangoapplicationstoaproductionserverPage1of13DeployingDjangoapplicationstoaproductionserverJoeLennonApril07,2009DjangoisaPython-basedopensourceWebapplicationframeworkthatfocusesonmakingtheprocessofcreatingdatabase-drivenWebsitesandWebapplicationseasier.
GettingstartedwithdevelopingDjangoapplicationsissimple,asadevelopmentWebserverisincludedwiththeframework.
However,thisserverisnotsuitableforuseinaproductionenvironment,sofurtherstepsarerequiredtodeployyourDjangoapplicationtotheWeb.
Inthisarticle,youwilllearnabouttheDjangoframeworkandhowtoinstallitonyourlocalmachine.
DiscoverhowaDjangoapplicationismadeandabouttheautomaticadministrationinterfacecreatedforyourapplication.
YouwillthenfindouthowtodeployyourDjangoapplicationtotheWebonaserverrunningApacheandmod_python.
Finally,learnhowDjangoapplicationscanandshouldbescaledasyourapplication'srequirementsgrow.
DjangoDjangoisanopensourceWebdevelopmentframeworkforthePythonlanguagethataimstoautomateasmanyprocessesaspossible,allowingyoutofocusondevelopingsoftwarewithoutworryingaboutreinventingthewheel.
Theframeworkisdesignedtobelooselycoupledandtightlycohesive,meaningthatdifferentpartsoftheframework,whileconnectedtooneanother,arenotdependentononeanother.
ThisindependencemeansyoucanuseonlythepartsofDjangoyouneed,withoutworryingaboutdependencyissues.
DjangomakeswritingWebapplicationsfaster,anditdrasticallycutsdowntheamountofcoderequired,makingitmucheasiertomaintaintheapplicationgoingforward.
DjangostrictlyobservestheDon'tRepeatYourself(DRY)principle,wherebyeverydistinctpieceofcodeordatalivesinonlyoneplace.
Thismeansthatwhenachangeneedstobemade,itonlyneedstobemadeinoneplace,leadingtotheprocessofchangingsoftwarebecomingmuchfasterandmucheasier.
DjangowasdevelopedbyateamofWebdevelopersattheLawrenceJournal-Worldnewspaperin2003.
Underpressuretoreleaseapplicationsandenhancementsunderseveretimeconstraints,theydecidedtocreateaWebframeworkthatwouldsavethemtime,allowingthemtomeettheirdifficultdeadlines.
TheteamreleasedtheframeworkasopensourcesoftwareinJuly2005,anditisnowdevelopedbyacommunityofthousandsofdevelopersacrosstheworld.
TheDjangoframeworkisreleasedundertheBerkeleySoftwareDistribution(BSD)opensourcelicense,whichpermitsredistributionandreuseofthesourcecodeandbinary,withorwithoutmodification,solongasthecopyrightnotice,licenseconditions,anddisclaimerareretaineddeveloperWorksibm.
com/developerWorks/DeployingDjangoapplicationstoaproductionserverPage2of13intheredistributedpackage.
Theseitemsmustalsobepresentintheredistributedsoftware'sdocumentationandsupplementarymaterialswhereapplicable.
AndthelicensespecifiesthatneithertheDjangonamenorthenamesofDjangocontributorscanbeusedtoendorseorpromotederivativeproductswithoutexpresswrittenpermission.
SettingupabasicDjangodevelopmentenvironmentFortunately,installingDjangoisstraightforward,sosettingupadevelopmentenvironmentisquickandeasy.
DjangoiswrittenentirelyinPython,sotoinstallDjango,youfirstneedtoinstallPython.
Ifyou'reusingMacOSXorLinux,it'slikelythatPythonisalreadyonyourmachine.
Simplyrunpythoninyourshell(useTerminal.
apponaMac)andyoushouldseesomethinglikeListing1.
Listing1.
MakesurePythonisrunning$pythonPython2.
5.
1(r251:54863,Nov112008,17:46:48)[GCC4.
0.
1(AppleInc.
build5465)]ondarwinType"help","copyright","credits"or"license"formoreinformation.
Listing1-CheckingforPythononMacOSXAslongasyoursystemhasaversionofPythonfrom2.
3to2.
6,youwillbeabletoinstallDjango.
IfyouareaMicrosoftWindowsuserorifyouneedtoupgradetoanewerversion,downloadPython.
AsimpleinstallationpackageisavailableforWindowsusers,soinstallingPythoncouldn'tbemucheasier.
WhenyouhaveverifiedthatPythonisinstalledonyourcomputer,youcanproceedtoinstallDjango.
Therearethreeoptions:installinganofficialrelease,installingadistribution-specificinstallationpackage,orinstallingthelatest"trunk"versionfromSubversion.
Forthesakeofthisarticle,Iwillonlywalkthroughtheinstallationfromanofficialrelease.
Forinformationaboutinstallingthetrunkversion,seetheofficialdocumentationinstructions(seeRelatedtopics).
ThefirststepininstallingtheofficialDjangoreleaseistogetthetarballfromtheDjangodownloadpage.
Onceyouhavedownloadedthisfile,extractitscontents.
InLinux,simplyissuethefollowingcommandatyourshellprompt(besuretonavigatetothedirectorywhereyoudownloadedthepackageto).
PleasenotethatV1.
0.
2wasthelatestreleaseatthetimeofwriting,sobesuretoreplacethisfilenamewiththeexactfilenameofthepackageyoudownloaded:tarzxvfDjango-1.
0.
2-final.
tar.
gz.
InMacOSX,it'slikelythatyourWebbrowserautomaticallydecompressedthepackagewhenitfinisheddownloading,sothefilewillbeDjango-1.
0.
2-final.
tar.
Toextractthisfile,simplyusethefollowingcommand:tarxvfDjango-1.
0.
2-final.
tar.
IfyouareusingWindows,youcanuseautilitysuchas7-Ziptoextractthetarball.
Nowthatyouhaveextractedthecontentsofthetarball(probablytoalocationlikeDjango-1.
0.
2-finalonyourharddrive),navigatetothatfolderinyourcommandprompt.
ToinstallDjango,issuethefollowingcommand(MacOSXorLinux):sudopythonsetup.
pyinstall.
Windowsusers,makesureyourcommandpromptisopenedwithadministratorprivilegesandissuethefollowingcommand:setup.
pyinstall.
ibm.
com/developerWorks/developerWorksDeployingDjangoapplicationstoaproductionserverPage3of13Onceyouhavedonethis,DjangowillhavebeeninstalledintoyourPythoninstallation'ssite-packagesfolder,andyouarereadytostartdevelopinginDjango.
BeforewemoveontotheanatomyofaDjangoapplication,wewilltestthatourdevelopmentenvironmentisupandrunningcorrectly.
First,wewillcheckthatDjangoisinstalledcorrectly.
OpenyourshellorcommandpromptandstartthePythoninteractivetoolbyissuingthecommandpython.
NowissuethecommandsshowninListing2atthePythonprompt(don'ttypethe>>>s):Listing2.
VerifythatDjangoisinstalledcorrectly>>>importdjango>>>django.
VERSIONIfyourinstallationwassuccessful,youshouldseethetextshowninListing3.
Listing3.
Successfulinstallation(1,0,2,'final',0)>>>NowthatwehaveverifiedthatDjangoisactuallyinstalled,wewilltestthatthedevelopmentserverisworking.
Todothis,weneedtocreateaproject.
CreateadirectorytostoreyourDjangoprojectsin(Iuse/home/joe/djangoonmyMacOSXsystem)andnavigatetothatdirectory.
Fromthere,issuethefollowingcommand:django-admin.
pystartprojecttestproject.
Thiswillcreateanewdirectorywithinyourprojectsdirectorycalledtestproject.
Thisdirectorycontainsfourfiles:__init__.
py,manage.
py,settings.
py,andurls.
py.
Don'tworryaboutwhatthesefilesdorightnow;wearegoingtojumpaheadandruntheproject.
Makesureyouareintheprojectfolder(usecdtestprojectattheprompt)andissuethefollowingcommand:pythonmanage.
pyrunserver.
Youshouldseetheoutputshownbelow.
Listing4.
RunningtheDjangodevelopmentserverValidatingmodels.
.
.
0errorsfoundDjangoversion1.
0.
2final,usingsettings'testproject.
settings'Developmentserverisrunningathttp://127.
0.
0.
1:8000/QuittheserverwithCONTROL-C.
ThismessagetellsusthatthedevelopmentserverisnowrunningattheURLhttp://127.
0.
0.
1:8000/.
OpenyourfavoriteWebbrowserandpasteinthisURLintheaddressbar.
Youshouldseeapageliketheoneshownbelow.
developerWorksibm.
com/developerWorks/DeployingDjangoapplicationstoaproductionserverPage4of13Figure1.
WelcometoDjangoPageYounowhaveaworkingDjangodevelopmentenvironmentupandrunning.
It'sworthmentioningthatalthoughyoucanrunfull-fledgedDjangoapplicationsinthisenvironment,itisnotsuitableforuseinaproductionenvironment.
WewillcoverdeployingDjangoapplicationsforproductionuselaterinthisarticle.
TheanatomyofaDjangoapplicationDjango'sarchitectureislooselybasedontheModel-View-Controller(MVC)patterninthatitseparatesapplicationlogic,userinterface(UI),anddata-accesslayers,withthegoalofallowingeachlayertobemodifiedindependently,withoutaffectingtheotherlayers.
AccordingtoDjangodocumentation,however,Djangofollowsasimilarpattern:whatitreferstoasaModel-Template-View(MTV)architecture.
TheModelcanbeseenasthedata-accesslayer,wheretheapplicationinteractswithanydatabasesandinformationsources.
TheTemplateisthelayerthatdefineshowthedatashouldbepresentedtotheuser,whereasthisisconsideredtheViewlayerinanMVCpattern.
InanMTVarchitecture,theViewlayerdescribeswhatdatashouldbepresentedtotheuser.
Itdoesnotdefineexactlyhowitshouldbepresented;itdelegatesthattasktothetemplatelayer.
AsforMVC'sControllerlayer,Djangoseesthisasbeingtheframeworkitself,asitdeterminestheappropriateviewtosendrequeststo,asdefinedintheURLconfiguration.
InadditiontoModels,Templates,andViews,Djangoofferssomeadvancedfeaturesoutofthebox,suchasURLconfigurations,anautomaticadministrativeinterface,caching,andmore.
LikePython,oneofthekeyphilosophiesbehindDjangoisthebatteries-includedapproach,meaningthatitcomeswithalargestandardlibraryofadditionalpackagesyoucanuseinyourapplicationswithoutadditionaldownloads.
ThemodellayerofaDjangoapplicationishandledbyDjango'sdata-accesslayer.
Withinthislayer,youwillfindeverythingrelatedtothedata:connectionsettings,validationparameters,relations,etc.
Outofthebox,DjangoincludessupportforPostgreSQL(thepreferreddatabaseofthecreatorsofDjango),MySQL,SQLite,andOracle.
Whichdatabasetouseisstoredinasettingsfile,andthemodellayeristhesamenomatterwhatoptionyouchoose.
ModelsinDjangocanbeseenasdescriptionsofthedatabasetableschemas,representedinPythoncode.
DjangousesthemodeltogenerateandexecuteSQLstatementsinthedatabase,whichinturnreturnaresult.
DjangothentranslatestoaPythondatastructure,whichcanbeusedbyyourDjangoapplication.
Anobviousadvantagehereisthatyoucanhot-swapamongdifferentibm.
com/developerWorks/developerWorksDeployingDjangoapplicationstoaproductionserverPage5of13databasessystems(forexample,changefromMySQLtoPostgreSQL)withouthavingtochangeyourmodels.
ThecodeinListing5isanexampleofamodeldefinition.
Thiswouldgenerallybestoredinamodels.
pyfileinaDjangoapplication'sdirectory.
Listing5.
SampleDjangoModelfromdjango.
dbimportmodelsclassPerson(models.
Model):first_name=models.
CharField(max_length=30)last_name=models.
CharField(max_length=30)email=models.
EmailField()date_of_birth=models.
DateField()TheTemplatelayerofaDjangoapplicationallowsyoutoseparatetheUIorpresentationlayoutofaWebapplicationfromitsdata.
Itusesplaceholdervariablesandsimplelogicstatementstodefinewhatdatashouldbepopulatedintothetemplate.
TemplatesusuallyproduceHTMLoutput,butcanalsoproduceXMLoranyothertypeofdocument.
TheideabehindtheTemplatelayeristhatthepresentationlayercodeisseparatefromthebusiness-layercode.
ThismeansaPythondevelopercanfocusondevelopingthesoftware,whileleavingaWebdesignertoworkonthetemplates.
Italsomeansthatthedeveloperandthedesignercanworkonthesameprojectatthesametime,asthetwocomponentsarecompletelyseparatefromoneanother.
It'simportanttonotethatDjango'stemplatesystemdoesnotallowPythoncodetobeexecuteddirectlyfromthetemplate.
Itoffersarudimentarysetofprogramming-stylefeatures,suchasvariables,logicstatements(ifstatements),andloopingconstructs(forloops),whichshouldoffermorethanenoughlogicrequiredforthepresentationofdata.
Listing6isanexampleofwhataDjangotemplatewouldlooklike.
Listing6.
SampleDjangoTemplateYourmessagehasbeensentThankyou!
Justwantedtosayaquickthanks,{{name}},forthemessageyouhavejustsent.
Itwassenton{{sent_date|date:"jFY"}}.
Weaimtorespondwithin48hours.
Thanksagain!
Listing7showshowthistemplatewouldbeusedinaDjangoapplication.
developerWorksibm.
com/developerWorks/DeployingDjangoapplicationstoaproductionserverPage6of13Listing7.
LoadingthesampleDjangoTemplateinaviewdefsend_message(request):name="JoeLennon"sent_date=datetime.
datetime.
now()returnrender_to_response('thankyou.
html',locals())Viewfunctions,or"views"astheyaremorecommonlyknown,arebasicallyPythonfunctionsthatacceptarequestparameterandreturnaresponse.
TherequestistypicallyarequestfromtheWebserver,andtheviewtakesanyparameterspassedalongwiththisrequest.
Theviewthenperformsthelogicrequiredtodeterminetheappropriateresponsebeforereturningthatresponse.
ViewscanbestoredanywhereinaDjangoapplication,butareusuallystoredinafilenamedviews.
py.
Listing5isanexampleofaviewfunction,namedsend_message.
Itacceptstherequestparameterinitsdefinitionandreturnsarenderedtemplate(thankyou.
html)asitsresponse.
Youjustreadthatviewscanbestoredanywhere.
Ifthatisthecase,howdoesDjangoknowwheretofindthemThisleadsusontoURLconfs,whichdefinewhatURLspointtowhatviews.
URLconfsarestoredinafilecalledurls.
pyandbasicallymapaURLtoaviewfunction.
Forexample,theurl/send_message/mightmaptooursend_messageview,asdescribedinListing7.
Infact,thewayURLconfsworkallowsthemtobeusedforprettyURLsoutofthebox—inotherwords,insteadofusingquerystringslikemyfile.
phpparam1=value1,yourURLmightbe/myfile/value1/.
ThecodeisListing8providesanexampleofaurls.
pyfile,whichconnectstheURL/send_message/tooursend_messageviewfunction,asdefinedinListing7.
Listing8.
SampleURLconffromdjango.
conf.
urls.
defaultsimport*fromtestproject.
viewsimportsend_messageurlpatterns=patterns('',('^send_message/$',send_message),)Oneofthemostinterestingandtalked-aboutfeaturesofDjangoisitsautomaticadministrativeinterface.
Webapplicationdeveloperswhohaveworkedonprojectsthatrequireback-endadmininterfacestobedevelopedinadditiontothefrontendmaybeabletorelatetothefrustrationandboredomthatcomesfromdevelopingsuchinterfaces.
Admininterfacesareusuallymind-numbing,don'trequiremuchskill,anddon'tflexyourprogrammingmuscleinanyway.
Django'sautomaticadmininterfacefeaturewillbeofenormousvalue,asittakesthisrequirementoutoftheequationbyautomatingtheentiretask.
Onceyouhavecreatedthemodelsforyourapplicationandsetupyourdatabasesettings,youcanenabletheadmininterfaceforyourapplication.
Onceyouhavedoneso,simplypointyourbrowsertohttp://127.
0.
0.
1:8000/admin/andlogintomanagethebackendofyourDjangoapplication.
Theinterfaceishighlycustomizableandfeaturesexcellentuserandgroup-basedauthenticationcontrols.
Ascreenshotofitinactionisshownbelow.
ibm.
com/developerWorks/developerWorksDeployingDjangoapplicationstoaproductionserverPage7of13Figure2.
DjangoautomaticadmininterfaceinactionWehavegivenahigh-leveloverviewofhowaDjangoapplicationiscreatedandofhowtheMTVpatternitisbasedonworks.
Wehavelookedattheconceptsofmodels,templates,views,andURLconfs;andwehaveseenaglimpseofDjango'sbrilliantautomaticadministrationinterfacesystem.
Ifyouarelookingforanin-depthguidetodevelopingDjangoapplications,visittheofficialDjangoprojectWebsiteandreadthedocumentationthereorreadtheDjangoBook(seeRelatedtopics).
Bothofferanexcellentassumption-freeguidetoallthingsDjangoandcovermuchmoredetailthanwecangetintohere.
Next,takealookattakingDjangoapplicationsanddeployingthemtoproductionservers.
ReadyingyourDjangoapplicationfordeploymentAswehaveseen,theDjangoframeworkconvenientlyincludesadevelopmentserver,whichisidealfordebuggingandtestingyourDjangoapplication.
Unfortunately,thisserverisonlydesignedtoruninalocalenvironmentandcouldnotwithstandthepressuresofaproductionWebapplicationusedbymanypeopleconcurrently.
Forthat,youneedtodeployDjangotoaproduction-gradeWebserver,suchasApacheorlighttpd.
Exploresomestepsthatneedtobetakentomakeyourapplicationproduction-ready,thenlearnwhat'sinvolvedinpreparingyourWebserverforservingupyourDjangoapplication.
BeforediscussinghowtosetupyourproductionenvironmentforyourDjangoapplication,thereareafewthingsyouneedtodoinyourDjangoapplication'ssettings.
ItisimportanttomakethesechangesbecauseanyvulnerabilitiesinyourDjangoapplicationmaybemadepublic,thankstodebugerrormessages,etc.
developerWorksibm.
com/developerWorks/DeployingDjangoapplicationstoaproductionserverPage8of13Naturally,youwon'twanttochangethesesettingsinyourdevelopmentenvironment,asdebugmessagesanderrorsareextremelyusefulwhenmaintainingyourapplication.
Tosolvethis,youcouldmaintaintwoseparatesettingsfiles:oneforyourdevelopmentserverandoneforyourproductionserver.
Alternatively,youcouldemploythefollowingtricktokeeptheminthesamefileandtellDjangotoonlyusethedevelopmentsettingsifitisinthedevelopmentenvironment.
Todothis,youwouldlayoutyoursettings.
pyfileinthefollowingway(obviously,replacejoe-mac-miniwithyourdevelopmentserver'shostname,asshowninListing9).
Listing9.
Separatesettingsfordevelopmentandproductionenvironmentsimportsocketifsocket.
get_hostname()=='joe-mac-mini':#DevelopmentServerSettingsgohereelse:#ProductionServerSettingsgohereNowthatwe'velookedatkeepingseparatesettingsforourtwoenvironments,let'sexaminethesettingsweneedtochangeinourproductionenvironment.
ThetwoessentialsettingsyoumustchangeinyourproductionenvironmentareDEBUGandTEMPLATE_DEBUG.
ThesearesettoTruebydefaultwhenyoucreateyourDjangoapplicationusingdjango-admin.
pystartproject.
ItisessentialthatyouchangethistoFalseforyourproductionenvironment.
Inyoursettings.
py,intheProductionsection,thislineshouldreadasfollows:DEBUG=TEMPLATE_DEBUG=False.
Bydefault,Djangoissetuptosendane-mailanytimeanunhandledexceptionisraisedinyourDjangoapplication.
Toenablethisfeature,tellDjangowhoitshouldsendthee-mailto.
ThisisdonewiththeADMINSsettinginthesettings.
pyfile.
Listing10.
DefiningapplicationadministratorsADMINS=(('JoeLennon','joe@joelennon.
ie'),)IfyoucomeacrosserrorsinyourcodewhendevelopingyourDjangoapplication,youmayhavenoticedtheerrorpagesDjangogenerates,fullofhelpfulinformationtoassistyouinfindingtherootoftheproblem.
Whenyouswitchdebugmodeoff,theseniceerrorpagesdisappear,astheyareapotentialsecuritythreat.
Asaresult,ifsomeonecomesacrossanerror(forexample,a404PageNotFound,403Forbidden,or500InternalServerError),hewillonlyseeanuglyerrorcodepage.
Torectifythis,itisadvisedtocreatenice,explanatoryerrortemplatepagesandputtheminyourapplication'stemplatefolder.
Eachtemplateshouldbenamedaccordingtotheerrorcodeitrepresents.
ForPageNotFound,youshouldnamethefile404.
html;forInternalServerError,use500.
html;etc.
Nowthatwehaveconfiguredoursettingsforuseinaproductionenvironment,wewillshowyouhowthisenvironmentshouldbesetuptohouseyourDjangoapplication.
AlthoughitispossibletorunDjangousingFastCGIandlighttpd,amoretypicalsetupisApacheandmod_python.
WewillnowlookathowtodeploytoaserverrunningApacheandmod_python.
Thenwe'lltakeabrieflookatdeployingtoasharedWeb-hostingenvironment,whereaccesstohttpd.
confisforbidden.
ibm.
com/developerWorks/developerWorksDeployingDjangoapplicationstoaproductionserverPage9of13DeployingDjangoapplicationstoApachewithmod_pythonAccordingtotheDjangodocumentation,asetupoftheApacheWebserverrunningmod_pythonistherecommendedoptionfordeployingDjangoapplications.
DjangosupportssetupswithatleastApacheHTTPServerV2.
0andmod_pythonV3.
0andlater.
mod_pythonisanApachemodulethatintegratessupportforthePythonprogramminglanguageintotheWebserver.
ItismuchfasterthanthetraditionalCGImethodofexecutingPythonscripts.
Toloadthemod_pythonmoduleintoApache,addthefollowinglinetoyourserver'shttpd.
conffile:LoadModulepython_module/usr/lib/apache2/modules/mod_python.
so.
Inadditiontoloadingthemod_pythonmodule,youalsoneedtosetupaLocationdirectivethattellsApachewhatURLtoassociatewithyourDjangoapplication.
Forthesakeofexample,thesettingsherearewhatwouldapplytothetestprojectprojectcreatedearlier.
Listing11.
testprojectLocationdirectiveSetHandlerpython-programPythonHandlerdjango.
core.
handlers.
modpythonSetEnvDJANGO_SETTINGS_MODULEtestproject.
settingsPythonDebugOffThistellsApachethatyourDjangotestprojectprojectisaccessibleviathe/testprojectURL.
Forexample,ifyourserver'sdomainnameisexample.
com,yourapplicationwouldbeaccessibleviahttp://www.
example.
com/testproject/.
ToloadthesenewsettingsintoApache,simplyrestarttheApacheserver.
Django'sdevelopershighlyrecommendthatyoudonotservemediafiles(suchasimages,video,audio,etc.
)fromthesameWebserverasyourWebapplication,butinmanycases,thatisnotanoption—atleastinitially.
InordertosetupanareaofyourWebsitewheremediafilescanbeserved,youcanaddthefollowingdirectivetoyourhttpd.
conffile.
Listing12.
TellingApachenottousemod_pythonformediafilesSetHandlerNoneThat'sallthereistosettingupApacheandmod_pythonfordeployingDjangotoaproductionWebserver.
Next,we'lltakealookatacommondeploymentscenariowheresomeoneisdeployingtoasharedWeb-hostingserverwheretheyarenotallowedtomodifyhttpd.
conf.
DeployingDjangoapplicationstoasharedWeb-hostingenvironmentUnfortunately,dedicatedserversandvirtualprivateserverstendtobequiteexpensiveand,asaresult,thesearenotviableoptionsfordeploymentforeveryone.
ItiscommonthatyouwillfirstdeployaWebapplicationonasharedhostingenvironment,upgradingtodedicatedsolutionsasdeveloperWorksibm.
com/developerWorks/DeployingDjangoapplicationstoaproductionserverPage10of13theapplicationgrowsinpopularity.
Luckily,mostsharedWeb-hostingprovidersincludePythonsupport,soitispossibletodeployDjangoapplicationsinthisscenario.
Unlikeadedicatedenvironment,enduserstypicallydonothavetheoptionofrunningaseparateserverprocessoreditingthehttpd.
confconfigurationfile.
Thismeanstheycannotmakethechangesoutlinedintheprevioussection,sotheycannotgetDjangoupandrunninginthismanner.
Fortunately,itispossibletodeployDjangotosharedhostingenvironments,usingWebserver-spawnedprocessesthatexecuteaFastCGIprogram.
Createafilecalled.
htaccessandplaceitinthesamedirectoryyouaredeployingyourDjangoapplicationto.
Listing13.
.
htaccessfileAddHandlerfastcgi-script.
fcgiRewriteEngineOnRewriteCond%{REQUEST_FILENAME}!
-fRewriteRule^(.
*)$testproject.
fcgi/$1[QSA,L]ThencreateasmallPythonscriptthatinformsApacheofthevarioussettingsforyourDjangoprojectandexecutestheFastCGIprogram.
Thenameofthefileisnotimportant,butitmustbethesameasthefilenameintheRewriteRulelineof.
htaccess.
InListing14,weusedthefilenametestproject.
fcgi,sothat'swhatIwillcallmyscript.
Listing14.
testproject.
fcgifile#!
/usr/bin/pythonimportsys,ossys.
path.
insert(0,"/home/joelennon/python")os.
environ['DJANGO_SETTINGS_MODULE']="testproject.
settings"fromdjango.
core.
servers.
fastcgiimportrunfastcgirunfastcgi(method="threaded",daemonize="false")Besuretomakethefileexecutable.
Ifyouhaveshellaccesstoyoursharedhostingserver,loginandchangetothedirectorythefileiscontainedinandrunchmod755testproject.
fcgi.
Ifyoudonothaveshellaccess,youcanchangefilepermissionswithmostdecentFTPclients.
Anytimeyouchangeyourapplication'scode,youneedtochangethetimestamponthisfile.
ThistellsApachethattheapplicationhasbeenupdated,anditwillcontinuetorestartyourDjangoapplication.
Ifyouhaveshellaccess,thisisassimpleasrunningtouchtestproject.
fcgi.
Ifyoudonothaveshellaccess,youcanupdatethetimestampofthefilebyreuploadingitorbyeditingitandresavingit.
Ifyouprefernottogetyourhandsdirtywiththeseconfigurationfiles,youcouldalwaysavailofahostingservicedesignedtosupportDjangoapplicationsoutofthebox.
ThepopularMediaTemplehostingprovideroffersaDjangoGridContaineradd-ontoitsGridServiceoffering,startingfrom$20/monthfor256MBofRAM.
TheGridContainerrunsonapre-tunedlighttpd/FastCGIsetup,andtheamountofRAMcanbeincreasedtoscalealongwithyourapplication.
ibm.
com/developerWorks/developerWorksDeployingDjangoapplicationstoaproductionserverPage11of13ScalingyourDjangodeploymentIfyourDjangoapplicationissuccessful,itislikelythatyouwillneedyourdeploymenttobeasscalableaspossible.
It'scommonforWebapplicationstoworkfineunderaverageloads,butphenomenaliketheDiggeffectcanforwardsomuchtraffictotheapplicationthatitbucklesunderthesurgeinload.
Fortunately,DjangoandPythonarehighlyscalablebynature,butthereareotherthingsyouneedtoconsiderasyourapplicationgrows.
IfyouarerunningyourDjangoapplicationonasharedhostingenvironmentandarestartingtofeelthatitisoutgrowingthelimitedresourcesavailabletoitinsuchaspace,yourobviousfirstportofcallisthemovetoadedicatedmachine.
Ifcostisanissue,virtualprivateserversofferaninexpensiveintermediarybetweensharedhostingandadedicatedserver.
Asyourapplicationgrows,eventheresourcesofadedicatedservercanbecomesparseveryquickly.
Thefollowingaresomeremediesthatmayeasetheburdenonyourserver:Turnoffanyunusedprocessesordaemons,suchasmailservers,streamingservers,gamingserversoranyotherunnecessaryprocesses,thatarehoggingpreciousCPUtimeandRAM.
Farmoffyourmediafilestoacloudplatform,suchasAmazonS3.
ThiswillallowyoutoonlyuseyourWebserverforDjangorequestsandkeepyourmediaonaseparateserver.
TurnoffApache'sKeep-Aliveoption.
Keep-AliveisanextensiontotheHTTPprotocol,whichallowspersistentconnectionsoverHTTP.
This,inturn,allowsmultiplerequeststobesentdownoverthesameTCPconnection,dramaticallyspeedinguptheservingofstaticHTMLdocumentsandimages.
Unfortunately,thisextensioncanhaveanegativeeffectontheperformanceofaDjangoapplication.
Pleasenotethatyoushouldonlyturnthisoptionoffifyouhavemovedyourmediafilestoadifferentserver.
ToturnoffKeep-Alive,findtherelevantlineinyourhttpd.
conffileandchangeittoKeep-AliveOff.
UseDjango'sbuilt-incacheframework.
Itispoweredbymemcached,apopulardistributedmemory-objectcachingsystem.
EffectivecachingcandrasticallyenhancetheperformanceofyourDjangoapplications.
Upgradeyourserver.
DedicateasmuchRAMaspossible,andifdiskspaceisanissue,consideraddinganewdisk.
Ifyourserverisstruggling,it'smorethanlikelythatit'sduetotheRAMbeingusedup.
Don'twasteyourmoneyupgradingprocessors—spendthemoneyonRAM,instead.
Buyanotherserver.
Theremaycomeatimewhenyourserverjustcan'thandletheloadfromyourDjangoapplicationonitsown.
Assoonasyoursingleserversetupstartstogiveway,addanotherserver.
YoushouldrunyourWebserverononemachineandyourdatabaseserverontheother.
BesuretousethemachinewithmoreRAMforyourdatabaseserver.
Ifrequired,upgradethenewmachinewithmoreRAManddiskspacewhennecessary.
Usedatabasereplication.
Ifyourdatabaseserverisrunningoutofresources,youcaneasetheburdenbyreplicatingitacrossmorethanoneserver.
Oncereplicationisinplace,youcanaddserverswhenrequiredtoprovideadditionalresources.
Addredundancy.
Withlarge-scaleapplications,havingasinglepointoffailureforyourWebserverordatabaseserverisadisasterwaitingtohappen.
Youshouldaddredundantserverswherepossible,whichwilltakeoverintheeventoftheprimaryserverfailing.
Additionally,developerWorksibm.
com/developerWorks/DeployingDjangoapplicationstoaproductionserverPage12of13usingload-balancinghardwareorsoftware,suchasmod_proxy,todistributethetrafficacrossyourserverscandrasticallyincreasetheperformanceofyourapplication.
ItisimportanttoconsiderascalingpathforyourDjangoapplicationasearlyaspossible.
Thisallowsyoutoputaplanofactioninplacethatcoverseverypossiblescenario.
So,iftheDiggeffecthasyourapplicationonitsknees,youcansimplykickthenextstageofyourscalingplanintoactionandembraceyournewuserswithopenarms—andmoreimportantly,afast-runningapplication.
SummaryWehavelookedattheDjangoframeworkfrombothendsofthespectrum—fromadeveloperwithnopriorexperienceusingtheframeworkstartingouttosomeonewhohasafullyreadyDjangoapplicationwaitingtobedeployedlookingforaguideonhowtotackledeployingtheapplicationtotheWeb.
We'vealsoexaminedwhattoconsiderintermsofscalabilityforthefuture.
WelookedatwhataDjangoapplicationismadeupofandlearnedabouttheModel-Template-View(MTV)patternitisbasedon.
WehaveseenthatDjangoisalightweight,easy-to-install,andeasy-to-learnframeworkwithexcellentdocumentationandavibrantcommunitysurroundingit,makingitagreatframeworkforyournextWebapplication.
ibm.
com/developerWorks/developerWorksDeployingDjangoapplicationstoaproductionserverPage13of13RelatedtopicsVisittheDjangoProjecttodownloadtheDjangoframeworkandsubscribetotheofficialDjangoblog.
CheckouttheDjangodocumentationforaplethoraoftutorialsandarticlesaboutDjangoandhowtouseittodeveloppowerfulWebapplications.
DjangoBook:ReadafreeonlineversionofanexcellentbookaboutDjango,coveringeverythingfromintroductoryconceptstodeployment,internationalizationandsecurity.
DiveIntoPython:ReadafreeonlineversionofthiscomprehensivebookonthePythonprogramminglanguage.
ReadtheWikipediaentryforDjango.
VisitDjangoSnippets.
orgforamultitudeofreusable,user-contributedDjangocodesnippetsyoucanfreelyuseinyourownprojects.
FollowdeveloperWorksonTwitter.
Startdevelopingwithproducttrials,freedownloads,andIBMBluemixservices.
CopyrightIBMCorporation2009(www.
ibm.
com/legal/copytrade.
shtml)Trademarks(www.
ibm.
com/developerworks/ibm/trademarks/)
Virmach自上次推出了短租30天的VPS后,也就是月抛型vps,到期不能续费,直接终止服务。此次又推出为期6个月的月抛VPS,可选圣何塞和水牛城机房,适合短期有需求的用户,有兴趣的可以关注一下。VirMach是一家创办于2014年的美国商家,支持支付宝、PayPal等方式,是一家主营廉价便宜VPS服务器的品牌,隶属于Virtual Machine Solutions LLC旗下!在廉价便宜美国...
硅云怎么样?硅云是一家专业的云服务商,硅云的主营产品包括域名和服务器,其中香港云服务器、香港云虚拟主机是非常受欢迎的产品。硅云香港可用区接入了中国电信CN2 GIA、中国联通直连、中国移动直连、HGC、NTT、COGENT、PCCW在内的数十家优质的全球顶级运营商,是为数不多的多线香港云服务商之一。目前,硅云香港云服务器,CN2+BGP线路,1核1G香港云主机仅188元/年起,域名无需备案,支持个...
wordpress高级跨屏企业主题,通用响应式跨平台站点开发,自适应PC端+各移动端屏幕设备,高级可视化自定义设置模块+高效的企业站搜索优化。wordpress绿色企业自适应主题采用标准的HTML5+CSS3语言开发,兼容当下的各种主流浏览器: IE 6+(以及类似360、遨游等基于IE内核的)、Firefox、Google Chrome、Safari、Opera等;同时支持移动终端的常用浏览器应...
rewritecond为你推荐
空间主机那个网站的空间主机比较好免费注册域名求一个免费的注册域名。空间域名空间域名什么意思网站空间域名网站、域名空间三者的关系台湾vps台湾服务器租用托管那里好jsp虚拟空间请问如何卖掉JSP虚拟主机国外网站空间怎么样把网站空间放到国外去?上海虚拟主机上海虚拟主机哪家好啊?山东虚拟主机青岛网络公司哪家好深圳虚拟主机深圳鼎峰网络科技 虚拟主机空间怎么样
天津虚拟主机 3322动态域名注册 金万维动态域名 google电话 圣迭戈 美国主机论坛 好看的桌面背景图片 网站实时监控 搜狗12306抢票助手 发包服务器 个人空间申请 京东商城0元抢购 双拼域名 双线主机 isp服务商 电信托管 raid10 dnspod 中国linux 免费php空间 更多