arelle-release 2.17.1__py3-none-any.whl → 2.37.71__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (893) hide show
  1. arelle/Aspect.py +6 -3
  2. arelle/BetaFeatures.py +3 -0
  3. arelle/Cntlr.py +117 -413
  4. arelle/CntlrCmdLine.py +364 -227
  5. arelle/CntlrQuickBooks.py +4 -2
  6. arelle/CntlrWebMain.py +179 -119
  7. arelle/CntlrWinMain.py +342 -124
  8. arelle/DialogAbout.py +1 -1
  9. arelle/DialogArcroleGroup.py +1 -1
  10. arelle/DialogFind.py +1 -1
  11. arelle/DialogFormulaParameters.py +2 -2
  12. arelle/DialogLanguage.py +45 -36
  13. arelle/DialogNewFactItem.py +1 -1
  14. arelle/DialogOpenArchive.py +30 -34
  15. arelle/DialogPackageManager.py +11 -8
  16. arelle/DialogPluginManager.py +43 -89
  17. arelle/DialogRssWatch.py +2 -2
  18. arelle/DialogURL.py +1 -1
  19. arelle/DialogUserPassword.py +1 -1
  20. arelle/DisclosureSystem.py +69 -1
  21. arelle/ErrorManager.py +321 -0
  22. arelle/FileSource.py +201 -99
  23. arelle/FunctionFn.py +44 -5
  24. arelle/FunctionIxt.py +16 -13
  25. arelle/FunctionUtil.py +1 -1
  26. arelle/FunctionXfi.py +68 -24
  27. arelle/FunctionXs.py +1 -1
  28. arelle/HtmlUtil.py +5 -4
  29. arelle/LeiUtil.py +63 -43
  30. arelle/LinkbaseType.py +94 -0
  31. arelle/LocalViewer.py +8 -2
  32. arelle/Locale.py +239 -79
  33. arelle/ModelDocument.py +180 -48
  34. arelle/ModelDtsObject.py +32 -27
  35. arelle/ModelFormulaObject.py +14 -6
  36. arelle/ModelInstanceObject.py +43 -14
  37. arelle/ModelManager.py +6 -1
  38. arelle/ModelObject.py +12 -8
  39. arelle/ModelObjectFactory.py +18 -2
  40. arelle/ModelRelationshipSet.py +46 -3
  41. arelle/ModelRenderingObject.py +899 -951
  42. arelle/ModelRssItem.py +2 -4
  43. arelle/ModelTestcaseObject.py +41 -4
  44. arelle/ModelValue.py +42 -14
  45. arelle/ModelVersReport.py +1 -1
  46. arelle/ModelXbrl.py +133 -273
  47. arelle/PackageManager.py +202 -176
  48. arelle/PluginManager.py +551 -239
  49. arelle/PluginUtils.py +54 -0
  50. arelle/PrototypeInstanceObject.py +53 -12
  51. arelle/PythonUtil.py +166 -25
  52. arelle/RuntimeOptions.py +32 -18
  53. arelle/SocketUtils.py +3 -0
  54. arelle/SystemInfo.py +1 -1
  55. arelle/TkTableWrapper.py +33 -5
  56. arelle/UITkTable.py +27 -21
  57. arelle/Updater.py +7 -3
  58. arelle/UrlUtil.py +6 -2
  59. arelle/Validate.py +596 -402
  60. arelle/ValidateDuplicateFacts.py +584 -0
  61. arelle/ValidateFileSource.py +38 -0
  62. arelle/ValidateFilingText.py +46 -29
  63. arelle/ValidateInfoset.py +104 -32
  64. arelle/ValidateUtr.py +31 -4
  65. arelle/ValidateXbrl.py +144 -120
  66. arelle/ValidateXbrlCalcs.py +51 -66
  67. arelle/ValidateXbrlDTS.py +98 -29
  68. arelle/Version.py +2 -7
  69. arelle/ViewFile.py +2 -0
  70. arelle/ViewFileDTS.py +7 -2
  71. arelle/ViewFileFactList.py +1 -1
  72. arelle/ViewFileFactTable.py +4 -4
  73. arelle/ViewFileRelationshipSet.py +36 -19
  74. arelle/ViewFileRenderedGrid.py +164 -753
  75. arelle/ViewFileRenderedLayout.py +174 -0
  76. arelle/ViewFileRenderedStructure.py +108 -0
  77. arelle/ViewWinDTS.py +4 -1
  78. arelle/ViewWinFactList.py +1 -1
  79. arelle/ViewWinFactTable.py +1 -1
  80. arelle/ViewWinRelationshipSet.py +14 -8
  81. arelle/ViewWinRenderedGrid.py +397 -287
  82. arelle/ViewWinRssFeed.py +4 -0
  83. arelle/ViewWinTree.py +15 -9
  84. arelle/ViewWinXml.py +1 -1
  85. arelle/WebCache.py +510 -272
  86. arelle/XbrlConst.py +202 -196
  87. arelle/XbrlUtil.py +2 -1
  88. arelle/XhtmlValidate.py +9 -23
  89. arelle/XmlUtil.py +24 -19
  90. arelle/XmlValidate.py +95 -67
  91. arelle/XmlValidateParticles.py +4 -4
  92. arelle/_version.py +33 -3
  93. arelle/api/Session.py +183 -0
  94. arelle/config/creationSoftwareNames.json +24 -10
  95. arelle/config/disclosuresystems.xml +1 -1
  96. arelle/config/disclosuresystems.xsd +3 -0
  97. arelle/config/sbr-text-formatting.xsd +737 -0
  98. arelle/conformance/CSVTestcaseLoader.py +102 -0
  99. arelle/formula/FactAspectsCache.py +10 -4
  100. arelle/formula/ValidateFormula.py +82 -194
  101. arelle/formula/XPathContext.py +42 -28
  102. arelle/formula/XPathParser.py +15 -9
  103. arelle/locale/ar_EG/LC_MESSAGES/ar_EG.po +3 -4
  104. arelle/locale/messages.pot +1 -2
  105. arelle/locale/ru/LC_MESSAGES/ru.po +2 -2
  106. arelle/logging/formatters/LogFormatter.py +47 -0
  107. arelle/logging/handlers/LogHandlerWithXml.py +94 -0
  108. arelle/logging/handlers/LogToBufferHandler.py +20 -0
  109. arelle/logging/handlers/LogToPrintHandler.py +41 -0
  110. arelle/logging/handlers/LogToXmlHandler.py +244 -0
  111. arelle/logging/handlers/StructuredMessageLogHandler.py +74 -0
  112. arelle/model/CommentBase.py +3 -0
  113. arelle/model/ElementBase.py +3 -0
  114. arelle/model/PIBase.py +3 -0
  115. arelle/model/__init__.py +3 -0
  116. arelle/oim/Load.py +2869 -0
  117. arelle/oim/Validate.py +155 -0
  118. arelle/oim/xml/Save.py +21 -0
  119. arelle/packages/PackageConst.py +7 -0
  120. arelle/packages/PackageType.py +13 -0
  121. arelle/packages/PackageUtils.py +22 -0
  122. arelle/packages/PackageValidation.py +200 -0
  123. arelle/packages/report/DetectReportPackage.py +13 -0
  124. arelle/packages/report/ReportPackage.py +265 -0
  125. arelle/packages/report/ReportPackageConst.py +79 -0
  126. arelle/packages/report/ReportPackageValidator.py +207 -0
  127. arelle/plugin/EdgarRendererAllReports.py +12 -12
  128. arelle/plugin/OimTaxonomy/ModelValueMore.py +15 -0
  129. arelle/plugin/OimTaxonomy/ValidateDTS.py +484 -0
  130. arelle/plugin/OimTaxonomy/ViewXbrlTxmyObj.py +239 -0
  131. arelle/plugin/OimTaxonomy/XbrlAbstract.py +16 -0
  132. arelle/plugin/OimTaxonomy/XbrlConcept.py +68 -0
  133. arelle/plugin/OimTaxonomy/XbrlConst.py +261 -0
  134. arelle/plugin/OimTaxonomy/XbrlCube.py +91 -0
  135. arelle/plugin/OimTaxonomy/XbrlDimension.py +38 -0
  136. arelle/plugin/OimTaxonomy/XbrlDts.py +152 -0
  137. arelle/plugin/OimTaxonomy/XbrlEntity.py +16 -0
  138. arelle/plugin/OimTaxonomy/XbrlGroup.py +22 -0
  139. arelle/plugin/OimTaxonomy/XbrlImportedTaxonomy.py +22 -0
  140. arelle/plugin/OimTaxonomy/XbrlLabel.py +31 -0
  141. arelle/plugin/OimTaxonomy/XbrlNetwork.py +100 -0
  142. arelle/plugin/OimTaxonomy/XbrlProperty.py +28 -0
  143. arelle/plugin/OimTaxonomy/XbrlReference.py +33 -0
  144. arelle/plugin/OimTaxonomy/XbrlReport.py +24 -0
  145. arelle/plugin/OimTaxonomy/XbrlTableTemplate.py +35 -0
  146. arelle/plugin/OimTaxonomy/XbrlTaxonomy.py +93 -0
  147. arelle/plugin/OimTaxonomy/XbrlTaxonomyObject.py +154 -0
  148. arelle/plugin/OimTaxonomy/XbrlTransform.py +17 -0
  149. arelle/plugin/OimTaxonomy/XbrlTypes.py +23 -0
  150. arelle/plugin/OimTaxonomy/XbrlUnit.py +17 -0
  151. arelle/plugin/OimTaxonomy/__init__.py +1037 -0
  152. arelle/plugin/OimTaxonomy/resources/iso4217.json +4479 -0
  153. arelle/plugin/OimTaxonomy/resources/oim-taxonomy-schema.json +935 -0
  154. arelle/plugin/OimTaxonomy/resources/ref.json +333 -0
  155. arelle/plugin/OimTaxonomy/resources/transform-types.json +2481 -0
  156. arelle/plugin/OimTaxonomy/resources/types.json +727 -0
  157. arelle/plugin/OimTaxonomy/resources/utr.json +3046 -0
  158. arelle/plugin/OimTaxonomy/resources/xbrlSpec.json +1082 -0
  159. arelle/plugin/formulaLoader.py +3 -3
  160. arelle/plugin/formulaSaver.py +4 -4
  161. arelle/plugin/inlineXbrlDocumentSet.py +331 -102
  162. arelle/plugin/internet/proxyNTLM/HTTPNtlmAuthHandler.py +1 -1
  163. arelle/plugin/loadFromExcel.py +13 -10
  164. arelle/plugin/loadFromOIM.py +16 -3096
  165. arelle/plugin/logging/saveMessages.py +1 -1
  166. arelle/plugin/saveHtmlEBAtables.py +293 -213
  167. arelle/plugin/saveLoadableOIM.py +652 -361
  168. arelle/plugin/saveOIMTaxonomy.py +311 -0
  169. arelle/plugin/streamingExtensions.py +1 -1
  170. arelle/plugin/systemInfo.py +46 -0
  171. arelle/plugin/transforms/tester.py +4 -4
  172. arelle/plugin/validate/CIPC/Const.py +18 -0
  173. arelle/plugin/validate/CIPC/__init__.py +34 -13
  174. arelle/plugin/validate/DBA/DisclosureSystems.py +12 -0
  175. arelle/plugin/validate/DBA/PluginValidationDataExtension.py +165 -0
  176. arelle/plugin/validate/DBA/ValidationPluginExtension.py +545 -0
  177. arelle/plugin/validate/DBA/__init__.py +49 -0
  178. arelle/plugin/validate/DBA/resources/config.xml +21 -0
  179. arelle/plugin/validate/DBA/rules/__init__.py +323 -0
  180. arelle/plugin/validate/DBA/rules/fr.py +1377 -0
  181. arelle/plugin/validate/DBA/rules/tc.py +45 -0
  182. arelle/plugin/validate/DBA/rules/th.py +172 -0
  183. arelle/plugin/validate/DBA/rules/tm.py +351 -0
  184. arelle/plugin/validate/DBA/rules/tr.py +373 -0
  185. arelle/plugin/validate/EBA/__init__.py +11 -12
  186. arelle/plugin/validate/EDINET/Constants.py +208 -0
  187. arelle/plugin/validate/EDINET/ContextRequirement.py +58 -0
  188. arelle/plugin/validate/EDINET/ControllerPluginData.py +298 -0
  189. arelle/plugin/validate/EDINET/CoverItemRequirements.py +42 -0
  190. arelle/plugin/validate/EDINET/DeiRequirements.py +118 -0
  191. arelle/plugin/validate/EDINET/DisclosureSystems.py +1 -0
  192. arelle/plugin/validate/EDINET/FilingFormat.py +275 -0
  193. arelle/plugin/validate/EDINET/FormType.py +134 -0
  194. arelle/plugin/validate/EDINET/ManifestInstance.py +236 -0
  195. arelle/plugin/validate/EDINET/PluginValidationDataExtension.py +640 -0
  196. arelle/plugin/validate/EDINET/ReportFolderType.py +162 -0
  197. arelle/plugin/validate/EDINET/Statement.py +139 -0
  198. arelle/plugin/validate/EDINET/TableOfContentsBuilder.py +493 -0
  199. arelle/plugin/validate/EDINET/UploadContents.py +48 -0
  200. arelle/plugin/validate/EDINET/ValidationPluginExtension.py +64 -0
  201. arelle/plugin/validate/EDINET/__init__.py +109 -0
  202. arelle/plugin/validate/EDINET/resources/config.xml +22 -0
  203. arelle/plugin/validate/EDINET/resources/cover-item-requirements.json +793 -0
  204. arelle/plugin/validate/EDINET/resources/dei-requirements.csv +27 -0
  205. arelle/plugin/validate/EDINET/resources/edinet-taxonomies.xml +62 -0
  206. arelle/plugin/validate/EDINET/rules/contexts.py +547 -0
  207. arelle/plugin/validate/EDINET/rules/edinet.py +1991 -0
  208. arelle/plugin/validate/EDINET/rules/frta.py +301 -0
  209. arelle/plugin/validate/EDINET/rules/gfm.py +2394 -0
  210. arelle/plugin/validate/EDINET/rules/manifests.py +88 -0
  211. arelle/plugin/validate/EDINET/rules/upload.py +1370 -0
  212. arelle/plugin/validate/ESEF/Const.py +16 -75
  213. arelle/plugin/validate/ESEF/Dimensions.py +2 -2
  214. arelle/plugin/validate/ESEF/ESEF_2021/DTS.py +6 -1
  215. arelle/plugin/validate/ESEF/ESEF_2021/Image.py +7 -4
  216. arelle/plugin/validate/ESEF/ESEF_2021/ValidateXbrlFinally.py +80 -57
  217. arelle/plugin/validate/ESEF/ESEF_Current/DTS.py +60 -22
  218. arelle/plugin/validate/ESEF/ESEF_Current/ValidateXbrlFinally.py +272 -133
  219. arelle/plugin/validate/ESEF/Util.py +5 -19
  220. arelle/plugin/validate/ESEF/__init__.py +61 -46
  221. arelle/plugin/validate/ESEF/resources/authority-validations.json +120 -10
  222. arelle/plugin/validate/ESEF/resources/config.xml +44 -3
  223. arelle/plugin/validate/FERC/__init__.py +31 -18
  224. arelle/plugin/validate/FERC/config.xml +18 -18
  225. arelle/plugin/validate/NL/DisclosureSystems.py +19 -3
  226. arelle/plugin/validate/NL/PluginValidationDataExtension.py +710 -7
  227. arelle/plugin/validate/NL/ValidationPluginExtension.py +117 -12
  228. arelle/plugin/validate/NL/__init__.py +21 -10
  229. arelle/plugin/validate/NL/resources/config.xml +27 -6
  230. arelle/plugin/validate/NL/rules/br_kvk.py +81 -21
  231. arelle/plugin/validate/NL/rules/fg_nl.py +292 -0
  232. arelle/plugin/validate/NL/rules/fr_kvk.py +60 -7
  233. arelle/plugin/validate/NL/rules/fr_nl.py +705 -24
  234. arelle/plugin/validate/NL/rules/nl_kvk.py +2182 -0
  235. arelle/plugin/validate/ROS/DisclosureSystems.py +1 -0
  236. arelle/plugin/validate/ROS/PluginValidationDataExtension.py +109 -0
  237. arelle/plugin/validate/ROS/ValidationPluginExtension.py +27 -0
  238. arelle/plugin/validate/ROS/__init__.py +28 -341
  239. arelle/plugin/validate/ROS/resources/config.xml +20 -0
  240. arelle/plugin/validate/ROS/rules/__init__.py +56 -0
  241. arelle/plugin/validate/ROS/rules/ros.py +393 -0
  242. arelle/plugin/validate/UK/ValidateUK.py +1372 -0
  243. arelle/plugin/validate/{HMRC → UK}/__init__.py +195 -189
  244. arelle/plugin/validate/{HMRC → UK}/config.xml +1 -1
  245. arelle/plugin/xbrlDB/SqlDb.py +1 -1
  246. arelle/plugin/xbrlDB/XbrlOpenSqlDB.py +5 -5
  247. arelle/plugin/xbrlDB/XbrlPublicPostgresDB.py +1 -1
  248. arelle/plugin/xbrlDB/XbrlSemanticJsonDB.py +1 -1
  249. arelle/plugin/xbrlDB/XbrlSemanticRdfDB.py +1 -1
  250. arelle/plugin/xbrlDB/__init__.py +4 -1
  251. arelle/{RenderingEvaluator.py → rendering/RenderingEvaluator.py} +120 -99
  252. arelle/rendering/RenderingLayout.py +476 -0
  253. arelle/rendering/RenderingResolution.py +814 -0
  254. arelle/resources/cache/http/www.eurofiling.info/eu/fr/xbrl/ext/filing-indicators.xsd +20 -0
  255. arelle/resources/cache/http/www.w3.org/2001/03/xml.xsd +117 -0
  256. arelle/resources/cache/http/www.w3.org/2001/XMLSchema.xsd +2534 -0
  257. arelle/resources/cache/http/www.w3.org/2001/xml.xsd +287 -0
  258. arelle/resources/cache/http/www.xbrl.org/2003/xbrl-instance-2003-12-31.xsd +779 -0
  259. arelle/resources/cache/http/www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd +486 -0
  260. arelle/resources/cache/http/www.xbrl.org/2003/xl-2003-12-31.xsd +251 -0
  261. arelle/resources/cache/http/www.xbrl.org/2003/xlink-2003-12-31.xsd +121 -0
  262. arelle/resources/cache/http/www.xbrl.org/2004/ref-2004-08-10.xsd +129 -0
  263. arelle/resources/cache/http/www.xbrl.org/2005/xbrldt-2005.xsd +53 -0
  264. arelle/resources/cache/http/www.xbrl.org/2006/ref-2006-02-27.xsd +120 -0
  265. arelle/resources/cache/http/www.xbrl.org/2006/xbrldi-2006.xsd +41 -0
  266. arelle/resources/cache/http/www.xbrl.org/2008/boolean-filter.xsd +51 -0
  267. arelle/resources/cache/http/www.xbrl.org/2008/concept-filter.xsd +127 -0
  268. arelle/resources/cache/http/www.xbrl.org/2008/conformance.xsd +116 -0
  269. arelle/resources/cache/http/www.xbrl.org/2008/conformanceFunction.xsd +51 -0
  270. arelle/resources/cache/http/www.xbrl.org/2008/consistency-assertion.xsd +66 -0
  271. arelle/resources/cache/http/www.xbrl.org/2008/dimension-filter.xsd +86 -0
  272. arelle/resources/cache/http/www.xbrl.org/2008/entity-filter.xsd +92 -0
  273. arelle/resources/cache/http/www.xbrl.org/2008/existence-assertion.xsd +44 -0
  274. arelle/resources/cache/http/www.xbrl.org/2008/formula.xsd +261 -0
  275. arelle/resources/cache/http/www.xbrl.org/2008/function.xsd +90 -0
  276. arelle/resources/cache/http/www.xbrl.org/2008/general-filter.xsd +38 -0
  277. arelle/resources/cache/http/www.xbrl.org/2008/generic-label.xsd +80 -0
  278. arelle/resources/cache/http/www.xbrl.org/2008/generic-link.xsd +81 -0
  279. arelle/resources/cache/http/www.xbrl.org/2008/generic-reference.xsd +63 -0
  280. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xbrl/xbrl-instance-2003-12-31-ixmod.xsd +788 -0
  281. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xbrl/xbrl-linkbase-2003-12-31-ixmod.xsd +488 -0
  282. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xbrl/xl-2003-12-31.xsd +248 -0
  283. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xbrl/xlink-2003-12-31.xsd +117 -0
  284. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xframes-1.xsd +166 -0
  285. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-applet-1.xsd +66 -0
  286. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-attribs-1.xsd +72 -0
  287. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-base-1.xsd +36 -0
  288. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-basic-form-1.xsd +195 -0
  289. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-basic-table-1.xsd +169 -0
  290. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-basic10-model-1.xsd +376 -0
  291. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-basic10-module-redefines-1.xsd +61 -0
  292. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-basic10-modules-1.xsd +259 -0
  293. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-basic10.xsd +98 -0
  294. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-bdo-1.xsd +78 -0
  295. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-blkphras-1.xsd +161 -0
  296. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-blkpres-1.xsd +37 -0
  297. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-blkstruct-1.xsd +49 -0
  298. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-charent-1.xsd +38 -0
  299. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-copyright-1.xsd +29 -0
  300. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-csismap-1.xsd +96 -0
  301. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-datatypes-1.xsd +128 -0
  302. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-edit-1.xsd +39 -0
  303. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-events-1.xsd +130 -0
  304. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-form-1.xsd +326 -0
  305. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-frames-1.xsd +113 -0
  306. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-framework-1.xsd +66 -0
  307. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-hypertext-1.xsd +47 -0
  308. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-iframe-1.xsd +68 -0
  309. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-image-1.xsd +45 -0
  310. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-inlphras-1.xsd +163 -0
  311. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-inlpres-1.xsd +39 -0
  312. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-inlstruct-1.xsd +50 -0
  313. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-inlstyle-1.xsd +27 -0
  314. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-legacy-1.xsd +97 -0
  315. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-link-1.xsd +45 -0
  316. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-list-1.xsd +99 -0
  317. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-meta-1.xsd +42 -0
  318. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-misc-1.xsd +441 -0
  319. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-nameident-1.xsd +63 -0
  320. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-notations-1.xsd +69 -0
  321. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-object-1.xsd +76 -0
  322. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-param-1.xsd +51 -0
  323. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-pres-1.xsd +51 -0
  324. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-ruby-1.xsd +171 -0
  325. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-ruby-basic-1.xsd +89 -0
  326. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-script-1.xsd +70 -0
  327. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-ssismap-1.xsd +43 -0
  328. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-struct-1.xsd +112 -0
  329. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-style-1.xsd +52 -0
  330. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-table-1.xsd +272 -0
  331. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-target-1.xsd +53 -0
  332. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml-text-1.xsd +67 -0
  333. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml11-model-1.xsd +677 -0
  334. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml11-module-redefines-1.xsd +335 -0
  335. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml11-modules-1.xsd +528 -0
  336. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml11.xsd +104 -0
  337. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xhtml2.xsd +21 -0
  338. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xml-events-1.xsd +73 -0
  339. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xml-events-2.xsd +74 -0
  340. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xml-events-attribs-1.xsd +73 -0
  341. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xml-events-attribs-2.xsd +75 -0
  342. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xml-events-copyright-1.xsd +34 -0
  343. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xml-events-copyright-2.xsd +34 -0
  344. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml/xml-handlers-2.xsd +98 -0
  345. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml-inlinexbrl-1_0-definitions.xsd +225 -0
  346. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml-inlinexbrl-1_0-model.xsd +681 -0
  347. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml-inlinexbrl-1_0-modules.xsd +535 -0
  348. arelle/resources/cache/http/www.xbrl.org/2008/inlinexbrl/xhtml-inlinexbrl-1_0.xsd +40 -0
  349. arelle/resources/cache/http/www.xbrl.org/2008/match-filter.xsd +94 -0
  350. arelle/resources/cache/http/www.xbrl.org/2008/period-filter.xsd +86 -0
  351. arelle/resources/cache/http/www.xbrl.org/2008/registry.xsd +145 -0
  352. arelle/resources/cache/http/www.xbrl.org/2008/relative-filter.xsd +38 -0
  353. arelle/resources/cache/http/www.xbrl.org/2008/segment-scenario-filter.xsd +41 -0
  354. arelle/resources/cache/http/www.xbrl.org/2008/tuple-filter.xsd +83 -0
  355. arelle/resources/cache/http/www.xbrl.org/2008/unit-filter.xsd +58 -0
  356. arelle/resources/cache/http/www.xbrl.org/2008/validation.xsd +78 -0
  357. arelle/resources/cache/http/www.xbrl.org/2008/value-assertion.xsd +43 -0
  358. arelle/resources/cache/http/www.xbrl.org/2008/value-filter.xsd +43 -0
  359. arelle/resources/cache/http/www.xbrl.org/2008/variable.xsd +240 -0
  360. arelle/resources/cache/http/www.xbrl.org/2010/aspect-cover-filter.xsd +67 -0
  361. arelle/resources/cache/http/www.xbrl.org/2010/concept-relation-filter.xsd +108 -0
  362. arelle/resources/cache/http/www.xbrl.org/2010/custom-function-implementation.xsd +71 -0
  363. arelle/resources/cache/http/www.xbrl.org/2010/generic-message.xsd +68 -0
  364. arelle/resources/cache/http/www.xbrl.org/2010/validation-message.xsd +50 -0
  365. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xbrl/xbrl-instance-2003-12-31-ixmod.xsd +788 -0
  366. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xbrl/xbrl-linkbase-2003-12-31-ixmod.xsd +488 -0
  367. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xbrl/xl-2003-12-31.xsd +248 -0
  368. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xbrl/xlink-2003-12-31.xsd +117 -0
  369. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xframes-1.xsd +166 -0
  370. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-applet-1.xsd +66 -0
  371. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-attribs-1.xsd +72 -0
  372. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-base-1.xsd +36 -0
  373. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-basic-form-1.xsd +195 -0
  374. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-basic-table-1.xsd +169 -0
  375. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-basic10-model-1.xsd +376 -0
  376. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-basic10-module-redefines-1.xsd +61 -0
  377. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-basic10-modules-1.xsd +259 -0
  378. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-basic10.xsd +98 -0
  379. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-bdo-1.xsd +78 -0
  380. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-blkphras-1.xsd +161 -0
  381. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-blkpres-1.xsd +37 -0
  382. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-blkstruct-1.xsd +49 -0
  383. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-charent-1.xsd +38 -0
  384. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-copyright-1.xsd +29 -0
  385. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-csismap-1.xsd +96 -0
  386. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-datatypes-1.xsd +128 -0
  387. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-edit-1.xsd +39 -0
  388. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-events-1.xsd +130 -0
  389. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-form-1.xsd +326 -0
  390. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-frames-1.xsd +113 -0
  391. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-framework-1.xsd +66 -0
  392. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-hypertext-1.xsd +47 -0
  393. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-iframe-1.xsd +68 -0
  394. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-image-1.xsd +45 -0
  395. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-inlphras-1.xsd +163 -0
  396. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-inlpres-1.xsd +39 -0
  397. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-inlstruct-1.xsd +50 -0
  398. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-inlstyle-1.xsd +27 -0
  399. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-legacy-1.xsd +97 -0
  400. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-link-1.xsd +45 -0
  401. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-list-1.xsd +99 -0
  402. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-meta-1.xsd +42 -0
  403. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-misc-1.xsd +441 -0
  404. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-nameident-1.xsd +63 -0
  405. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-notations-1.xsd +69 -0
  406. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-object-1.xsd +76 -0
  407. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-param-1.xsd +51 -0
  408. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-pres-1.xsd +51 -0
  409. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-ruby-1.xsd +171 -0
  410. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-ruby-basic-1.xsd +89 -0
  411. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-script-1.xsd +70 -0
  412. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-ssismap-1.xsd +43 -0
  413. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-struct-1.xsd +112 -0
  414. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-style-1.xsd +52 -0
  415. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-table-1.xsd +272 -0
  416. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-target-1.xsd +53 -0
  417. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml-text-1.xsd +67 -0
  418. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml11-model-1.xsd +677 -0
  419. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml11-module-redefines-1.xsd +335 -0
  420. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml11-modules-1.xsd +528 -0
  421. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml11.xsd +104 -0
  422. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xhtml2.xsd +21 -0
  423. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xml-events-1.xsd +73 -0
  424. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xml-events-2.xsd +74 -0
  425. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xml-events-attribs-1.xsd +73 -0
  426. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xml-events-attribs-2.xsd +75 -0
  427. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xml-events-copyright-1.xsd +34 -0
  428. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xml-events-copyright-2.xsd +34 -0
  429. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml/xml-handlers-2.xsd +98 -0
  430. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml-inlinexbrl-1_1-definitions.xsd +252 -0
  431. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml-inlinexbrl-1_1-model.xsd +681 -0
  432. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml-inlinexbrl-1_1-modules.xsd +535 -0
  433. arelle/resources/cache/http/www.xbrl.org/2013/inlineXBRL/xhtml-inlinexbrl-1_1.xsd +40 -0
  434. arelle/resources/cache/http/www.xbrl.org/2013/match-filter.xsd +94 -0
  435. arelle/resources/cache/http/www.xbrl.org/2013/preferred-label.xsd +12 -0
  436. arelle/resources/cache/http/www.xbrl.org/2013/versioning-base.xsd +142 -0
  437. arelle/resources/cache/http/www.xbrl.org/2013/versioning-concept-details.xsd +143 -0
  438. arelle/resources/cache/http/www.xbrl.org/2013/versioning-concept-use.xsd +64 -0
  439. arelle/resources/cache/http/www.xbrl.org/2013/versioning-dimensions.xsd +162 -0
  440. arelle/resources/cache/http/www.xbrl.org/2014/extensible-enumerations.xsd +27 -0
  441. arelle/resources/cache/http/www.xbrl.org/2014/table.xsd +356 -0
  442. arelle/resources/cache/http/www.xbrl.org/2014/tablemodel.xsd +156 -0
  443. arelle/resources/cache/http/www.xbrl.org/2016/assertion-severity.xsd +29 -0
  444. arelle/resources/cache/http/www.xbrl.org/2016/severities.xml +21 -0
  445. arelle/resources/cache/http/www.xbrl.org/2016/taxonomy-package-catalog.xsd +38 -0
  446. arelle/resources/cache/http/www.xbrl.org/2016/taxonomy-package.xsd +154 -0
  447. arelle/resources/cache/http/www.xbrl.org/2022/assertion-severity.xsd +43 -0
  448. arelle/resources/cache/http/www.xbrl.org/2022/severities.xml +21 -0
  449. arelle/resources/cache/http/www.xbrl.org/dtr/type/nonNumeric-2009-12-16.xsd +76 -0
  450. arelle/resources/cache/http/www.xbrl.org/dtr/type/numeric-2009-12-16.xsd +78 -0
  451. arelle/resources/cache/http/www.xbrl.org/lrr/arcrole/accounting-arcrole-2023-01-04.xsd +39 -0
  452. arelle/resources/cache/http/www.xbrl.org/lrr/arcrole/deprecated-2009-12-16.xsd +29 -0
  453. arelle/resources/cache/http/www.xbrl.org/lrr/arcrole/esma-arcrole-2018-11-21.xsd +14 -0
  454. arelle/resources/cache/http/www.xbrl.org/lrr/arcrole/factExplanatory-2009-12-16.xsd +13 -0
  455. arelle/resources/cache/http/www.xbrl.org/lrr/arcrole/jpfr-arcrole-2007-11-07.xsd +27 -0
  456. arelle/resources/cache/http/www.xbrl.org/lrr/arcrole/parent-child-2013-09-19.xsd +12 -0
  457. arelle/resources/cache/http/www.xbrl.org/lrr/role/deprecated-2009-12-16.xsd +17 -0
  458. arelle/resources/cache/http/www.xbrl.org/lrr/role/jpfr-role-2007-11-07.xsd +47 -0
  459. arelle/resources/cache/http/www.xbrl.org/lrr/role/negated-2008-03-31.xsd +30 -0
  460. arelle/resources/cache/http/www.xbrl.org/lrr/role/negated-2009-12-16.xsd +33 -0
  461. arelle/resources/cache/http/www.xbrl.org/lrr/role/negative-2009-12-16.xsd +25 -0
  462. arelle/resources/cache/http/www.xbrl.org/lrr/role/net-2009-12-16.xsd +13 -0
  463. arelle/resources/cache/http/www.xbrl.org/lrr/role/positive-2009-12-16.xsd +25 -0
  464. arelle/resources/cache/http/www.xbrl.org/lrr/role/property-2022-09-28.xsd +15 -0
  465. arelle/resources/cache/http/www.xbrl.org/lrr/role/reference-2009-12-16.xsd +21 -0
  466. arelle/resources/cache/http/www.xbrl.org/lrr/role/restated-2006-02-21.xsd +19 -0
  467. arelle/resources/cache/http/www.xbrl.org/utr/2012-01-30/utr.xml +4543 -0
  468. arelle/resources/cache/http/www.xbrl.org/utr/2012-10-31/utr.xml +4510 -0
  469. arelle/resources/cache/http/www.xbrl.org/utr/2012-11-30/utr.xml +4567 -0
  470. arelle/resources/cache/http/www.xbrl.org/utr/2013-02-28/utr.xml +5180 -0
  471. arelle/resources/cache/http/www.xbrl.org/utr/2013-05-17/utr.xml +5349 -0
  472. arelle/resources/cache/http/www.xbrl.org/utr/2016-08-10/utr.xml +5363 -0
  473. arelle/resources/cache/http/www.xbrl.org/utr/2017-07-12/utr.xml +6164 -0
  474. arelle/resources/cache/http/www.xbrl.org/utr/2021-02-16/utr.xml +6370 -0
  475. arelle/resources/cache/http/www.xbrl.org/utr/2021-12-08/utr.xml +6493 -0
  476. arelle/resources/cache/http/www.xbrl.org/utr/2022-02-16/utr.xml +6551 -0
  477. arelle/resources/cache/http/www.xbrl.org/utr/2022-07-20/utr.xml +6638 -0
  478. arelle/resources/cache/http/www.xbrl.org/utr/2023-12-20/utr.xml +6680 -0
  479. arelle/resources/cache/http/www.xbrl.org/utr/2024-01-31/utr.xml +6680 -0
  480. arelle/resources/cache/http/www.xbrl.org/utr/2024-10-22/utr.xml +6693 -0
  481. arelle/resources/cache/http/www.xbrl.org/utr/utr.xml +6693 -0
  482. arelle/resources/cache/https/www.xbrl.org/2005/conformance.xsd +87 -0
  483. arelle/resources/cache/https/www.xbrl.org/2020/extensible-enumerations-2.0.xsd +51 -0
  484. arelle/resources/cache/https/www.xbrl.org/2023/calculation-1.1.xsd +27 -0
  485. arelle/resources/cache/https/www.xbrl.org/dtr/type/2020-01-21/types.xsd +812 -0
  486. arelle/resources/cache/https/www.xbrl.org/dtr/type/2022-03-31/types.xsd +847 -0
  487. arelle/resources/cache/https/www.xbrl.org/dtr/type/2024-01-31/types.xsd +897 -0
  488. arelle/resources/cache/https/www.xbrl.org/taxonomy/int/filing-indicators/REC/2021-02-03/filing-indicators-def.xml +68 -0
  489. arelle/resources/cache/https/www.xbrl.org/taxonomy/int/filing-indicators/REC/2021-02-03/filing-indicators-label.xml +84 -0
  490. arelle/resources/cache/https/www.xbrl.org/taxonomy/int/filing-indicators/REC/2021-02-03/filing-indicators.xsd +67 -0
  491. arelle/resources/libs/Tktable2.11/linux-x86_64/README.txt +149 -0
  492. arelle/resources/libs/Tktable2.11/linux-x86_64/html/tkTable.html +2039 -0
  493. arelle/resources/libs/Tktable2.11/linux-x86_64/libTktable2.11.so +0 -0
  494. arelle/resources/libs/Tktable2.11/linux-x86_64/license.txt +51 -0
  495. arelle/resources/libs/Tktable2.11/linux-x86_64/pkgIndex.tcl +3 -0
  496. arelle/resources/libs/Tktable2.11/linux-x86_64/tkTable.tcl +825 -0
  497. arelle/resources/libs/Tktable2.11/linux-x86_64/tktable.py +674 -0
  498. arelle/resources/libs/Tktable2.11/macos-arm64/README.txt +149 -0
  499. arelle/resources/libs/Tktable2.11/macos-arm64/html/tkTable.html +2039 -0
  500. arelle/resources/libs/Tktable2.11/macos-arm64/libTktable2.11.dylib +0 -0
  501. arelle/resources/libs/Tktable2.11/macos-arm64/license.txt +51 -0
  502. arelle/resources/libs/Tktable2.11/macos-arm64/pkgIndex.tcl +2 -0
  503. arelle/resources/libs/Tktable2.11/macos-arm64/tkTable.tcl +825 -0
  504. arelle/resources/libs/Tktable2.11/macos-arm64/tktable.py +674 -0
  505. arelle/resources/libs/Tktable2.11/macos-x86_64/README.txt +149 -0
  506. arelle/resources/libs/Tktable2.11/macos-x86_64/html/tkTable.html +2039 -0
  507. arelle/resources/libs/Tktable2.11/macos-x86_64/libTktable2.11.dylib +0 -0
  508. arelle/resources/libs/Tktable2.11/macos-x86_64/license.txt +51 -0
  509. arelle/resources/libs/Tktable2.11/macos-x86_64/pkgIndex.tcl +2 -0
  510. arelle/resources/libs/Tktable2.11/macos-x86_64/tkTable.tcl +825 -0
  511. arelle/resources/libs/Tktable2.11/macos-x86_64/tktable.py +674 -0
  512. arelle/resources/libs/Tktable2.11/win-x86_64/Tktable.dll +0 -0
  513. arelle/resources/libs/Tktable2.11/win-x86_64/pkgIndex.tcl +2 -0
  514. arelle/resources/libs/Tktable2.11/win-x86_64/tkTable.tcl +825 -0
  515. arelle/typing.py +9 -4
  516. arelle/utils/Contexts.py +38 -0
  517. arelle/utils/EntryPointDetection.py +139 -0
  518. arelle/utils/Equivalence.py +22 -0
  519. arelle/utils/{validate/PluginValidationData.py → PluginData.py} +5 -2
  520. arelle/utils/PluginHooks.py +256 -5
  521. arelle/utils/Units.py +36 -0
  522. arelle/utils/validate/Decorator.py +5 -3
  523. arelle/utils/validate/DetectScriptsInXhtml.py +99 -0
  524. arelle/utils/validate/ESEFImage.py +283 -0
  525. arelle/utils/validate/Validation.py +9 -1
  526. arelle/utils/validate/ValidationPlugin.py +74 -11
  527. arelle/utils/validate/ValidationUtil.py +55 -0
  528. arelle/webserver/bottle.py +5 -4424
  529. {arelle_release-2.17.1.dist-info → arelle_release-2.37.71.dist-info}/METADATA +51 -42
  530. arelle_release-2.37.71.dist-info/RECORD +697 -0
  531. {arelle_release-2.17.1.dist-info → arelle_release-2.37.71.dist-info}/WHEEL +1 -1
  532. {arelle_release-2.17.1.dist-info → arelle_release-2.37.71.dist-info/licenses}/LICENSE.md +1 -4
  533. {arelle_release-2.17.1.dist-info → arelle_release-2.37.71.dist-info}/top_level.txt +0 -1
  534. arelle/DialogOpenTaxonomyPackage.py +0 -1
  535. arelle/RenderingResolver.py +0 -624
  536. arelle/examples/.pydevproject +0 -5
  537. arelle/examples/CustomLogger.py +0 -43
  538. arelle/examples/LoadEFMvalidate.py +0 -32
  539. arelle/examples/LoadSavePreLbCsv.py +0 -26
  540. arelle/examples/LoadValidate.cs +0 -31
  541. arelle/examples/LoadValidate.py +0 -36
  542. arelle/examples/LoadValidateCmdLine.java +0 -69
  543. arelle/examples/LoadValidatePostedZip.java +0 -57
  544. arelle/examples/LoadValidateWebService.java +0 -34
  545. arelle/examples/SaveTableToExelle.py +0 -140
  546. arelle/examples/TR3toTR4.py +0 -88
  547. arelle/examples/plugin/bigInstance.py +0 -394
  548. arelle/examples/plugin/cmdWebServerExtension.py +0 -42
  549. arelle/examples/plugin/crashTest.py +0 -38
  550. arelle/examples/plugin/formulaSuiteConverter.py +0 -212
  551. arelle/examples/plugin/functionsCustom.py +0 -59
  552. arelle/examples/plugin/hello_dolly.py +0 -64
  553. arelle/examples/plugin/hello_i18n.pot +0 -26
  554. arelle/examples/plugin/hello_i18n.py +0 -32
  555. arelle/examples/plugin/importTestChild1.py +0 -21
  556. arelle/examples/plugin/importTestChild2.py +0 -22
  557. arelle/examples/plugin/importTestGrandchild1.py +0 -21
  558. arelle/examples/plugin/importTestGrandchild2.py +0 -21
  559. arelle/examples/plugin/importTestImported1.py +0 -23
  560. arelle/examples/plugin/importTestImported11.py +0 -22
  561. arelle/examples/plugin/importTestParent.py +0 -48
  562. arelle/examples/plugin/locale/fr/LC_MESSAGES/hello_i18n.po +0 -25
  563. arelle/examples/plugin/packagedImportTest/__init__.py +0 -47
  564. arelle/examples/plugin/packagedImportTest/importTestChild1.py +0 -21
  565. arelle/examples/plugin/packagedImportTest/importTestChild2.py +0 -22
  566. arelle/examples/plugin/packagedImportTest/importTestGrandchild1.py +0 -21
  567. arelle/examples/plugin/packagedImportTest/importTestGrandchild2.py +0 -21
  568. arelle/examples/plugin/packagedImportTest/importTestImported1.py +0 -24
  569. arelle/examples/plugin/packagedImportTest/importTestImported11.py +0 -21
  570. arelle/examples/plugin/packagedImportTest/subdir/importTestImported111.py +0 -21
  571. arelle/examples/plugin/packagedImportTest/subdir/subsubdir/importTestImported1111.py +0 -21
  572. arelle/examples/plugin/sakaCalendar.py +0 -215
  573. arelle/examples/plugin/saveInstanceInfoset.py +0 -121
  574. arelle/examples/plugin/streamingExtensions.py +0 -335
  575. arelle/examples/plugin/testcaseCalc11ValidateSetup.py +0 -32
  576. arelle/examples/plugin/testcaseIxExpectedHtmlFixup.py +0 -45
  577. arelle/examples/plugin/updateTableLB.py +0 -242
  578. arelle/examples/plugin/validate/XYZ/DisclosureSystems.py +0 -2
  579. arelle/examples/plugin/validate/XYZ/PluginValidationDataExtension.py +0 -10
  580. arelle/examples/plugin/validate/XYZ/ValidationPluginExtension.py +0 -49
  581. arelle/examples/plugin/validate/XYZ/__init__.py +0 -75
  582. arelle/examples/plugin/validate/XYZ/resources/config.xml +0 -16
  583. arelle/examples/plugin/validate/XYZ/rules/rules01.py +0 -109
  584. arelle/examples/plugin/validate/XYZ/rules/rules02.py +0 -58
  585. arelle/examples/plugin/validateSchemaLxml.py +0 -156
  586. arelle/examples/plugin/validateTableInfoset.py +0 -52
  587. arelle/examples/us-gaap-dei-docType-extraction-frm.xml +0 -90
  588. arelle/examples/us-gaap-dei-ratio-cash-frm.xml +0 -150
  589. arelle/plugin/functionsXmlCreation.py +0 -106
  590. arelle/plugin/instanceInfo.py +0 -306
  591. arelle/plugin/loadFromOIM-2018.py +0 -1282
  592. arelle/plugin/objectmaker.py +0 -285
  593. arelle/plugin/sphinx/FormulaGenerator.py +0 -823
  594. arelle/plugin/sphinx/SphinxContext.py +0 -404
  595. arelle/plugin/sphinx/SphinxEvaluator.py +0 -783
  596. arelle/plugin/sphinx/SphinxMethods.py +0 -1287
  597. arelle/plugin/sphinx/SphinxParser.py +0 -1093
  598. arelle/plugin/sphinx/SphinxValidator.py +0 -163
  599. arelle/plugin/sphinx/US-GAAP Ratios Example.xsr +0 -52
  600. arelle/plugin/sphinx/__init__.py +0 -285
  601. arelle/plugin/transforms/SEC/__init__.py +0 -308
  602. arelle/plugin/transforms/SEC/conf/README.md +0 -39
  603. arelle/plugin/transforms/SEC/conf/extractTestcase.sh +0 -2
  604. arelle/plugin/transforms/SEC/conf/extractTestcase.xsl +0 -109
  605. arelle/plugin/transforms/SEC/conf/runIxtSecTests.sh +0 -16
  606. arelle/plugin/transforms/SEC/conf/saxon9.jar +0 -0
  607. arelle/plugin/transforms/SEC/conf/testcase.xml +0 -7117
  608. arelle/plugin/transforms/SEC/conf/tests.xml +0 -848
  609. arelle/plugin/transforms/SEC/text2num.py +0 -110
  610. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-boolballotbox.xml +0 -66
  611. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-countrynameen.xml +0 -65
  612. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-datequarterend.xml +0 -66
  613. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-durday.xml +0 -61
  614. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-durhour.xml +0 -69
  615. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-durmonth.xml +0 -71
  616. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-durweek.xml +0 -70
  617. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-durwordsen.xml +0 -56
  618. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-duryear.xml +0 -64
  619. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-edgarprovcountryen.xml +0 -65
  620. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-entityfilercategoryen.xml +0 -63
  621. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-exchnameen.xml +0 -86
  622. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-numwordsen.xml +0 -55
  623. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-stateprovnameen.xml +0 -64
  624. arelle/plugin/transforms/SEC/transformationRegistry/registry/ixt-sec-yesnoballotbox.xml +0 -66
  625. arelle/plugin/transforms/SEC/transformationRegistry/registry/transform-registry.xml +0 -314
  626. arelle/plugin/transforms/SEC/transformationRegistry/schema/inlinexbrl-sec-transformation.xsd +0 -418
  627. arelle/plugin/validate/EFM/Consts.py +0 -362
  628. arelle/plugin/validate/EFM/DTS.py +0 -569
  629. arelle/plugin/validate/EFM/Dimensions.py +0 -264
  630. arelle/plugin/validate/EFM/Document.py +0 -206
  631. arelle/plugin/validate/EFM/Filing.py +0 -4383
  632. arelle/plugin/validate/EFM/IsolateSeparateIXDSes.py +0 -19
  633. arelle/plugin/validate/EFM/MessageNumericId.py +0 -142
  634. arelle/plugin/validate/EFM/PreCalAlignment.py +0 -324
  635. arelle/plugin/validate/EFM/Util.py +0 -688
  636. arelle/plugin/validate/EFM/__init__.py +0 -843
  637. arelle/plugin/validate/EFM/config.xml +0 -333
  638. arelle/plugin/validate/EFM/resources/README.md +0 -57
  639. arelle/plugin/validate/EFM/resources/axiswarnings.json +0 -27
  640. arelle/plugin/validate/EFM/resources/cef-deprecated-concepts.json +0 -8
  641. arelle/plugin/validate/EFM/resources/country-deprecated-concepts.json +0 -19
  642. arelle/plugin/validate/EFM/resources/currency-deprecated-concepts.json +0 -7
  643. arelle/plugin/validate/EFM/resources/dei-deprecated-concepts.json +0 -8
  644. arelle/plugin/validate/EFM/resources/dei-validations.json +0 -2884
  645. arelle/plugin/validate/EFM/resources/dqc-us-rules.json +0 -1389
  646. arelle/plugin/validate/EFM/resources/ecd-deprecated-concepts.json +0 -1
  647. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-16-4.xml +0 -115
  648. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-17-0-4.xml +0 -300
  649. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-17-1.xml +0 -304
  650. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-17-2.xml +0 -290
  651. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-17-3-1.xml +0 -294
  652. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-18.1.xml +0 -549
  653. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-18.2.xml +0 -506
  654. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-18.3.xml +0 -496
  655. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-19-1.xml +0 -662
  656. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-19-2.xml +0 -3761
  657. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-19-3.xml +0 -3577
  658. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-20-1.xml +0 -4020
  659. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-20-2.xml +0 -3320
  660. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-20-3.xml +0 -2998
  661. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-2012.xml +0 -957
  662. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-2013.xml +0 -982
  663. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-2014.xml +0 -1001
  664. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-2015.xml +0 -1076
  665. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-2016.xml +0 -120
  666. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-21-1.xml +0 -3329
  667. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-21-2.xml +0 -1230
  668. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-21-3.xml +0 -1113
  669. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-21-4.xml +0 -1321
  670. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-22-1-preview.xml +0 -1721
  671. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-22-1.xml +0 -1841
  672. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-22-2-2.xml +0 -1450
  673. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-22-2.xml +0 -1429
  674. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-22-4.xml +0 -1527
  675. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-23-1-1.xml +0 -2049
  676. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-23-1.xml +0 -2065
  677. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-23-2.xml +0 -1674
  678. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-23-3.xml +0 -1715
  679. arelle/plugin/validate/EFM/resources/edgartaxonomies/edgartaxonomies-all-years.xml +0 -10671
  680. arelle/plugin/validate/EFM/resources/edgartaxonomies/erxl.xsd +0 -69
  681. arelle/plugin/validate/EFM/resources/edgartaxonomies/extendedtaxonomies-all-years.xml +0 -18
  682. arelle/plugin/validate/EFM/resources/edgartaxonomies/ifrs-taxonomies.xml +0 -3126
  683. arelle/plugin/validate/EFM/resources/edgartaxonomies/ifrstaxonomies-all-years.xml +0 -22
  684. arelle/plugin/validate/EFM/resources/ex26-validations.json +0 -255
  685. arelle/plugin/validate/EFM/resources/exch-deprecated-concepts.json +0 -163
  686. arelle/plugin/validate/EFM/resources/ifrs-full-deprecated-concepts.json +0 -204
  687. arelle/plugin/validate/EFM/resources/invest-deprecated-concepts.json +0 -99
  688. arelle/plugin/validate/EFM/resources/ixbrl-transform-registries.json +0 -16
  689. arelle/plugin/validate/EFM/resources/naics-deprecated-concepts.json +0 -295
  690. arelle/plugin/validate/EFM/resources/oef-deprecated-concepts.json +0 -59
  691. arelle/plugin/validate/EFM/resources/other-standard-taxonomies.json +0 -12
  692. arelle/plugin/validate/EFM/resources/rr-deprecated-concepts.json +0 -14
  693. arelle/plugin/validate/EFM/resources/rxp-deprecated-concepts.json +0 -1
  694. arelle/plugin/validate/EFM/resources/shr-deprecated-concepts.json +0 -1
  695. arelle/plugin/validate/EFM/resources/sic-deprecated-concepts.json +0 -1
  696. arelle/plugin/validate/EFM/resources/signwarnings.json +0 -112
  697. arelle/plugin/validate/EFM/resources/srt-deprecated-concepts.json +0 -1
  698. arelle/plugin/validate/EFM/resources/stpr-deprecated-concepts.json +0 -1
  699. arelle/plugin/validate/EFM/resources/taxonomy-compatibility.json +0 -79
  700. arelle/plugin/validate/EFM/resources/us-gaap-deprecated-concepts.json +0 -2886
  701. arelle/plugin/validate/EFM/resources/us-gaap-rels-2020.json +0 -29068
  702. arelle/plugin/validate/EFM/resources/us-gaap-rels-2021.json +0 -29598
  703. arelle/plugin/validate/EFM/resources/us-gaap-rels-2022.json +0 -29141
  704. arelle/plugin/validate/EFM/resources/us-gaap-rels-2023.json +0 -29400
  705. arelle/plugin/validate/EFM/resources/vip-deprecated-concepts.json +0 -1
  706. arelle/plugin/validate/EFM/tools/CheckTxmyRefs.py +0 -180
  707. arelle/plugin/validate/EFM-htm/Const.py +0 -205
  708. arelle/plugin/validate/EFM-htm/__init__.py +0 -217
  709. arelle/plugin/validate/EFM-htm/config.xml +0 -17
  710. arelle/plugin/validate/EFM-htm/resources/efm-htm.dtd +0 -664
  711. arelle/plugin/validate/ESEF/ESEF_Current/Image.py +0 -199
  712. arelle/plugin/validate/ESEF_2022/__init__.py +0 -47
  713. arelle/plugin/validate/GFM/__init__.py +0 -59
  714. arelle/plugin/validate/GFM/config.xml +0 -82
  715. arelle/plugin/validate/SBRnl/CustomLoader.py +0 -19
  716. arelle/plugin/validate/SBRnl/DTS.py +0 -305
  717. arelle/plugin/validate/SBRnl/Dimensions.py +0 -357
  718. arelle/plugin/validate/SBRnl/Document.py +0 -799
  719. arelle/plugin/validate/SBRnl/Filing.py +0 -467
  720. arelle/plugin/validate/SBRnl/__init__.py +0 -75
  721. arelle/plugin/validate/SBRnl/config.xml +0 -26
  722. arelle/plugin/validate/SBRnl/sbr-nl-taxonomies.xml +0 -754
  723. arelle/plugin/validate/USBestPractices.py +0 -570
  724. arelle/plugin/validate/USCorpAction.py +0 -557
  725. arelle/plugin/validate/USSecTagging.py +0 -337
  726. arelle/plugin/validate/XDC/__init__.py +0 -77
  727. arelle/plugin/validate/XDC/config.xml +0 -20
  728. arelle/plugin/validate/XFsyntax/__init__.py +0 -64
  729. arelle/plugin/validate/XFsyntax/xf.py +0 -2227
  730. arelle/plugin/validate/__init__.py +0 -20
  731. arelle/plugin/validate/calc2.py +0 -536
  732. arelle/plugin/validateSBRnl.py +0 -530
  733. arelle/scripts-macOS/startWebServer.command +0 -3
  734. arelle/scripts-unix/startWebServer.sh +0 -1
  735. arelle/scripts-windows/startWebServer.bat +0 -5
  736. arelle_release-2.17.1.dist-info/RECORD +0 -676
  737. tests/__init__.py +0 -0
  738. tests/integration_tests/ui_tests/ArelleGUITest/ArelleGUITest/ArelleGUITest.csproj +0 -30
  739. tests/integration_tests/ui_tests/ArelleGUITest/ArelleGUITest/Tests.cs +0 -381
  740. tests/integration_tests/ui_tests/ArelleGUITest/ArelleGUITest/Usings.cs +0 -1
  741. tests/integration_tests/ui_tests/ArelleGUITest/ArelleGUITest.sln +0 -31
  742. tests/integration_tests/ui_tests/resources/workiva.zip +0 -0
  743. tests/integration_tests/validation/README.md +0 -50
  744. tests/integration_tests/validation/conformance_suite_config.py +0 -59
  745. tests/integration_tests/validation/conformance_suite_configs.py +0 -63
  746. tests/integration_tests/validation/conformance_suite_configurations/efm_current.py +0 -261
  747. tests/integration_tests/validation/conformance_suite_configurations/esef_ixbrl_2021.py +0 -85
  748. tests/integration_tests/validation/conformance_suite_configurations/esef_ixbrl_2022.py +0 -90
  749. tests/integration_tests/validation/conformance_suite_configurations/esef_xhtml_2021.py +0 -15
  750. tests/integration_tests/validation/conformance_suite_configurations/esef_xhtml_2022.py +0 -15
  751. tests/integration_tests/validation/conformance_suite_configurations/nl_nt16.py +0 -13
  752. tests/integration_tests/validation/conformance_suite_configurations/nl_nt17.py +0 -13
  753. tests/integration_tests/validation/conformance_suite_configurations/nl_nt18.py +0 -13
  754. tests/integration_tests/validation/conformance_suite_configurations/xbrl_2_1.py +0 -34
  755. tests/integration_tests/validation/conformance_suite_configurations/xbrl_calculations_1_1.py +0 -40
  756. tests/integration_tests/validation/conformance_suite_configurations/xbrl_dimensions_1_0.py +0 -28
  757. tests/integration_tests/validation/conformance_suite_configurations/xbrl_extensible_enumerations_1_0.py +0 -10
  758. tests/integration_tests/validation/conformance_suite_configurations/xbrl_extensible_enumerations_2_0.py +0 -10
  759. tests/integration_tests/validation/conformance_suite_configurations/xbrl_formula_1_0.py +0 -9
  760. tests/integration_tests/validation/conformance_suite_configurations/xbrl_formula_1_0_assertion_severity_2_0.py +0 -9
  761. tests/integration_tests/validation/conformance_suite_configurations/xbrl_formula_1_0_function_registry.py +0 -14
  762. tests/integration_tests/validation/conformance_suite_configurations/xbrl_ixbrl_1_1.py +0 -22
  763. tests/integration_tests/validation/conformance_suite_configurations/xbrl_link_role_registry_1_0.py +0 -11
  764. tests/integration_tests/validation/conformance_suite_configurations/xbrl_oim_1_0.py +0 -19
  765. tests/integration_tests/validation/conformance_suite_configurations/xbrl_table_linkbase_1_0.py +0 -296
  766. tests/integration_tests/validation/conformance_suite_configurations/xbrl_taxonomy_packages_1_0.py +0 -13
  767. tests/integration_tests/validation/conformance_suite_configurations/xbrl_transformation_registry_3.py +0 -13
  768. tests/integration_tests/validation/conformance_suite_configurations/xbrl_transformation_registry_4.py +0 -13
  769. tests/integration_tests/validation/conformance_suite_configurations/xbrl_transformation_registry_5.py +0 -13
  770. tests/integration_tests/validation/conformance_suite_configurations/xbrl_utr_malformed_1_0.py +0 -31
  771. tests/integration_tests/validation/conformance_suite_configurations/xbrl_utr_registry_1_0.py +0 -22
  772. tests/integration_tests/validation/conformance_suite_configurations/xbrl_utr_structure_1_0.py +0 -18
  773. tests/integration_tests/validation/conftest.py +0 -24
  774. tests/integration_tests/validation/discover_tests.py +0 -22
  775. tests/integration_tests/validation/download_conformance_suites.py +0 -47
  776. tests/integration_tests/validation/run_conformance_suites.py +0 -175
  777. tests/integration_tests/validation/test_conformance_suites.py +0 -14
  778. tests/integration_tests/validation/validation_util.py +0 -271
  779. tests/resources/conformance_suites/nl_nt16/br_kvk/2-04-invalid-period.xbrl +0 -63
  780. tests/resources/conformance_suites/nl_nt16/br_kvk/2-04-testcase.xml +0 -22
  781. tests/resources/conformance_suites/nl_nt16/br_kvk/3-01-missing.xbrl +0 -53
  782. tests/resources/conformance_suites/nl_nt16/br_kvk/3-01-multiple.xbrl +0 -60
  783. tests/resources/conformance_suites/nl_nt16/br_kvk/3-01-testcase.xml +0 -33
  784. tests/resources/conformance_suites/nl_nt16/br_kvk/4-07-invalid.xbrl +0 -57
  785. tests/resources/conformance_suites/nl_nt16/br_kvk/4-07-testcase.xml +0 -22
  786. tests/resources/conformance_suites/nl_nt16/br_kvk/4-10-invalid.xbrl +0 -58
  787. tests/resources/conformance_suites/nl_nt16/br_kvk/4-10-testcase.xml +0 -22
  788. tests/resources/conformance_suites/nl_nt16/br_kvk/4-12-invalid.xbrl +0 -63
  789. tests/resources/conformance_suites/nl_nt16/br_kvk/4-12-testcase.xml +0 -22
  790. tests/resources/conformance_suites/nl_nt16/br_kvk/4-16-missing.xbrl +0 -61
  791. tests/resources/conformance_suites/nl_nt16/br_kvk/4-16-testcase.xml +0 -22
  792. tests/resources/conformance_suites/nl_nt16/br_kvk/4-20-invalid-date.xbrl +0 -89
  793. tests/resources/conformance_suites/nl_nt16/br_kvk/4-20-testcase.xml +0 -22
  794. tests/resources/conformance_suites/nl_nt16/fr_kvk/1-01-invalid-file-extension.xml +0 -56
  795. tests/resources/conformance_suites/nl_nt16/fr_kvk/1-01-testcase.xml +0 -22
  796. tests/resources/conformance_suites/nl_nt16/fr_kvk/2-01-invalid-lang.xbrl +0 -56
  797. tests/resources/conformance_suites/nl_nt16/fr_kvk/2-01-missing-lang.xbrl +0 -55
  798. tests/resources/conformance_suites/nl_nt16/fr_kvk/2-01-testcase.xml +0 -33
  799. tests/resources/conformance_suites/nl_nt16/fr_kvk/2-03-entrypoint.xsd +0 -6
  800. tests/resources/conformance_suites/nl_nt16/fr_kvk/2-03-invalid-entrypoint.xbrl +0 -63
  801. tests/resources/conformance_suites/nl_nt16/fr_kvk/2-03-testcase.xml +0 -22
  802. tests/resources/conformance_suites/nl_nt16/fr_kvk/5-01-invalid-decimals.xbrl +0 -49
  803. tests/resources/conformance_suites/nl_nt16/fr_kvk/5-01-testcase.xml +0 -22
  804. tests/resources/conformance_suites/nl_nt16/fr_kvk/5-02-invalid-decimals.xbrl +0 -49
  805. tests/resources/conformance_suites/nl_nt16/fr_kvk/5-02-testcase.xml +0 -22
  806. tests/resources/conformance_suites/nl_nt16/fr_nl/1-01-invalid-file.xbrl +0 -2
  807. tests/resources/conformance_suites/nl_nt16/fr_nl/1-01-invalid-zip.zip +0 -0
  808. tests/resources/conformance_suites/nl_nt16/fr_nl/1-01-testcase.xml +0 -33
  809. tests/resources/conformance_suites/nl_nt16/fr_nl/1-03-invalid-doctype.xbrl +0 -4
  810. tests/resources/conformance_suites/nl_nt16/fr_nl/1-03-testcase.xml +0 -22
  811. tests/resources/conformance_suites/nl_nt16/fr_nl/1-05-invalid-encoding.xbrl +0 -0
  812. tests/resources/conformance_suites/nl_nt16/fr_nl/1-05-testcase.xml +0 -22
  813. tests/resources/conformance_suites/nl_nt16/fr_nl/1-06-testcase.xml +0 -22
  814. tests/resources/conformance_suites/nl_nt16/fr_nl/1-06.invalid.xbrl +0 -2
  815. tests/resources/conformance_suites/nl_nt16/fr_nl/2-06-invalid-file.xbrl +0 -8
  816. tests/resources/conformance_suites/nl_nt16/fr_nl/2-06-invalid-zip.zip +0 -0
  817. tests/resources/conformance_suites/nl_nt16/fr_nl/2-06-testcase.xml +0 -33
  818. tests/resources/conformance_suites/nl_nt16/index.xml +0 -20
  819. tests/resources/conformance_suites/nl_nt17/br_kvk/2-04-invalid-period.xbrl +0 -63
  820. tests/resources/conformance_suites/nl_nt17/br_kvk/2-04-testcase.xml +0 -22
  821. tests/resources/conformance_suites/nl_nt17/br_kvk/3-01-missing.xbrl +0 -53
  822. tests/resources/conformance_suites/nl_nt17/br_kvk/3-01-multiple.xbrl +0 -60
  823. tests/resources/conformance_suites/nl_nt17/br_kvk/3-01-testcase.xml +0 -33
  824. tests/resources/conformance_suites/nl_nt17/br_kvk/4-07-invalid.xbrl +0 -57
  825. tests/resources/conformance_suites/nl_nt17/br_kvk/4-07-testcase.xml +0 -22
  826. tests/resources/conformance_suites/nl_nt17/br_kvk/4-10-invalid.xbrl +0 -58
  827. tests/resources/conformance_suites/nl_nt17/br_kvk/4-10-testcase.xml +0 -22
  828. tests/resources/conformance_suites/nl_nt17/br_kvk/4-12-invalid.xbrl +0 -63
  829. tests/resources/conformance_suites/nl_nt17/br_kvk/4-12-testcase.xml +0 -22
  830. tests/resources/conformance_suites/nl_nt17/br_kvk/4-16-missing.xbrl +0 -61
  831. tests/resources/conformance_suites/nl_nt17/br_kvk/4-16-testcase.xml +0 -22
  832. tests/resources/conformance_suites/nl_nt17/br_kvk/4-20-invalid-date.xbrl +0 -89
  833. tests/resources/conformance_suites/nl_nt17/br_kvk/4-20-testcase.xml +0 -22
  834. tests/resources/conformance_suites/nl_nt17/fr_kvk/1-01-invalid-file-extension.xml +0 -56
  835. tests/resources/conformance_suites/nl_nt17/fr_kvk/1-01-testcase.xml +0 -22
  836. tests/resources/conformance_suites/nl_nt17/fr_kvk/2-01-invalid-lang.xbrl +0 -56
  837. tests/resources/conformance_suites/nl_nt17/fr_kvk/2-01-missing-lang.xbrl +0 -55
  838. tests/resources/conformance_suites/nl_nt17/fr_kvk/2-01-testcase.xml +0 -33
  839. tests/resources/conformance_suites/nl_nt17/fr_kvk/2-03-entrypoint.xsd +0 -6
  840. tests/resources/conformance_suites/nl_nt17/fr_kvk/2-03-invalid-entrypoint.xbrl +0 -63
  841. tests/resources/conformance_suites/nl_nt17/fr_kvk/2-03-testcase.xml +0 -22
  842. tests/resources/conformance_suites/nl_nt17/fr_kvk/5-01-invalid-decimals.xbrl +0 -49
  843. tests/resources/conformance_suites/nl_nt17/fr_kvk/5-01-testcase.xml +0 -22
  844. tests/resources/conformance_suites/nl_nt17/fr_kvk/5-02-invalid-decimals.xbrl +0 -49
  845. tests/resources/conformance_suites/nl_nt17/fr_kvk/5-02-testcase.xml +0 -22
  846. tests/resources/conformance_suites/nl_nt17/fr_nl/1-01-invalid-file.xbrl +0 -2
  847. tests/resources/conformance_suites/nl_nt17/fr_nl/1-01-invalid-zip.zip +0 -0
  848. tests/resources/conformance_suites/nl_nt17/fr_nl/1-01-testcase.xml +0 -33
  849. tests/resources/conformance_suites/nl_nt17/fr_nl/1-03-invalid-doctype.xbrl +0 -4
  850. tests/resources/conformance_suites/nl_nt17/fr_nl/1-03-testcase.xml +0 -22
  851. tests/resources/conformance_suites/nl_nt17/fr_nl/1-05-invalid-encoding.xbrl +0 -0
  852. tests/resources/conformance_suites/nl_nt17/fr_nl/1-05-testcases.xml +0 -22
  853. tests/resources/conformance_suites/nl_nt17/fr_nl/1-06-testcase.xml +0 -22
  854. tests/resources/conformance_suites/nl_nt17/fr_nl/1-06.invalid.xbrl +0 -2
  855. tests/resources/conformance_suites/nl_nt17/fr_nl/2-06-invalid-file.xbrl +0 -8
  856. tests/resources/conformance_suites/nl_nt17/fr_nl/2-06-invalid-zip.zip +0 -0
  857. tests/resources/conformance_suites/nl_nt17/fr_nl/2-06-testcase.xml +0 -33
  858. tests/resources/conformance_suites/nl_nt17/index.xml +0 -20
  859. tests/resources/conformance_suites/nl_nt18/fr_nl/1-03-invalid-doctype.xbrl +0 -4
  860. tests/resources/conformance_suites/nl_nt18/fr_nl/1-03-testcase.xml +0 -22
  861. tests/resources/conformance_suites/nl_nt18/fr_nl/1-05-invalid-encoding.xbrl +0 -0
  862. tests/resources/conformance_suites/nl_nt18/fr_nl/1-05-testcases.xml +0 -22
  863. tests/resources/conformance_suites/nl_nt18/fr_nl/1-06-testcase.xml +0 -22
  864. tests/resources/conformance_suites/nl_nt18/fr_nl/1-06.invalid.xbrl +0 -2
  865. tests/resources/conformance_suites/nl_nt18/fr_nl/1.01-invalid-file.xbrl +0 -2
  866. tests/resources/conformance_suites/nl_nt18/fr_nl/1.01-invalid-zip.zip +0 -0
  867. tests/resources/conformance_suites/nl_nt18/fr_nl/1.01-testcase.xml +0 -33
  868. tests/resources/conformance_suites/nl_nt18/fr_nl/2-06-invalid-file.xbrl +0 -8
  869. tests/resources/conformance_suites/nl_nt18/fr_nl/2-06-invalid-zip.zip +0 -0
  870. tests/resources/conformance_suites/nl_nt18/fr_nl/2-06-testcase.xml +0 -33
  871. tests/resources/conformance_suites/nl_nt18/index.xml +0 -8
  872. tests/unit_tests/arelle/conftest.py +0 -16
  873. tests/unit_tests/arelle/formula/test_fact_aspects_cache.py +0 -170
  874. tests/unit_tests/arelle/plugin/test_loadfromoim.py +0 -40
  875. tests/unit_tests/arelle/plugin/test_plugin_imports.py +0 -27
  876. tests/unit_tests/arelle/test_betafeatures.py +0 -81
  877. tests/unit_tests/arelle/test_cntlr.py +0 -28
  878. tests/unit_tests/arelle/test_import.py +0 -40
  879. tests/unit_tests/arelle/test_locale.py +0 -73
  880. tests/unit_tests/arelle/test_modelmanager.py +0 -15
  881. tests/unit_tests/arelle/test_packagemanager.py +0 -65
  882. tests/unit_tests/arelle/test_pluginmanager.py +0 -176
  883. tests/unit_tests/arelle/test_qname.py +0 -140
  884. tests/unit_tests/arelle/test_runtimeoptions.py +0 -56
  885. tests/unit_tests/arelle/test_system_info.py +0 -26
  886. tests/unit_tests/arelle/test_updater.py +0 -507
  887. tests/unit_tests/arelle/test_urlutil.py +0 -49
  888. tests/unit_tests/arelle/test_version.py +0 -46
  889. tests/unit_tests/arelle/utils/validate/test_decorator.py +0 -59
  890. /arelle/{examples/plugin/validate/XYZ → plugin/validate/EDINET}/rules/__init__.py +0 -0
  891. /arelle/plugin/validate/{HMRC → UK}/consistencyChecksByName.json +0 -0
  892. /arelle/plugin/validate/{HMRC → UK}/hmrc-taxonomies.xml +0 -0
  893. {arelle_release-2.17.1.dist-info → arelle_release-2.37.71.dist-info}/entry_points.txt +0 -0
