Boilerplateforbootstrappingscalablemulti-pageDashapplications
DashisaPythonframeworkforbuildinganalyticalwebapplications.Slapdashprovidesasensibleprojectlayoutforquicklybuildingoutamulti-pageDashapplicationwithroomforgrowth.Italsoincludes:
Pre-builtlayoutsbasedonBootstrap(withthehelpofDashBootstrapComponents),whichcanbeextendedorswappedoutforlayoutsconstructedusingyourownDash/CSScomponents.ScriptsforconvenientlylaunchingyourappinbothdevandprodenvironmentsAURLrouterthathelpsyoumanageyourapplication'spagesThisprojectisintendedforbootstrappinginitialDashapplications,ratherthanbeingadependencyforyourapplication.Youshouldn'tassumethatSlapdash'sinternalstructureandinterfaceswillbestable,astheywillchange.
BoilerplateOverview__init__.pyContainshelperfunctionsforcreatingtheFlaskandDashinstances.app.pyEntrypointintotheapp.CreatesboththeFlaskandDashinstancesusedfortheappandthenimportstherestoftheappthroughtheindexmodule.index.pyURLroutesandtherouteraredefinedhere,alongwiththenavbaranditscorrespondingentries.wsgi.pyContainstheFlaskapplicationattributesuitableforpointingWSGIserversat.settings.pyConfigurablesettingsfortheapplication.prod_settings.pyConfigurablesettingsforrunningtheapplicationinaproductionenvironment.Settingsdefinedherewilltakeprecedenceoverthosefoundinsettings.py.exceptions.pyExceptionsusedbyyourappcanbedefinedhere.components.pyConvenientPythonpseudo-componentsaredefinedhere.utils.pyUtilitythings.pagesThesuggestedprojectlayoutistoplaceeachpageofyourappwithinthisdirectory,treatingeachpageasamodularsub-appcontainingalayoutsattributethatyoucanregisterwiththerouterinindex.py.assetsLocationforstaticassetsthatwillbeexposedtothewebserver.InstallationNote:SlapdashrequiresPython3.6+
SlapdashisaCookiecutterproject.ThismeansyoufirstneedtogenerateyourownprojectfromtheSlapdashprojecttemplate.
InstallthelatestCookiecutterifyouhaven'tinstalledityet:
pipinstall-UcookiecutterGenerateyourprojectbyrunningthiscommandandfollowingtheprompts:
cookiecutterhttps://github.com/ned2/slapdashTheresultingprojectisaPythonpackage,whichyouthenneedtoinstalllikeso:
$pipinstallPATH_TO_PROJECTDuringdevelopmentyouwilllikelywanttoperformaneditableinstallsothatchangestothesourcecodetakeimmediateeffectontheinstalledpackage.
$pipinstall-ePATH_TO_PROJECTUsageInapp.py,selectthemainlayoutyouwantfromlayouts.py.Createthepagesofyourappindifferentfileswithinthepagesdirectory,bydefiningwithineachatop-levellayoutattributeandcallbacksregisteredwiththeDashappinstancefromtheappmodule.AddthepagesofyourapptotheURLrouterinindex.py.Addanydesiredpagestonavbarinindex.py.Modifyassets/slapdash.cssoraddadditionalstylesheetsinassets.Modifyconfiginsettings.pyasrequired.TheURLRouterSlapdashusesDash'sbuilt-insupportforcreatingmulti-pageapps.Thisinvolvescreatingacallbackthattargetsacontainerhtml.Divinyourlayout,andinjectslayoutfragmentsintothechildrenpropertyofthecontainerwhenusersclickonlinksconstructedwithdcc.Link.SlapdashprovidesaconvenienceclassDashRouter,whichassistswiththeconstructionofthiscallback.Thefollowingsnippetprovidesanexampleofitsuse:
urls=(("",page1.layout),("page1",page1.layout),("page2",page2.layout),("page3",page3.get_layout),)router=DashRouter(app,urls)TheDashRouterclasstakesasinputaDashinstance,andasequenceofURLtuples,whereeachtuplecontainsastringrepresentingtheURLendpointforthepageasthefirstitem,andthelayoutfragmenttoassociatewiththatURLasthesecond.ThelayoutfragmentcaneitherbeaninstanceofDash'sComponentclass(suchasanhtml.Div)oracallablethatreturnsaComponentinstance,suchasthefunctionget_layoutintheabovesnippet.Thiscallableshouldtakeavariablenumberofkeywordarguments,asanyqueryparameterspresentintheURLwillbepassedintothelayoutcallableaskeywordarguments.forexampleyoucouldpassvaluesintothelayoutfunctionbelowusingtheURLhttps://hostname?param1=value1¶m2=value2.
defget_layout(**query_params):param1_value=query_params.get("param1","param1notprovided")param2_value=query_params.get("param2","param1notprovided")returnhtml.Div([param1_value,param2_value])NotethattheURLendpointswillbeautomaticallyprefixedwithDash's'routes_pathname_prefix'parameter,sowhenspecifyinginternalURLlinkswithinyourlayout,youwillwanttouseutil.get_urlwhichprefixestheURLpathforyou.
LoadingSpinnersSlapdashcomeswithsomeCSSloadingspinnersbuilt-in.Inordertousethem,simplyaddoneoftheclassesloaderorloader-fadetothecomponentyouwanttobevisuallyrenderedasloadingwhileitiswaitingforacallbacktocomplete.Bothspinnerswillwaitonesecondbeforebeingappliedtoavoidanunpleasantflickeringeffectforresponsivecallbacks.Theloaderspinnerwillhidethecontentsofthecomponentanddisplayaspinner,whiletheloader-fadewillreducetheopacityofthecomponent'scontentsandalsodisplayaspinner.
RunningYourAppThisprojectcomeswithtwoconveniencescriptsforrunningyourprojectindevelopmentandproductionenvironments,oryoucanuseyourownWSGIservertoruntheapp.
RunDevAppInstallingthispackageintoyourvirtualenvwillresultintothedevelopmentexecutablebeinginstalledintoyourpathwhenthevirtualenvisactivated.ThiscommandinvokesyourDashapp'srun_servermethod,whichinturnusestheFlaskdevelopmentservertorunyourapp.Thecommandisinvokedasfollows,withproj_slugbeingreplacedbythevalueprovidedforthiscookiecutterparameter.
$run-project_slug-devThescripttakesacoupleofargumentsoptionalparameters,whichyoucandiscoverwiththe--helpflag.Youmayneedtosettheportusingthe--portparameter.Ifyouneedtoexposeyourappoutsideyourlocalmachine,youwillwanttoset--host0.0.0.0.
RunProdAppWhileconvenient,thedevelopmentwebservershouldnotbeusedinproduction.Installingthispackagewillalsoresultinaproductionexecutablebeinginstalledinyourvirtualenv.Thisisawrapperaroundthemod_wsgi-expresscommand,whichstreamlinesuseofthemod_wsgiApachemoduletorunyouryourapp.Inadditiontoinstallingthemod_wsgiPythonpackage,youwillneedtohaveinstalledApache.Seeinstallationinstructionsinthemod_wsgidocumentation.Thisscriptalsotakesarangeofcommandlinearguments,whichcanbediscoveredwiththe--helpflag.
$run-project_slug-prodThisscriptwillalsoapplysettingsfoundinthemoduleproject_slug.prod_settings(oracustomPythonfilesuppliedwiththe--settingsflag)andwhichtakesprecedenceoverthesamesettingsfoundinproject_slug.settings.
Anotableadvantageofusingmod_wsgioverotherWSGIserversisthatwedonotneedtoconfigureandrunawebserverseparatetotheWSGIserver.WhenusingotherWSGIservers(suchasGunicornoruWSGI),youdonotwanttoexposethemdirectlytowebrequestsfromtheoutsideworldfortworeasons:1)incomingrequestswillnotbebuffered,exposingyoutopotentialdenialofserviceattacks,and2)youwillbeservingyourstaticassetsviaDash'sFlaskinstance,whichisslow.Theproductionscriptusesmod_wsgi-expresstospinupanApacheprocess(separatetoanyprocessalreadyrunningandlisteningonport80)thatwillbufferrequests,passingthemofftotheworkerprocessesrunningyourapp,andwillalsosetuptheApacheinstancetoserveyourstaticassetsmuchfasterthanwouldbethecasethroughthePythonworkerprocesses.
Note:Youwillneedtoreinstallthispackageinorderforchangestotheprodscripttotakeeffectevenifyouusedaneditableinstall(iepipinstall-e).
RunningwithadifferentWSGIServerYoucaneasilyrunyourappusingaWSGIserverofyourchoice(suchasGunicornforexample)withtheproject_slug.wsgientrypoint(definedinwsgi.py)likeso:
$gunicornproject_slug.wsgiNote:ifyouwanttoenableDash'sdebugmodewhilerunningwithaWSGIserver,you'llneedtoexporttheDASH_DEBUGenvironmentvariabletotrue.SeetheDevToolssectionoftheDashDocsformoredetails.
IncludedLibrariesSlapdashincludesafewlibrariesforgettingfullyfunctionalapplicationsoffthegroundfaster.Theseinclude:
DashBootstrapComponents:AsuiteofDashcomponentsthatwrapBootstrapclasses,allowingforcleanerintegrationofBootstrapwithDashlayouts.Bootstrap-LocalcopyofBootstrapCSSfilessoyoucanruntheappoffline.FontAwesome-LocalcopyofFontAwesomefilesforofflineaccess.Becauseeveryonewantsprettyicons.UsefulReferencesTheDashUserGuide
PlotlyPythonclientfigurereferenceDocumentsthecontentsofplotly.graph_objs,whichcontainsthedifferenttypesofchartsavailable,aswelltheLayoutclass,forcustomisingtheappearanceofcharts.
TheDashCommunityForum
DashShowandTellCommunityThread
TheDashGitHubRepository
ContributingPRsarewelcome!Ifyouhavebroaderchangesinmind,thencreatinganissuefirstfordiscussionwouldbebest.
SeetingupaDevEnvironmentAfterchangingdirectorytothetoplevelSlapdashdirectory:
InstallSlapdashintoyourvirtualenv:$pipinstall-e.Installthedevelopmentrequirements:$pipinstall-rrequirements-dev.txtInstallthepre-commithook(fortheBlackcodeformatter)$pre-commitinstall
评论