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/)
Webhosting24宣布自7月1日起开始对日本机房的VPS进行NVMe和流量大升级,几乎是翻倍了硬盘和流量,价格依旧不变。目前来看,日本VPS国内过去走的是NTT直连,服务器托管机房应该是CDN77*(也就是datapacket.com),加上高性能平台(AMD Ryzen 9 3900X+NVMe),还是有相当大的性价比的。此外在6月30日,又新增了洛杉矶机房,CPU为AMD Ryzen 9...
无忧云怎么样?无忧云服务器好不好?无忧云值不值得购买?无忧云,无忧云是一家成立于2017年的老牌商家旗下的服务器销售品牌,现由深圳市云上无忧网络科技有限公司运营,是正规持证IDC/ISP/IRCS商家,自营有国内雅安高防、洛阳BGP企业线路、香港CN2线路、国外服务器产品等,非常适合需要稳定的线路的用户,如游戏、企业建站业务需求和各种负载较高的项目,同时还有自营的高性能、高配置的BGP线路高防物理...
介绍:819云怎么样?819云创办于2019,由一家从2017年开始从业的idc行业商家创办,主要从事云服务器,和物理机器819云—-带来了9月最新的秋季便宜vps促销活动,一共4款便宜vps,从2~32G内存,支持Windows系统,…高速建站的美国vps位于洛杉矶cera机房,服务器接入1Gbps带宽,采用魔方管理系统,适合新手玩耍!官方网站:https://www.8...
rewritecond为你推荐
美国免费主机免费主机可以建几个站?免费美国主机谁有免费空间?给我提供一个,主机屋的就不要了,美国主机也行,但是必须得稳定,谢谢空间租用网站空间申请是免费的吗?还有就是使用租用空间,这种便宜空间好使吗?免费云主机免费云主机哪家好?域名购买在网上购买域名 会受骗吗个人虚拟主机个人商城要选多大的虚拟主机?网站域名空间网站域名和空间免备案虚拟空间想买个免备案的虚拟主机,不知道哪里的好点虚拟空间哪个好虚拟主机哪家的最好?网站空间商域名空间商怎么做
美国vps租用 论坛虚拟主机 万网域名注册 域名注册中心 冰山互联 kddi 新世界电讯 一点优惠网 主机合租 cpanel空间 北京双线机房 如何注册阿里云邮箱 空间登录首页 万网空间 阿里云邮箱怎么注册 免 碳云 免费网站加速 qq空间打开很慢 server2008 更多