@@ -1,4425 +1,6 @@
1
- #!/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
- """
4
- Bottle is a fast and simple micro-framework for small web applications. It
5
- offers request dispatching (Routes) with URL parameter support, templates,
6
- a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and
7
- template engines - all in a single file and with no dependencies other than the
8
- Python Standard Library.
1
+ # This is a redirection module that re-exports all symbols from the pip-installed bottle module for backwards
2
+ # compatibility from when Arelle commited this file directly instead of using the pip-installed version.
3
+ # This is required because external plugin import this file directly.
9
4
 
10
- Homepage and documentation: http://bottlepy.org/
11
-
12
- Copyright (c) 2009-2018, Marcel Hellkamp.
13
- License: MIT (see LICENSE for details)
14
- """
15
-
16
- from __future__ import print_function
17
- import sys
18
-
19
- __author__ = 'Marcel Hellkamp'
20
- __version__ = '0.13-dev'
21
- __license__ = 'MIT'
22
-
23
- ###############################################################################
24
- # Command-line interface ######################################################
25
- ###############################################################################
26
- # INFO: Some server adapters need to monkey-patch std-lib modules before they
27
- # are imported. This is why some of the command-line handling is done here, but
28
- # the actual call to _main() is at the end of the file.
29
-
30
-
31
- def _cli_parse(args): # pragma: no coverage
32
- from argparse import ArgumentParser
33
-
34
- parser = ArgumentParser(prog=args[0], usage="%(prog)s [options] package.module:app")
35
- opt = parser.add_argument
36
- opt("--version", action="store_true", help="show version number.")
37
- opt("-b", "--bind", metavar="ADDRESS", help="bind socket to ADDRESS.")
38
- opt("-s", "--server", default='wsgiref', help="use SERVER as backend.")
39
- opt("-p", "--plugin", action="append", help="install additional plugin/s.")
40
- opt("-c", "--conf", action="append", metavar="FILE",
41
- help="load config values from FILE.")
42
- opt("-C", "--param", action="append", metavar="NAME=VALUE",
43
- help="override config values.")
44
- opt("--debug", action="store_true", help="start server in debug mode.")
45
- opt("--reload", action="store_true", help="auto-reload on file changes.")
46
- opt('app', help='WSGI app entry point.', nargs='?')
47
-
48
- cli_args = parser.parse_args(args[1:])
49
-
50
- return cli_args, parser
51
-
52
-
53
- def _cli_patch(cli_args): # pragma: no coverage
54
- parsed_args, _ = _cli_parse(cli_args)
55
- opts = parsed_args
56
- if opts.server:
57
- if opts.server.startswith('gevent'):
58
- import gevent.monkey
59
- gevent.monkey.patch_all()
60
- elif opts.server.startswith('eventlet'):
61
- import eventlet
62
- eventlet.monkey_patch()
63
-
64
-
65
- if __name__ == '__main__':
66
- _cli_patch(sys.argv)
67
-
68
- ###############################################################################
69
- # Imports and Python 2/3 unification ##########################################
70
- ###############################################################################
71
-
72
- import base64, calendar, cgi, email.utils, functools, hmac, imp, itertools,\
73
- mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib
74
-
75
- from types import FunctionType
76
- from datetime import date as datedate, datetime, timedelta
77
- from tempfile import TemporaryFile
78
- from traceback import format_exc, print_exc
79
- from unicodedata import normalize
80
-
81
- try:
82
- from ujson import dumps as json_dumps, loads as json_lds
83
- except ImportError:
84
- from json import dumps as json_dumps, loads as json_lds
85
-
86
- # inspect.getargspec was removed in Python 3.6, use
87
- # Signature-based version where we can (Python 3.3+)
88
- try:
89
- from inspect import signature
90
- def getargspec(func):
91
- params = signature(func).parameters
92
- args, varargs, keywords, defaults = [], None, None, []
93
- for name, param in params.items():
94
- if param.kind == param.VAR_POSITIONAL:
95
- varargs = name
96
- elif param.kind == param.VAR_KEYWORD:
97
- keywords = name
98
- else:
99
- args.append(name)
100
- if param.default is not param.empty:
101
- defaults.append(param.default)
102
- return (args, varargs, keywords, tuple(defaults) or None)
103
- except ImportError:
104
- try:
105
- from inspect import getfullargspec
106
- def getargspec(func):
107
- spec = getfullargspec(func)
108
- kwargs = makelist(spec[0]) + makelist(spec.kwonlyargs)
109
- return kwargs, spec[1], spec[2], spec[3]
110
- except ImportError:
111
- from inspect import getargspec
112
-
113
-
114
- py = sys.version_info
115
- py3k = py.major > 2
116
-
117
- # Lots of stdlib and builtin differences.
118
- if py3k:
119
- import http.client as httplib
120
- import _thread as thread
121
- from urllib.parse import urljoin, SplitResult as UrlSplitResult
122
- from urllib.parse import urlencode, quote as urlquote, unquote as urlunquote
123
- urlunquote = functools.partial(urlunquote, encoding='latin1')
124
- from http.cookies import SimpleCookie, Morsel, CookieError
125
- from collections.abc import MutableMapping as DictMixin
126
- import pickle
127
- from io import BytesIO
128
- import configparser
129
-
130
- basestring = str
131
- unicode = str
132
- json_loads = lambda s: json_lds(touni(s))
133
- callable = lambda x: hasattr(x, '__call__')
134
- imap = map
135
-
136
- def _raise(*a):
137
- raise a[0](a[1]).with_traceback(a[2])
138
- else: # 2.x
139
- import httplib
140
- import thread
141
- from urlparse import urljoin, SplitResult as UrlSplitResult
142
- from urllib import urlencode, quote as urlquote, unquote as urlunquote
143
- from Cookie import SimpleCookie, Morsel, CookieError
144
- from itertools import imap
145
- import cPickle as pickle
146
- from StringIO import StringIO as BytesIO
147
- import ConfigParser as configparser
148
- from collections import MutableMapping as DictMixin
149
- unicode = unicode
150
- json_loads = json_lds
151
- exec(compile('def _raise(*a): raise a[0], a[1], a[2]', '<py3fix>', 'exec'))
152
-
153
- # Some helpers for string/byte handling
154
- def tob(s, enc='utf8'):
155
- if isinstance(s, unicode):
156
- return s.encode(enc)
157
- return b'' if s is None else bytes(s)
158
-
159
-
160
- def touni(s, enc='utf8', err='strict'):
161
- if isinstance(s, bytes):
162
- return s.decode(enc, err)
163
- return unicode("" if s is None else s)
164
-
165
-
166
- tonat = touni if py3k else tob
167
-
168
-
169
- def _stderr(*args):
170
- try:
171
- print(*args, file=sys.stderr)
172
- except (IOError, AttributeError):
173
- pass # Some environments do not allow printing (mod_wsgi)
174
-
175
-
176
- # A bug in functools causes it to break if the wrapper is an instance method
177
- def update_wrapper(wrapper, wrapped, *a, **ka):
178
- try:
179
- functools.update_wrapper(wrapper, wrapped, *a, **ka)
180
- except AttributeError:
181
- pass
182
-
183
- # These helpers are used at module level and need to be defined first.
184
- # And yes, I know PEP-8, but sometimes a lower-case classname makes more sense.
185
-
186
-
187
- def depr(major, minor, cause, fix):
188
- text = "Warning: Use of deprecated feature or API. (Deprecated in Bottle-%d.%d)\n"\
189
- "Cause: %s\n"\
190
- "Fix: %s\n" % (major, minor, cause, fix)
191
- if DEBUG == 'strict':
192
- raise DeprecationWarning(text)
193
- warnings.warn(text, DeprecationWarning, stacklevel=3)
194
- return DeprecationWarning(text)
195
-
196
-
197
- def makelist(data): # This is just too handy
198
- if isinstance(data, (tuple, list, set, dict)):
199
- return list(data)
200
- elif data:
201
- return [data]
202
- else:
203
- return []
204
-
205
-
206
- class DictProperty(object):
207
- """ Property that maps to a key in a local dict-like attribute. """
208
-
209
- def __init__(self, attr, key=None, read_only=False):
210
- self.attr, self.key, self.read_only = attr, key, read_only
211
-
212
- def __call__(self, func):
213
- functools.update_wrapper(self, func, updated=[])
214
- self.getter, self.key = func, self.key or func.__name__
215
- return self
216
-
217
- def __get__(self, obj, cls):
218
- if obj is None: return self
219
- key, storage = self.key, getattr(obj, self.attr)
220
- if key not in storage: storage[key] = self.getter(obj)
221
- return storage[key]
222
-
223
- def __set__(self, obj, value):
224
- if self.read_only: raise AttributeError("Read-Only property.")
225
- getattr(obj, self.attr)[self.key] = value
226
-
227
- def __delete__(self, obj):
228
- if self.read_only: raise AttributeError("Read-Only property.")
229
- del getattr(obj, self.attr)[self.key]
230
-
231
-
232
- class cached_property(object):
233
- """ A property that is only computed once per instance and then replaces
234
- itself with an ordinary attribute. Deleting the attribute resets the
235
- property. """
236
-
237
- def __init__(self, func):
238
- update_wrapper(self, func)
239
- self.func = func
240
-
241
- def __get__(self, obj, cls):
242
- if obj is None: return self
243
- value = obj.__dict__[self.func.__name__] = self.func(obj)
244
- return value
245
-
246
-
247
- class lazy_attribute(object):
248
- """ A property that caches itself to the class object. """
249
-
250
- def __init__(self, func):
251
- functools.update_wrapper(self, func, updated=[])
252
- self.getter = func
253
-
254
- def __get__(self, obj, cls):
255
- value = self.getter(cls)
256
- setattr(cls, self.__name__, value)
257
- return value
258
-
259
- ###############################################################################
260
- # Exceptions and Events #######################################################
261
- ###############################################################################
262
-
263
-
264
- class BottleException(Exception):
265
- """ A base class for exceptions used by bottle. """
266
- pass
267
-
268
- ###############################################################################
269
- # Routing ######################################################################
270
- ###############################################################################
271
-
272
-
273
- class RouteError(BottleException):
274
- """ This is a base class for all routing related exceptions """
275
-
276
-
277
- class RouteReset(BottleException):
278
- """ If raised by a plugin or request handler, the route is reset and all
279
- plugins are re-applied. """
280
-
281
-
282
- class RouterUnknownModeError(RouteError):
283
-
284
- pass
285
-
286
-
287
- class RouteSyntaxError(RouteError):
288
- """ The route parser found something not supported by this router. """
289
-
290
-
291
- class RouteBuildError(RouteError):
292
- """ The route could not be built. """
293
-
294
-
295
- def _re_flatten(p):
296
- """ Turn all capturing groups in a regular expression pattern into
297
- non-capturing groups. """
298
- if '(' not in p:
299
- return p
300
- return re.sub(r'(\\*)(\(\?P<[^>]+>|\((?!\?))', lambda m: m.group(0) if
301
- len(m.group(1)) % 2 else m.group(1) + '(?:', p)
302
-
303
-
304
- class Router(object):
305
- """ A Router is an ordered collection of route->target pairs. It is used to
306
- efficiently match WSGI requests against a number of routes and return
307
- the first target that satisfies the request. The target may be anything,
308
- usually a string, ID or callable object. A route consists of a path-rule
309
- and a HTTP method.
310
-
311
- The path-rule is either a static path (e.g. `/contact`) or a dynamic
312
- path that contains wildcards (e.g. `/wiki/<page>`). The wildcard syntax
313
- and details on the matching order are described in docs:`routing`.
314
- """
315
-
316
- default_pattern = '[^/]+'
317
- default_filter = 're'
318
-
319
- #: The current CPython regexp implementation does not allow more
320
- #: than 99 matching groups per regular expression.
321
- _MAX_GROUPS_PER_PATTERN = 99
322
-
323
- def __init__(self, strict=False):
324
- self.rules = [] # All rules in order
325
- self._groups = {} # index of regexes to find them in dyna_routes
326
- self.builder = {} # Data structure for the url builder
327
- self.static = {} # Search structure for static routes
328
- self.dyna_routes = {}
329
- self.dyna_regexes = {} # Search structure for dynamic routes
330
- #: If true, static routes are no longer checked first.
331
- self.strict_order = strict
332
- self.filters = {
333
- 're': lambda conf: (_re_flatten(conf or self.default_pattern),
334
- None, None),
335
- 'int': lambda conf: (r'-?\d+', int, lambda x: str(int(x))),
336
- 'float': lambda conf: (r'-?[\d.]+', float, lambda x: str(float(x))),
337
- 'path': lambda conf: (r'.+?', None, None)
338
- }
339
-
340
- def add_filter(self, name, func):
341
- """ Add a filter. The provided function is called with the configuration
342
- string as parameter and must return a (regexp, to_python, to_url) tuple.
343
- The first element is a string, the last two are callables or None. """
344
- self.filters[name] = func
345
-
346
- rule_syntax = re.compile('(\\\\*)'
347
- '(?:(?::([a-zA-Z_][a-zA-Z_0-9]*)?()(?:#(.*?)#)?)'
348
- '|(?:<([a-zA-Z_][a-zA-Z_0-9]*)?(?::([a-zA-Z_]*)'
349
- '(?::((?:\\\\.|[^\\\\>])+)?)?)?>))')
350
-
351
- def _itertokens(self, rule):
352
- offset, prefix = 0, ''
353
- for match in self.rule_syntax.finditer(rule):
354
- prefix += rule[offset:match.start()]
355
- g = match.groups()
356
- if g[2] is not None:
357
- depr(0, 13, "Use of old route syntax.",
358
- "Use <name> instead of :name in routes.")
359
- if len(g[0]) % 2: # Escaped wildcard
360
- prefix += match.group(0)[len(g[0]):]
361
- offset = match.end()
362
- continue
363
- if prefix:
364
- yield prefix, None, None
365
- name, filtr, conf = g[4:7] if g[2] is None else g[1:4]
366
- yield name, filtr or 'default', conf or None
367
- offset, prefix = match.end(), ''
368
- if offset <= len(rule) or prefix:
369
- yield prefix + rule[offset:], None, None
370
-
371
- def add(self, rule, method, target, name=None):
372
- """ Add a new rule or replace the target for an existing rule. """
373
- anons = 0 # Number of anonymous wildcards found
374
- keys = [] # Names of keys
375
- pattern = '' # Regular expression pattern with named groups
376
- filters = [] # Lists of wildcard input filters
377
- builder = [] # Data structure for the URL builder
378
- is_static = True
379
-
380
- for key, mode, conf in self._itertokens(rule):
381
- if mode:
382
- is_static = False
383
- if mode == 'default': mode = self.default_filter
384
- mask, in_filter, out_filter = self.filters[mode](conf)
385
- if not key:
386
- pattern += '(?:%s)' % mask
387
- key = 'anon%d' % anons
388
- anons += 1
389
- else:
390
- pattern += '(?P<%s>%s)' % (key, mask)
391
- keys.append(key)
392
- if in_filter: filters.append((key, in_filter))
393
- builder.append((key, out_filter or str))
394
- elif key:
395
- pattern += re.escape(key)
396
- builder.append((None, key))
397
-
398
- self.builder[rule] = builder
399
- if name: self.builder[name] = builder
400
-
401
- if is_static and not self.strict_order:
402
- self.static.setdefault(method, {})
403
- self.static[method][self.build(rule)] = (target, None)
404
- return
405
-
406
- try:
407
- re_pattern = re.compile('^(%s)$' % pattern)
408
- re_match = re_pattern.match
409
- except re.error as e:
410
- raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, e))
411
-
412
- if filters:
413
-
414
- def getargs(path):
415
- url_args = re_match(path).groupdict()
416
- for name, wildcard_filter in filters:
417
- try:
418
- url_args[name] = wildcard_filter(url_args[name])
419
- except ValueError:
420
- raise HTTPError(400, 'Path has wrong format.')
421
- return url_args
422
- elif re_pattern.groupindex:
423
-
424
- def getargs(path):
425
- return re_match(path).groupdict()
426
- else:
427
- getargs = None
428
-
429
- flatpat = _re_flatten(pattern)
430
- whole_rule = (rule, flatpat, target, getargs)
431
-
432
- if (flatpat, method) in self._groups:
433
- if DEBUG:
434
- msg = 'Route <%s %s> overwrites a previously defined route'
435
- warnings.warn(msg % (method, rule), RuntimeWarning)
436
- self.dyna_routes[method][
437
- self._groups[flatpat, method]] = whole_rule
438
- else:
439
- self.dyna_routes.setdefault(method, []).append(whole_rule)
440
- self._groups[flatpat, method] = len(self.dyna_routes[method]) - 1
441
-
442
- self._compile(method)
443
-
444
- def _compile(self, method):
445
- all_rules = self.dyna_routes[method]
446
- comborules = self.dyna_regexes[method] = []
447
- maxgroups = self._MAX_GROUPS_PER_PATTERN
448
- for x in range(0, len(all_rules), maxgroups):
449
- some = all_rules[x:x + maxgroups]
450
- combined = (flatpat for (_, flatpat, _, _) in some)
451
- combined = '|'.join('(^%s$)' % flatpat for flatpat in combined)
452
- combined = re.compile(combined).match
453
- rules = [(target, getargs) for (_, _, target, getargs) in some]
454
- comborules.append((combined, rules))
455
-
456
- def build(self, _name, *anons, **query):
457
- """ Build an URL by filling the wildcards in a rule. """
458
- builder = self.builder.get(_name)
459
- if not builder:
460
- raise RouteBuildError("No route with that name.", _name)
461
- try:
462
- for i, value in enumerate(anons):
463
- query['anon%d' % i] = value
464
- url = ''.join([f(query.pop(n)) if n else f for (n, f) in builder])
465
- return url if not query else url + '?' + urlencode(query)
466
- except KeyError as E:
467
- raise RouteBuildError('Missing URL argument: %r' % E.args[0])
468
-
469
- def match(self, environ):
470
- """ Return a (target, url_args) tuple or raise HTTPError(400/404/405). """
471
- verb = environ['REQUEST_METHOD'].upper()
472
- path = environ['PATH_INFO'] or '/'
473
-
474
- methods = ('PROXY', 'HEAD', 'GET', 'ANY') if verb == 'HEAD' else ('PROXY', verb, 'ANY')
475
-
476
- for method in methods:
477
- if method in self.static and path in self.static[method]:
478
- target, getargs = self.static[method][path]
479
- return target, getargs(path) if getargs else {}
480
- elif method in self.dyna_regexes:
481
- for combined, rules in self.dyna_regexes[method]:
482
- match = combined(path)
483
- if match:
484
- target, getargs = rules[match.lastindex - 1]
485
- return target, getargs(path) if getargs else {}
486
-
487
- # No matching route found. Collect alternative methods for 405 response
488
- allowed = set([])
489
- nocheck = set(methods)
490
- for method in set(self.static) - nocheck:
491
- if path in self.static[method]:
492
- allowed.add(method)
493
- for method in set(self.dyna_regexes) - allowed - nocheck:
494
- for combined, rules in self.dyna_regexes[method]:
495
- match = combined(path)
496
- if match:
497
- allowed.add(method)
498
- if allowed:
499
- allow_header = ",".join(sorted(allowed))
500
- raise HTTPError(405, "Method not allowed.", Allow=allow_header)
501
-
502
- # No matching route and no alternative method found. We give up
503
- raise HTTPError(404, "Not found: " + repr(path))
504
-
505
-
506
- class Route(object):
507
- """ This class wraps a route callback along with route specific metadata and
508
- configuration and applies Plugins on demand. It is also responsible for
509
- turning an URL path rule into a regular expression usable by the Router.
510
- """
511
-
512
- def __init__(self, app, rule, method, callback,
513
- name=None,
514
- plugins=None,
515
- skiplist=None, **config):
516
- #: The application this route is installed to.
517
- self.app = app
518
- #: The path-rule string (e.g. ``/wiki/<page>``).
519
- self.rule = rule
520
- #: The HTTP method as a string (e.g. ``GET``).
521
- self.method = method
522
- #: The original callback with no plugins applied. Useful for introspection.
523
- self.callback = callback
524
- #: The name of the route (if specified) or ``None``.
525
- self.name = name or None
526
- #: A list of route-specific plugins (see :meth:`Bottle.route`).
527
- self.plugins = plugins or []
528
- #: A list of plugins to not apply to this route (see :meth:`Bottle.route`).
529
- self.skiplist = skiplist or []
530
- #: Additional keyword arguments passed to the :meth:`Bottle.route`
531
- #: decorator are stored in this dictionary. Used for route-specific
532
- #: plugin configuration and meta-data.
533
- self.config = app.config._make_overlay()
534
- self.config.load_dict(config)
535
-
536
- @cached_property
537
- def call(self):
538
- """ The route callback with all plugins applied. This property is
539
- created on demand and then cached to speed up subsequent requests."""
540
- return self._make_callback()
541
-
542
- def reset(self):
543
- """ Forget any cached values. The next time :attr:`call` is accessed,
544
- all plugins are re-applied. """
545
- self.__dict__.pop('call', None)
546
-
547
- def prepare(self):
548
- """ Do all on-demand work immediately (useful for debugging)."""
549
- self.call
550
-
551
- def all_plugins(self):
552
- """ Yield all Plugins affecting this route. """
553
- unique = set()
554
- for p in reversed(self.app.plugins + self.plugins):
555
- if True in self.skiplist: break
556
- name = getattr(p, 'name', False)
557
- if name and (name in self.skiplist or name in unique): continue
558
- if p in self.skiplist or type(p) in self.skiplist: continue
559
- if name: unique.add(name)
560
- yield p
561
-
562
- def _make_callback(self):
563
- callback = self.callback
564
- for plugin in self.all_plugins():
565
- try:
566
- if hasattr(plugin, 'apply'):
567
- callback = plugin.apply(callback, self)
568
- else:
569
- callback = plugin(callback)
570
- except RouteReset: # Try again with changed configuration.
571
- return self._make_callback()
572
- if callback is not self.callback:
573
- update_wrapper(callback, self.callback)
574
- return callback
575
-
576
- def get_undecorated_callback(self):
577
- """ Return the callback. If the callback is a decorated function, try to
578
- recover the original function. """
579
- func = self.callback
580
- func = getattr(func, '__func__' if py3k else 'im_func', func)
581
- closure_attr = '__closure__' if py3k else 'func_closure'
582
- while hasattr(func, closure_attr) and getattr(func, closure_attr):
583
- attributes = getattr(func, closure_attr)
584
- func = attributes[0].cell_contents
585
-
586
- # in case of decorators with multiple arguments
587
- if not isinstance(func, FunctionType):
588
- # pick first FunctionType instance from multiple arguments
589
- func = filter(lambda x: isinstance(x, FunctionType),
590
- map(lambda x: x.cell_contents, attributes))
591
- func = list(func)[0] # py3 support
592
- return func
593
-
594
- def get_callback_args(self):
595
- """ Return a list of argument names the callback (most likely) accepts
596
- as keyword arguments. If the callback is a decorated function, try
597
- to recover the original function before inspection. """
598
- return getargspec(self.get_undecorated_callback())[0]
599
-
600
- def get_config(self, key, default=None):
601
- """ Lookup a config field and return its value, first checking the
602
- route.config, then route.app.config."""
603
- depr(0, 13, "Route.get_config() is deprecated.",
604
- "The Route.config property already includes values from the"
605
- " application config for missing keys. Access it directly.")
606
- return self.config.get(key, default)
607
-
608
- def __repr__(self):
609
- cb = self.get_undecorated_callback()
610
- return '<%s %s -> %s:%s>' % (self.method, self.rule, cb.__module__, cb.__name__)
611
-
612
- ###############################################################################
613
- # Application Object ###########################################################
614
- ###############################################################################
615
-
616
-
617
- class Bottle(object):
618
- """ Each Bottle object represents a single, distinct web application and
619
- consists of routes, callbacks, plugins, resources and configuration.
620
- Instances are callable WSGI applications.
621
-
622
- :param catchall: If true (default), handle all exceptions. Turn off to
623
- let debugging middleware handle exceptions.
624
- """
625
-
626
- @lazy_attribute
627
- def _global_config(cls):
628
- cfg = ConfigDict()
629
- cfg.meta_set('catchall', 'validate', bool)
630
- return cfg
631
-
632
- def __init__(self, **kwargs):
633
- #: A :class:`ConfigDict` for app specific configuration.
634
- self.config = self._global_config._make_overlay()
635
- self.config._add_change_listener(
636
- functools.partial(self.trigger_hook, 'config'))
637
-
638
- self.config.update({
639
- "catchall": True
640
- })
641
-
642
- if kwargs.get('catchall') is False:
643
- depr(0, 13, "Bottle(catchall) keyword argument.",
644
- "The 'catchall' setting is now part of the app "
645
- "configuration. Fix: `app.config['catchall'] = False`")
646
- self.config['catchall'] = False
647
- if kwargs.get('autojson') is False:
648
- depr(0, 13, "Bottle(autojson) keyword argument.",
649
- "The 'autojson' setting is now part of the app "
650
- "configuration. Fix: `app.config['json.enable'] = False`")
651
- self.config['json.disable'] = True
652
-
653
- self._mounts = []
654
-
655
- #: A :class:`ResourceManager` for application files
656
- self.resources = ResourceManager()
657
-
658
- self.routes = [] # List of installed :class:`Route` instances.
659
- self.router = Router() # Maps requests to :class:`Route` instances.
660
- self.error_handler = {}
661
-
662
- # Core plugins
663
- self.plugins = [] # List of installed plugins.
664
- self.install(JSONPlugin())
665
- self.install(TemplatePlugin())
666
-
667
- #: If true, most exceptions are caught and returned as :exc:`HTTPError`
668
- catchall = DictProperty('config', 'catchall')
669
-
670
- __hook_names = 'before_request', 'after_request', 'app_reset', 'config'
671
- __hook_reversed = {'after_request'}
672
-
673
- @cached_property
674
- def _hooks(self):
675
- return dict((name, []) for name in self.__hook_names)
676
-
677
- def add_hook(self, name, func):
678
- """ Attach a callback to a hook. Three hooks are currently implemented:
679
-
680
- before_request
681
- Executed once before each request. The request context is
682
- available, but no routing has happened yet.
683
- after_request
684
- Executed once after each request regardless of its outcome.
685
- app_reset
686
- Called whenever :meth:`Bottle.reset` is called.
687
- """
688
- if name in self.__hook_reversed:
689
- self._hooks[name].insert(0, func)
690
- else:
691
- self._hooks[name].append(func)
692
-
693
- def remove_hook(self, name, func):
694
- """ Remove a callback from a hook. """
695
- if name in self._hooks and func in self._hooks[name]:
696
- self._hooks[name].remove(func)
697
- return True
698
-
699
- def trigger_hook(self, __name, *args, **kwargs):
700
- """ Trigger a hook and return a list of results. """
701
- return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]
702
-
703
- def hook(self, name):
704
- """ Return a decorator that attaches a callback to a hook. See
705
- :meth:`add_hook` for details."""
706
-
707
- def decorator(func):
708
- self.add_hook(name, func)
709
- return func
710
-
711
- return decorator
712
-
713
- def _mount_wsgi(self, prefix, app, **options):
714
- segments = [p for p in prefix.split('/') if p]
715
- if not segments:
716
- raise ValueError('WSGI applications cannot be mounted to "/".')
717
- path_depth = len(segments)
718
-
719
- def mountpoint_wrapper():
720
- try:
721
- request.path_shift(path_depth)
722
- rs = HTTPResponse([])
723
-
724
- def start_response(status, headerlist, exc_info=None):
725
- if exc_info:
726
- _raise(*exc_info)
727
- if py3k:
728
- # Errors here mean that the mounted WSGI app did not
729
- # follow PEP-3333 (which requires latin1) or used a
730
- # pre-encoding other than utf8 :/
731
- status = status.encode('latin1').decode('utf8')
732
- headerlist = [(k, v.encode('latin1').decode('utf8'))
733
- for (k, v) in headerlist]
734
- rs.status = status
735
- for name, value in headerlist:
736
- rs.add_header(name, value)
737
- return rs.body.append
738
-
739
- body = app(request.environ, start_response)
740
- rs.body = itertools.chain(rs.body, body) if rs.body else body
741
- return rs
742
- finally:
743
- request.path_shift(-path_depth)
744
-
745
- options.setdefault('skip', True)
746
- options.setdefault('method', 'PROXY')
747
- options.setdefault('mountpoint', {'prefix': prefix, 'target': app})
748
- options['callback'] = mountpoint_wrapper
749
-
750
- self.route('/%s/<:re:.*>' % '/'.join(segments), **options)
751
- if not prefix.endswith('/'):
752
- self.route('/' + '/'.join(segments), **options)
753
-
754
- def _mount_app(self, prefix, app, **options):
755
- if app in self._mounts or '_mount.app' in app.config:
756
- depr(0, 13, "Application mounted multiple times. Falling back to WSGI mount.",
757
- "Clone application before mounting to a different location.")
758
- return self._mount_wsgi(prefix, app, **options)
759
-
760
- if options:
761
- depr(0, 13, "Unsupported mount options. Falling back to WSGI mount.",
762
- "Do not specify any route options when mounting bottle application.")
763
- return self._mount_wsgi(prefix, app, **options)
764
-
765
- if not prefix.endswith("/"):
766
- depr(0, 13, "Prefix must end in '/'. Falling back to WSGI mount.",
767
- "Consider adding an explicit redirect from '/prefix' to '/prefix/' in the parent application.")
768
- return self._mount_wsgi(prefix, app, **options)
769
-
770
- self._mounts.append(app)
771
- app.config['_mount.prefix'] = prefix
772
- app.config['_mount.app'] = self
773
- for route in app.routes:
774
- route.rule = prefix + route.rule.lstrip('/')
775
- self.add_route(route)
776
-
777
- def mount(self, prefix, app, **options):
778
- """ Mount an application (:class:`Bottle` or plain WSGI) to a specific
779
- URL prefix. Example::
780
-
781
- parent_app.mount('/prefix/', child_app)
782
-
783
- :param prefix: path prefix or `mount-point`.
784
- :param app: an instance of :class:`Bottle` or a WSGI application.
785
-
786
- Plugins from the parent application are not applied to the routes
787
- of the mounted child application. If you need plugins in the child
788
- application, install them separately.
789
-
790
- While it is possible to use path wildcards within the prefix path
791
- (:class:`Bottle` childs only), it is highly discouraged.
792
-
793
- The prefix path must end with a slash. If you want to access the
794
- root of the child application via `/prefix` in addition to
795
- `/prefix/`, consider adding a route with a 307 redirect to the
796
- parent application.
797
- """
798
-
799
- if not prefix.startswith('/'):
800
- raise ValueError("Prefix must start with '/'")
801
-
802
- if isinstance(app, Bottle):
803
- return self._mount_app(prefix, app, **options)
804
- else:
805
- return self._mount_wsgi(prefix, app, **options)
806
-
807
- def merge(self, routes):
808
- """ Merge the routes of another :class:`Bottle` application or a list of
809
- :class:`Route` objects into this application. The routes keep their
810
- 'owner', meaning that the :data:`Route.app` attribute is not
811
- changed. """
812
- if isinstance(routes, Bottle):
813
- routes = routes.routes
814
- for route in routes:
815
- self.add_route(route)
816
-
817
- def install(self, plugin):
818
- """ Add a plugin to the list of plugins and prepare it for being
819
- applied to all routes of this application. A plugin may be a simple
820
- decorator or an object that implements the :class:`Plugin` API.
821
- """
822
- if hasattr(plugin, 'setup'): plugin.setup(self)
823
- if not callable(plugin) and not hasattr(plugin, 'apply'):
824
- raise TypeError("Plugins must be callable or implement .apply()")
825
- self.plugins.append(plugin)
826
- self.reset()
827
- return plugin
828
-
829
- def uninstall(self, plugin):
830
- """ Uninstall plugins. Pass an instance to remove a specific plugin, a type
831
- object to remove all plugins that match that type, a string to remove
832
- all plugins with a matching ``name`` attribute or ``True`` to remove all
833
- plugins. Return the list of removed plugins. """
834
- removed, remove = [], plugin
835
- for i, plugin in list(enumerate(self.plugins))[::-1]:
836
- if remove is True or remove is plugin or remove is type(plugin) \
837
- or getattr(plugin, 'name', True) == remove:
838
- removed.append(plugin)
839
- del self.plugins[i]
840
- if hasattr(plugin, 'close'): plugin.close()
841
- if removed: self.reset()
842
- return removed
843
-
844
- def reset(self, route=None):
845
- """ Reset all routes (force plugins to be re-applied) and clear all
846
- caches. If an ID or route object is given, only that specific route
847
- is affected. """
848
- if route is None: routes = self.routes
849
- elif isinstance(route, Route): routes = [route]
850
- else: routes = [self.routes[route]]
851
- for route in routes:
852
- route.reset()
853
- if DEBUG:
854
- for route in routes:
855
- route.prepare()
856
- self.trigger_hook('app_reset')
857
-
858
- def close(self):
859
- """ Close the application and all installed plugins. """
860
- for plugin in self.plugins:
861
- if hasattr(plugin, 'close'): plugin.close()
862
-
863
- def run(self, **kwargs):
864
- """ Calls :func:`run` with the same parameters. """
865
- run(self, **kwargs)
866
-
867
- def match(self, environ):
868
- """ Search for a matching route and return a (:class:`Route`, urlargs)
869
- tuple. The second value is a dictionary with parameters extracted
870
- from the URL. Raise :exc:`HTTPError` (404/405) on a non-match."""
871
- return self.router.match(environ)
872
-
873
- def get_url(self, routename, **kargs):
874
- """ Return a string that matches a named route """
875
- scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/'
876
- location = self.router.build(routename, **kargs).lstrip('/')
877
- return urljoin(urljoin('/', scriptname), location)
878
-
879
- def add_route(self, route):
880
- """ Add a route object, but do not change the :data:`Route.app`
881
- attribute."""
882
- self.routes.append(route)
883
- self.router.add(route.rule, route.method, route, name=route.name)
884
- if DEBUG: route.prepare()
885
-
886
- def route(self,
887
- path=None,
888
- method='GET',
889
- callback=None,
890
- name=None,
891
- apply=None,
892
- skip=None, **config):
893
- """ A decorator to bind a function to a request URL. Example::
894
-
895
- @app.route('/hello/<name>')
896
- def hello(name):
897
- return 'Hello %s' % name
898
-
899
- The ``<name>`` part is a wildcard. See :class:`Router` for syntax
900
- details.
901
-
902
- :param path: Request path or a list of paths to listen to. If no
903
- path is specified, it is automatically generated from the
904
- signature of the function.
905
- :param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of
906
- methods to listen to. (default: `GET`)
907
- :param callback: An optional shortcut to avoid the decorator
908
- syntax. ``route(..., callback=func)`` equals ``route(...)(func)``
909
- :param name: The name for this route. (default: None)
910
- :param apply: A decorator or plugin or a list of plugins. These are
911
- applied to the route callback in addition to installed plugins.
912
- :param skip: A list of plugins, plugin classes or names. Matching
913
- plugins are not installed to this route. ``True`` skips all.
914
-
915
- Any additional keyword arguments are stored as route-specific
916
- configuration and passed to plugins (see :meth:`Plugin.apply`).
917
- """
918
- if callable(path): path, callback = None, path
919
- plugins = makelist(apply)
920
- skiplist = makelist(skip)
921
-
922
- def decorator(callback):
923
- if isinstance(callback, basestring): callback = load(callback)
924
- for rule in makelist(path) or yieldroutes(callback):
925
- for verb in makelist(method):
926
- verb = verb.upper()
927
- route = Route(self, rule, verb, callback,
928
- name=name,
929
- plugins=plugins,
930
- skiplist=skiplist, **config)
931
- self.add_route(route)
932
- return callback
933
-
934
- return decorator(callback) if callback else decorator
935
-
936
- def get(self, path=None, method='GET', **options):
937
- """ Equals :meth:`route`. """
938
- return self.route(path, method, **options)
939
-
940
- def post(self, path=None, method='POST', **options):
941
- """ Equals :meth:`route` with a ``POST`` method parameter. """
942
- return self.route(path, method, **options)
943
-
944
- def put(self, path=None, method='PUT', **options):
945
- """ Equals :meth:`route` with a ``PUT`` method parameter. """
946
- return self.route(path, method, **options)
947
-
948
- def delete(self, path=None, method='DELETE', **options):
949
- """ Equals :meth:`route` with a ``DELETE`` method parameter. """
950
- return self.route(path, method, **options)
951
-
952
- def patch(self, path=None, method='PATCH', **options):
953
- """ Equals :meth:`route` with a ``PATCH`` method parameter. """
954
- return self.route(path, method, **options)
955
-
956
- def error(self, code=500, callback=None):
957
- """ Register an output handler for a HTTP error code. Can
958
- be used as a decorator or called directly ::
959
-
960
- def error_handler_500(error):
961
- return 'error_handler_500'
962
-
963
- app.error(code=500, callback=error_handler_500)
964
-
965
- @app.error(404)
966
- def error_handler_404(error):
967
- return 'error_handler_404'
968
-
969
- """
970
-
971
- def decorator(callback):
972
- if isinstance(callback, basestring): callback = load(callback)
973
- self.error_handler[int(code)] = callback
974
- return callback
975
-
976
- return decorator(callback) if callback else decorator
977
-
978
- def default_error_handler(self, res):
979
- return tob(template(ERROR_PAGE_TEMPLATE, e=res, template_settings=dict(name='__ERROR_PAGE_TEMPLATE')))
980
-
981
- def _handle(self, environ):
982
- path = environ['bottle.raw_path'] = environ['PATH_INFO']
983
- if py3k:
984
- environ['PATH_INFO'] = path.encode('latin1').decode('utf8', 'ignore')
985
-
986
- environ['bottle.app'] = self
987
- request.bind(environ)
988
- response.bind()
989
-
990
- try:
991
- while True: # Remove in 0.14 together with RouteReset
992
- out = None
993
- try:
994
- self.trigger_hook('before_request')
995
- route, args = self.router.match(environ)
996
- environ['route.handle'] = route
997
- environ['bottle.route'] = route
998
- environ['route.url_args'] = args
999
- out = route.call(**args)
1000
- break
1001
- except HTTPResponse as E:
1002
- out = E
1003
- break
1004
- except RouteReset:
1005
- depr(0, 13, "RouteReset exception deprecated",
1006
- "Call route.call() after route.reset() and "
1007
- "return the result.")
1008
- route.reset()
1009
- continue
1010
- finally:
1011
- if isinstance(out, HTTPResponse):
1012
- out.apply(response)
1013
- try:
1014
- self.trigger_hook('after_request')
1015
- except HTTPResponse as E:
1016
- out = E
1017
- out.apply(response)
1018
- except (KeyboardInterrupt, SystemExit, MemoryError):
1019
- raise
1020
- except Exception as E:
1021
- if not self.catchall: raise
1022
- stacktrace = format_exc()
1023
- environ['wsgi.errors'].write(stacktrace)
1024
- environ['wsgi.errors'].flush()
1025
- environ['bottle.exc_info'] = sys.exc_info()
1026
- out = HTTPError(500, "Internal Server Error", E, stacktrace)
1027
- out.apply(response)
1028
-
1029
- return out
1030
-
1031
- def _cast(self, out, peek=None):
1032
- """ Try to convert the parameter into something WSGI compatible and set
1033
- correct HTTP headers when possible.
1034
- Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
1035
- iterable of strings and iterable of unicodes
1036
- """
1037
-
1038
- # Empty output is done here
1039
- if not out:
1040
- if 'Content-Length' not in response:
1041
- response['Content-Length'] = 0
1042
- return []
1043
- # Join lists of byte or unicode strings. Mixed lists are NOT supported
1044
- if isinstance(out, (tuple, list))\
1045
- and isinstance(out[0], (bytes, unicode)):
1046
- out = out[0][0:0].join(out) # b'abc'[0:0] -> b''
1047
- # Encode unicode strings
1048
- if isinstance(out, unicode):
1049
- out = out.encode(response.charset)
1050
- # Byte Strings are just returned
1051
- if isinstance(out, bytes):
1052
- if 'Content-Length' not in response:
1053
- response['Content-Length'] = len(out)
1054
- return [out]
1055
- # HTTPError or HTTPException (recursive, because they may wrap anything)
1056
- # TODO: Handle these explicitly in handle() or make them iterable.
1057
- if isinstance(out, HTTPError):
1058
- out.apply(response)
1059
- out = self.error_handler.get(out.status_code,
1060
- self.default_error_handler)(out)
1061
- return self._cast(out)
1062
- if isinstance(out, HTTPResponse):
1063
- out.apply(response)
1064
- return self._cast(out.body)
1065
-
1066
- # File-like objects.
1067
- if hasattr(out, 'read'):
1068
- if 'wsgi.file_wrapper' in request.environ:
1069
- return request.environ['wsgi.file_wrapper'](out)
1070
- elif hasattr(out, 'close') or not hasattr(out, '__iter__'):
1071
- return WSGIFileWrapper(out)
1072
-
1073
- # Handle Iterables. We peek into them to detect their inner type.
1074
- try:
1075
- iout = iter(out)
1076
- first = next(iout)
1077
- while not first:
1078
- first = next(iout)
1079
- except StopIteration:
1080
- return self._cast('')
1081
- except HTTPResponse as E:
1082
- first = E
1083
- except (KeyboardInterrupt, SystemExit, MemoryError):
1084
- raise
1085
- except Exception as error:
1086
- if not self.catchall: raise
1087
- first = HTTPError(500, 'Unhandled exception', error, format_exc())
1088
-
1089
- # These are the inner types allowed in iterator or generator objects.
1090
- if isinstance(first, HTTPResponse):
1091
- return self._cast(first)
1092
- elif isinstance(first, bytes):
1093
- new_iter = itertools.chain([first], iout)
1094
- elif isinstance(first, unicode):
1095
- encoder = lambda x: x.encode(response.charset)
1096
- new_iter = imap(encoder, itertools.chain([first], iout))
1097
- else:
1098
- msg = 'Unsupported response type: %s' % type(first)
1099
- return self._cast(HTTPError(500, msg))
1100
- if hasattr(out, 'close'):
1101
- new_iter = _closeiter(new_iter, out.close)
1102
- return new_iter
1103
-
1104
- def wsgi(self, environ, start_response):
1105
- """ The bottle WSGI-interface. """
1106
- try:
1107
- out = self._cast(self._handle(environ))
1108
- # rfc2616 section 4.3
1109
- if response._status_code in (100, 101, 204, 304)\
1110
- or environ['REQUEST_METHOD'] == 'HEAD':
1111
- if hasattr(out, 'close'): out.close()
1112
- out = []
1113
- exc_info = environ.get('bottle.exc_info')
1114
- if exc_info is not None:
1115
- del environ['bottle.exc_info']
1116
- start_response(response._wsgi_status_line(), response.headerlist, exc_info)
1117
- return out
1118
- except (KeyboardInterrupt, SystemExit, MemoryError):
1119
- raise
1120
- except Exception as E:
1121
- if not self.catchall: raise
1122
- err = '<h1>Critical error while processing request: %s</h1>' \
1123
- % html_escape(environ.get('PATH_INFO', '/'))
1124
- if DEBUG:
1125
- err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
1126
- '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
1127
- % (html_escape(repr(E)), html_escape(format_exc()))
1128
- environ['wsgi.errors'].write(err)
1129
- environ['wsgi.errors'].flush()
1130
- headers = [('Content-Type', 'text/html; charset=UTF-8')]
1131
- start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info())
1132
- return [tob(err)]
1133
-
1134
- def __call__(self, environ, start_response):
1135
- """ Each instance of :class:'Bottle' is a WSGI application. """
1136
- return self.wsgi(environ, start_response)
1137
-
1138
- def __enter__(self):
1139
- """ Use this application as default for all module-level shortcuts. """
1140
- default_app.push(self)
1141
- return self
1142
-
1143
- def __exit__(self, exc_type, exc_value, traceback):
1144
- default_app.pop()
1145
-
1146
- def __setattr__(self, name, value):
1147
- if name in self.__dict__:
1148
- raise AttributeError("Attribute %s already defined. Plugin conflict?" % name)
1149
- self.__dict__[name] = value
1150
-
1151
-
1152
- ###############################################################################
1153
- # HTTP and WSGI Tools ##########################################################
1154
- ###############################################################################
1155
-
1156
-
1157
- class BaseRequest(object):
1158
- """ A wrapper for WSGI environment dictionaries that adds a lot of
1159
- convenient access methods and properties. Most of them are read-only.
1160
-
1161
- Adding new attributes to a request actually adds them to the environ
1162
- dictionary (as 'bottle.request.ext.<name>'). This is the recommended
1163
- way to store and access request-specific data.
1164
- """
1165
-
1166
- __slots__ = ('environ', )
1167
-
1168
- #: Maximum size of memory buffer for :attr:`body` in bytes.
1169
- MEMFILE_MAX = 102400
1170
-
1171
- def __init__(self, environ=None):
1172
- """ Wrap a WSGI environ dictionary. """
1173
- #: The wrapped WSGI environ dictionary. This is the only real attribute.
1174
- #: All other attributes actually are read-only properties.
1175
- self.environ = {} if environ is None else environ
1176
- self.environ['bottle.request'] = self
1177
-
1178
- @DictProperty('environ', 'bottle.app', read_only=True)
1179
- def app(self):
1180
- """ Bottle application handling this request. """
1181
- raise RuntimeError('This request is not connected to an application.')
1182
-
1183
- @DictProperty('environ', 'bottle.route', read_only=True)
1184
- def route(self):
1185
- """ The bottle :class:`Route` object that matches this request. """
1186
- raise RuntimeError('This request is not connected to a route.')
1187
-
1188
- @DictProperty('environ', 'route.url_args', read_only=True)
1189
- def url_args(self):
1190
- """ The arguments extracted from the URL. """
1191
- raise RuntimeError('This request is not connected to a route.')
1192
-
1193
- @property
1194
- def path(self):
1195
- """ The value of ``PATH_INFO`` with exactly one prefixed slash (to fix
1196
- broken clients and avoid the "empty path" edge case). """
1197
- return '/' + self.environ.get('PATH_INFO', '').lstrip('/')
1198
-
1199
- @property
1200
- def method(self):
1201
- """ The ``REQUEST_METHOD`` value as an uppercase string. """
1202
- return self.environ.get('REQUEST_METHOD', 'GET').upper()
1203
-
1204
- @DictProperty('environ', 'bottle.request.headers', read_only=True)
1205
- def headers(self):
1206
- """ A :class:`WSGIHeaderDict` that provides case-insensitive access to
1207
- HTTP request headers. """
1208
- return WSGIHeaderDict(self.environ)
1209
-
1210
- def get_header(self, name, default=None):
1211
- """ Return the value of a request header, or a given default value. """
1212
- return self.headers.get(name, default)
1213
-
1214
- @DictProperty('environ', 'bottle.request.cookies', read_only=True)
1215
- def cookies(self):
1216
- """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
1217
- decoded. Use :meth:`get_cookie` if you expect signed cookies. """
1218
- cookies = SimpleCookie(self.environ.get('HTTP_COOKIE', '')).values()
1219
- return FormsDict((c.key, c.value) for c in cookies)
1220
-
1221
- def get_cookie(self, key, default=None, secret=None, digestmod=hashlib.sha256):
1222
- """ Return the content of a cookie. To read a `Signed Cookie`, the
1223
- `secret` must match the one used to create the cookie (see
1224
- :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing
1225
- cookie or wrong signature), return a default value. """
1226
- value = self.cookies.get(key)
1227
- if secret:
1228
- # See BaseResponse.set_cookie for details on signed cookies.
1229
- if value and value.startswith('!') and '?' in value:
1230
- sig, msg = map(tob, value[1:].split('?', 1))
1231
- hash = hmac.new(tob(secret), msg, digestmod=digestmod).digest()
1232
- if _lscmp(sig, base64.b64encode(hash)):
1233
- dst = pickle.loads(base64.b64decode(msg))
1234
- if dst and dst[0] == key:
1235
- return dst[1]
1236
- return default
1237
- return value or default
1238
-
1239
- @DictProperty('environ', 'bottle.request.query', read_only=True)
1240
- def query(self):
1241
- """ The :attr:`query_string` parsed into a :class:`FormsDict`. These
1242
- values are sometimes called "URL arguments" or "GET parameters", but
1243
- not to be confused with "URL wildcards" as they are provided by the
1244
- :class:`Router`. """
1245
- get = self.environ['bottle.get'] = FormsDict()
1246
- pairs = _parse_qsl(self.environ.get('QUERY_STRING', ''))
1247
- for key, value in pairs:
1248
- get[key] = value
1249
- return get
1250
-
1251
- @DictProperty('environ', 'bottle.request.forms', read_only=True)
1252
- def forms(self):
1253
- """ Form values parsed from an `url-encoded` or `multipart/form-data`
1254
- encoded POST or PUT request body. The result is returned as a
1255
- :class:`FormsDict`. All keys and values are strings. File uploads
1256
- are stored separately in :attr:`files`. """
1257
- forms = FormsDict()
1258
- forms.recode_unicode = self.POST.recode_unicode
1259
- for name, item in self.POST.allitems():
1260
- if not isinstance(item, FileUpload):
1261
- forms[name] = item
1262
- return forms
1263
-
1264
- @DictProperty('environ', 'bottle.request.params', read_only=True)
1265
- def params(self):
1266
- """ A :class:`FormsDict` with the combined values of :attr:`query` and
1267
- :attr:`forms`. File uploads are stored in :attr:`files`. """
1268
- params = FormsDict()
1269
- for key, value in self.query.allitems():
1270
- params[key] = value
1271
- for key, value in self.forms.allitems():
1272
- params[key] = value
1273
- return params
1274
-
1275
- @DictProperty('environ', 'bottle.request.files', read_only=True)
1276
- def files(self):
1277
- """ File uploads parsed from `multipart/form-data` encoded POST or PUT
1278
- request body. The values are instances of :class:`FileUpload`.
1279
-
1280
- """
1281
- files = FormsDict()
1282
- files.recode_unicode = self.POST.recode_unicode
1283
- for name, item in self.POST.allitems():
1284
- if isinstance(item, FileUpload):
1285
- files[name] = item
1286
- return files
1287
-
1288
- @DictProperty('environ', 'bottle.request.json', read_only=True)
1289
- def json(self):
1290
- """ If the ``Content-Type`` header is ``application/json`` or
1291
- ``application/json-rpc``, this property holds the parsed content
1292
- of the request body. Only requests smaller than :attr:`MEMFILE_MAX`
1293
- are processed to avoid memory exhaustion.
1294
- Invalid JSON raises a 400 error response.
1295
- """
1296
- ctype = self.environ.get('CONTENT_TYPE', '').lower().split(';')[0]
1297
- if ctype in ('application/json', 'application/json-rpc'):
1298
- b = self._get_body_string(self.MEMFILE_MAX)
1299
- if not b:
1300
- return None
1301
- try:
1302
- return json_loads(b)
1303
- except (ValueError, TypeError):
1304
- raise HTTPError(400, 'Invalid JSON')
1305
- return None
1306
-
1307
- def _iter_body(self, read, bufsize):
1308
- maxread = max(0, self.content_length)
1309
- while maxread:
1310
- part = read(min(maxread, bufsize))
1311
- if not part: break
1312
- yield part
1313
- maxread -= len(part)
1314
-
1315
- @staticmethod
1316
- def _iter_chunked(read, bufsize):
1317
- err = HTTPError(400, 'Error while parsing chunked transfer body.')
1318
- rn, sem, bs = tob('\r\n'), tob(';'), tob('')
1319
- while True:
1320
- header = read(1)
1321
- while header[-2:] != rn:
1322
- c = read(1)
1323
- header += c
1324
- if not c: raise err
1325
- if len(header) > bufsize: raise err
1326
- size, _, _ = header.partition(sem)
1327
- try:
1328
- maxread = int(tonat(size.strip()), 16)
1329
- except ValueError:
1330
- raise err
1331
- if maxread == 0: break
1332
- buff = bs
1333
- while maxread > 0:
1334
- if not buff:
1335
- buff = read(min(maxread, bufsize))
1336
- part, buff = buff[:maxread], buff[maxread:]
1337
- if not part: raise err
1338
- yield part
1339
- maxread -= len(part)
1340
- if read(2) != rn:
1341
- raise err
1342
-
1343
- @DictProperty('environ', 'bottle.request.body', read_only=True)
1344
- def _body(self):
1345
- try:
1346
- read_func = self.environ['wsgi.input'].read
1347
- except KeyError:
1348
- self.environ['wsgi.input'] = BytesIO()
1349
- return self.environ['wsgi.input']
1350
- body_iter = self._iter_chunked if self.chunked else self._iter_body
1351
- body, body_size, is_temp_file = BytesIO(), 0, False
1352
- for part in body_iter(read_func, self.MEMFILE_MAX):
1353
- body.write(part)
1354
- body_size += len(part)
1355
- if not is_temp_file and body_size > self.MEMFILE_MAX:
1356
- body, tmp = TemporaryFile(mode='w+b'), body
1357
- body.write(tmp.getvalue())
1358
- del tmp
1359
- is_temp_file = True
1360
- self.environ['wsgi.input'] = body
1361
- body.seek(0)
1362
- return body
1363
-
1364
- def _get_body_string(self, maxread):
1365
- """ Read body into a string. Raise HTTPError(413) on requests that are
1366
- to large. """
1367
- if self.content_length > maxread:
1368
- raise HTTPError(413, 'Request entity too large')
1369
- data = self.body.read(maxread + 1)
1370
- if len(data) > maxread:
1371
- raise HTTPError(413, 'Request entity too large')
1372
- return data
1373
-
1374
- @property
1375
- def body(self):
1376
- """ The HTTP request body as a seek-able file-like object. Depending on
1377
- :attr:`MEMFILE_MAX`, this is either a temporary file or a
1378
- :class:`io.BytesIO` instance. Accessing this property for the first
1379
- time reads and replaces the ``wsgi.input`` environ variable.
1380
- Subsequent accesses just do a `seek(0)` on the file object. """
1381
- self._body.seek(0)
1382
- return self._body
1383
-
1384
- @property
1385
- def chunked(self):
1386
- """ True if Chunked transfer encoding was. """
1387
- return 'chunked' in self.environ.get(
1388
- 'HTTP_TRANSFER_ENCODING', '').lower()
1389
-
1390
- #: An alias for :attr:`query`.
1391
- GET = query
1392
-
1393
- @DictProperty('environ', 'bottle.request.post', read_only=True)
1394
- def POST(self):
1395
- """ The values of :attr:`forms` and :attr:`files` combined into a single
1396
- :class:`FormsDict`. Values are either strings (form values) or
1397
- instances of :class:`cgi.FieldStorage` (file uploads).
1398
- """
1399
- post = FormsDict()
1400
- # We default to application/x-www-form-urlencoded for everything that
1401
- # is not multipart and take the fast path (also: 3.1 workaround)
1402
- if not self.content_type.startswith('multipart/'):
1403
- body = tonat(self._get_body_string(self.MEMFILE_MAX), 'latin1')
1404
- for key, value in _parse_qsl(body):
1405
- post[key] = value
1406
- return post
1407
-
1408
- safe_env = {'QUERY_STRING': ''} # Build a safe environment for cgi
1409
- for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'):
1410
- if key in self.environ: safe_env[key] = self.environ[key]
1411
- args = dict(fp=self.body, environ=safe_env, keep_blank_values=True)
1412
-
1413
- if py3k:
1414
- args['encoding'] = 'utf8'
1415
- post.recode_unicode = False
1416
- data = cgi.FieldStorage(**args)
1417
- self['_cgi.FieldStorage'] = data #http://bugs.python.org/issue18394
1418
- data = data.list or []
1419
- for item in data:
1420
- if item.filename:
1421
- post[item.name] = FileUpload(item.file, item.name,
1422
- item.filename, item.headers)
1423
- else:
1424
- post[item.name] = item.value
1425
- return post
1426
-
1427
- @property
1428
- def url(self):
1429
- """ The full request URI including hostname and scheme. If your app
1430
- lives behind a reverse proxy or load balancer and you get confusing
1431
- results, make sure that the ``X-Forwarded-Host`` header is set
1432
- correctly. """
1433
- return self.urlparts.geturl()
1434
-
1435
- @DictProperty('environ', 'bottle.request.urlparts', read_only=True)
1436
- def urlparts(self):
1437
- """ The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.
1438
- The tuple contains (scheme, host, path, query_string and fragment),
1439
- but the fragment is always empty because it is not visible to the
1440
- server. """
1441
- env = self.environ
1442
- http = env.get('HTTP_X_FORWARDED_PROTO') \
1443
- or env.get('wsgi.url_scheme', 'http')
1444
- host = env.get('HTTP_X_FORWARDED_HOST') or env.get('HTTP_HOST')
1445
- if not host:
1446
- # HTTP 1.1 requires a Host-header. This is for HTTP/1.0 clients.
1447
- host = env.get('SERVER_NAME', '127.0.0.1')
1448
- port = env.get('SERVER_PORT')
1449
- if port and port != ('80' if http == 'http' else '443'):
1450
- host += ':' + port
1451
- path = urlquote(self.fullpath)
1452
- return UrlSplitResult(http, host, path, env.get('QUERY_STRING'), '')
1453
-
1454
- @property
1455
- def fullpath(self):
1456
- """ Request path including :attr:`script_name` (if present). """
1457
- return urljoin(self.script_name, self.path.lstrip('/'))
1458
-
1459
- @property
1460
- def query_string(self):
1461
- """ The raw :attr:`query` part of the URL (everything in between ``?``
1462
- and ``#``) as a string. """
1463
- return self.environ.get('QUERY_STRING', '')
1464
-
1465
- @property
1466
- def script_name(self):
1467
- """ The initial portion of the URL's `path` that was removed by a higher
1468
- level (server or routing middleware) before the application was
1469
- called. This script path is returned with leading and tailing
1470
- slashes. """
1471
- script_name = self.environ.get('SCRIPT_NAME', '').strip('/')
1472
- return '/' + script_name + '/' if script_name else '/'
1473
-
1474
- def path_shift(self, shift=1):
1475
- """ Shift path segments from :attr:`path` to :attr:`script_name` and
1476
- vice versa.
1477
-
1478
- :param shift: The number of path segments to shift. May be negative
1479
- to change the shift direction. (default: 1)
1480
- """
1481
- script, path = path_shift(self.environ.get('SCRIPT_NAME', '/'), self.path, shift)
1482
- self['SCRIPT_NAME'], self['PATH_INFO'] = script, path
1483
-
1484
- @property
1485
- def content_length(self):
1486
- """ The request body length as an integer. The client is responsible to
1487
- set this header. Otherwise, the real length of the body is unknown
1488
- and -1 is returned. In this case, :attr:`body` will be empty. """
1489
- return int(self.environ.get('CONTENT_LENGTH') or -1)
1490
-
1491
- @property
1492
- def content_type(self):
1493
- """ The Content-Type header as a lowercase-string (default: empty). """
1494
- return self.environ.get('CONTENT_TYPE', '').lower()
1495
-
1496
- @property
1497
- def is_xhr(self):
1498
- """ True if the request was triggered by a XMLHttpRequest. This only
1499
- works with JavaScript libraries that support the `X-Requested-With`
1500
- header (most of the popular libraries do). """
1501
- requested_with = self.environ.get('HTTP_X_REQUESTED_WITH', '')
1502
- return requested_with.lower() == 'xmlhttprequest'
1503
-
1504
- @property
1505
- def is_ajax(self):
1506
- """ Alias for :attr:`is_xhr`. "Ajax" is not the right term. """
1507
- return self.is_xhr
1508
-
1509
- @property
1510
- def auth(self):
1511
- """ HTTP authentication data as a (user, password) tuple. This
1512
- implementation currently supports basic (not digest) authentication
1513
- only. If the authentication happened at a higher level (e.g. in the
1514
- front web-server or a middleware), the password field is None, but
1515
- the user field is looked up from the ``REMOTE_USER`` environ
1516
- variable. On any errors, None is returned. """
1517
- basic = parse_auth(self.environ.get('HTTP_AUTHORIZATION', ''))
1518
- if basic: return basic
1519
- ruser = self.environ.get('REMOTE_USER')
1520
- if ruser: return (ruser, None)
1521
- return None
1522
-
1523
- @property
1524
- def remote_route(self):
1525
- """ A list of all IPs that were involved in this request, starting with
1526
- the client IP and followed by zero or more proxies. This does only
1527
- work if all proxies support the ```X-Forwarded-For`` header. Note
1528
- that this information can be forged by malicious clients. """
1529
- proxy = self.environ.get('HTTP_X_FORWARDED_FOR')
1530
- if proxy: return [ip.strip() for ip in proxy.split(',')]
1531
- remote = self.environ.get('REMOTE_ADDR')
1532
- return [remote] if remote else []
1533
-
1534
- @property
1535
- def remote_addr(self):
1536
- """ The client IP as a string. Note that this information can be forged
1537
- by malicious clients. """
1538
- route = self.remote_route
1539
- return route[0] if route else None
1540
-
1541
- def copy(self):
1542
- """ Return a new :class:`Request` with a shallow :attr:`environ` copy. """
1543
- return Request(self.environ.copy())
1544
-
1545
- def get(self, value, default=None):
1546
- return self.environ.get(value, default)
1547
-
1548
- def __getitem__(self, key):
1549
- return self.environ[key]
1550
-
1551
- def __delitem__(self, key):
1552
- self[key] = ""
1553
- del (self.environ[key])
1554
-
1555
- def __iter__(self):
1556
- return iter(self.environ)
1557
-
1558
- def __len__(self):
1559
- return len(self.environ)
1560
-
1561
- def keys(self):
1562
- return self.environ.keys()
1563
-
1564
- def __setitem__(self, key, value):
1565
- """ Change an environ value and clear all caches that depend on it. """
1566
-
1567
- if self.environ.get('bottle.request.readonly'):
1568
- raise KeyError('The environ dictionary is read-only.')
1569
-
1570
- self.environ[key] = value
1571
- todelete = ()
1572
-
1573
- if key == 'wsgi.input':
1574
- todelete = ('body', 'forms', 'files', 'params', 'post', 'json')
1575
- elif key == 'QUERY_STRING':
1576
- todelete = ('query', 'params')
1577
- elif key.startswith('HTTP_'):
1578
- todelete = ('headers', 'cookies')
1579
-
1580
- for key in todelete:
1581
- self.environ.pop('bottle.request.' + key, None)
1582
-
1583
- def __repr__(self):
1584
- return '<%s: %s %s>' % (self.__class__.__name__, self.method, self.url)
1585
-
1586
- def __getattr__(self, name):
1587
- """ Search in self.environ for additional user defined attributes. """
1588
- try:
1589
- var = self.environ['bottle.request.ext.%s' % name]
1590
- return var.__get__(self) if hasattr(var, '__get__') else var
1591
- except KeyError:
1592
- raise AttributeError('Attribute %r not defined.' % name)
1593
-
1594
- def __setattr__(self, name, value):
1595
- if name == 'environ': return object.__setattr__(self, name, value)
1596
- key = 'bottle.request.ext.%s' % name
1597
- if key in self.environ:
1598
- raise AttributeError("Attribute already defined: %s" % name)
1599
- self.environ[key] = value
1600
-
1601
- def __delattr__(self, name):
1602
- try:
1603
- del self.environ['bottle.request.ext.%s' % name]
1604
- except KeyError:
1605
- raise AttributeError("Attribute not defined: %s" % name)
1606
-
1607
-
1608
- def _hkey(key):
1609
- if '\n' in key or '\r' in key or '\0' in key:
1610
- raise ValueError("Header names must not contain control characters: %r" % key)
1611
- return key.title().replace('_', '-')
1612
-
1613
-
1614
- def _hval(value):
1615
- value = tonat(value)
1616
- if '\n' in value or '\r' in value or '\0' in value:
1617
- raise ValueError("Header value must not contain control characters: %r" % value)
1618
- return value
1619
-
1620
-
1621
- class HeaderProperty(object):
1622
- def __init__(self, name, reader=None, writer=None, default=''):
1623
- self.name, self.default = name, default
1624
- self.reader, self.writer = reader, writer
1625
- self.__doc__ = 'Current value of the %r header.' % name.title()
1626
-
1627
- def __get__(self, obj, _):
1628
- if obj is None: return self
1629
- value = obj.get_header(self.name, self.default)
1630
- return self.reader(value) if self.reader else value
1631
-
1632
- def __set__(self, obj, value):
1633
- obj[self.name] = self.writer(value) if self.writer else value
1634
-
1635
- def __delete__(self, obj):
1636
- del obj[self.name]
1637
-
1638
-
1639
- class BaseResponse(object):
1640
- """ Storage class for a response body as well as headers and cookies.
1641
-
1642
- This class does support dict-like case-insensitive item-access to
1643
- headers, but is NOT a dict. Most notably, iterating over a response
1644
- yields parts of the body and not the headers.
1645
-
1646
- :param body: The response body as one of the supported types.
1647
- :param status: Either an HTTP status code (e.g. 200) or a status line
1648
- including the reason phrase (e.g. '200 OK').
1649
- :param headers: A dictionary or a list of name-value pairs.
1650
-
1651
- Additional keyword arguments are added to the list of headers.
1652
- Underscores in the header name are replaced with dashes.
1653
- """
1654
-
1655
- default_status = 200
1656
- default_content_type = 'text/html; charset=UTF-8'
1657
-
1658
- # Header blacklist for specific response codes
1659
- # (rfc2616 section 10.2.3 and 10.3.5)
1660
- bad_headers = {
1661
- 204: frozenset(('Content-Type', 'Content-Length')),
1662
- 304: frozenset(('Allow', 'Content-Encoding', 'Content-Language',
1663
- 'Content-Length', 'Content-Range', 'Content-Type',
1664
- 'Content-Md5', 'Last-Modified'))
1665
- }
1666
-
1667
- def __init__(self, body='', status=None, headers=None, **more_headers):
1668
- self._cookies = None
1669
- self._headers = {}
1670
- self.body = body
1671
- self.status = status or self.default_status
1672
- if headers:
1673
- if isinstance(headers, dict):
1674
- headers = headers.items()
1675
- for name, value in headers:
1676
- self.add_header(name, value)
1677
- if more_headers:
1678
- for name, value in more_headers.items():
1679
- self.add_header(name, value)
1680
-
1681
- def copy(self, cls=None):
1682
- """ Returns a copy of self. """
1683
- cls = cls or BaseResponse
1684
- assert issubclass(cls, BaseResponse)
1685
- copy = cls()
1686
- copy.status = self.status
1687
- copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
1688
- if self._cookies:
1689
- cookies = copy._cookies = SimpleCookie()
1690
- for k,v in self._cookies.items():
1691
- cookies[k] = v.value
1692
- cookies[k].update(v) # also copy cookie attributes
1693
- return copy
1694
-
1695
- def __iter__(self):
1696
- return iter(self.body)
1697
-
1698
- def close(self):
1699
- if hasattr(self.body, 'close'):
1700
- self.body.close()
1701
-
1702
- @property
1703
- def status_line(self):
1704
- """ The HTTP status line as a string (e.g. ``404 Not Found``)."""
1705
- return self._status_line
1706
-
1707
- @property
1708
- def status_code(self):
1709
- """ The HTTP status code as an integer (e.g. 404)."""
1710
- return self._status_code
1711
-
1712
- def _set_status(self, status):
1713
- if isinstance(status, int):
1714
- code, status = status, _HTTP_STATUS_LINES.get(status)
1715
- elif ' ' in status:
1716
- if '\n' in status or '\r' in status or '\0' in status:
1717
- raise ValueError('Status line must not include control chars.')
1718
- status = status.strip()
1719
- code = int(status.split()[0])
1720
- else:
1721
- raise ValueError('String status line without a reason phrase.')
1722
- if not 100 <= code <= 999:
1723
- raise ValueError('Status code out of range.')
1724
- self._status_code = code
1725
- self._status_line = str(status or ('%d Unknown' % code))
1726
-
1727
- def _get_status(self):
1728
- return self._status_line
1729
-
1730
- status = property(
1731
- _get_status, _set_status, None,
1732
- ''' A writeable property to change the HTTP response status. It accepts
1733
- either a numeric code (100-999) or a string with a custom reason
1734
- phrase (e.g. "404 Brain not found"). Both :data:`status_line` and
1735
- :data:`status_code` are updated accordingly. The return value is
1736
- always a status string. ''')
1737
- del _get_status, _set_status
1738
-
1739
- @property
1740
- def headers(self):
1741
- """ An instance of :class:`HeaderDict`, a case-insensitive dict-like
1742
- view on the response headers. """
1743
- hdict = HeaderDict()
1744
- hdict.dict = self._headers
1745
- return hdict
1746
-
1747
- def __contains__(self, name):
1748
- return _hkey(name) in self._headers
1749
-
1750
- def __delitem__(self, name):
1751
- del self._headers[_hkey(name)]
1752
-
1753
- def __getitem__(self, name):
1754
- return self._headers[_hkey(name)][-1]
1755
-
1756
- def __setitem__(self, name, value):
1757
- self._headers[_hkey(name)] = [_hval(value)]
1758
-
1759
- def get_header(self, name, default=None):
1760
- """ Return the value of a previously defined header. If there is no
1761
- header with that name, return a default value. """
1762
- return self._headers.get(_hkey(name), [default])[-1]
1763
-
1764
- def set_header(self, name, value):
1765
- """ Create a new response header, replacing any previously defined
1766
- headers with the same name. """
1767
- self._headers[_hkey(name)] = [_hval(value)]
1768
-
1769
- def add_header(self, name, value):
1770
- """ Add an additional response header, not removing duplicates. """
1771
- self._headers.setdefault(_hkey(name), []).append(_hval(value))
1772
-
1773
- def iter_headers(self):
1774
- """ Yield (header, value) tuples, skipping headers that are not
1775
- allowed with the current response status code. """
1776
- return self.headerlist
1777
-
1778
- def _wsgi_status_line(self):
1779
- """ WSGI conform status line (latin1-encodeable) """
1780
- if py3k:
1781
- return self._status_line.encode('utf8').decode('latin1')
1782
- return self._status_line
1783
-
1784
- @property
1785
- def headerlist(self):
1786
- """ WSGI conform list of (header, value) tuples. """
1787
- out = []
1788
- headers = list(self._headers.items())
1789
- if 'Content-Type' not in self._headers:
1790
- headers.append(('Content-Type', [self.default_content_type]))
1791
- if self._status_code in self.bad_headers:
1792
- bad_headers = self.bad_headers[self._status_code]
1793
- headers = [h for h in headers if h[0] not in bad_headers]
1794
- out += [(name, val) for (name, vals) in headers for val in vals]
1795
- if self._cookies:
1796
- for c in self._cookies.values():
1797
- out.append(('Set-Cookie', _hval(c.OutputString())))
1798
- if py3k:
1799
- out = [(k, v.encode('utf8').decode('latin1')) for (k, v) in out]
1800
- return out
1801
-
1802
- content_type = HeaderProperty('Content-Type')
1803
- content_length = HeaderProperty('Content-Length', reader=int, default=-1)
1804
- expires = HeaderProperty(
1805
- 'Expires',
1806
- reader=lambda x: datetime.utcfromtimestamp(parse_date(x)),
1807
- writer=lambda x: http_date(x))
1808
-
1809
- @property
1810
- def charset(self, default='UTF-8'):
1811
- """ Return the charset specified in the content-type header (default: utf8). """
1812
- if 'charset=' in self.content_type:
1813
- return self.content_type.split('charset=')[-1].split(';')[0].strip()
1814
- return default
1815
-
1816
- def set_cookie(self, name, value, secret=None, digestmod=hashlib.sha256, **options):
1817
- """ Create a new cookie or replace an old one. If the `secret` parameter is
1818
- set, create a `Signed Cookie` (described below).
1819
-
1820
- :param name: the name of the cookie.
1821
- :param value: the value of the cookie.
1822
- :param secret: a signature key required for signed cookies.
1823
-
1824
- Additionally, this method accepts all RFC 2109 attributes that are
1825
- supported by :class:`cookie.Morsel`, including:
1826
-
1827
- :param maxage: maximum age in seconds. (default: None)
1828
- :param expires: a datetime object or UNIX timestamp. (default: None)
1829
- :param domain: the domain that is allowed to read the cookie.
1830
- (default: current domain)
1831
- :param path: limits the cookie to a given path (default: current path)
1832
- :param secure: limit the cookie to HTTPS connections (default: off).
1833
- :param httponly: prevents client-side javascript to read this cookie
1834
- (default: off, requires Python 2.6 or newer).
1835
- :param samesite: Control or disable third-party use for this cookie.
1836
- Possible values: `lax`, `strict` or `none` (default).
1837
-
1838
- If neither `expires` nor `maxage` is set (default), the cookie will
1839
- expire at the end of the browser session (as soon as the browser
1840
- window is closed).
1841
-
1842
- Signed cookies may store any pickle-able object and are
1843
- cryptographically signed to prevent manipulation. Keep in mind that
1844
- cookies are limited to 4kb in most browsers.
1845
-
1846
- Warning: Pickle is a potentially dangerous format. If an attacker
1847
- gains access to the secret key, he could forge cookies that execute
1848
- code on server side if unpickled. Using pickle is discouraged and
1849
- support for it will be removed in later versions of bottle.
1850
-
1851
- Warning: Signed cookies are not encrypted (the client can still see
1852
- the content) and not copy-protected (the client can restore an old
1853
- cookie). The main intention is to make pickling and unpickling
1854
- save, not to store secret information at client side.
1855
- """
1856
- if not self._cookies:
1857
- self._cookies = SimpleCookie()
1858
-
1859
- # Monkey-patch Cookie lib to support 'SameSite' parameter
1860
- # https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1
1861
- if py < (3, 8, 0):
1862
- Morsel._reserved.setdefault('samesite', 'SameSite')
1863
-
1864
- if secret:
1865
- if not isinstance(value, basestring):
1866
- depr(0, 13, "Pickling of arbitrary objects into cookies is "
1867
- "deprecated.", "Only store strings in cookies. "
1868
- "JSON strings are fine, too.")
1869
- encoded = base64.b64encode(pickle.dumps([name, value], -1))
1870
- sig = base64.b64encode(hmac.new(tob(secret), encoded,
1871
- digestmod=digestmod).digest())
1872
- value = touni(tob('!') + sig + tob('?') + encoded)
1873
- elif not isinstance(value, basestring):
1874
- raise TypeError('Secret key required for non-string cookies.')
1875
-
1876
- # Cookie size plus options must not exceed 4kb.
1877
- if len(name) + len(value) > 3800:
1878
- raise ValueError('Content does not fit into a cookie.')
1879
-
1880
- self._cookies[name] = value
1881
-
1882
- for key, value in options.items():
1883
- if key in ('max_age', 'maxage'): # 'maxage' variant added in 0.13
1884
- key = 'max-age'
1885
- if isinstance(value, timedelta):
1886
- value = value.seconds + value.days * 24 * 3600
1887
- if key == 'expires':
1888
- value = http_date(value)
1889
- if key in ('same_site', 'samesite'): # 'samesite' variant added in 0.13
1890
- key, value = 'samesite', (value or "none").lower()
1891
- if value not in ('lax', 'strict', 'none'):
1892
- raise CookieError("Invalid value for SameSite")
1893
- if key in ('secure', 'httponly') and not value:
1894
- continue
1895
- self._cookies[name][key] = value
1896
-
1897
- def delete_cookie(self, key, **kwargs):
1898
- """ Delete a cookie. Be sure to use the same `domain` and `path`
1899
- settings as used to create the cookie. """
1900
- kwargs['max_age'] = -1
1901
- kwargs['expires'] = 0
1902
- self.set_cookie(key, '', **kwargs)
1903
-
1904
- def __repr__(self):
1905
- out = ''
1906
- for name, value in self.headerlist:
1907
- out += '%s: %s\n' % (name.title(), value.strip())
1908
- return out
1909
-
1910
-
1911
- def _local_property():
1912
- ls = threading.local()
1913
-
1914
- def fget(_):
1915
- try:
1916
- return ls.var
1917
- except AttributeError:
1918
- raise RuntimeError("Request context not initialized.")
1919
-
1920
- def fset(_, value):
1921
- ls.var = value
1922
-
1923
- def fdel(_):
1924
- del ls.var
1925
-
1926
- return property(fget, fset, fdel, 'Thread-local property')
1927
-
1928
-
1929
- class LocalRequest(BaseRequest):
1930
- """ A thread-local subclass of :class:`BaseRequest` with a different
1931
- set of attributes for each thread. There is usually only one global
1932
- instance of this class (:data:`request`). If accessed during a
1933
- request/response cycle, this instance always refers to the *current*
1934
- request (even on a multithreaded server). """
1935
- bind = BaseRequest.__init__
1936
- environ = _local_property()
1937
-
1938
-
1939
- class LocalResponse(BaseResponse):
1940
- """ A thread-local subclass of :class:`BaseResponse` with a different
1941
- set of attributes for each thread. There is usually only one global
1942
- instance of this class (:data:`response`). Its attributes are used
1943
- to build the HTTP response at the end of the request/response cycle.
1944
- """
1945
- bind = BaseResponse.__init__
1946
- _status_line = _local_property()
1947
- _status_code = _local_property()
1948
- _cookies = _local_property()
1949
- _headers = _local_property()
1950
- body = _local_property()
1951
-
1952
-
1953
- Request = BaseRequest
1954
- Response = BaseResponse
1955
-
1956
-
1957
- class HTTPResponse(Response, BottleException):
1958
- def __init__(self, body='', status=None, headers=None, **more_headers):
1959
- super(HTTPResponse, self).__init__(body, status, headers, **more_headers)
1960
-
1961
- def apply(self, other):
1962
- other._status_code = self._status_code
1963
- other._status_line = self._status_line
1964
- other._headers = self._headers
1965
- other._cookies = self._cookies
1966
- other.body = self.body
1967
-
1968
-
1969
- class HTTPError(HTTPResponse):
1970
- default_status = 500
1971
-
1972
- def __init__(self,
1973
- status=None,
1974
- body=None,
1975
- exception=None,
1976
- traceback=None, **more_headers):
1977
- self.exception = exception
1978
- self.traceback = traceback
1979
- super(HTTPError, self).__init__(body, status, **more_headers)
1980
-
1981
- ###############################################################################
1982
- # Plugins ######################################################################
1983
- ###############################################################################
1984
-
1985
-
1986
- class PluginError(BottleException):
1987
- pass
1988
-
1989
-
1990
- class JSONPlugin(object):
1991
- name = 'json'
1992
- api = 2
1993
-
1994
- def __init__(self, json_dumps=json_dumps):
1995
- self.json_dumps = json_dumps
1996
-
1997
- def setup(self, app):
1998
- app.config._define('json.enable', default=True, validate=bool,
1999
- help="Enable or disable automatic dict->json filter.")
2000
- app.config._define('json.ascii', default=False, validate=bool,
2001
- help="Use only 7-bit ASCII characters in output.")
2002
- app.config._define('json.indent', default=True, validate=bool,
2003
- help="Add whitespace to make json more readable.")
2004
- app.config._define('json.dump_func', default=None,
2005
- help="If defined, use this function to transform"
2006
- " dict into json. The other options no longer"
2007
- " apply.")
2008
-
2009
- def apply(self, callback, route):
2010
- dumps = self.json_dumps
2011
- if not self.json_dumps: return callback
2012
-
2013
- def wrapper(*a, **ka):
2014
- try:
2015
- rv = callback(*a, **ka)
2016
- except HTTPResponse as resp:
2017
- rv = resp
2018
-
2019
- if isinstance(rv, dict):
2020
- #Attempt to serialize, raises exception on failure
2021
- json_response = dumps(rv)
2022
- #Set content type only if serialization successful
2023
- response.content_type = 'application/json'
2024
- return json_response
2025
- elif isinstance(rv, HTTPResponse) and isinstance(rv.body, dict):
2026
- rv.body = dumps(rv.body)
2027
- rv.content_type = 'application/json'
2028
- return rv
2029
-
2030
- return wrapper
2031
-
2032
-
2033
- class TemplatePlugin(object):
2034
- """ This plugin applies the :func:`view` decorator to all routes with a
2035
- `template` config parameter. If the parameter is a tuple, the second
2036
- element must be a dict with additional options (e.g. `template_engine`)
2037
- or default variables for the template. """
2038
- name = 'template'
2039
- api = 2
2040
-
2041
- def setup(self, app):
2042
- app.tpl = self
2043
-
2044
- def apply(self, callback, route):
2045
- conf = route.config.get('template')
2046
- if isinstance(conf, (tuple, list)) and len(conf) == 2:
2047
- return view(conf[0], **conf[1])(callback)
2048
- elif isinstance(conf, str):
2049
- return view(conf)(callback)
2050
- else:
2051
- return callback
2052
-
2053
-
2054
- #: Not a plugin, but part of the plugin API. TODO: Find a better place.
2055
- class _ImportRedirect(object):
2056
- def __init__(self, name, impmask):
2057
- """ Create a virtual package that redirects imports (see PEP 302). """
2058
- self.name = name
2059
- self.impmask = impmask
2060
- self.module = sys.modules.setdefault(name, imp.new_module(name))
2061
- self.module.__dict__.update({
2062
- '__file__': __file__,
2063
- '__path__': [],
2064
- '__all__': [],
2065
- '__loader__': self
2066
- })
2067
- sys.meta_path.append(self)
2068
-
2069
- def find_module(self, fullname, path=None):
2070
- if '.' not in fullname: return
2071
- packname = fullname.rsplit('.', 1)[0]
2072
- if packname != self.name: return
2073
- return self
2074
-
2075
- def load_module(self, fullname):
2076
- if fullname in sys.modules: return sys.modules[fullname]
2077
- modname = fullname.rsplit('.', 1)[1]
2078
- realname = self.impmask % modname
2079
- __import__(realname)
2080
- module = sys.modules[fullname] = sys.modules[realname]
2081
- setattr(self.module, modname, module)
2082
- module.__loader__ = self
2083
- return module
2084
-
2085
- ###############################################################################
2086
- # Common Utilities #############################################################
2087
- ###############################################################################
2088
-
2089
-
2090
- class MultiDict(DictMixin):
2091
- """ This dict stores multiple values per key, but behaves exactly like a
2092
- normal dict in that it returns only the newest value for any given key.
2093
- There are special methods available to access the full list of values.
2094
- """
2095
-
2096
- def __init__(self, *a, **k):
2097
- self.dict = dict((k, [v]) for (k, v) in dict(*a, **k).items())
2098
-
2099
- def __len__(self):
2100
- return len(self.dict)
2101
-
2102
- def __iter__(self):
2103
- return iter(self.dict)
2104
-
2105
- def __contains__(self, key):
2106
- return key in self.dict
2107
-
2108
- def __delitem__(self, key):
2109
- del self.dict[key]
2110
-
2111
- def __getitem__(self, key):
2112
- return self.dict[key][-1]
2113
-
2114
- def __setitem__(self, key, value):
2115
- self.append(key, value)
2116
-
2117
- def keys(self):
2118
- return self.dict.keys()
2119
-
2120
- if py3k:
2121
-
2122
- def values(self):
2123
- return (v[-1] for v in self.dict.values())
2124
-
2125
- def items(self):
2126
- return ((k, v[-1]) for k, v in self.dict.items())
2127
-
2128
- def allitems(self):
2129
- return ((k, v) for k, vl in self.dict.items() for v in vl)
2130
-
2131
- iterkeys = keys
2132
- itervalues = values
2133
- iteritems = items
2134
- iterallitems = allitems
2135
-
2136
- else:
2137
-
2138
- def values(self):
2139
- return [v[-1] for v in self.dict.values()]
2140
-
2141
- def items(self):
2142
- return [(k, v[-1]) for k, v in self.dict.items()]
2143
-
2144
- def iterkeys(self):
2145
- return self.dict.iterkeys()
2146
-
2147
- def itervalues(self):
2148
- return (v[-1] for v in self.dict.itervalues())
2149
-
2150
- def iteritems(self):
2151
- return ((k, v[-1]) for k, v in self.dict.iteritems())
2152
-
2153
- def iterallitems(self):
2154
- return ((k, v) for k, vl in self.dict.iteritems() for v in vl)
2155
-
2156
- def allitems(self):
2157
- return [(k, v) for k, vl in self.dict.iteritems() for v in vl]
2158
-
2159
- def get(self, key, default=None, index=-1, type=None):
2160
- """ Return the most recent value for a key.
2161
-
2162
- :param default: The default value to be returned if the key is not
2163
- present or the type conversion fails.
2164
- :param index: An index for the list of available values.
2165
- :param type: If defined, this callable is used to cast the value
2166
- into a specific type. Exception are suppressed and result in
2167
- the default value to be returned.
2168
- """
2169
- try:
2170
- val = self.dict[key][index]
2171
- return type(val) if type else val
2172
- except Exception:
2173
- pass
2174
- return default
2175
-
2176
- def append(self, key, value):
2177
- """ Add a new value to the list of values for this key. """
2178
- self.dict.setdefault(key, []).append(value)
2179
-
2180
- def replace(self, key, value):
2181
- """ Replace the list of values with a single value. """
2182
- self.dict[key] = [value]
2183
-
2184
- def getall(self, key):
2185
- """ Return a (possibly empty) list of values for a key. """
2186
- return self.dict.get(key) or []
2187
-
2188
- #: Aliases for WTForms to mimic other multi-dict APIs (Django)
2189
- getone = get
2190
- getlist = getall
2191
-
2192
-
2193
- class FormsDict(MultiDict):
2194
- """ This :class:`MultiDict` subclass is used to store request form data.
2195
- Additionally to the normal dict-like item access methods (which return
2196
- unmodified data as native strings), this container also supports
2197
- attribute-like access to its values. Attributes are automatically de-
2198
- or recoded to match :attr:`input_encoding` (default: 'utf8'). Missing
2199
- attributes default to an empty string. """
2200
-
2201
- #: Encoding used for attribute values.
2202
- input_encoding = 'utf8'
2203
- #: If true (default), unicode strings are first encoded with `latin1`
2204
- #: and then decoded to match :attr:`input_encoding`.
2205
- recode_unicode = True
2206
-
2207
- def _fix(self, s, encoding=None):
2208
- if isinstance(s, unicode) and self.recode_unicode: # Python 3 WSGI
2209
- return s.encode('latin1').decode(encoding or self.input_encoding)
2210
- elif isinstance(s, bytes): # Python 2 WSGI
2211
- return s.decode(encoding or self.input_encoding)
2212
- else:
2213
- return s
2214
-
2215
- def decode(self, encoding=None):
2216
- """ Returns a copy with all keys and values de- or recoded to match
2217
- :attr:`input_encoding`. Some libraries (e.g. WTForms) want a
2218
- unicode dictionary. """
2219
- copy = FormsDict()
2220
- enc = copy.input_encoding = encoding or self.input_encoding
2221
- copy.recode_unicode = False
2222
- for key, value in self.allitems():
2223
- copy.append(self._fix(key, enc), self._fix(value, enc))
2224
- return copy
2225
-
2226
- def getunicode(self, name, default=None, encoding=None):
2227
- """ Return the value as a unicode string, or the default. """
2228
- try:
2229
- return self._fix(self[name], encoding)
2230
- except (UnicodeError, KeyError):
2231
- return default
2232
-
2233
- def __getattr__(self, name, default=unicode()):
2234
- # Without this guard, pickle generates a cryptic TypeError:
2235
- if name.startswith('__') and name.endswith('__'):
2236
- return super(FormsDict, self).__getattr__(name)
2237
- return self.getunicode(name, default=default)
2238
-
2239
- class HeaderDict(MultiDict):
2240
- """ A case-insensitive version of :class:`MultiDict` that defaults to
2241
- replace the old value instead of appending it. """
2242
-
2243
- def __init__(self, *a, **ka):
2244
- self.dict = {}
2245
- if a or ka: self.update(*a, **ka)
2246
-
2247
- def __contains__(self, key):
2248
- return _hkey(key) in self.dict
2249
-
2250
- def __delitem__(self, key):
2251
- del self.dict[_hkey(key)]
2252
-
2253
- def __getitem__(self, key):
2254
- return self.dict[_hkey(key)][-1]
2255
-
2256
- def __setitem__(self, key, value):
2257
- self.dict[_hkey(key)] = [_hval(value)]
2258
-
2259
- def append(self, key, value):
2260
- self.dict.setdefault(_hkey(key), []).append(_hval(value))
2261
-
2262
- def replace(self, key, value):
2263
- self.dict[_hkey(key)] = [_hval(value)]
2264
-
2265
- def getall(self, key):
2266
- return self.dict.get(_hkey(key)) or []
2267
-
2268
- def get(self, key, default=None, index=-1):
2269
- return MultiDict.get(self, _hkey(key), default, index)
2270
-
2271
- def filter(self, names):
2272
- for name in (_hkey(n) for n in names):
2273
- if name in self.dict:
2274
- del self.dict[name]
2275
-
2276
-
2277
- class WSGIHeaderDict(DictMixin):
2278
- """ This dict-like class wraps a WSGI environ dict and provides convenient
2279
- access to HTTP_* fields. Keys and values are native strings
2280
- (2.x bytes or 3.x unicode) and keys are case-insensitive. If the WSGI
2281
- environment contains non-native string values, these are de- or encoded
2282
- using a lossless 'latin1' character set.
2283
-
2284
- The API will remain stable even on changes to the relevant PEPs.
2285
- Currently PEP 333, 444 and 3333 are supported. (PEP 444 is the only one
2286
- that uses non-native strings.)
2287
- """
2288
- #: List of keys that do not have a ``HTTP_`` prefix.
2289
- cgikeys = ('CONTENT_TYPE', 'CONTENT_LENGTH')
2290
-
2291
- def __init__(self, environ):
2292
- self.environ = environ
2293
-
2294
- def _ekey(self, key):
2295
- """ Translate header field name to CGI/WSGI environ key. """
2296
- key = key.replace('-', '_').upper()
2297
- if key in self.cgikeys:
2298
- return key
2299
- return 'HTTP_' + key
2300
-
2301
- def raw(self, key, default=None):
2302
- """ Return the header value as is (may be bytes or unicode). """
2303
- return self.environ.get(self._ekey(key), default)
2304
-
2305
- def __getitem__(self, key):
2306
- val = self.environ[self._ekey(key)]
2307
- if py3k:
2308
- if isinstance(val, unicode):
2309
- val = val.encode('latin1').decode('utf8')
2310
- else:
2311
- val = val.decode('utf8')
2312
- return val
2313
-
2314
- def __setitem__(self, key, value):
2315
- raise TypeError("%s is read-only." % self.__class__)
2316
-
2317
- def __delitem__(self, key):
2318
- raise TypeError("%s is read-only." % self.__class__)
2319
-
2320
- def __iter__(self):
2321
- for key in self.environ:
2322
- if key[:5] == 'HTTP_':
2323
- yield _hkey(key[5:])
2324
- elif key in self.cgikeys:
2325
- yield _hkey(key)
2326
-
2327
- def keys(self):
2328
- return [x for x in self]
2329
-
2330
- def __len__(self):
2331
- return len(self.keys())
2332
-
2333
- def __contains__(self, key):
2334
- return self._ekey(key) in self.environ
2335
-
2336
- _UNSET = object()
2337
-
2338
- class ConfigDict(dict):
2339
- """ A dict-like configuration storage with additional support for
2340
- namespaces, validators, meta-data, overlays and more.
2341
-
2342
- This dict-like class is heavily optimized for read access. All read-only
2343
- methods as well as item access should be as fast as the built-in dict.
2344
- """
2345
-
2346
- __slots__ = ('_meta', '_change_listener', '_overlays', '_virtual_keys', '_source', '__weakref__')
2347
-
2348
- def __init__(self):
2349
- self._meta = {}
2350
- self._change_listener = []
2351
- #: Weak references of overlays that need to be kept in sync.
2352
- self._overlays = []
2353
- #: Config that is the source for this overlay.
2354
- self._source = None
2355
- #: Keys of values copied from the source (values we do not own)
2356
- self._virtual_keys = set()
2357
-
2358
- def load_module(self, path, squash=True):
2359
- """Load values from a Python module.
2360
-
2361
- Example modue ``config.py``::
2362
-
2363
- DEBUG = True
2364
- SQLITE = {
2365
- "db": ":memory:"
2366
- }
2367
-
2368
-
2369
- >>> c = ConfigDict()
2370
- >>> c.load_module('config')
2371
- {DEBUG: True, 'SQLITE.DB': 'memory'}
2372
- >>> c.load_module("config", False)
2373
- {'DEBUG': True, 'SQLITE': {'DB': 'memory'}}
2374
-
2375
- :param squash: If true (default), dictionary values are assumed to
2376
- represent namespaces (see :meth:`load_dict`).
2377
- """
2378
- config_obj = load(path)
2379
- obj = {key: getattr(config_obj, key) for key in dir(config_obj)
2380
- if key.isupper()}
2381
-
2382
- if squash:
2383
- self.load_dict(obj)
2384
- else:
2385
- self.update(obj)
2386
- return self
2387
-
2388
- def load_config(self, filename, **options):
2389
- """ Load values from an ``*.ini`` style config file.
2390
-
2391
- A configuration file consists of sections, each led by a
2392
- ``[section]`` header, followed by key/value entries separated by
2393
- either ``=`` or ``:``. Section names and keys are case-insensitive.
2394
- Leading and trailing whitespace is removed from keys and values.
2395
- Values can be omitted, in which case the key/value delimiter may
2396
- also be left out. Values can also span multiple lines, as long as
2397
- they are indented deeper than the first line of the value. Commands
2398
- are prefixed by ``#`` or ``;`` and may only appear on their own on
2399
- an otherwise empty line.
2400
-
2401
- Both section and key names may contain dots (``.``) as namespace
2402
- separators. The actual configuration parameter name is constructed
2403
- by joining section name and key name together and converting to
2404
- lower case.
2405
-
2406
- The special sections ``bottle`` and ``ROOT`` refer to the root
2407
- namespace and the ``DEFAULT`` section defines default values for all
2408
- other sections.
2409
-
2410
- With Python 3, extended string interpolation is enabled.
2411
-
2412
- :param filename: The path of a config file, or a list of paths.
2413
- :param options: All keyword parameters are passed to the underlying
2414
- :class:`python:configparser.ConfigParser` constructor call.
2415
-
2416
- """
2417
- options.setdefault('allow_no_value', True)
2418
- if py3k:
2419
- options.setdefault('interpolation',
2420
- configparser.ExtendedInterpolation())
2421
- conf = configparser.ConfigParser(**options)
2422
- conf.read(filename)
2423
- for section in conf.sections():
2424
- for key in conf.options(section):
2425
- value = conf.get(section, key)
2426
- if section not in ('bottle', 'ROOT'):
2427
- key = section + '.' + key
2428
- self[key.lower()] = value
2429
- return self
2430
-
2431
- def load_dict(self, source, namespace=''):
2432
- """ Load values from a dictionary structure. Nesting can be used to
2433
- represent namespaces.
2434
-
2435
- >>> c = ConfigDict()
2436
- >>> c.load_dict({'some': {'namespace': {'key': 'value'} } })
2437
- {'some.namespace.key': 'value'}
2438
- """
2439
- for key, value in source.items():
2440
- if isinstance(key, basestring):
2441
- nskey = (namespace + '.' + key).strip('.')
2442
- if isinstance(value, dict):
2443
- self.load_dict(value, namespace=nskey)
2444
- else:
2445
- self[nskey] = value
2446
- else:
2447
- raise TypeError('Key has type %r (not a string)' % type(key))
2448
- return self
2449
-
2450
- def update(self, *a, **ka):
2451
- """ If the first parameter is a string, all keys are prefixed with this
2452
- namespace. Apart from that it works just as the usual dict.update().
2453
-
2454
- >>> c = ConfigDict()
2455
- >>> c.update('some.namespace', key='value')
2456
- """
2457
- prefix = ''
2458
- if a and isinstance(a[0], basestring):
2459
- prefix = a[0].strip('.') + '.'
2460
- a = a[1:]
2461
- for key, value in dict(*a, **ka).items():
2462
- self[prefix + key] = value
2463
-
2464
- def setdefault(self, key, value):
2465
- if key not in self:
2466
- self[key] = value
2467
- return self[key]
2468
-
2469
- def __setitem__(self, key, value):
2470
- if not isinstance(key, basestring):
2471
- raise TypeError('Key has type %r (not a string)' % type(key))
2472
-
2473
- self._virtual_keys.discard(key)
2474
-
2475
- value = self.meta_get(key, 'filter', lambda x: x)(value)
2476
- if key in self and self[key] is value:
2477
- return
2478
-
2479
- self._on_change(key, value)
2480
- dict.__setitem__(self, key, value)
2481
-
2482
- for overlay in self._iter_overlays():
2483
- overlay._set_virtual(key, value)
2484
-
2485
- def __delitem__(self, key):
2486
- if key not in self:
2487
- raise KeyError(key)
2488
- if key in self._virtual_keys:
2489
- raise KeyError("Virtual keys cannot be deleted: %s" % key)
2490
-
2491
- if self._source and key in self._source:
2492
- # Not virtual, but present in source -> Restore virtual value
2493
- dict.__delitem__(self, key)
2494
- self._set_virtual(key, self._source[key])
2495
- else: # not virtual, not present in source. This is OUR value
2496
- self._on_change(key, None)
2497
- dict.__delitem__(self, key)
2498
- for overlay in self._iter_overlays():
2499
- overlay._delete_virtual(key)
2500
-
2501
- def _set_virtual(self, key, value):
2502
- """ Recursively set or update virtual keys. Do nothing if non-virtual
2503
- value is present. """
2504
- if key in self and key not in self._virtual_keys:
2505
- return # Do nothing for non-virtual keys.
2506
-
2507
- self._virtual_keys.add(key)
2508
- if key in self and self[key] is not value:
2509
- self._on_change(key, value)
2510
- dict.__setitem__(self, key, value)
2511
- for overlay in self._iter_overlays():
2512
- overlay._set_virtual(key, value)
2513
-
2514
- def _delete_virtual(self, key):
2515
- """ Recursively delete virtual entry. Do nothing if key is not virtual.
2516
- """
2517
- if key not in self._virtual_keys:
2518
- return # Do nothing for non-virtual keys.
2519
-
2520
- if key in self:
2521
- self._on_change(key, None)
2522
- dict.__delitem__(self, key)
2523
- self._virtual_keys.discard(key)
2524
- for overlay in self._iter_overlays():
2525
- overlay._delete_virtual(key)
2526
-
2527
- def _on_change(self, key, value):
2528
- for cb in self._change_listener:
2529
- if cb(self, key, value):
2530
- return True
2531
-
2532
- def _add_change_listener(self, func):
2533
- self._change_listener.append(func)
2534
- return func
2535
-
2536
- def meta_get(self, key, metafield, default=None):
2537
- """ Return the value of a meta field for a key. """
2538
- return self._meta.get(key, {}).get(metafield, default)
2539
-
2540
- def meta_set(self, key, metafield, value):
2541
- """ Set the meta field for a key to a new value. """
2542
- self._meta.setdefault(key, {})[metafield] = value
2543
-
2544
- def meta_list(self, key):
2545
- """ Return an iterable of meta field names defined for a key. """
2546
- return self._meta.get(key, {}).keys()
2547
-
2548
- def _define(self, key, default=_UNSET, help=_UNSET, validate=_UNSET):
2549
- """ (Unstable) Shortcut for plugins to define own config parameters. """
2550
- if default is not _UNSET:
2551
- self.setdefault(key, default)
2552
- if help is not _UNSET:
2553
- self.meta_set(key, 'help', help)
2554
- if validate is not _UNSET:
2555
- self.meta_set(key, 'validate', validate)
2556
-
2557
- def _iter_overlays(self):
2558
- for ref in self._overlays:
2559
- overlay = ref()
2560
- if overlay is not None:
2561
- yield overlay
2562
-
2563
- def _make_overlay(self):
2564
- """ (Unstable) Create a new overlay that acts like a chained map: Values
2565
- missing in the overlay are copied from the source map. Both maps
2566
- share the same meta entries.
2567
-
2568
- Entries that were copied from the source are called 'virtual'. You
2569
- can not delete virtual keys, but overwrite them, which turns them
2570
- into non-virtual entries. Setting keys on an overlay never affects
2571
- its source, but may affect any number of child overlays.
2572
-
2573
- Other than collections.ChainMap or most other implementations, this
2574
- approach does not resolve missing keys on demand, but instead
2575
- actively copies all values from the source to the overlay and keeps
2576
- track of virtual and non-virtual keys internally. This removes any
2577
- lookup-overhead. Read-access is as fast as a build-in dict for both
2578
- virtual and non-virtual keys.
2579
-
2580
- Changes are propagated recursively and depth-first. A failing
2581
- on-change handler in an overlay stops the propagation of virtual
2582
- values and may result in an partly updated tree. Take extra care
2583
- here and make sure that on-change handlers never fail.
2584
-
2585
- Used by Route.config
2586
- """
2587
- # Cleanup dead references
2588
- self._overlays[:] = [ref for ref in self._overlays if ref() is not None]
2589
-
2590
- overlay = ConfigDict()
2591
- overlay._meta = self._meta
2592
- overlay._source = self
2593
- self._overlays.append(weakref.ref(overlay))
2594
- for key in self:
2595
- overlay._set_virtual(key, self[key])
2596
- return overlay
2597
-
2598
-
2599
-
2600
-
2601
- class AppStack(list):
2602
- """ A stack-like list. Calling it returns the head of the stack. """
2603
-
2604
- def __call__(self):
2605
- """ Return the current default application. """
2606
- return self.default
2607
-
2608
- def push(self, value=None):
2609
- """ Add a new :class:`Bottle` instance to the stack """
2610
- if not isinstance(value, Bottle):
2611
- value = Bottle()
2612
- self.append(value)
2613
- return value
2614
- new_app = push
2615
-
2616
- @property
2617
- def default(self):
2618
- try:
2619
- return self[-1]
2620
- except IndexError:
2621
- return self.push()
2622
-
2623
-
2624
- class WSGIFileWrapper(object):
2625
- def __init__(self, fp, buffer_size=1024 * 64):
2626
- self.fp, self.buffer_size = fp, buffer_size
2627
- for attr in 'fileno', 'close', 'read', 'readlines', 'tell', 'seek':
2628
- if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr))
2629
-
2630
- def __iter__(self):
2631
- buff, read = self.buffer_size, self.read
2632
- part = read(buff)
2633
- while part:
2634
- yield part
2635
- part = read(buff)
2636
-
2637
-
2638
- class _closeiter(object):
2639
- """ This only exists to be able to attach a .close method to iterators that
2640
- do not support attribute assignment (most of itertools). """
2641
-
2642
- def __init__(self, iterator, close=None):
2643
- self.iterator = iterator
2644
- self.close_callbacks = makelist(close)
2645
-
2646
- def __iter__(self):
2647
- return iter(self.iterator)
2648
-
2649
- def close(self):
2650
- for func in self.close_callbacks:
2651
- func()
2652
-
2653
-
2654
- class ResourceManager(object):
2655
- """ This class manages a list of search paths and helps to find and open
2656
- application-bound resources (files).
2657
-
2658
- :param base: default value for :meth:`add_path` calls.
2659
- :param opener: callable used to open resources.
2660
- :param cachemode: controls which lookups are cached. One of 'all',
2661
- 'found' or 'none'.
2662
- """
2663
-
2664
- def __init__(self, base='./', opener=open, cachemode='all'):
2665
- self.opener = opener
2666
- self.base = base
2667
- self.cachemode = cachemode
2668
-
2669
- #: A list of search paths. See :meth:`add_path` for details.
2670
- self.path = []
2671
- #: A cache for resolved paths. ``res.cache.clear()`` clears the cache.
2672
- self.cache = {}
2673
-
2674
- def add_path(self, path, base=None, index=None, create=False):
2675
- """ Add a new path to the list of search paths. Return False if the
2676
- path does not exist.
2677
-
2678
- :param path: The new search path. Relative paths are turned into
2679
- an absolute and normalized form. If the path looks like a file
2680
- (not ending in `/`), the filename is stripped off.
2681
- :param base: Path used to absolutize relative search paths.
2682
- Defaults to :attr:`base` which defaults to ``os.getcwd()``.
2683
- :param index: Position within the list of search paths. Defaults
2684
- to last index (appends to the list).
2685
-
2686
- The `base` parameter makes it easy to reference files installed
2687
- along with a python module or package::
2688
-
2689
- res.add_path('./resources/', __file__)
2690
- """
2691
- base = os.path.abspath(os.path.dirname(base or self.base))
2692
- path = os.path.abspath(os.path.join(base, os.path.dirname(path)))
2693
- path += os.sep
2694
- if path in self.path:
2695
- self.path.remove(path)
2696
- if create and not os.path.isdir(path):
2697
- os.makedirs(path)
2698
- if index is None:
2699
- self.path.append(path)
2700
- else:
2701
- self.path.insert(index, path)
2702
- self.cache.clear()
2703
- return os.path.exists(path)
2704
-
2705
- def __iter__(self):
2706
- """ Iterate over all existing files in all registered paths. """
2707
- search = self.path[:]
2708
- while search:
2709
- path = search.pop()
2710
- if not os.path.isdir(path): continue
2711
- for name in os.listdir(path):
2712
- full = os.path.join(path, name)
2713
- if os.path.isdir(full): search.append(full)
2714
- else: yield full
2715
-
2716
- def lookup(self, name):
2717
- """ Search for a resource and return an absolute file path, or `None`.
2718
-
2719
- The :attr:`path` list is searched in order. The first match is
2720
- returned. Symlinks are followed. The result is cached to speed up
2721
- future lookups. """
2722
- if name not in self.cache or DEBUG:
2723
- for path in self.path:
2724
- fpath = os.path.join(path, name)
2725
- if os.path.isfile(fpath):
2726
- if self.cachemode in ('all', 'found'):
2727
- self.cache[name] = fpath
2728
- return fpath
2729
- if self.cachemode == 'all':
2730
- self.cache[name] = None
2731
- return self.cache[name]
2732
-
2733
- def open(self, name, mode='r', *args, **kwargs):
2734
- """ Find a resource and return a file object, or raise IOError. """
2735
- fname = self.lookup(name)
2736
- if not fname: raise IOError("Resource %r not found." % name)
2737
- return self.opener(fname, mode=mode, *args, **kwargs)
2738
-
2739
-
2740
- class FileUpload(object):
2741
- def __init__(self, fileobj, name, filename, headers=None):
2742
- """ Wrapper for file uploads. """
2743
- #: Open file(-like) object (BytesIO buffer or temporary file)
2744
- self.file = fileobj
2745
- #: Name of the upload form field
2746
- self.name = name
2747
- #: Raw filename as sent by the client (may contain unsafe characters)
2748
- self.raw_filename = filename
2749
- #: A :class:`HeaderDict` with additional headers (e.g. content-type)
2750
- self.headers = HeaderDict(headers) if headers else HeaderDict()
2751
-
2752
- content_type = HeaderProperty('Content-Type')
2753
- content_length = HeaderProperty('Content-Length', reader=int, default=-1)
2754
-
2755
- def get_header(self, name, default=None):
2756
- """ Return the value of a header within the multipart part. """
2757
- return self.headers.get(name, default)
2758
-
2759
- @cached_property
2760
- def filename(self):
2761
- """ Name of the file on the client file system, but normalized to ensure
2762
- file system compatibility. An empty filename is returned as 'empty'.
2763
-
2764
- Only ASCII letters, digits, dashes, underscores and dots are
2765
- allowed in the final filename. Accents are removed, if possible.
2766
- Whitespace is replaced by a single dash. Leading or tailing dots
2767
- or dashes are removed. The filename is limited to 255 characters.
2768
- """
2769
- fname = self.raw_filename
2770
- if not isinstance(fname, unicode):
2771
- fname = fname.decode('utf8', 'ignore')
2772
- fname = normalize('NFKD', fname)
2773
- fname = fname.encode('ASCII', 'ignore').decode('ASCII')
2774
- fname = os.path.basename(fname.replace('\\', os.path.sep))
2775
- fname = re.sub(r'[^a-zA-Z0-9-_.\s]', '', fname).strip()
2776
- fname = re.sub(r'[-\s]+', '-', fname).strip('.-')
2777
- return fname[:255] or 'empty'
2778
-
2779
- def _copy_file(self, fp, chunk_size=2 ** 16):
2780
- read, write, offset = self.file.read, fp.write, self.file.tell()
2781
- while 1:
2782
- buf = read(chunk_size)
2783
- if not buf: break
2784
- write(buf)
2785
- self.file.seek(offset)
2786
-
2787
- def save(self, destination, overwrite=False, chunk_size=2 ** 16):
2788
- """ Save file to disk or copy its content to an open file(-like) object.
2789
- If *destination* is a directory, :attr:`filename` is added to the
2790
- path. Existing files are not overwritten by default (IOError).
2791
-
2792
- :param destination: File path, directory or file(-like) object.
2793
- :param overwrite: If True, replace existing files. (default: False)
2794
- :param chunk_size: Bytes to read at a time. (default: 64kb)
2795
- """
2796
- if isinstance(destination, basestring): # Except file-likes here
2797
- if os.path.isdir(destination):
2798
- destination = os.path.join(destination, self.filename)
2799
- if not overwrite and os.path.exists(destination):
2800
- raise IOError('File exists.')
2801
- with open(destination, 'wb') as fp:
2802
- self._copy_file(fp, chunk_size)
2803
- else:
2804
- self._copy_file(destination, chunk_size)
2805
-
2806
- ###############################################################################
2807
- # Application Helper ###########################################################
2808
- ###############################################################################
2809
-
2810
-
2811
- def abort(code=500, text='Unknown Error.'):
2812
- """ Aborts execution and causes a HTTP error. """
2813
- raise HTTPError(code, text)
2814
-
2815
-
2816
- def redirect(url, code=None):
2817
- """ Aborts execution and causes a 303 or 302 redirect, depending on
2818
- the HTTP protocol version. """
2819
- if not code:
2820
- code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
2821
- res = response.copy(cls=HTTPResponse)
2822
- res.status = code
2823
- res.body = ""
2824
- res.set_header('Location', urljoin(request.url, url))
2825
- raise res
2826
-
2827
-
2828
- def _file_iter_range(fp, offset, bytes, maxread=1024 * 1024, close=False):
2829
- """ Yield chunks from a range in a file, optionally closing it at the end.
2830
- No chunk is bigger than maxread. """
2831
- fp.seek(offset)
2832
- while bytes > 0:
2833
- part = fp.read(min(bytes, maxread))
2834
- if not part:
2835
- break
2836
- bytes -= len(part)
2837
- yield part
2838
- if close:
2839
- fp.close()
2840
-
2841
-
2842
- def static_file(filename, root,
2843
- mimetype=True,
2844
- download=False,
2845
- charset='UTF-8',
2846
- etag=None,
2847
- headers=None):
2848
- """ Open a file in a safe way and return an instance of :exc:`HTTPResponse`
2849
- that can be sent back to the client.
2850
-
2851
- :param filename: Name or path of the file to send, relative to ``root``.
2852
- :param root: Root path for file lookups. Should be an absolute directory
2853
- path.
2854
- :param mimetype: Provide the content-type header (default: guess from
2855
- file extension)
2856
- :param download: If True, ask the browser to open a `Save as...` dialog
2857
- instead of opening the file with the associated program. You can
2858
- specify a custom filename as a string. If not specified, the
2859
- original filename is used (default: False).
2860
- :param charset: The charset for files with a ``text/*`` mime-type.
2861
- (default: UTF-8)
2862
- :param etag: Provide a pre-computed ETag header. If set to ``False``,
2863
- ETag handling is disabled. (default: auto-generate ETag header)
2864
- :param headers: Additional headers dict to add to the response.
2865
-
2866
- While checking user input is always a good idea, this function provides
2867
- additional protection against malicious ``filename`` parameters from
2868
- breaking out of the ``root`` directory and leaking sensitive information
2869
- to an attacker.
2870
-
2871
- Read-protected files or files outside of the ``root`` directory are
2872
- answered with ``403 Access Denied``. Missing files result in a
2873
- ``404 Not Found`` response. Conditional requests (``If-Modified-Since``,
2874
- ``If-None-Match``) are answered with ``304 Not Modified`` whenever
2875
- possible. ``HEAD`` and ``Range`` requests (used by download managers to
2876
- check or continue partial downloads) are also handled automatically.
2877
-
2878
- """
2879
-
2880
- root = os.path.join(os.path.abspath(root), '')
2881
- filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
2882
- headers = headers.copy() if headers else {}
2883
-
2884
- if not filename.startswith(root):
2885
- return HTTPError(403, "Access denied.")
2886
- if not os.path.exists(filename) or not os.path.isfile(filename):
2887
- return HTTPError(404, "File does not exist.")
2888
- if not os.access(filename, os.R_OK):
2889
- return HTTPError(403, "You do not have permission to access this file.")
2890
-
2891
- if mimetype is True:
2892
- if download and download is not True:
2893
- mimetype, encoding = mimetypes.guess_type(download)
2894
- else:
2895
- mimetype, encoding = mimetypes.guess_type(filename)
2896
- if encoding:
2897
- headers['Content-Encoding'] = encoding
2898
-
2899
- if mimetype:
2900
- if (mimetype[:5] == 'text/' or mimetype == 'application/javascript')\
2901
- and charset and 'charset' not in mimetype:
2902
- mimetype += '; charset=%s' % charset
2903
- headers['Content-Type'] = mimetype
2904
-
2905
- if download:
2906
- download = os.path.basename(filename if download is True else download)
2907
- headers['Content-Disposition'] = 'attachment; filename="%s"' % download
2908
-
2909
- stats = os.stat(filename)
2910
- headers['Content-Length'] = clen = stats.st_size
2911
- headers['Last-Modified'] = email.utils.formatdate(stats.st_mtime,
2912
- usegmt=True)
2913
- headers['Date'] = email.utils.formatdate(time.time(), usegmt=True)
2914
-
2915
- getenv = request.environ.get
2916
-
2917
- if etag is None:
2918
- etag = '%d:%d:%d:%d:%s' % (stats.st_dev, stats.st_ino, stats.st_mtime,
2919
- clen, filename)
2920
- etag = hashlib.sha1(tob(etag)).hexdigest()
2921
-
2922
- if etag:
2923
- headers['ETag'] = etag
2924
- check = getenv('HTTP_IF_NONE_MATCH')
2925
- if check and check == etag:
2926
- return HTTPResponse(status=304, **headers)
2927
-
2928
- ims = getenv('HTTP_IF_MODIFIED_SINCE')
2929
- if ims:
2930
- ims = parse_date(ims.split(";")[0].strip())
2931
- if ims is not None and ims >= int(stats.st_mtime):
2932
- return HTTPResponse(status=304, **headers)
2933
-
2934
- body = '' if request.method == 'HEAD' else open(filename, 'rb')
2935
-
2936
- headers["Accept-Ranges"] = "bytes"
2937
- range_header = getenv('HTTP_RANGE')
2938
- if range_header:
2939
- ranges = list(parse_range_header(range_header, clen))
2940
- if not ranges:
2941
- return HTTPError(416, "Requested Range Not Satisfiable")
2942
- offset, end = ranges[0]
2943
- headers["Content-Range"] = "bytes %d-%d/%d" % (offset, end - 1, clen)
2944
- headers["Content-Length"] = str(end - offset)
2945
- if body: body = _file_iter_range(body, offset, end - offset, close=True)
2946
- return HTTPResponse(body, status=206, **headers)
2947
- return HTTPResponse(body, **headers)
2948
-
2949
- ###############################################################################
2950
- # HTTP Utilities and MISC (TODO) ###############################################
2951
- ###############################################################################
2952
-
2953
-
2954
- def debug(mode=True):
2955
- """ Change the debug level.
2956
- There is only one debug level supported at the moment."""
2957
- global DEBUG
2958
- if mode: warnings.simplefilter('default')
2959
- DEBUG = bool(mode)
2960
-
2961
-
2962
- def http_date(value):
2963
- if isinstance(value, basestring):
2964
- return value
2965
- if isinstance(value, datetime):
2966
- # aware datetime.datetime is converted to UTC time
2967
- # naive datetime.datetime is treated as UTC time
2968
- value = value.utctimetuple()
2969
- elif isinstance(value, datedate):
2970
- # datetime.date is naive, and is treated as UTC time
2971
- value = value.timetuple()
2972
- if not isinstance(value, (int, float)):
2973
- # convert struct_time in UTC to UNIX timestamp
2974
- value = calendar.timegm(value)
2975
- return email.utils.formatdate(value, usegmt=True)
2976
-
2977
-
2978
- def parse_date(ims):
2979
- """ Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """
2980
- try:
2981
- ts = email.utils.parsedate_tz(ims)
2982
- return calendar.timegm(ts[:8] + (0, )) - (ts[9] or 0)
2983
- except (TypeError, ValueError, IndexError, OverflowError):
2984
- return None
2985
-
2986
-
2987
- def parse_auth(header):
2988
- """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"""
2989
- try:
2990
- method, data = header.split(None, 1)
2991
- if method.lower() == 'basic':
2992
- user, pwd = touni(base64.b64decode(tob(data))).split(':', 1)
2993
- return user, pwd
2994
- except (KeyError, ValueError):
2995
- return None
2996
-
2997
-
2998
- def parse_range_header(header, maxlen=0):
2999
- """ Yield (start, end) ranges parsed from a HTTP Range header. Skip
3000
- unsatisfiable ranges. The end index is non-inclusive."""
3001
- if not header or header[:6] != 'bytes=': return
3002
- ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
3003
- for start, end in ranges:
3004
- try:
3005
- if not start: # bytes=-100 -> last 100 bytes
3006
- start, end = max(0, maxlen - int(end)), maxlen
3007
- elif not end: # bytes=100- -> all but the first 99 bytes
3008
- start, end = int(start), maxlen
3009
- else: # bytes=100-200 -> bytes 100-200 (inclusive)
3010
- start, end = int(start), min(int(end) + 1, maxlen)
3011
- if 0 <= start < end <= maxlen:
3012
- yield start, end
3013
- except ValueError:
3014
- pass
3015
-
3016
-
3017
- #: Header tokenizer used by _parse_http_header()
3018
- _hsplit = re.compile('(?:(?:"((?:[^"\\\\]|\\\\.)*)")|([^;,=]+))([;,=]?)').findall
3019
-
3020
- def _parse_http_header(h):
3021
- """ Parses a typical multi-valued and parametrised HTTP header (e.g. Accept headers) and returns a list of values
3022
- and parameters. For non-standard or broken input, this implementation may return partial results.
3023
- :param h: A header string (e.g. ``text/html,text/plain;q=0.9,*/*;q=0.8``)
3024
- :return: List of (value, params) tuples. The second element is a (possibly empty) dict.
3025
- """
3026
- values = []
3027
- if '"' not in h: # INFO: Fast path without regexp (~2x faster)
3028
- for value in h.split(','):
3029
- parts = value.split(';')
3030
- values.append((parts[0].strip(), {}))
3031
- for attr in parts[1:]:
3032
- name, value = attr.split('=', 1)
3033
- values[-1][1][name.strip()] = value.strip()
3034
- else:
3035
- lop, key, attrs = ',', None, {}
3036
- for quoted, plain, tok in _hsplit(h):
3037
- value = plain.strip() if plain else quoted.replace('\\"', '"')
3038
- if lop == ',':
3039
- attrs = {}
3040
- values.append((value, attrs))
3041
- elif lop == ';':
3042
- if tok == '=':
3043
- key = value
3044
- else:
3045
- attrs[value] = ''
3046
- elif lop == '=' and key:
3047
- attrs[key] = value
3048
- key = None
3049
- lop = tok
3050
- return values
3051
-
3052
-
3053
- def _parse_qsl(qs):
3054
- r = []
3055
- for pair in qs.split('&'):
3056
- if not pair: continue
3057
- nv = pair.split('=', 1)
3058
- if len(nv) != 2: nv.append('')
3059
- key = urlunquote(nv[0].replace('+', ' '))
3060
- value = urlunquote(nv[1].replace('+', ' '))
3061
- r.append((key, value))
3062
- return r
3063
-
3064
-
3065
- def _lscmp(a, b):
3066
- """ Compares two strings in a cryptographically safe way:
3067
- Runtime is not affected by length of common prefix. """
3068
- return not sum(0 if x == y else 1
3069
- for x, y in zip(a, b)) and len(a) == len(b)
3070
-
3071
-
3072
- def cookie_encode(data, key, digestmod=None):
3073
- """ Encode and sign a pickle-able object. Return a (byte) string """
3074
- depr(0, 13, "cookie_encode() will be removed soon.",
3075
- "Do not use this API directly.")
3076
- digestmod = digestmod or hashlib.sha256
3077
- msg = base64.b64encode(pickle.dumps(data, -1))
3078
- sig = base64.b64encode(hmac.new(tob(key), msg, digestmod=digestmod).digest())
3079
- return tob('!') + sig + tob('?') + msg
3080
-
3081
-
3082
- def cookie_decode(data, key, digestmod=None):
3083
- """ Verify and decode an encoded string. Return an object or None."""
3084
- depr(0, 13, "cookie_decode() will be removed soon.",
3085
- "Do not use this API directly.")
3086
- data = tob(data)
3087
- if cookie_is_encoded(data):
3088
- sig, msg = data.split(tob('?'), 1)
3089
- digestmod = digestmod or hashlib.sha256
3090
- hashed = hmac.new(tob(key), msg, digestmod=digestmod).digest()
3091
- if _lscmp(sig[1:], base64.b64encode(hashed)):
3092
- return pickle.loads(base64.b64decode(msg))
3093
- return None
3094
-
3095
-
3096
- def cookie_is_encoded(data):
3097
- """ Return True if the argument looks like a encoded cookie."""
3098
- depr(0, 13, "cookie_is_encoded() will be removed soon.",
3099
- "Do not use this API directly.")
3100
- return bool(data.startswith(tob('!')) and tob('?') in data)
3101
-
3102
-
3103
- def html_escape(string):
3104
- """ Escape HTML special characters ``&<>`` and quotes ``'"``. """
3105
- return string.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')\
3106
- .replace('"', '&quot;').replace("'", '&#039;')
3107
-
3108
-
3109
- def html_quote(string):
3110
- """ Escape and quote a string to be used as an HTTP attribute."""
3111
- return '"%s"' % html_escape(string).replace('\n', '&#10;')\
3112
- .replace('\r', '&#13;').replace('\t', '&#9;')
3113
-
3114
-
3115
- def yieldroutes(func):
3116
- """ Return a generator for routes that match the signature (name, args)
3117
- of the func parameter. This may yield more than one route if the function
3118
- takes optional keyword arguments. The output is best described by example::
3119
-
3120
- a() -> '/a'
3121
- b(x, y) -> '/b/<x>/<y>'
3122
- c(x, y=5) -> '/c/<x>' and '/c/<x>/<y>'
3123
- d(x=5, y=6) -> '/d' and '/d/<x>' and '/d/<x>/<y>'
3124
- """
3125
- path = '/' + func.__name__.replace('__', '/').lstrip('/')
3126
- spec = getargspec(func)
3127
- argc = len(spec[0]) - len(spec[3] or [])
3128
- path += ('/<%s>' * argc) % tuple(spec[0][:argc])
3129
- yield path
3130
- for arg in spec[0][argc:]:
3131
- path += '/<%s>' % arg
3132
- yield path
3133
-
3134
-
3135
- def path_shift(script_name, path_info, shift=1):
3136
- """ Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
3137
-
3138
- :return: The modified paths.
3139
- :param script_name: The SCRIPT_NAME path.
3140
- :param script_name: The PATH_INFO path.
3141
- :param shift: The number of path fragments to shift. May be negative to
3142
- change the shift direction. (default: 1)
3143
- """
3144
- if shift == 0: return script_name, path_info
3145
- pathlist = path_info.strip('/').split('/')
3146
- scriptlist = script_name.strip('/').split('/')
3147
- if pathlist and pathlist[0] == '': pathlist = []
3148
- if scriptlist and scriptlist[0] == '': scriptlist = []
3149
- if 0 < shift <= len(pathlist):
3150
- moved = pathlist[:shift]
3151
- scriptlist = scriptlist + moved
3152
- pathlist = pathlist[shift:]
3153
- elif 0 > shift >= -len(scriptlist):
3154
- moved = scriptlist[shift:]
3155
- pathlist = moved + pathlist
3156
- scriptlist = scriptlist[:shift]
3157
- else:
3158
- empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO'
3159
- raise AssertionError("Cannot shift. Nothing left from %s" % empty)
3160
- new_script_name = '/' + '/'.join(scriptlist)
3161
- new_path_info = '/' + '/'.join(pathlist)
3162
- if path_info.endswith('/') and pathlist: new_path_info += '/'
3163
- return new_script_name, new_path_info
3164
-
3165
-
3166
- def auth_basic(check, realm="private", text="Access denied"):
3167
- """ Callback decorator to require HTTP auth (basic).
3168
- TODO: Add route(check_auth=...) parameter. """
3169
-
3170
- def decorator(func):
3171
-
3172
- @functools.wraps(func)
3173
- def wrapper(*a, **ka):
3174
- user, password = request.auth or (None, None)
3175
- if user is None or not check(user, password):
3176
- err = HTTPError(401, text)
3177
- err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
3178
- return err
3179
- return func(*a, **ka)
3180
-
3181
- return wrapper
3182
-
3183
- return decorator
3184
-
3185
- # Shortcuts for common Bottle methods.
3186
- # They all refer to the current default application.
3187
-
3188
-
3189
- def make_default_app_wrapper(name):
3190
- """ Return a callable that relays calls to the current default app. """
3191
-
3192
- @functools.wraps(getattr(Bottle, name))
3193
- def wrapper(*a, **ka):
3194
- return getattr(app(), name)(*a, **ka)
3195
-
3196
- return wrapper
3197
-
3198
-
3199
- route = make_default_app_wrapper('route')
3200
- get = make_default_app_wrapper('get')
3201
- post = make_default_app_wrapper('post')
3202
- put = make_default_app_wrapper('put')
3203
- delete = make_default_app_wrapper('delete')
3204
- patch = make_default_app_wrapper('patch')
3205
- error = make_default_app_wrapper('error')
3206
- mount = make_default_app_wrapper('mount')
3207
- hook = make_default_app_wrapper('hook')
3208
- install = make_default_app_wrapper('install')
3209
- uninstall = make_default_app_wrapper('uninstall')
3210
- url = make_default_app_wrapper('get_url')
3211
-
3212
- ###############################################################################
3213
- # Server Adapter ###############################################################
3214
- ###############################################################################
3215
-
3216
- # Before you edit or add a server adapter, please read:
3217
- # - https://github.com/bottlepy/bottle/pull/647#issuecomment-60152870
3218
- # - https://github.com/bottlepy/bottle/pull/865#issuecomment-242795341
3219
-
3220
- class ServerAdapter(object):
3221
- quiet = False
3222
-
3223
- def __init__(self, host='127.0.0.1', port=8080, **options):
3224
- self.options = options
3225
- self.host = host
3226
- self.port = int(port)
3227
-
3228
- def run(self, handler): # pragma: no cover
3229
- pass
3230
-
3231
- def __repr__(self):
3232
- args = ', '.join('%s=%s' % (k, repr(v))
3233
- for k, v in self.options.items())
3234
- return "%s(%s)" % (self.__class__.__name__, args)
3235
-
3236
-
3237
- class CGIServer(ServerAdapter):
3238
- quiet = True
3239
-
3240
- def run(self, handler): # pragma: no cover
3241
- from wsgiref.handlers import CGIHandler
3242
-
3243
- def fixed_environ(environ, start_response):
3244
- environ.setdefault('PATH_INFO', '')
3245
- return handler(environ, start_response)
3246
-
3247
- CGIHandler().run(fixed_environ)
3248
-
3249
-
3250
- class FlupFCGIServer(ServerAdapter):
3251
- def run(self, handler): # pragma: no cover
3252
- import flup.server.fcgi
3253
- self.options.setdefault('bindAddress', (self.host, self.port))
3254
- flup.server.fcgi.WSGIServer(handler, **self.options).run()
3255
-
3256
-
3257
- class WSGIRefServer(ServerAdapter):
3258
- def run(self, app): # pragma: no cover
3259
- from wsgiref.simple_server import make_server
3260
- from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
3261
- import socket
3262
-
3263
- class FixedHandler(WSGIRequestHandler):
3264
- def address_string(self): # Prevent reverse DNS lookups please.
3265
- return self.client_address[0]
3266
-
3267
- def log_request(*args, **kw):
3268
- if not self.quiet:
3269
- return WSGIRequestHandler.log_request(*args, **kw)
3270
-
3271
- handler_cls = self.options.get('handler_class', FixedHandler)
3272
- server_cls = self.options.get('server_class', WSGIServer)
3273
-
3274
- if ':' in self.host: # Fix wsgiref for IPv6 addresses.
3275
- if getattr(server_cls, 'address_family') == socket.AF_INET:
3276
-
3277
- class server_cls(server_cls):
3278
- address_family = socket.AF_INET6
3279
-
3280
- self.srv = make_server(self.host, self.port, app, server_cls,
3281
- handler_cls)
3282
- self.port = self.srv.server_port # update port actual port (0 means random)
3283
- try:
3284
- self.srv.serve_forever()
3285
- except KeyboardInterrupt:
3286
- self.srv.server_close() # Prevent ResourceWarning: unclosed socket
3287
- raise
3288
-
3289
-
3290
- class CherryPyServer(ServerAdapter):
3291
- def run(self, handler): # pragma: no cover
3292
- depr(0, 13, "The wsgi server part of cherrypy was split into a new "
3293
- "project called 'cheroot'.", "Use the 'cheroot' server "
3294
- "adapter instead of cherrypy.")
3295
- from cherrypy import wsgiserver # This will fail for CherryPy >= 9
3296
-
3297
- self.options['bind_addr'] = (self.host, self.port)
3298
- self.options['wsgi_app'] = handler
3299
-
3300
- certfile = self.options.get('certfile')
3301
- if certfile:
3302
- del self.options['certfile']
3303
- keyfile = self.options.get('keyfile')
3304
- if keyfile:
3305
- del self.options['keyfile']
3306
-
3307
- server = wsgiserver.CherryPyWSGIServer(**self.options)
3308
- if certfile:
3309
- server.ssl_certificate = certfile
3310
- if keyfile:
3311
- server.ssl_private_key = keyfile
3312
-
3313
- try:
3314
- server.start()
3315
- finally:
3316
- server.stop()
3317
-
3318
-
3319
- class CherootServer(ServerAdapter):
3320
- def run(self, handler): # pragma: no cover
3321
- from cheroot import wsgi
3322
- from cheroot.ssl import builtin
3323
- self.options['bind_addr'] = (self.host, self.port)
3324
- self.options['wsgi_app'] = handler
3325
- certfile = self.options.pop('certfile', None)
3326
- keyfile = self.options.pop('keyfile', None)
3327
- chainfile = self.options.pop('chainfile', None)
3328
- server = wsgi.Server(**self.options)
3329
- if certfile and keyfile:
3330
- server.ssl_adapter = builtin.BuiltinSSLAdapter(
3331
- certfile, keyfile, chainfile)
3332
- try:
3333
- server.start()
3334
- finally:
3335
- server.stop()
3336
-
3337
-
3338
- class WaitressServer(ServerAdapter):
3339
- def run(self, handler):
3340
- from waitress import serve
3341
- serve(handler, host=self.host, port=self.port, _quiet=self.quiet, **self.options)
3342
-
3343
-
3344
- class PasteServer(ServerAdapter):
3345
- def run(self, handler): # pragma: no cover
3346
- from paste import httpserver
3347
- from paste.translogger import TransLogger
3348
- handler = TransLogger(handler, setup_console_handler=(not self.quiet))
3349
- httpserver.serve(handler,
3350
- host=self.host,
3351
- port=str(self.port), **self.options)
3352
-
3353
-
3354
- class MeinheldServer(ServerAdapter):
3355
- def run(self, handler):
3356
- from meinheld import server
3357
- server.listen((self.host, self.port))
3358
- server.run(handler)
3359
-
3360
-
3361
- class FapwsServer(ServerAdapter):
3362
- """ Extremely fast webserver using libev. See http://www.fapws.org/ """
3363
-
3364
- def run(self, handler): # pragma: no cover
3365
- depr(0, 13, "fapws3 is not maintained and support will be dropped.")
3366
- import fapws._evwsgi as evwsgi
3367
- from fapws import base, config
3368
- port = self.port
3369
- if float(config.SERVER_IDENT[-2:]) > 0.4:
3370
- # fapws3 silently changed its API in 0.5
3371
- port = str(port)
3372
- evwsgi.start(self.host, port)
3373
- # fapws3 never releases the GIL. Complain upstream. I tried. No luck.
3374
- if 'BOTTLE_CHILD' in os.environ and not self.quiet:
3375
- _stderr("WARNING: Auto-reloading does not work with Fapws3.")
3376
- _stderr(" (Fapws3 breaks python thread support)")
3377
- evwsgi.set_base_module(base)
3378
-
3379
- def app(environ, start_response):
3380
- environ['wsgi.multiprocess'] = False
3381
- return handler(environ, start_response)
3382
-
3383
- evwsgi.wsgi_cb(('', app))
3384
- evwsgi.run()
3385
-
3386
-
3387
- class TornadoServer(ServerAdapter):
3388
- """ The super hyped asynchronous server by facebook. Untested. """
3389
-
3390
- def run(self, handler): # pragma: no cover
3391
- import tornado.wsgi, tornado.httpserver, tornado.ioloop
3392
- container = tornado.wsgi.WSGIContainer(handler)
3393
- server = tornado.httpserver.HTTPServer(container)
3394
- server.listen(port=self.port, address=self.host)
3395
- tornado.ioloop.IOLoop.instance().start()
3396
-
3397
-
3398
- class AppEngineServer(ServerAdapter):
3399
- """ Adapter for Google App Engine. """
3400
- quiet = True
3401
-
3402
- def run(self, handler):
3403
- depr(0, 13, "AppEngineServer no longer required",
3404
- "Configure your application directly in your app.yaml")
3405
- from google.appengine.ext.webapp import util
3406
- # A main() function in the handler script enables 'App Caching'.
3407
- # Lets makes sure it is there. This _really_ improves performance.
3408
- module = sys.modules.get('__main__')
3409
- if module and not hasattr(module, 'main'):
3410
- module.main = lambda: util.run_wsgi_app(handler)
3411
- util.run_wsgi_app(handler)
3412
-
3413
-
3414
- class TwistedServer(ServerAdapter):
3415
- """ Untested. """
3416
-
3417
- def run(self, handler):
3418
- from twisted.web import server, wsgi
3419
- from twisted.python.threadpool import ThreadPool
3420
- from twisted.internet import reactor
3421
- thread_pool = ThreadPool()
3422
- thread_pool.start()
3423
- reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop)
3424
- factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler))
3425
- reactor.listenTCP(self.port, factory, interface=self.host)
3426
- if not reactor.running:
3427
- reactor.run()
3428
-
3429
-
3430
- class DieselServer(ServerAdapter):
3431
- """ Untested. """
3432
-
3433
- def run(self, handler):
3434
- depr(0, 13, "Diesel is not tested or supported and will be removed.")
3435
- from diesel.protocols.wsgi import WSGIApplication
3436
- app = WSGIApplication(handler, port=self.port)
3437
- app.run()
3438
-
3439
-
3440
- class GeventServer(ServerAdapter):
3441
- """ Untested. Options:
3442
-
3443
- * See gevent.wsgi.WSGIServer() documentation for more options.
3444
- """
3445
-
3446
- def run(self, handler):
3447
- from gevent import pywsgi, local
3448
- if not isinstance(threading.local(), local.local):
3449
- msg = "Bottle requires gevent.monkey.patch_all() (before import)"
3450
- raise RuntimeError(msg)
3451
- if self.quiet:
3452
- self.options['log'] = None
3453
- address = (self.host, self.port)
3454
- server = pywsgi.WSGIServer(address, handler, **self.options)
3455
- if 'BOTTLE_CHILD' in os.environ:
3456
- import signal
3457
- signal.signal(signal.SIGINT, lambda s, f: server.stop())
3458
- server.serve_forever()
3459
-
3460
-
3461
- class GunicornServer(ServerAdapter):
3462
- """ Untested. See http://gunicorn.org/configure.html for options. """
3463
-
3464
- def run(self, handler):
3465
- from gunicorn.app.base import BaseApplication
3466
-
3467
- if self.host.startswith("unix:"):
3468
- config = {'bind': self.host}
3469
- else:
3470
- config = {'bind': "%s:%d" % (self.host, self.port)}
3471
-
3472
- config.update(self.options)
3473
-
3474
- class GunicornApplication(BaseApplication):
3475
- def load_config(self):
3476
- for key, value in config.items():
3477
- self.cfg.set(key, value)
3478
-
3479
- def load(self):
3480
- return handler
3481
-
3482
- GunicornApplication().run()
3483
-
3484
-
3485
- class EventletServer(ServerAdapter):
3486
- """ Untested. Options:
3487
-
3488
- * `backlog` adjust the eventlet backlog parameter which is the maximum
3489
- number of queued connections. Should be at least 1; the maximum
3490
- value is system-dependent.
3491
- * `family`: (default is 2) socket family, optional. See socket
3492
- documentation for available families.
3493
- """
3494
-
3495
- def run(self, handler):
3496
- from eventlet import wsgi, listen, patcher
3497
- if not patcher.is_monkey_patched(os):
3498
- msg = "Bottle requires eventlet.monkey_patch() (before import)"
3499
- raise RuntimeError(msg)
3500
- socket_args = {}
3501
- for arg in ('backlog', 'family'):
3502
- try:
3503
- socket_args[arg] = self.options.pop(arg)
3504
- except KeyError:
3505
- pass
3506
- address = (self.host, self.port)
3507
- try:
3508
- wsgi.server(listen(address, **socket_args), handler,
3509
- log_output=(not self.quiet))
3510
- except TypeError:
3511
- # Fallback, if we have old version of eventlet
3512
- wsgi.server(listen(address), handler)
3513
-
3514
-
3515
- class BjoernServer(ServerAdapter):
3516
- """ Fast server written in C: https://github.com/jonashaag/bjoern """
3517
-
3518
- def run(self, handler):
3519
- from bjoern import run
3520
- run(handler, self.host, self.port, reuse_port=True)
3521
-
3522
- class AsyncioServerAdapter(ServerAdapter):
3523
- """ Extend ServerAdapter for adding custom event loop """
3524
- def get_event_loop(self):
3525
- pass
3526
-
3527
- class AiohttpServer(AsyncioServerAdapter):
3528
- """ Asynchronous HTTP client/server framework for asyncio
3529
- https://pypi.python.org/pypi/aiohttp/
3530
- https://pypi.org/project/aiohttp-wsgi/
3531
- """
3532
-
3533
- def get_event_loop(self):
3534
- import asyncio
3535
- return asyncio.new_event_loop()
3536
-
3537
- def run(self, handler):
3538
- import asyncio
3539
- from aiohttp_wsgi.wsgi import serve
3540
- self.loop = self.get_event_loop()
3541
- asyncio.set_event_loop(self.loop)
3542
-
3543
- if 'BOTTLE_CHILD' in os.environ:
3544
- import signal
3545
- signal.signal(signal.SIGINT, lambda s, f: self.loop.stop())
3546
-
3547
- serve(handler, host=self.host, port=self.port)
3548
-
3549
-
3550
- class AiohttpUVLoopServer(AiohttpServer):
3551
- """uvloop
3552
- https://github.com/MagicStack/uvloop
3553
- """
3554
- def get_event_loop(self):
3555
- import uvloop
3556
- return uvloop.new_event_loop()
3557
-
3558
- class AutoServer(ServerAdapter):
3559
- """ Untested. """
3560
- adapters = [WaitressServer, PasteServer, TwistedServer, CherryPyServer,
3561
- CherootServer, WSGIRefServer]
3562
-
3563
- def run(self, handler):
3564
- for sa in self.adapters:
3565
- try:
3566
- return sa(self.host, self.port, **self.options).run(handler)
3567
- except ImportError:
3568
- pass
3569
-
3570
-
3571
- server_names = {
3572
- 'cgi': CGIServer,
3573
- 'flup': FlupFCGIServer,
3574
- 'wsgiref': WSGIRefServer,
3575
- 'waitress': WaitressServer,
3576
- 'cherrypy': CherryPyServer,
3577
- 'cheroot': CherootServer,
3578
- 'paste': PasteServer,
3579
- 'fapws3': FapwsServer,
3580
- 'tornado': TornadoServer,
3581
- 'gae': AppEngineServer,
3582
- 'twisted': TwistedServer,
3583
- 'diesel': DieselServer,
3584
- 'meinheld': MeinheldServer,
3585
- 'gunicorn': GunicornServer,
3586
- 'eventlet': EventletServer,
3587
- 'gevent': GeventServer,
3588
- 'bjoern': BjoernServer,
3589
- 'aiohttp': AiohttpServer,
3590
- 'uvloop': AiohttpUVLoopServer,
3591
- 'auto': AutoServer,
3592
- }
3593
-
3594
- ###############################################################################
3595
- # Application Control ##########################################################
3596
- ###############################################################################
3597
-
3598
-
3599
- def load(target, **namespace):
3600
- """ Import a module or fetch an object from a module.
3601
-
3602
- * ``package.module`` returns `module` as a module object.
3603
- * ``pack.mod:name`` returns the module variable `name` from `pack.mod`.
3604
- * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result.
3605
-
3606
- The last form accepts not only function calls, but any type of
3607
- expression. Keyword arguments passed to this function are available as
3608
- local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``
3609
- """
3610
- module, target = target.split(":", 1) if ':' in target else (target, None)
3611
- if module not in sys.modules: __import__(module)
3612
- if not target: return sys.modules[module]
3613
- if target.isalnum(): return getattr(sys.modules[module], target)
3614
- package_name = module.split('.')[0]
3615
- namespace[package_name] = sys.modules[package_name]
3616
- return eval('%s.%s' % (module, target), namespace)
3617
-
3618
-
3619
- def load_app(target):
3620
- """ Load a bottle application from a module and make sure that the import
3621
- does not affect the current default application, but returns a separate
3622
- application object. See :func:`load` for the target parameter. """
3623
- global NORUN
3624
- NORUN, nr_old = True, NORUN
3625
- tmp = default_app.push() # Create a new "default application"
3626
- try:
3627
- rv = load(target) # Import the target module
3628
- return rv if callable(rv) else tmp
3629
- finally:
3630
- default_app.remove(tmp) # Remove the temporary added default application
3631
- NORUN = nr_old
3632
-
3633
-
3634
- _debug = debug
3635
-
3636
-
3637
- def run(app=None,
3638
- server='wsgiref',
3639
- host='127.0.0.1',
3640
- port=8080,
3641
- interval=1,
3642
- reloader=False,
3643
- quiet=False,
3644
- plugins=None,
3645
- debug=None,
3646
- config=None, **kargs):
3647
- """ Start a server instance. This method blocks until the server terminates.
3648
-
3649
- :param app: WSGI application or target string supported by
3650
- :func:`load_app`. (default: :func:`default_app`)
3651
- :param server: Server adapter to use. See :data:`server_names` keys
3652
- for valid names or pass a :class:`ServerAdapter` subclass.
3653
- (default: `wsgiref`)
3654
- :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on
3655
- all interfaces including the external one. (default: 127.0.0.1)
3656
- :param port: Server port to bind to. Values below 1024 require root
3657
- privileges. (default: 8080)
3658
- :param reloader: Start auto-reloading server? (default: False)
3659
- :param interval: Auto-reloader interval in seconds (default: 1)
3660
- :param quiet: Suppress output to stdout and stderr? (default: False)
3661
- :param options: Options passed to the server adapter.
3662
- """
3663
- if NORUN: return
3664
- if reloader and not os.environ.get('BOTTLE_CHILD'):
3665
- import subprocess
3666
- lockfile = None
3667
- try:
3668
- fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock')
3669
- os.close(fd) # We only need this file to exist. We never write to it
3670
- while os.path.exists(lockfile):
3671
- args = [sys.executable] + sys.argv
3672
- environ = os.environ.copy()
3673
- environ['BOTTLE_CHILD'] = 'true'
3674
- environ['BOTTLE_LOCKFILE'] = lockfile
3675
- p = subprocess.Popen(args, env=environ)
3676
- while p.poll() is None: # Busy wait...
3677
- os.utime(lockfile, None) # I am alive!
3678
- time.sleep(interval)
3679
- if p.poll() != 3:
3680
- if os.path.exists(lockfile): os.unlink(lockfile)
3681
- sys.exit(p.poll())
3682
- except KeyboardInterrupt:
3683
- pass
3684
- finally:
3685
- if os.path.exists(lockfile):
3686
- os.unlink(lockfile)
3687
- return
3688
-
3689
- try:
3690
- if debug is not None: _debug(debug)
3691
- app = app or default_app()
3692
- if isinstance(app, basestring):
3693
- app = load_app(app)
3694
- if not callable(app):
3695
- raise ValueError("Application is not callable: %r" % app)
3696
-
3697
- for plugin in plugins or []:
3698
- if isinstance(plugin, basestring):
3699
- plugin = load(plugin)
3700
- app.install(plugin)
3701
-
3702
- if config:
3703
- app.config.update(config)
3704
-
3705
- if server in server_names:
3706
- server = server_names.get(server)
3707
- if isinstance(server, basestring):
3708
- server = load(server)
3709
- if isinstance(server, type):
3710
- server = server(host=host, port=port, **kargs)
3711
- if not isinstance(server, ServerAdapter):
3712
- raise ValueError("Unknown or unsupported server: %r" % server)
3713
-
3714
- server.quiet = server.quiet or quiet
3715
- if not server.quiet:
3716
- _stderr("Bottle v%s server starting up (using %s)..." %
3717
- (__version__, repr(server)))
3718
- if server.host.startswith("unix:"):
3719
- _stderr("Listening on %s" % server.host)
3720
- else:
3721
- _stderr("Listening on http://%s:%d/" %
3722
- (server.host, server.port))
3723
- _stderr("Hit Ctrl-C to quit.\n")
3724
-
3725
- if reloader:
3726
- lockfile = os.environ.get('BOTTLE_LOCKFILE')
3727
- bgcheck = FileCheckerThread(lockfile, interval)
3728
- with bgcheck:
3729
- server.run(app)
3730
- if bgcheck.status == 'reload':
3731
- sys.exit(3)
3732
- else:
3733
- server.run(app)
3734
- except KeyboardInterrupt:
3735
- pass
3736
- except (SystemExit, MemoryError):
3737
- raise
3738
- except:
3739
- if not reloader: raise
3740
- if not getattr(server, 'quiet', quiet):
3741
- print_exc()
3742
- time.sleep(interval)
3743
- sys.exit(3)
3744
-
3745
-
3746
- class FileCheckerThread(threading.Thread):
3747
- """ Interrupt main-thread as soon as a changed module file is detected,
3748
- the lockfile gets deleted or gets too old. """
3749
-
3750
- def __init__(self, lockfile, interval):
3751
- threading.Thread.__init__(self)
3752
- self.daemon = True
3753
- self.lockfile, self.interval = lockfile, interval
3754
- #: Is one of 'reload', 'error' or 'exit'
3755
- self.status = None
3756
-
3757
- def run(self):
3758
- exists = os.path.exists
3759
- mtime = lambda p: os.stat(p).st_mtime
3760
- files = dict()
3761
-
3762
- for module in list(sys.modules.values()):
3763
- path = getattr(module, '__file__', '') or ''
3764
- if path[-4:] in ('.pyo', '.pyc'): path = path[:-1]
3765
- if path and exists(path): files[path] = mtime(path)
3766
-
3767
- while not self.status:
3768
- if not exists(self.lockfile)\
3769
- or mtime(self.lockfile) < time.time() - self.interval - 5:
3770
- self.status = 'error'
3771
- thread.interrupt_main()
3772
- for path, lmtime in list(files.items()):
3773
- if not exists(path) or mtime(path) > lmtime:
3774
- self.status = 'reload'
3775
- thread.interrupt_main()
3776
- break
3777
- time.sleep(self.interval)
3778
-
3779
- def __enter__(self):
3780
- self.start()
3781
-
3782
- def __exit__(self, exc_type, *_):
3783
- if not self.status: self.status = 'exit' # silent exit
3784
- self.join()
3785
- return exc_type is not None and issubclass(exc_type, KeyboardInterrupt)
3786
-
3787
- ###############################################################################
3788
- # Template Adapters ############################################################
3789
- ###############################################################################
3790
-
3791
-
3792
- class TemplateError(BottleException):
3793
- pass
3794
-
3795
-
3796
- class BaseTemplate(object):
3797
- """ Base class and minimal API for template adapters """
3798
- extensions = ['tpl', 'html', 'thtml', 'stpl']
3799
- settings = {} #used in prepare()
3800
- defaults = {} #used in render()
3801
-
3802
- def __init__(self,
3803
- source=None,
3804
- name=None,
3805
- lookup=None,
3806
- encoding='utf8', **settings):
3807
- """ Create a new template.
3808
- If the source parameter (str or buffer) is missing, the name argument
3809
- is used to guess a template filename. Subclasses can assume that
3810
- self.source and/or self.filename are set. Both are strings.
3811
- The lookup, encoding and settings parameters are stored as instance
3812
- variables.
3813
- The lookup parameter stores a list containing directory paths.
3814
- The encoding parameter should be used to decode byte strings or files.
3815
- The settings parameter contains a dict for engine-specific settings.
3816
- """
3817
- self.name = name
3818
- self.source = source.read() if hasattr(source, 'read') else source
3819
- self.filename = source.filename if hasattr(source, 'filename') else None
3820
- self.lookup = [os.path.abspath(x) for x in lookup] if lookup else []
3821
- self.encoding = encoding
3822
- self.settings = self.settings.copy() # Copy from class variable
3823
- self.settings.update(settings) # Apply
3824
- if not self.source and self.name:
3825
- self.filename = self.search(self.name, self.lookup)
3826
- if not self.filename:
3827
- raise TemplateError('Template %s not found.' % repr(name))
3828
- if not self.source and not self.filename:
3829
- raise TemplateError('No template specified.')
3830
- self.prepare(**self.settings)
3831
-
3832
- @classmethod
3833
- def search(cls, name, lookup=None):
3834
- """ Search name in all directories specified in lookup.
3835
- First without, then with common extensions. Return first hit. """
3836
- if not lookup:
3837
- raise depr(0, 12, "Empty template lookup path.", "Configure a template lookup path.")
3838
-
3839
- if os.path.isabs(name):
3840
- raise depr(0, 12, "Use of absolute path for template name.",
3841
- "Refer to templates with names or paths relative to the lookup path.")
3842
-
3843
- for spath in lookup:
3844
- spath = os.path.abspath(spath) + os.sep
3845
- fname = os.path.abspath(os.path.join(spath, name))
3846
- if not fname.startswith(spath): continue
3847
- if os.path.isfile(fname): return fname
3848
- for ext in cls.extensions:
3849
- if os.path.isfile('%s.%s' % (fname, ext)):
3850
- return '%s.%s' % (fname, ext)
3851
-
3852
- @classmethod
3853
- def global_config(cls, key, *args):
3854
- """ This reads or sets the global settings stored in class.settings. """
3855
- if args:
3856
- cls.settings = cls.settings.copy() # Make settings local to class
3857
- cls.settings[key] = args[0]
3858
- else:
3859
- return cls.settings[key]
3860
-
3861
- def prepare(self, **options):
3862
- """ Run preparations (parsing, caching, ...).
3863
- It should be possible to call this again to refresh a template or to
3864
- update settings.
3865
- """
3866
- raise NotImplementedError
3867
-
3868
- def render(self, *args, **kwargs):
3869
- """ Render the template with the specified local variables and return
3870
- a single byte or unicode string. If it is a byte string, the encoding
3871
- must match self.encoding. This method must be thread-safe!
3872
- Local variables may be provided in dictionaries (args)
3873
- or directly, as keywords (kwargs).
3874
- """
3875
- raise NotImplementedError
3876
-
3877
-
3878
- class MakoTemplate(BaseTemplate):
3879
- def prepare(self, **options):
3880
- from mako.template import Template
3881
- from mako.lookup import TemplateLookup
3882
- options.update({'input_encoding': self.encoding})
3883
- options.setdefault('format_exceptions', bool(DEBUG))
3884
- lookup = TemplateLookup(directories=self.lookup, **options)
3885
- if self.source:
3886
- self.tpl = Template(self.source, lookup=lookup, **options)
3887
- else:
3888
- self.tpl = Template(uri=self.name,
3889
- filename=self.filename,
3890
- lookup=lookup, **options)
3891
-
3892
- def render(self, *args, **kwargs):
3893
- for dictarg in args:
3894
- kwargs.update(dictarg)
3895
- _defaults = self.defaults.copy()
3896
- _defaults.update(kwargs)
3897
- return self.tpl.render(**_defaults)
3898
-
3899
-
3900
- class CheetahTemplate(BaseTemplate):
3901
- def prepare(self, **options):
3902
- from Cheetah.Template import Template
3903
- self.context = threading.local()
3904
- self.context.vars = {}
3905
- options['searchList'] = [self.context.vars]
3906
- if self.source:
3907
- self.tpl = Template(source=self.source, **options)
3908
- else:
3909
- self.tpl = Template(file=self.filename, **options)
3910
-
3911
- def render(self, *args, **kwargs):
3912
- for dictarg in args:
3913
- kwargs.update(dictarg)
3914
- self.context.vars.update(self.defaults)
3915
- self.context.vars.update(kwargs)
3916
- out = str(self.tpl)
3917
- self.context.vars.clear()
3918
- return out
3919
-
3920
-
3921
- class Jinja2Template(BaseTemplate):
3922
- def prepare(self, filters=None, tests=None, globals={}, **kwargs):
3923
- from jinja2 import Environment, FunctionLoader
3924
- self.env = Environment(loader=FunctionLoader(self.loader), **kwargs)
3925
- if filters: self.env.filters.update(filters)
3926
- if tests: self.env.tests.update(tests)
3927
- if globals: self.env.globals.update(globals)
3928
- if self.source:
3929
- self.tpl = self.env.from_string(self.source)
3930
- else:
3931
- self.tpl = self.env.get_template(self.name)
3932
-
3933
- def render(self, *args, **kwargs):
3934
- for dictarg in args:
3935
- kwargs.update(dictarg)
3936
- _defaults = self.defaults.copy()
3937
- _defaults.update(kwargs)
3938
- return self.tpl.render(**_defaults)
3939
-
3940
- def loader(self, name):
3941
- if name == self.filename:
3942
- fname = name
3943
- else:
3944
- fname = self.search(name, self.lookup)
3945
- if not fname: return
3946
- with open(fname, "rb") as f:
3947
- return (f.read().decode(self.encoding), fname, lambda: False)
3948
-
3949
-
3950
- class SimpleTemplate(BaseTemplate):
3951
- def prepare(self,
3952
- escape_func=html_escape,
3953
- noescape=False,
3954
- syntax=None, **ka):
3955
- self.cache = {}
3956
- enc = self.encoding
3957
- self._str = lambda x: touni(x, enc)
3958
- self._escape = lambda x: escape_func(touni(x, enc))
3959
- self.syntax = syntax
3960
- if noescape:
3961
- self._str, self._escape = self._escape, self._str
3962
-
3963
- @cached_property
3964
- def co(self):
3965
- return compile(self.code, self.filename or '<string>', 'exec')
3966
-
3967
- @cached_property
3968
- def code(self):
3969
- source = self.source
3970
- if not source:
3971
- with open(self.filename, 'rb') as f:
3972
- source = f.read()
3973
- try:
3974
- source, encoding = touni(source), 'utf8'
3975
- except UnicodeError:
3976
- raise depr(0, 11, 'Unsupported template encodings.', 'Use utf-8 for templates.')
3977
- parser = StplParser(source, encoding=encoding, syntax=self.syntax)
3978
- code = parser.translate()
3979
- self.encoding = parser.encoding
3980
- return code
3981
-
3982
- def _rebase(self, _env, _name=None, **kwargs):
3983
- _env['_rebase'] = (_name, kwargs)
3984
-
3985
- def _include(self, _env, _name=None, **kwargs):
3986
- env = _env.copy()
3987
- env.update(kwargs)
3988
- if _name not in self.cache:
3989
- self.cache[_name] = self.__class__(name=_name, lookup=self.lookup, syntax=self.syntax)
3990
- return self.cache[_name].execute(env['_stdout'], env)
3991
-
3992
- def execute(self, _stdout, kwargs):
3993
- env = self.defaults.copy()
3994
- env.update(kwargs)
3995
- env.update({
3996
- '_stdout': _stdout,
3997
- '_printlist': _stdout.extend,
3998
- 'include': functools.partial(self._include, env),
3999
- 'rebase': functools.partial(self._rebase, env),
4000
- '_rebase': None,
4001
- '_str': self._str,
4002
- '_escape': self._escape,
4003
- 'get': env.get,
4004
- 'setdefault': env.setdefault,
4005
- 'defined': env.__contains__
4006
- })
4007
- exec(self.co, env)
4008
- if env.get('_rebase'):
4009
- subtpl, rargs = env.pop('_rebase')
4010
- rargs['base'] = ''.join(_stdout) #copy stdout
4011
- del _stdout[:] # clear stdout
4012
- return self._include(env, subtpl, **rargs)
4013
- return env
4014
-
4015
- def render(self, *args, **kwargs):
4016
- """ Render the template using keyword arguments as local variables. """
4017
- env = {}
4018
- stdout = []
4019
- for dictarg in args:
4020
- env.update(dictarg)
4021
- env.update(kwargs)
4022
- self.execute(stdout, env)
4023
- return ''.join(stdout)
4024
-
4025
-
4026
- class StplSyntaxError(TemplateError):
4027
- pass
4028
-
4029
-
4030
- class StplParser(object):
4031
- """ Parser for stpl templates. """
4032
- _re_cache = {} #: Cache for compiled re patterns
4033
-
4034
- # This huge pile of voodoo magic splits python code into 8 different tokens.
4035
- # We use the verbose (?x) regex mode to make this more manageable
4036
-
4037
- _re_tok = r'''(
4038
- [urbURB]*
4039
- (?: ''(?!')
4040
- |""(?!")
4041
- |'{6}
4042
- |"{6}
4043
- |'(?:[^\\']|\\.)+?'
4044
- |"(?:[^\\"]|\\.)+?"
4045
- |'{3}(?:[^\\]|\\.|\n)+?'{3}
4046
- |"{3}(?:[^\\]|\\.|\n)+?"{3}
4047
- )
4048
- )'''
4049
-
4050
- _re_inl = _re_tok.replace(r'|\n', '') # We re-use this string pattern later
4051
-
4052
- _re_tok += r'''
4053
- # 2: Comments (until end of line, but not the newline itself)
4054
- |(\#.*)
4055
-
4056
- # 3: Open and close (4) grouping tokens
4057
- |([\[\{\(])
4058
- |([\]\}\)])
4059
-
4060
- # 5,6: Keywords that start or continue a python block (only start of line)
4061
- |^([\ \t]*(?:if|for|while|with|try|def|class)\b)
4062
- |^([\ \t]*(?:elif|else|except|finally)\b)
4063
-
4064
- # 7: Our special 'end' keyword (but only if it stands alone)
4065
- |((?:^|;)[\ \t]*end[\ \t]*(?=(?:%(block_close)s[\ \t]*)?\r?$|;|\#))
4066
-
4067
- # 8: A customizable end-of-code-block template token (only end of line)
4068
- |(%(block_close)s[\ \t]*(?=\r?$))
4069
-
4070
- # 9: And finally, a single newline. The 10th token is 'everything else'
4071
- |(\r?\n)
4072
- '''
4073
-
4074
- # Match the start tokens of code areas in a template
4075
- _re_split = r'''(?m)^[ \t]*(\\?)((%(line_start)s)|(%(block_start)s))'''
4076
- # Match inline statements (may contain python strings)
4077
- _re_inl = r'''%%(inline_start)s((?:%s|[^'"\n])*?)%%(inline_end)s''' % _re_inl
4078
-
4079
- # add the flag in front of the regexp to avoid Deprecation warning (see Issue #949)
4080
- # verbose and dot-matches-newline mode
4081
- _re_tok = '(?mx)' + _re_tok
4082
- _re_inl = '(?mx)' + _re_inl
4083
-
4084
-
4085
- default_syntax = '<% %> % {{ }}'
4086
-
4087
- def __init__(self, source, syntax=None, encoding='utf8'):
4088
- self.source, self.encoding = touni(source, encoding), encoding
4089
- self.set_syntax(syntax or self.default_syntax)
4090
- self.code_buffer, self.text_buffer = [], []
4091
- self.lineno, self.offset = 1, 0
4092
- self.indent, self.indent_mod = 0, 0
4093
- self.paren_depth = 0
4094
-
4095
- def get_syntax(self):
4096
- """ Tokens as a space separated string (default: <% %> % {{ }}) """
4097
- return self._syntax
4098
-
4099
- def set_syntax(self, syntax):
4100
- self._syntax = syntax
4101
- self._tokens = syntax.split()
4102
- if syntax not in self._re_cache:
4103
- names = 'block_start block_close line_start inline_start inline_end'
4104
- etokens = map(re.escape, self._tokens)
4105
- pattern_vars = dict(zip(names.split(), etokens))
4106
- patterns = (self._re_split, self._re_tok, self._re_inl)
4107
- patterns = [re.compile(p % pattern_vars) for p in patterns]
4108
- self._re_cache[syntax] = patterns
4109
- self.re_split, self.re_tok, self.re_inl = self._re_cache[syntax]
4110
-
4111
- syntax = property(get_syntax, set_syntax)
4112
-
4113
- def translate(self):
4114
- if self.offset: raise RuntimeError('Parser is a one time instance.')
4115
- while True:
4116
- m = self.re_split.search(self.source, pos=self.offset)
4117
- if m:
4118
- text = self.source[self.offset:m.start()]
4119
- self.text_buffer.append(text)
4120
- self.offset = m.end()
4121
- if m.group(1): # Escape syntax
4122
- line, sep, _ = self.source[self.offset:].partition('\n')
4123
- self.text_buffer.append(self.source[m.start():m.start(1)] +
4124
- m.group(2) + line + sep)
4125
- self.offset += len(line + sep)
4126
- continue
4127
- self.flush_text()
4128
- self.offset += self.read_code(self.source[self.offset:],
4129
- multiline=bool(m.group(4)))
4130
- else:
4131
- break
4132
- self.text_buffer.append(self.source[self.offset:])
4133
- self.flush_text()
4134
- return ''.join(self.code_buffer)
4135
-
4136
- def read_code(self, pysource, multiline):
4137
- code_line, comment = '', ''
4138
- offset = 0
4139
- while True:
4140
- m = self.re_tok.search(pysource, pos=offset)
4141
- if not m:
4142
- code_line += pysource[offset:]
4143
- offset = len(pysource)
4144
- self.write_code(code_line.strip(), comment)
4145
- break
4146
- code_line += pysource[offset:m.start()]
4147
- offset = m.end()
4148
- _str, _com, _po, _pc, _blk1, _blk2, _end, _cend, _nl = m.groups()
4149
- if self.paren_depth > 0 and (_blk1 or _blk2): # a if b else c
4150
- code_line += _blk1 or _blk2
4151
- continue
4152
- if _str: # Python string
4153
- code_line += _str
4154
- elif _com: # Python comment (up to EOL)
4155
- comment = _com
4156
- if multiline and _com.strip().endswith(self._tokens[1]):
4157
- multiline = False # Allow end-of-block in comments
4158
- elif _po: # open parenthesis
4159
- self.paren_depth += 1
4160
- code_line += _po
4161
- elif _pc: # close parenthesis
4162
- if self.paren_depth > 0:
4163
- # we could check for matching parentheses here, but it's
4164
- # easier to leave that to python - just check counts
4165
- self.paren_depth -= 1
4166
- code_line += _pc
4167
- elif _blk1: # Start-block keyword (if/for/while/def/try/...)
4168
- code_line = _blk1
4169
- self.indent += 1
4170
- self.indent_mod -= 1
4171
- elif _blk2: # Continue-block keyword (else/elif/except/...)
4172
- code_line = _blk2
4173
- self.indent_mod -= 1
4174
- elif _cend: # The end-code-block template token (usually '%>')
4175
- if multiline: multiline = False
4176
- else: code_line += _cend
4177
- elif _end:
4178
- self.indent -= 1
4179
- self.indent_mod += 1
4180
- else: # \n
4181
- self.write_code(code_line.strip(), comment)
4182
- self.lineno += 1
4183
- code_line, comment, self.indent_mod = '', '', 0
4184
- if not multiline:
4185
- break
4186
-
4187
- return offset
4188
-
4189
- def flush_text(self):
4190
- text = ''.join(self.text_buffer)
4191
- del self.text_buffer[:]
4192
- if not text: return
4193
- parts, pos, nl = [], 0, '\\\n' + ' ' * self.indent
4194
- for m in self.re_inl.finditer(text):
4195
- prefix, pos = text[pos:m.start()], m.end()
4196
- if prefix:
4197
- parts.append(nl.join(map(repr, prefix.splitlines(True))))
4198
- if prefix.endswith('\n'): parts[-1] += nl
4199
- parts.append(self.process_inline(m.group(1).strip()))
4200
- if pos < len(text):
4201
- prefix = text[pos:]
4202
- lines = prefix.splitlines(True)
4203
- if lines[-1].endswith('\\\\\n'): lines[-1] = lines[-1][:-3]
4204
- elif lines[-1].endswith('\\\\\r\n'): lines[-1] = lines[-1][:-4]
4205
- parts.append(nl.join(map(repr, lines)))
4206
- code = '_printlist((%s,))' % ', '.join(parts)
4207
- self.lineno += code.count('\n') + 1
4208
- self.write_code(code)
4209
-
4210
- @staticmethod
4211
- def process_inline(chunk):
4212
- if chunk[0] == '!': return '_str(%s)' % chunk[1:]
4213
- return '_escape(%s)' % chunk
4214
-
4215
- def write_code(self, line, comment=''):
4216
- code = ' ' * (self.indent + self.indent_mod)
4217
- code += line.lstrip() + comment + '\n'
4218
- self.code_buffer.append(code)
4219
-
4220
-
4221
- def template(*args, **kwargs):
4222
- """
4223
- Get a rendered template as a string iterator.
4224
- You can use a name, a filename or a template string as first parameter.
4225
- Template rendering arguments can be passed as dictionaries
4226
- or directly (as keyword arguments).
4227
- """
4228
- tpl = args[0] if args else None
4229
- for dictarg in args[1:]:
4230
- kwargs.update(dictarg)
4231
- adapter = kwargs.pop('template_adapter', SimpleTemplate)
4232
- lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
4233
- tplid = (id(lookup), tpl)
4234
- if tplid not in TEMPLATES or DEBUG:
4235
- settings = kwargs.pop('template_settings', {})
4236
- if isinstance(tpl, adapter):
4237
- TEMPLATES[tplid] = tpl
4238
- if settings: TEMPLATES[tplid].prepare(**settings)
4239
- elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
4240
- TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings)
4241
- else:
4242
- TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings)
4243
- if not TEMPLATES[tplid]:
4244
- abort(500, 'Template (%s) not found' % tpl)
4245
- return TEMPLATES[tplid].render(kwargs)
4246
-
4247
-
4248
- mako_template = functools.partial(template, template_adapter=MakoTemplate)
4249
- cheetah_template = functools.partial(template,
4250
- template_adapter=CheetahTemplate)
4251
- jinja2_template = functools.partial(template, template_adapter=Jinja2Template)
4252
-
4253
-
4254
- def view(tpl_name, **defaults):
4255
- """ Decorator: renders a template for a handler.
4256
- The handler can control its behavior like that:
4257
-
4258
- - return a dict of template vars to fill out the template
4259
- - return something other than a dict and the view decorator will not
4260
- process the template, but return the handler result as is.
4261
- This includes returning a HTTPResponse(dict) to get,
4262
- for instance, JSON with autojson or other castfilters.
4263
- """
4264
-
4265
- def decorator(func):
4266
-
4267
- @functools.wraps(func)
4268
- def wrapper(*args, **kwargs):
4269
- result = func(*args, **kwargs)
4270
- if isinstance(result, (dict, DictMixin)):
4271
- tplvars = defaults.copy()
4272
- tplvars.update(result)
4273
- return template(tpl_name, **tplvars)
4274
- elif result is None:
4275
- return template(tpl_name, defaults)
4276
- return result
4277
-
4278
- return wrapper
4279
-
4280
- return decorator
4281
-
4282
-
4283
- mako_view = functools.partial(view, template_adapter=MakoTemplate)
4284
- cheetah_view = functools.partial(view, template_adapter=CheetahTemplate)
4285
- jinja2_view = functools.partial(view, template_adapter=Jinja2Template)
4286
-
4287
- ###############################################################################
4288
- # Constants and Globals ########################################################
4289
- ###############################################################################
4290
-
4291
- TEMPLATE_PATH = ['./', './views/']
4292
- TEMPLATES = {}
4293
- DEBUG = False
4294
- NORUN = False # If set, run() does nothing. Used by load_app()
4295
-
4296
- #: A dict to map HTTP status codes (e.g. 404) to phrases (e.g. 'Not Found')
4297
- HTTP_CODES = httplib.responses.copy()
4298
- HTTP_CODES[418] = "I'm a teapot" # RFC 2324
4299
- HTTP_CODES[428] = "Precondition Required"
4300
- HTTP_CODES[429] = "Too Many Requests"
4301
- HTTP_CODES[431] = "Request Header Fields Too Large"
4302
- HTTP_CODES[451] = "Unavailable For Legal Reasons" # RFC 7725
4303
- HTTP_CODES[511] = "Network Authentication Required"
4304
- _HTTP_STATUS_LINES = dict((k, '%d %s' % (k, v))
4305
- for (k, v) in HTTP_CODES.items())
4306
-
4307
- #: The default template used for error pages. Override with @error()
4308
- ERROR_PAGE_TEMPLATE = """
4309
- %%try:
4310
- %%from %s import DEBUG, request
4311
- <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
4312
- <html>
4313
- <head>
4314
- <title>Error: {{e.status}}</title>
4315
- <style type="text/css">
4316
- html {background-color: #eee; font-family: sans-serif;}
4317
- body {background-color: #fff; border: 1px solid #ddd;
4318
- padding: 15px; margin: 15px;}
4319
- pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;}
4320
- </style>
4321
- </head>
4322
- <body>
4323
- <h1>Error: {{e.status}}</h1>
4324
- <p>Sorry, the requested URL <tt>{{repr(request.url)}}</tt>
4325
- caused an error:</p>
4326
- <pre>{{e.body}}</pre>
4327
- %%if DEBUG and e.exception:
4328
- <h2>Exception:</h2>
4329
- %%try:
4330
- %%exc = repr(e.exception)
4331
- %%except:
4332
- %%exc = '<unprintable %%s object>' %% type(e.exception).__name__
4333
- %%end
4334
- <pre>{{exc}}</pre>
4335
- %%end
4336
- %%if DEBUG and e.traceback:
4337
- <h2>Traceback:</h2>
4338
- <pre>{{e.traceback}}</pre>
4339
- %%end
4340
- </body>
4341
- </html>
4342
- %%except ImportError:
4343
- <b>ImportError:</b> Could not generate the error page. Please add bottle to
4344
- the import path.
4345
- %%end
4346
- """ % __name__
4347
-
4348
- #: A thread-safe instance of :class:`LocalRequest`. If accessed from within a
4349
- #: request callback, this instance always refers to the *current* request
4350
- #: (even on a multi-threaded server).
4351
- request = LocalRequest()
4352
-
4353
- #: A thread-safe instance of :class:`LocalResponse`. It is used to change the
4354
- #: HTTP response for the *current* request.
4355
- response = LocalResponse()
4356
-
4357
- #: A thread-safe namespace. Not used by Bottle.
4358
- local = threading.local()
4359
-
4360
- # Initialize app stack (create first empty Bottle app now deferred until needed)
4361
- # BC: 0.6.4 and needed for run()
4362
- apps = app = default_app = AppStack()
4363
-
4364
- #: A virtual package that redirects import statements.
4365
- #: Example: ``import bottle.ext.sqlite`` actually imports `bottle_sqlite`.
4366
- ext = _ImportRedirect('bottle.ext' if __name__ == '__main__' else
4367
- __name__ + ".ext", 'bottle_%s').module
4368
-
4369
-
4370
- def _main(argv): # pragma: no coverage
4371
- args, parser = _cli_parse(argv)
4372
-
4373
- def _cli_error(cli_msg):
4374
- parser.print_help()
4375
- _stderr('\nError: %s\n' % cli_msg)
4376
- sys.exit(1)
4377
-
4378
- if args.version:
4379
- print('Bottle %s' % __version__)
4380
- sys.exit(0)
4381
- if not args.app:
4382
- _cli_error("No application entry point specified.")
4383
-
4384
- sys.path.insert(0, '.')
4385
- sys.modules.setdefault('bottle', sys.modules['__main__'])
4386
-
4387
- host, port = (args.bind or 'localhost'), 8080
4388
- if ':' in host and host.rfind(']') < host.rfind(':'):
4389
- host, port = host.rsplit(':', 1)
4390
- host = host.strip('[]')
4391
-
4392
- config = ConfigDict()
4393
-
4394
- for cfile in args.conf or []:
4395
- try:
4396
- if cfile.endswith('.json'):
4397
- with open(cfile, 'rb') as fp:
4398
- config.load_dict(json_loads(fp.read()))
4399
- else:
4400
- config.load_config(cfile)
4401
- except configparser.Error as parse_error:
4402
- _cli_error(parse_error)
4403
- except IOError:
4404
- _cli_error("Unable to read config file %r" % cfile)
4405
- except (UnicodeError, TypeError, ValueError) as error:
4406
- _cli_error("Unable to parse config file %r: %s" % (cfile, error))
4407
-
4408
- for cval in args.param or []:
4409
- if '=' in cval:
4410
- config.update((cval.split('=', 1),))
4411
- else:
4412
- config[cval] = True
4413
-
4414
- run(args.app,
4415
- host=host,
4416
- port=int(port),
4417
- server=args.server,
4418
- reloader=args.reload,
4419
- plugins=args.plugin,
4420
- debug=args.debug,
4421
- config=config)
4422
-
4423
-
4424
- if __name__ == '__main__': # pragma: no coverage
4425
- _main(sys.argv)
5
+ # Rexport all public symbols from pip-installed bottle
6
+ from bottle import *