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/)
iWebFusion(iWFHosting)在部落分享过很多次了,这是成立于2001年的老牌国外主机商H4Y旗下站点,提供的产品包括虚拟主机、VPS和独立服务器租用等等,其中VPS主机基于KVM架构,数据中心可选美国洛杉矶、北卡、本德、蒙蒂塞洛等。商家独立服务器可选5个不同机房,最低每月57美元起,而大流量10Gbps带宽服务器也仅149美元起。首先我们分享几款常规服务器配置信息,以下机器可选择5...
青云互联怎么样?青云互联是一家成立于2020年的主机服务商,致力于为用户提供高性价比稳定快速的主机托管服务,目前提供有美国免费主机、香港主机、韩国服务器、香港服务器、美国云服务器,香港安畅cn2弹性云限时首月五折,15元/月起;可选Windows/可自定义配置,让您的网站高速、稳定运行。点击进入:青云互联官方网站地址青云互联优惠码:八折优惠码:ltY8sHMh (续费同价)青云互联香港云服务器活动...
IT狗为用户提供 在线ping、在线tcping、在线路由追踪、域名被墙检测、域名被污染检测 等实用工具。【工具地址】https://www.itdog.cn/【工具特色】1、目前同类网站中,在线ping 仅支持1次或少量次数的测试,无法客观的展现目标服务器一段时间的网络状况,IT狗Ping工具可持续的进行一段时间的ping测试,并生成更为直观的网络质量柱状图,让用户更容易掌握服务器在各地区、各线...
rewritecond为你推荐
网站空间租赁网站空间租用好一些还是云主机好一些?免费虚拟主机空间免费的虚拟主机空间有没有国外主机空间2个国外主机空间,都放了BLOG,看看哪个更快?美国网站空间论坛选择空间可以选美国网站空间吗?深圳网站空间深圳网站设计 哪家好一些?国内最好的虚拟主机国内虚拟主机哪家的好?虚拟主机系统虚拟主机上的系统与电脑操作系统差别?成都虚拟主机成都唯度科技有限公司怎么样?成都虚拟主机一个虚拟主机最多支持几个子目录呢?一个百度推广账户是不是只能推广一个主域名下的网站?广西虚拟主机怎样建立虚拟机和本地计算机的桥接
怎么注册域名 日本私人vps 北京vps 2014年感恩节 服务器怎么绑定域名 商家促销 免费ftp站点 铁通流量查询 合肥鹏博士 股票老左 速度云 nerds 卡巴斯基试用版 免费美国空间 中国网通测速 银盘服务 国外在线代理服务器 网站加速 买空间网 国内空间 更多