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/)
Megalayer 商家算是新晋的服务商,商家才开始的时候主要是以香港、美国独立服务器。后来有新增菲律宾机房,包括有VPS云服务器、独立服务器、站群服务器等产品。线路上有CN2优化带宽、全向带宽和国际带宽,这里有看到商家的特价方案有增加至9个,之前是四个的。在这篇文章中,我来整理看看。第一、香港服务器系列这里香港服务器会根据带宽的不同区别。我这里将香港机房的都整理到一个系列里。核心内存硬盘IP带宽...
sharktech怎么样?sharktech (鲨鱼机房)是一家成立于 2003 年的知名美国老牌主机商,又称鲨鱼机房或者SK 机房,一直主打高防系列产品,提供独立服务器租用业务和 VPS 主机,自营机房在美国洛杉矶、丹佛、芝加哥和荷兰阿姆斯特丹,所有产品均提供 DDoS 防护。不知道大家是否注意到sharktech的所有服务器的带宽价格全部跳楼跳水,降幅简直不忍直视了,还没有见过这么便宜的独立服...
国外主机测评昨天接到Hostigger(现Hostiger)商家邮件推送,称其又推出了一款特价大内存VPS,机房位于土耳其的亚欧交界城市伊斯坦布尔,核50G SSD硬盘200Mbps带宽不限月流量只要$59/年。 最近一次分享的促销信息还是5月底,当时商家推出的是同机房同配置的大内存VPS,价格是$59.99/年,不过内存只有10G,虽然同样是大内存,但想必这次商家给出16G,价格却是$59/年,...
rewritecond为你推荐
主机租用注册域名主机租用服务器空间租用个人网络域名空间租用虚拟主机购买虚拟主机哪里购买的好?虚拟主机推荐谁可以给推荐下好用的虚拟主机英文域名求好听的个性英语域名?手机网站空间手机登陆qq空间网址是什么?虚拟主机控制面板万网的虚拟主机控制面板指的是什么呢?安徽虚拟主机合肥金马网络科技有限公司怎么样?shopex虚拟主机支持PHPwind、ShopEx等建站程序的主机什么最好?备案域名域名一共有几种?哪些域名需要备案?
域名备案流程 搜狗12306抢票助手 商家促销 500m空间 33456 shopex主机 游戏服务器出租 七牛云存储 apnic cdn服务 月付空间 美国vpn代理 美国十大啦 godaddy中文 什么是dns apache启动失败 cpu使用率过高怎么办 美国vpn服务器 easypanel 木马检测 更多