匿名用户2021年12月10日
49阅读
开发技术Python
所属分类Web应用开发、Web框架
授权协议MIT License

作品详情

Slapdash

Boilerplateforbootstrappingscalablemulti-pageDashapplications

DashisaPythonframeworkforbuildinganalyticalwebapplications.Slapdashprovidesasensibleprojectlayoutforquicklybuildingoutamulti-pageDashapplicationwithroomforgrowth.Italsoincludes:

Pre-builtlayoutsbasedonBootstrap(withthehelpofDashBootstrapComponents),whichcanbeextendedorswappedoutforlayoutsconstructedusingyourownDash/CSScomponents.ScriptsforconvenientlylaunchingyourappinbothdevandprodenvironmentsAURLrouterthathelpsyoumanageyourapplication'spages

ThisprojectisintendedforbootstrappinginitialDashapplications,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.Installation

Note:SlapdashrequiresPython3.6+

SlapdashisaCookiecutterproject.ThismeansyoufirstneedtogenerateyourownprojectfromtheSlapdashprojecttemplate.

InstallthelatestCookiecutterifyouhaven'tinstalledityet:

pipinstall-Ucookiecutter

Generateyourprojectbyrunningthiscommandandfollowingtheprompts:

cookiecutterhttps://github.com/ned2/slapdash

TheresultingprojectisaPythonpackage,whichyouthenneedtoinstalllikeso:

$pipinstallPATH_TO_PROJECT

Duringdevelopmentyouwilllikelywanttoperformaneditableinstallsothatchangestothesourcecodetakeimmediateeffectontheinstalledpackage.

$pipinstall-ePATH_TO_PROJECTUsageInapp.py,selectthemainlayoutyouwantfromlayouts.py.Createthepagesofyourappindifferentfileswithinthepagesdirectory,bydefiningwithineachatop-levellayoutattributeandcallbacksregisteredwiththeDashappinstancefromtheappmodule.AddthepagesofyourapptotheURLrouterinindex.py.Addanydesiredpagestonavbarinindex.py.Modifyassets/slapdash.cssoraddadditionalstylesheetsinassets.Modifyconfiginsettings.pyasrequired.TheURLRouter

SlapdashusesDash'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&param2=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.

LoadingSpinners

SlapdashcomeswithsomeCSSloadingspinnersbuilt-in.Inordertousethem,simplyaddoneoftheclassesloaderorloader-fadetothecomponentyouwanttobevisuallyrenderedasloadingwhileitiswaitingforacallbacktocomplete.Bothspinnerswillwaitonesecondbeforebeingappliedtoavoidanunpleasantflickeringeffectforresponsivecallbacks.Theloaderspinnerwillhidethecontentsofthecomponentanddisplayaspinner,whiletheloader-fadewillreducetheopacityofthecomponent'scontentsandalsodisplayaspinner.

RunningYourApp

Thisprojectcomeswithtwoconveniencescriptsforrunningyourprojectindevelopmentandproductionenvironments,oryoucanuseyourownWSGIservertoruntheapp.

RunDevApp

Installingthispackageintoyourvirtualenvwillresultintothedevelopmentexecutablebeinginstalledintoyourpathwhenthevirtualenvisactivated.ThiscommandinvokesyourDashapp'srun_servermethod,whichinturnusestheFlaskdevelopmentservertorunyourapp.Thecommandisinvokedasfollows,withproj_slugbeingreplacedbythevalueprovidedforthiscookiecutterparameter.

$run-project_slug-dev

Thescripttakesacoupleofargumentsoptionalparameters,whichyoucandiscoverwiththe--helpflag.Youmayneedtosettheportusingthe--portparameter.Ifyouneedtoexposeyourappoutsideyourlocalmachine,youwillwanttoset--host0.0.0.0.

RunProdApp

Whileconvenient,thedevelopmentwebservershouldnotbeusedinproduction.Installingthispackagewillalsoresultinaproductionexecutablebeinginstalledinyourvirtualenv.Thisisawrapperaroundthemod_wsgi-expresscommand,whichstreamlinesuseofthemod_wsgiApachemoduletorunyouryourapp.Inadditiontoinstallingthemod_wsgiPythonpackage,youwillneedtohaveinstalledApache.Seeinstallationinstructionsinthemod_wsgidocumentation.Thisscriptalsotakesarangeofcommandlinearguments,whichcanbediscoveredwiththe--helpflag.

$run-project_slug-prod

Thisscriptwillalsoapplysettingsfoundinthemoduleproject_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).

RunningwithadifferentWSGIServer

YoucaneasilyrunyourappusingaWSGIserverofyourchoice(suchasGunicornforexample)withtheproject_slug.wsgientrypoint(definedinwsgi.py)likeso:

$gunicornproject_slug.wsgi

Note:ifyouwanttoenableDash'sdebugmodewhilerunningwithaWSGIserver,you'llneedtoexporttheDASH_DEBUGenvironmentvariabletotrue.SeetheDevToolssectionoftheDashDocsformoredetails.

IncludedLibraries

Slapdashincludesafewlibrariesforgettingfullyfunctionalapplicationsoffthegroundfaster.Theseinclude:

DashBootstrapComponents:AsuiteofDashcomponentsthatwrapBootstrapclasses,allowingforcleanerintegrationofBootstrapwithDashlayouts.Bootstrap-LocalcopyofBootstrapCSSfilessoyoucanruntheappoffline.FontAwesome-LocalcopyofFontAwesomefilesforofflineaccess.Becauseeveryonewantsprettyicons.UsefulReferences

TheDashUserGuide

PlotlyPythonclientfigurereferenceDocumentsthecontentsofplotly.graph_objs,whichcontainsthedifferenttypesofchartsavailable,aswelltheLayoutclass,forcustomisingtheappearanceofcharts.

TheDashCommunityForum

DashShowandTellCommunityThread

TheDashGitHubRepository

Contributing

PRsarewelcome!Ifyouhavebroaderchangesinmind,thencreatinganissuefirstfordiscussionwouldbebest.

SeetingupaDevEnvironment

AfterchangingdirectorytothetoplevelSlapdashdirectory:

InstallSlapdashintoyourvirtualenv:$pipinstall-e.Installthedevelopmentrequirements:$pipinstall-rrequirements-dev.txtInstallthepre-commithook(fortheBlackcodeformatter)$pre-commitinstall
声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论