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/)
也有在上个月介绍到糖果主机商12周年的促销活动,我有看到不少的朋友还是选择他们家的香港虚拟主机和美国虚拟主机比较多,同时有一个网友有联系到推荐入门的个人网站主机,最后建议他选择糖果主机的迷你主机方案,适合单个站点的。这次商家又推出所谓的秋季活动促销,这里一并整理看看这个服务商在秋季活动中有哪些值得选择的主机方案,比如虚拟主机最低可以享受六折,云服务器可以享受五折优惠。 官网地址:糖果主机秋季活动促...
bgpto怎么样?bgp.to日本机房、新加坡机房的独立服务器在搞特价促销,日本独立服务器低至6.5折优惠,新加坡独立服务器低至7.5折优惠,所有优惠都是循环的,终身不涨价。服务器不限制流量,支持升级带宽,免费支持Linux和Windows server中文版(还包括Windows 10). 特色:自动部署,无需人工干预,用户可以在后台自己重装系统、重启、关机等操作!bgpto主打日本(东京、大阪...
A400互联是一家成立于2020年的商家,主要推行洛杉矶服务器采用kvm架构,线路优质,延迟低,稳定性高!全场产品对标腾讯云轻量,服务器线路有有美国洛杉矶cn2_gia、香港cn2+cmi,目前推行的vps服务器均为精心挑选的优质线路机房,A400互联推出了夏季优惠洛杉矶5折、香港7折促销活动,质量可靠,价格实惠!二:优惠码洛杉矶五折优惠码:20210620香港cn2七折优惠码:0710三、优惠方...
rewritecond为你推荐
海外主机租用请问如何租一个国外的服务器?大概需要多少钱?企业虚拟主机企业虚拟主机现在具体是多少价位?广东虚拟主机大家推荐一下广东地区稳定的IDC中文域名注册查询如何注册中文域名?请问个人怎样注册中文域名。cn的,个人注册别人公司的可以吗?违法吗?或者怎样才能注册com域名空间.com的域名+300M的空间要多少钱?asp主机空间Asp空间是什么空间啊?跟有的网站提供的免费空间有什么区别吗?域名注册查询如何查域名有没有被注册国内ip代理全国各省代理IP虚拟主机申请在哪里可以申请到虚拟主机呢虚拟主机申请个人虚拟主机怎么申请?
淘宝二级域名 网站监控 新世界电讯 服务器cpu性能排行 阿里云浏览器 免费美国空间 www789 谷歌台湾 购买空间 七牛云存储 mteam sonya 免费网站加速 删除域名 防盗链 卡巴下载 日本小学生 挂马检测工具 瓦工工具 免费网络电视软件 更多