├── .gitignore ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── Makefile ├── Pipfile ├── README.rst ├── docs ├── Makefile ├── _static │ └── itsdangerous.png ├── _themes │ ├── .gitignore │ ├── LICENSE │ ├── README │ ├── flask_small │ │ ├── layout.html │ │ ├── static │ │ │ └── flasky.css_t │ │ └── theme.conf │ └── flask_theme_support.py ├── conf.py ├── index.rst └── make.bat ├── example ├── README ├── app1 │ └── plugins │ │ └── secret.py ├── app2 │ └── plugins │ │ └── randomstr.py ├── builtin_plugins │ ├── lowercase.py │ └── uppercase.py └── example.py ├── pluginbase.py ├── setup.py ├── tests ├── conftest.py ├── dummy.py ├── plugins │ ├── advanced.py │ ├── hello.py │ ├── hello2.py │ └── withresources │ │ ├── __init__.py │ │ └── hello.txt ├── shutdown.py ├── test_advanced.py ├── test_basics.py └── test_shutdown.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.pyo 3 | *.egg-info 4 | .tox 5 | dist 6 | build 7 | docs/_build 8 | Pipfile.lock 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.7" 4 | - "3.4" 5 | - "3.5" 6 | - "3.6" 7 | - "3.7" 8 | - "3.8" 9 | - "3.9" 10 | - "pypy" 11 | 12 | install: 13 | - pip install --editable . 14 | 15 | script: make test 16 | 17 | notifications: 18 | email: false 19 | irc: 20 | channels: 21 | - "chat.freenode.net#pocoo" 22 | on_success: change 23 | on_failure: always 24 | use_notice: true 25 | skip_join: true 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 by Armin Ronacher. 2 | 3 | Some rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are 7 | met: 8 | 9 | * Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above 13 | copyright notice, this list of conditions and the following 14 | disclaimer in the documentation and/or other materials provided 15 | with the distribution. 16 | 17 | * The names of the contributors may not be used to endorse or 18 | promote products derived from this software without specific 19 | prior written permission. 20 | 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 24 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include Makefile LICENSE 2 | recursive-include tests * 3 | recursive-include docs * 4 | recursive-exclude docs *.pyc 5 | recursive-exclude docs *.pyo 6 | recursive-exclude tests *.pyc 7 | recursive-exclude tests *.pyo 8 | prune docs/_build 9 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | test: 2 | @cd tests; PYTHONPATH=.. py.test --tb=native 3 | 4 | upload-docs: 5 | $(MAKE) -C docs dirhtml 6 | rsync -a docs/_build/dirhtml/* flow.srv.pocoo.org:/srv/websites/pluginbase.pocoo.org/static/ 7 | 8 | .PHONY: test upload-docs 9 | -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | name = "pypi" 3 | url = "https://pypi.org/simple" 4 | verify_ssl = true 5 | 6 | [packages] 7 | 8 | [dev-packages] 9 | pytest = "*" 10 | 11 | [scripts] 12 | release = 'sh -c "python setup.py build sdist && twine upload --verbose dist/*"' 13 | tests = 'sh -c "cd tests; PYTHONPATH=.. py.test --tb=native"' 14 | 15 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | PluginBase 2 | ========== 3 | 4 | PluginBase is a module for Python that enables the development of flexible plugin systems in Python. 5 | 6 | Step 1: 7 | 8 | .. code-block:: python 9 | 10 | from pluginbase import PluginBase 11 | plugin_base = PluginBase(package='yourapplication.plugins') 12 | 13 | Step 2: 14 | 15 | .. code-block:: python 16 | 17 | plugin_source = plugin_base.make_plugin_source( 18 | searchpath=['./path/to/plugins', './path/to/more/plugins']) 19 | 20 | Step 3: 21 | 22 | .. code-block:: python 23 | 24 | with plugin_source: 25 | from yourapplication.plugins import my_plugin 26 | my_plugin.do_something_cool() 27 | 28 | Or alternatively: 29 | 30 | .. code-block:: python 31 | 32 | my_plugin = plugin_source.load_plugin('my_plugin') 33 | my_plugin.do_something_cool() 34 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | 15 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest 16 | 17 | help: 18 | @echo "Please use \`make ' where is one of" 19 | @echo " html to make standalone HTML files" 20 | @echo " dirhtml to make HTML files named index.html in directories" 21 | @echo " singlehtml to make a single large HTML file" 22 | @echo " pickle to make pickle files" 23 | @echo " json to make JSON files" 24 | @echo " htmlhelp to make HTML files and a HTML help project" 25 | @echo " qthelp to make HTML files and a qthelp project" 26 | @echo " devhelp to make HTML files and a Devhelp project" 27 | @echo " epub to make an epub" 28 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 29 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 30 | @echo " text to make text files" 31 | @echo " man to make manual pages" 32 | @echo " changes to make an overview of all changed/added/deprecated items" 33 | @echo " linkcheck to check all external links for integrity" 34 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 35 | 36 | clean: 37 | -rm -rf $(BUILDDIR)/* 38 | 39 | html: 40 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 41 | @echo 42 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 43 | 44 | dirhtml: 45 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 48 | 49 | singlehtml: 50 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 51 | @echo 52 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 53 | 54 | pickle: 55 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 56 | @echo 57 | @echo "Build finished; now you can process the pickle files." 58 | 59 | json: 60 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 61 | @echo 62 | @echo "Build finished; now you can process the JSON files." 63 | 64 | htmlhelp: 65 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 66 | @echo 67 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 68 | ".hhp project file in $(BUILDDIR)/htmlhelp." 69 | 70 | qthelp: 71 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 72 | @echo 73 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 74 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 75 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Classy.qhcp" 76 | @echo "To view the help file:" 77 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Classy.qhc" 78 | 79 | devhelp: 80 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 81 | @echo 82 | @echo "Build finished." 83 | @echo "To view the help file:" 84 | @echo "# mkdir -p $$HOME/.local/share/devhelp/Classy" 85 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Classy" 86 | @echo "# devhelp" 87 | 88 | epub: 89 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 90 | @echo 91 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 92 | 93 | latex: 94 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 95 | @echo 96 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 97 | @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ 98 | "run these through (pdf)latex." 99 | 100 | latexpdf: latex 101 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 102 | @echo "Running LaTeX files through pdflatex..." 103 | make -C $(BUILDDIR)/latex all-pdf 104 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 105 | 106 | text: 107 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 108 | @echo 109 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 110 | 111 | man: 112 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 113 | @echo 114 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 115 | 116 | changes: 117 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 118 | @echo 119 | @echo "The overview file is in $(BUILDDIR)/changes." 120 | 121 | linkcheck: 122 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 123 | @echo 124 | @echo "Link check complete; look for any errors in the above output " \ 125 | "or in $(BUILDDIR)/linkcheck/output.txt." 126 | 127 | doctest: 128 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 129 | @echo "Testing of doctests in the sources finished, look at the " \ 130 | "results in $(BUILDDIR)/doctest/output.txt." 131 | -------------------------------------------------------------------------------- /docs/_static/itsdangerous.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitsuhiko/pluginbase/2a5db4c0bba11dc6dff0110c298e3ab9d8521532/docs/_static/itsdangerous.png -------------------------------------------------------------------------------- /docs/_themes/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.pyo 3 | .DS_Store 4 | -------------------------------------------------------------------------------- /docs/_themes/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010 by Armin Ronacher. 2 | 3 | Some rights reserved. 4 | 5 | Redistribution and use in source and binary forms of the theme, with or 6 | without modification, are permitted provided that the following conditions 7 | are met: 8 | 9 | * Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above 13 | copyright notice, this list of conditions and the following 14 | disclaimer in the documentation and/or other materials provided 15 | with the distribution. 16 | 17 | * The names of the contributors may not be used to endorse or 18 | promote products derived from this software without specific 19 | prior written permission. 20 | 21 | We kindly ask you to only use these themes in an unmodified manner just 22 | for Flask and Flask-related products, not for unrelated projects. If you 23 | like the visual style and want to use it for your own projects, please 24 | consider making some larger changes to the themes (such as changing 25 | font faces, sizes, colors or margins). 26 | 27 | THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 28 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 29 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 30 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 31 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 32 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 33 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 34 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 35 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 36 | ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE 37 | POSSIBILITY OF SUCH DAMAGE. 38 | -------------------------------------------------------------------------------- /docs/_themes/README: -------------------------------------------------------------------------------- 1 | Flask Sphinx Styles 2 | =================== 3 | 4 | This repository contains sphinx styles for Flask and Flask related 5 | projects. To use this style in your Sphinx documentation, follow 6 | this guide: 7 | 8 | 1. put this folder as _themes into your docs folder. Alternatively 9 | you can also use git submodules to check out the contents there. 10 | 2. add this to your conf.py: 11 | 12 | sys.path.append(os.path.abspath('_themes')) 13 | html_theme_path = ['_themes'] 14 | html_theme = 'flask' 15 | 16 | The following themes exist: 17 | 18 | - 'flask' - the standard flask documentation theme for large 19 | projects 20 | - 'flask_small' - small one-page theme. Intended to be used by 21 | very small addon libraries for flask. 22 | 23 | The following options exist for the flask_small theme: 24 | 25 | [options] 26 | index_logo = '' filename of a picture in _static 27 | to be used as replacement for the 28 | h1 in the index.rst file. 29 | index_logo_height = 120px height of the index logo 30 | github_fork = '' repository name on github for the 31 | "fork me" badge 32 | -------------------------------------------------------------------------------- /docs/_themes/flask_small/layout.html: -------------------------------------------------------------------------------- 1 | {% extends "basic/layout.html" %} 2 | {% block header %} 3 | 6 | {{ super() }} 7 | {% if pagename == 'index' %} 8 |
9 | {% endif %} 10 | {% endblock %} 11 | {% block footer %} 12 | {% if pagename == 'index' %} 13 |
14 | {% endif %} 15 | {% endblock %} 16 | {# do not display relbars #} 17 | {% block relbar1 %}{% endblock %} 18 | {% block relbar2 %} 19 | {% if theme_github_fork %} 20 | Fork me on GitHub 22 | {% endif %} 23 | {% endblock %} 24 | {% block sidebar1 %}{% endblock %} 25 | {% block sidebar2 %}{% endblock %} 26 | -------------------------------------------------------------------------------- /docs/_themes/flask_small/static/flasky.css_t: -------------------------------------------------------------------------------- 1 | /* 2 | * flasky.css_t 3 | * ~~~~~~~~~~~~ 4 | * 5 | * Sphinx stylesheet -- flasky theme based on nature theme. 6 | * 7 | * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS. 8 | * :license: BSD, see LICENSE for details. 9 | * 10 | */ 11 | 12 | @import url("basic.css"); 13 | @import url(http://fonts.googleapis.com/css?family=Karla:400); 14 | {% set font_family = "'Karla', sans-serif" %} 15 | 16 | /* -- page layout ----------------------------------------------------------- */ 17 | 18 | body { 19 | font-family: {{ font_family }}; 20 | font-weight: normal; 21 | font-size: 17px; 22 | color: #000; 23 | background: white; 24 | margin: 0; 25 | padding: 0; 26 | } 27 | 28 | div.documentwrapper { 29 | float: left; 30 | width: 100%; 31 | } 32 | 33 | div.bodywrapper { 34 | margin: 40px auto 0 auto; 35 | width: 700px; 36 | } 37 | 38 | hr { 39 | border: 1px solid #B1B4B6; 40 | } 41 | 42 | div.body { 43 | background-color: #ffffff; 44 | color: #3E4349; 45 | padding: 0 30px 30px 30px; 46 | } 47 | 48 | img.floatingflask { 49 | padding: 0 0 10px 10px; 50 | float: right; 51 | } 52 | 53 | div.footer { 54 | text-align: right; 55 | color: #888; 56 | padding: 10px; 57 | font-size: 14px; 58 | width: 650px; 59 | margin: 0 auto 40px auto; 60 | } 61 | 62 | div.footer a { 63 | color: #888; 64 | text-decoration: underline; 65 | } 66 | 67 | div.related { 68 | line-height: 32px; 69 | color: #888; 70 | } 71 | 72 | div.related ul { 73 | padding: 0 0 0 10px; 74 | } 75 | 76 | div.related a { 77 | color: #444; 78 | } 79 | 80 | /* -- body styles ----------------------------------------------------------- */ 81 | 82 | a { 83 | color: #215974; 84 | text-decoration: underline; 85 | } 86 | 87 | a:hover { 88 | color: #888; 89 | text-decoration: underline; 90 | } 91 | 92 | div.body { 93 | padding-bottom: 40px; /* saved for footer */ 94 | } 95 | 96 | div.body h1, 97 | div.body h2, 98 | div.body h3, 99 | div.body h4, 100 | div.body h5, 101 | div.body h6 { 102 | font-family: {{ font_family }}; 103 | font-weight: normal; 104 | margin: 30px 0px 10px 0px; 105 | padding: 0; 106 | color: black; 107 | } 108 | 109 | div.body h1 { font-size: 240%; } 110 | div.body h2 { font-size: 180%; } 111 | div.body h3 { font-size: 150%; } 112 | div.body h4 { font-size: 130%; } 113 | div.body h5 { font-size: 100%; } 114 | div.body h6 { font-size: 100%; } 115 | 116 | a.headerlink { 117 | color: white; 118 | padding: 0 4px; 119 | text-decoration: none; 120 | } 121 | 122 | a.headerlink:hover { 123 | color: #444; 124 | background: #eaeaea; 125 | } 126 | 127 | div.body p, div.body dd, div.body li, div.body blockquote { 128 | line-height: 1.3em; 129 | } 130 | 131 | div.admonition { 132 | background: #fafafa; 133 | margin: 20px -30px; 134 | padding: 10px 30px; 135 | border-top: 1px solid #ccc; 136 | border-bottom: 1px solid #ccc; 137 | } 138 | 139 | div.admonition p.admonition-title { 140 | font-family: 'Garamond', 'Georgia', serif; 141 | font-weight: normal; 142 | font-size: 24px; 143 | margin: 0 0 10px 0; 144 | padding: 0; 145 | line-height: 1; 146 | } 147 | 148 | div.admonition p.last { 149 | margin-bottom: 0; 150 | } 151 | 152 | div.highlight{ 153 | background-color: white; 154 | } 155 | 156 | dt:target, .highlight { 157 | background: #FAF3E8; 158 | } 159 | 160 | div.note { 161 | background-color: #eee; 162 | border: 1px solid #ccc; 163 | } 164 | 165 | div.seealso { 166 | background-color: #ffc; 167 | border: 1px solid #ff6; 168 | } 169 | 170 | div.topic { 171 | background-color: #eee; 172 | } 173 | 174 | div.warning { 175 | background-color: #ffe4e4; 176 | border: 1px solid #f66; 177 | } 178 | 179 | p.admonition-title { 180 | display: inline; 181 | } 182 | 183 | p.admonition-title:after { 184 | content: ":"; 185 | } 186 | 187 | pre, tt { 188 | font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; 189 | font-size: 0.85em; 190 | } 191 | 192 | img.screenshot { 193 | } 194 | 195 | tt.descname, tt.descclassname { 196 | font-size: 0.95em; 197 | } 198 | 199 | tt.descname { 200 | padding-right: 0.08em; 201 | } 202 | 203 | img.screenshot { 204 | -moz-box-shadow: 2px 2px 4px #eee; 205 | -webkit-box-shadow: 2px 2px 4px #eee; 206 | box-shadow: 2px 2px 4px #eee; 207 | } 208 | 209 | table.docutils { 210 | border: 1px solid #888; 211 | -moz-box-shadow: 2px 2px 4px #eee; 212 | -webkit-box-shadow: 2px 2px 4px #eee; 213 | box-shadow: 2px 2px 4px #eee; 214 | } 215 | 216 | table.docutils td, table.docutils th { 217 | border: 1px solid #888; 218 | padding: 0.25em 0.7em; 219 | } 220 | 221 | table.field-list, table.footnote { 222 | border: none; 223 | -moz-box-shadow: none; 224 | -webkit-box-shadow: none; 225 | box-shadow: none; 226 | } 227 | 228 | table.footnote { 229 | margin: 15px 0; 230 | width: 100%; 231 | border: 1px solid #eee; 232 | } 233 | 234 | table.field-list th { 235 | padding: 0 0.8em 0 0; 236 | } 237 | 238 | table.field-list td { 239 | padding: 0; 240 | } 241 | 242 | table.footnote td { 243 | padding: 0.5em; 244 | } 245 | 246 | dl { 247 | margin: 0; 248 | padding: 0; 249 | } 250 | 251 | dl dd { 252 | margin-left: 30px; 253 | } 254 | 255 | pre { 256 | padding: 0; 257 | margin: 15px -30px; 258 | padding: 8px; 259 | line-height: 1.3em; 260 | padding: 7px 30px; 261 | background: #eee; 262 | border-radius: 2px; 263 | -moz-border-radius: 2px; 264 | -webkit-border-radius: 2px; 265 | } 266 | 267 | dl pre { 268 | margin-left: -60px; 269 | padding-left: 60px; 270 | } 271 | 272 | tt { 273 | background-color: #ecf0f3; 274 | color: #222; 275 | /* padding: 1px 2px; */ 276 | } 277 | 278 | tt.xref, a tt { 279 | background-color: #FBFBFB; 280 | } 281 | 282 | a:hover tt { 283 | background: #EEE; 284 | } 285 | -------------------------------------------------------------------------------- /docs/_themes/flask_small/theme.conf: -------------------------------------------------------------------------------- 1 | [theme] 2 | inherit = basic 3 | stylesheet = flasky.css 4 | nosidebar = true 5 | pygments_style = flask_theme_support.FlaskyStyle 6 | 7 | [options] 8 | index_logo = '' 9 | index_logo_height = 160px 10 | github_fork = 11 | -------------------------------------------------------------------------------- /docs/_themes/flask_theme_support.py: -------------------------------------------------------------------------------- 1 | # flasky extensions. flasky pygments style based on tango style 2 | from pygments.style import Style 3 | from pygments.token import Keyword, Name, Comment, String, Error, \ 4 | Number, Operator, Generic, Whitespace, Punctuation, Other, Literal 5 | 6 | 7 | class FlaskyStyle(Style): 8 | background_color = "#f8f8f8" 9 | default_style = "" 10 | 11 | styles = { 12 | # No corresponding class for the following: 13 | #Text: "", # class: '' 14 | Whitespace: "underline #f8f8f8", # class: 'w' 15 | Error: "#a40000 border:#ef2929", # class: 'err' 16 | Other: "#000000", # class 'x' 17 | 18 | Comment: "italic #8f5902", # class: 'c' 19 | Comment.Preproc: "noitalic", # class: 'cp' 20 | 21 | Keyword: "bold #004461", # class: 'k' 22 | Keyword.Constant: "bold #004461", # class: 'kc' 23 | Keyword.Declaration: "bold #004461", # class: 'kd' 24 | Keyword.Namespace: "bold #004461", # class: 'kn' 25 | Keyword.Pseudo: "bold #004461", # class: 'kp' 26 | Keyword.Reserved: "bold #004461", # class: 'kr' 27 | Keyword.Type: "bold #004461", # class: 'kt' 28 | 29 | Operator: "#582800", # class: 'o' 30 | Operator.Word: "bold #004461", # class: 'ow' - like keywords 31 | 32 | Punctuation: "bold #000000", # class: 'p' 33 | 34 | # because special names such as Name.Class, Name.Function, etc. 35 | # are not recognized as such later in the parsing, we choose them 36 | # to look the same as ordinary variables. 37 | Name: "#000000", # class: 'n' 38 | Name.Attribute: "#c4a000", # class: 'na' - to be revised 39 | Name.Builtin: "#004461", # class: 'nb' 40 | Name.Builtin.Pseudo: "#3465a4", # class: 'bp' 41 | Name.Class: "#000000", # class: 'nc' - to be revised 42 | Name.Constant: "#000000", # class: 'no' - to be revised 43 | Name.Decorator: "#888", # class: 'nd' - to be revised 44 | Name.Entity: "#ce5c00", # class: 'ni' 45 | Name.Exception: "bold #cc0000", # class: 'ne' 46 | Name.Function: "#000000", # class: 'nf' 47 | Name.Property: "#000000", # class: 'py' 48 | Name.Label: "#f57900", # class: 'nl' 49 | Name.Namespace: "#000000", # class: 'nn' - to be revised 50 | Name.Other: "#000000", # class: 'nx' 51 | Name.Tag: "bold #004461", # class: 'nt' - like a keyword 52 | Name.Variable: "#000000", # class: 'nv' - to be revised 53 | Name.Variable.Class: "#000000", # class: 'vc' - to be revised 54 | Name.Variable.Global: "#000000", # class: 'vg' - to be revised 55 | Name.Variable.Instance: "#000000", # class: 'vi' - to be revised 56 | 57 | Number: "#990000", # class: 'm' 58 | 59 | Literal: "#000000", # class: 'l' 60 | Literal.Date: "#000000", # class: 'ld' 61 | 62 | String: "#4e9a06", # class: 's' 63 | String.Backtick: "#4e9a06", # class: 'sb' 64 | String.Char: "#4e9a06", # class: 'sc' 65 | String.Doc: "italic #8f5902", # class: 'sd' - like a comment 66 | String.Double: "#4e9a06", # class: 's2' 67 | String.Escape: "#4e9a06", # class: 'se' 68 | String.Heredoc: "#4e9a06", # class: 'sh' 69 | String.Interpol: "#4e9a06", # class: 'si' 70 | String.Other: "#4e9a06", # class: 'sx' 71 | String.Regex: "#4e9a06", # class: 'sr' 72 | String.Single: "#4e9a06", # class: 's1' 73 | String.Symbol: "#4e9a06", # class: 'ss' 74 | 75 | Generic: "#000000", # class: 'g' 76 | Generic.Deleted: "#a40000", # class: 'gd' 77 | Generic.Emph: "italic #000000", # class: 'ge' 78 | Generic.Error: "#ef2929", # class: 'gr' 79 | Generic.Heading: "bold #000080", # class: 'gh' 80 | Generic.Inserted: "#00A000", # class: 'gi' 81 | Generic.Output: "#888", # class: 'go' 82 | Generic.Prompt: "#745334", # class: 'gp' 83 | Generic.Strong: "bold #000000", # class: 'gs' 84 | Generic.Subheading: "bold #800080", # class: 'gu' 85 | Generic.Traceback: "bold #a40000", # class: 'gt' 86 | } 87 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # pluginbase documentation build configuration file, created by 4 | # sphinx-quickstart on Mon Apr 26 19:53:01 2010. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | sys.path.append(os.path.abspath('_themes')) 20 | sys.path.append(os.path.abspath('..')) 21 | 22 | # -- General configuration ----------------------------------------------------- 23 | 24 | # If your documentation needs a minimal Sphinx version, state it here. 25 | #needs_sphinx = '1.0' 26 | 27 | # Add any Sphinx extension module names here, as strings. They can be extensions 28 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 29 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] 30 | 31 | # Add any paths that contain templates here, relative to this directory. 32 | templates_path = ['_templates'] 33 | 34 | # The suffix of source filenames. 35 | source_suffix = '.rst' 36 | 37 | # The encoding of source files. 38 | #source_encoding = 'utf-8-sig' 39 | 40 | # The master toctree document. 41 | master_doc = 'index' 42 | 43 | # General information about the project. 44 | project = u'pluginbase' 45 | copyright = u'2014, Armin Ronacher' 46 | 47 | # The version info for the project you're documenting, acts as replacement for 48 | # |version| and |release|, also used in various other places throughout the 49 | # built documents. 50 | # 51 | # The short X.Y version. 52 | version = '1.0' 53 | # The full version, including alpha/beta/rc tags. 54 | release = '1.0' 55 | 56 | # The language for content autogenerated by Sphinx. Refer to documentation 57 | # for a list of supported languages. 58 | #language = None 59 | 60 | # There are two options for replacing |today|: either, you set today to some 61 | # non-false value, then it is used: 62 | #today = '' 63 | # Else, today_fmt is used as the format for a strftime call. 64 | #today_fmt = '%B %d, %Y' 65 | 66 | # List of patterns, relative to source directory, that match files and 67 | # directories to ignore when looking for source files. 68 | exclude_patterns = ['_build'] 69 | 70 | # The reST default role (used for this markup: `text`) to use for all documents. 71 | #default_role = None 72 | 73 | # If true, '()' will be appended to :func: etc. cross-reference text. 74 | #add_function_parentheses = True 75 | 76 | # If true, the current module name will be prepended to all description 77 | # unit titles (such as .. function::). 78 | #add_module_names = True 79 | 80 | # If true, sectionauthor and moduleauthor directives will be shown in the 81 | # output. They are ignored by default. 82 | #show_authors = False 83 | 84 | # A list of ignored prefixes for module index sorting. 85 | #modindex_common_prefix = [] 86 | 87 | 88 | # -- Options for HTML output --------------------------------------------------- 89 | 90 | # The theme to use for HTML and HTML Help pages. Major themes that come with 91 | # Sphinx are currently 'default' and 'sphinxdoc'. 92 | html_theme = 'flask_small' 93 | 94 | # Theme options are theme-specific and customize the look and feel of a theme 95 | # further. For a list of options available for each theme, see the 96 | # documentation. 97 | html_theme_options = { 98 | 'github_fork': 'mitsuhiko/pluginbase' 99 | } 100 | 101 | # Add any paths that contain custom themes here, relative to this directory. 102 | html_theme_path = ['_themes'] 103 | 104 | # The name for this set of Sphinx documents. If None, it defaults to 105 | # " v documentation". 106 | html_title = 'pluginbase' 107 | 108 | # A shorter title for the navigation bar. Default is the same as html_title. 109 | #html_short_title = None 110 | 111 | # The name of an image file (relative to this directory) to place at the top 112 | # of the sidebar. 113 | #html_logo = None 114 | 115 | # The name of an image file (within the static path) to use as favicon of the 116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 117 | # pixels large. 118 | #html_favicon = None 119 | 120 | # Add any paths that contain custom static files (such as style sheets) here, 121 | # relative to this directory. They are copied after the builtin static files, 122 | # so a file named "default.css" will overwrite the builtin "default.css". 123 | html_static_path = ['_static'] 124 | 125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 126 | # using the given strftime format. 127 | #html_last_updated_fmt = '%b %d, %Y' 128 | 129 | # If true, SmartyPants will be used to convert quotes and dashes to 130 | # typographically correct entities. 131 | #html_use_smartypants = True 132 | 133 | # Custom sidebar templates, maps document names to template names. 134 | #html_sidebars = {} 135 | 136 | # Additional templates that should be rendered to pages, maps page names to 137 | # template names. 138 | #html_additional_pages = {} 139 | 140 | # If false, no module index is generated. 141 | #html_domain_indices = True 142 | 143 | # If false, no index is generated. 144 | #html_use_index = True 145 | 146 | # If true, the index is split into individual pages for each letter. 147 | #html_split_index = False 148 | 149 | # If true, links to the reST sources are added to the pages. 150 | #html_show_sourcelink = True 151 | 152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 153 | #html_show_sphinx = True 154 | 155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 156 | #html_show_copyright = True 157 | 158 | # If true, an OpenSearch description file will be output, and all pages will 159 | # contain a tag referring to it. The value of this option must be the 160 | # base URL from which the finished HTML is served. 161 | #html_use_opensearch = '' 162 | 163 | # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). 164 | #html_file_suffix = '' 165 | 166 | # Output file base name for HTML help builder. 167 | htmlhelp_basename = 'pluginbasedoc' 168 | 169 | 170 | # -- Options for LaTeX output -------------------------------------------------- 171 | 172 | # The paper size ('letter' or 'a4'). 173 | #latex_paper_size = 'letter' 174 | 175 | # The font size ('10pt', '11pt' or '12pt'). 176 | #latex_font_size = '10pt' 177 | 178 | # Grouping the document tree into LaTeX files. List of tuples 179 | # (source start file, target name, title, author, documentclass [howto/manual]). 180 | latex_documents = [ 181 | ('index', 'pluginbase.tex', u'pluginbase documentation', 182 | u'Armin Ronacher', 'manual'), 183 | ] 184 | 185 | # The name of an image file (relative to this directory) to place at the top of 186 | # the title page. 187 | #latex_logo = None 188 | 189 | # For "manual" documents, if this is true, then toplevel headings are parts, 190 | # not chapters. 191 | #latex_use_parts = False 192 | 193 | # Additional stuff for the LaTeX preamble. 194 | #latex_preamble = '' 195 | 196 | # Documents to append as an appendix to all manuals. 197 | #latex_appendices = [] 198 | 199 | # If false, no module index is generated. 200 | #latex_domain_indices = True 201 | 202 | 203 | # -- Options for manual page output -------------------------------------------- 204 | 205 | # One entry per manual page. List of tuples 206 | # (source start file, name, description, authors, manual section). 207 | man_pages = [ 208 | ('index', 'pluginbase', u'pluginbase documentation', 209 | [u'Armin Ronacher'], 1) 210 | ] 211 | 212 | intersphinx_mapping = { 213 | 'http://docs.python.org/dev': None 214 | } 215 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | PluginBase 2 | ========== 3 | 4 | .. module:: pluginbase 5 | 6 | Ever tried creating a plugin system for a Python application and you 7 | discovered fighting against the import system? Me too. This is where 8 | PluginBase comes in. 9 | 10 | PluginBase is a module for Python which extends the import system for 11 | the most common form of plugin usage which is providing a consistent 12 | import experience for plugins from a variety of sources. Essentially it 13 | allows you to build very flexible plugin based applications which pull in 14 | plugins from bundled sources as well as application specific ones without 15 | bypassing the Python import system. 16 | 17 | How does it work? It's super simple: 18 | 19 | Step 1: 20 | 21 | Create a "plugin base" object. It defines a pseudo package under 22 | which all your plugins will reside. For instance it could be 23 | ``yourapplication.plugins``:: 24 | 25 | from pluginbase import PluginBase 26 | plugin_base = PluginBase(package='yourapplication.plugins') 27 | 28 | Step 2: 29 | 30 | Now that you have a plugin base, you can define a plugin source 31 | which is the list of all sources which provide plugins:: 32 | 33 | plugin_source = plugin_base.make_plugin_source( 34 | searchpath=['./path/to/plugins', './path/to/more/plugins']) 35 | 36 | Step 3: 37 | 38 | To import a plugin all you need to do is to use the regular import 39 | system. The only change is that you need to import the plugin 40 | source through the ``with`` statement:: 41 | 42 | with plugin_source: 43 | from yourapplication.plugins import my_plugin 44 | my_plugin.do_something_cool() 45 | 46 | Alternatively you can also import plugins programmatically instead of 47 | using the import statement:: 48 | 49 | my_plugin = plugin_source.load_plugin('my_plugin') 50 | 51 | For a more complex example see the one from the git repo: 52 | `pluginbase-example `__. 53 | 54 | Installation 55 | ------------ 56 | 57 | You can get the library directly from PyPI:: 58 | 59 | pip install pluginbase 60 | 61 | 62 | FAQ 63 | --- 64 | 65 | Q: Why is there a plugin base and a plugin source class? 66 | 67 | This decision was taken so that multiple applications can co-exist 68 | together. For instance imagine you have an application that 69 | implements a wiki but you want multiple instances of that wiki 70 | to exist in the same Python interpreter. The plugin sources split 71 | out the load paths of the different applications. 72 | 73 | Each instance of the wiki would have its own plugin source and they 74 | can work independently of each other. 75 | 76 | Q: Do plugins pollute ``sys.modules``? 77 | 78 | While a plugin source is alive the plugins do indeed reside in 79 | ``sys.modules``. This decision was made consciously so that as little 80 | as possible of the Python library ecosystem breaks. However when the 81 | plugin source gets garbage collected all loaded plugins will 82 | also get garbage collected. 83 | 84 | Q: How does PluginBase deal with different versions of the same plugin? 85 | 86 | Each plugin source works independently of each other. The way this 87 | works is by internally translating the module name. By default that 88 | module name is a random number but it can also be forced to a hash of 89 | a specific value to make it stable across restarts which allows 90 | pickle and similar libraries to work. 91 | 92 | This internal module renaming means that 93 | ``yourapplication.module.foo`` will internally be called 94 | ``pluginbase._internalspace._sp7...be4`` for instance. The same 95 | plugin loaded from another plugin source will have a different 96 | internal name. 97 | 98 | Q: What happens if a plugin wants to import other modules? 99 | 100 | All fine. Plugins can import from itself as well as other plugins 101 | that can be located. 102 | 103 | Q: Does PluginBase support pickle? 104 | 105 | Yes, pickle works fine for plugins but it does require defining a 106 | stable identifier when creating a plugin source. This could for 107 | instance be a file system path:: 108 | 109 | plugin_source = base.make_plugin_source( 110 | searchpath=[app.plugin_path], 111 | identifier=app.config_filename) 112 | 113 | Q: What happens if I import from the plugin module without the 114 | plugin source activated through the ``with`` statement? 115 | 116 | The import will fail with a descriptive error message explaining 117 | that a plugin source needs to be activated. 118 | 119 | Q: Can I automatically discover all modules that are available? 120 | 121 | Yes you can. Just use the :meth:`PluginSource.list_plugins` method 122 | which returns a list of all plugins that a source can import. 123 | 124 | Q: Why would I use this over setuptools based plugins? 125 | 126 | PluginBase and setuptools based plugins solve very different problems 127 | and are incompatible on an architectural point of view. PluginBase 128 | does not solve plugin distribution through PyPI but allows plugins to 129 | be virtualized from each other. Setuptools on the other hand is based 130 | on PyPI based distribution but piggybacks on top of the regular import 131 | system. 132 | 133 | There are advantages and disadvantages to both of them. Setuptools 134 | based plugins are very useful to extend libraries from other 135 | libraries. For instance the Jinja2 template engine hooks into the 136 | Babel library for internationalization through setuptools. 137 | 138 | On the other hand applications distributed to users can benefit from a 139 | PluginBase based system which allows them to take control over how 140 | plugins are distributed and full separation from each other. 141 | 142 | 143 | API 144 | --- 145 | 146 | High Level 147 | `````````` 148 | 149 | .. autoclass:: PluginBase 150 | :members: 151 | 152 | .. autoclass:: PluginSource 153 | :members: 154 | 155 | .. autofunction:: get_plugin_source 156 | 157 | .. autofunction:: get_searchpath 158 | 159 | Import Hook Control 160 | ``````````````````` 161 | 162 | .. autofunction:: pluginbase.import_hook.enable 163 | 164 | .. autofunction:: pluginbase.import_hook.disable 165 | 166 | .. data:: pluginbase.import_hook.enabled 167 | 168 | Indicates if the import hook is currently active or not. 169 | 170 | Internals 171 | ````````` 172 | 173 | .. autodata:: pluginbase._internalspace 174 | 175 | This module is where pluginbase keeps track of all loaded plugins. 176 | Generally one can completely ignore the existence of it, but in some 177 | situations it might be useful to discover currently loaded modules 178 | through this when debugging. 179 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | if NOT "%PAPER%" == "" ( 11 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 12 | ) 13 | 14 | if "%1" == "" goto help 15 | 16 | if "%1" == "help" ( 17 | :help 18 | echo.Please use `make ^` where ^ is one of 19 | echo. html to make standalone HTML files 20 | echo. dirhtml to make HTML files named index.html in directories 21 | echo. singlehtml to make a single large HTML file 22 | echo. pickle to make pickle files 23 | echo. json to make JSON files 24 | echo. htmlhelp to make HTML files and a HTML help project 25 | echo. qthelp to make HTML files and a qthelp project 26 | echo. devhelp to make HTML files and a Devhelp project 27 | echo. epub to make an epub 28 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 29 | echo. text to make text files 30 | echo. man to make manual pages 31 | echo. changes to make an overview over all changed/added/deprecated items 32 | echo. linkcheck to check all external links for integrity 33 | echo. doctest to run all doctests embedded in the documentation if enabled 34 | goto end 35 | ) 36 | 37 | if "%1" == "clean" ( 38 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 39 | del /q /s %BUILDDIR%\* 40 | goto end 41 | ) 42 | 43 | if "%1" == "html" ( 44 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 45 | echo. 46 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 47 | goto end 48 | ) 49 | 50 | if "%1" == "dirhtml" ( 51 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 52 | echo. 53 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 54 | goto end 55 | ) 56 | 57 | if "%1" == "singlehtml" ( 58 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 59 | echo. 60 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 61 | goto end 62 | ) 63 | 64 | if "%1" == "pickle" ( 65 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 66 | echo. 67 | echo.Build finished; now you can process the pickle files. 68 | goto end 69 | ) 70 | 71 | if "%1" == "json" ( 72 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 73 | echo. 74 | echo.Build finished; now you can process the JSON files. 75 | goto end 76 | ) 77 | 78 | if "%1" == "htmlhelp" ( 79 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 80 | echo. 81 | echo.Build finished; now you can run HTML Help Workshop with the ^ 82 | .hhp project file in %BUILDDIR%/htmlhelp. 83 | goto end 84 | ) 85 | 86 | if "%1" == "qthelp" ( 87 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 88 | echo. 89 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 90 | .qhcp project file in %BUILDDIR%/qthelp, like this: 91 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Classy.qhcp 92 | echo.To view the help file: 93 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Classy.ghc 94 | goto end 95 | ) 96 | 97 | if "%1" == "devhelp" ( 98 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 99 | echo. 100 | echo.Build finished. 101 | goto end 102 | ) 103 | 104 | if "%1" == "epub" ( 105 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 106 | echo. 107 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 108 | goto end 109 | ) 110 | 111 | if "%1" == "latex" ( 112 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 113 | echo. 114 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 115 | goto end 116 | ) 117 | 118 | if "%1" == "text" ( 119 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 120 | echo. 121 | echo.Build finished. The text files are in %BUILDDIR%/text. 122 | goto end 123 | ) 124 | 125 | if "%1" == "man" ( 126 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 127 | echo. 128 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 129 | goto end 130 | ) 131 | 132 | if "%1" == "changes" ( 133 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 134 | echo. 135 | echo.The overview file is in %BUILDDIR%/changes. 136 | goto end 137 | ) 138 | 139 | if "%1" == "linkcheck" ( 140 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 141 | echo. 142 | echo.Link check complete; look for any errors in the above output ^ 143 | or in %BUILDDIR%/linkcheck/output.txt. 144 | goto end 145 | ) 146 | 147 | if "%1" == "doctest" ( 148 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 149 | echo. 150 | echo.Testing of doctests in the sources finished, look at the ^ 151 | results in %BUILDDIR%/doctest/output.txt. 152 | goto end 153 | ) 154 | 155 | :end 156 | -------------------------------------------------------------------------------- /example/README: -------------------------------------------------------------------------------- 1 | 2 | { pluginbase example } 3 | 4 | A simple example that shows how plugin systems can be 5 | built with pluginbase. 6 | 7 | How to use: 8 | 9 | 1. Make sure pluginbase is installed: 10 | 11 | pip install --editable .. 12 | 13 | 2. Run the example: 14 | 15 | python example.py 16 | 17 | -------------------------------------------------------------------------------- /example/app1/plugins/secret.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | 4 | def make_secret(s): 5 | chars = list(s) 6 | for idx, char in enumerate(chars): 7 | if char not in string.punctuation and not char.isspace(): 8 | chars[idx] = 'x' 9 | return ''.join(chars) 10 | 11 | 12 | def setup(app): 13 | app.register_formatter('secret', make_secret) 14 | -------------------------------------------------------------------------------- /example/app2/plugins/randomstr.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | 4 | 5 | def make_random(s): 6 | chars = list(s) 7 | for idx, char in enumerate(chars): 8 | if char not in string.punctuation and not char.isspace(): 9 | chars[idx] = random.choice(string.ascii_letters) 10 | return ''.join(chars) 11 | 12 | 13 | def setup(app): 14 | app.register_formatter('random', make_random) 15 | -------------------------------------------------------------------------------- /example/builtin_plugins/lowercase.py: -------------------------------------------------------------------------------- 1 | def make_lowercase(s): 2 | return s.lower() 3 | 4 | 5 | def setup(app): 6 | app.register_formatter('lowercase', make_lowercase) 7 | -------------------------------------------------------------------------------- /example/builtin_plugins/uppercase.py: -------------------------------------------------------------------------------- 1 | def make_uppercase(s): 2 | return s.upper() 3 | 4 | 5 | def setup(app): 6 | app.register_formatter('uppercase', make_uppercase) 7 | -------------------------------------------------------------------------------- /example/example.py: -------------------------------------------------------------------------------- 1 | import os 2 | from functools import partial 3 | from pluginbase import PluginBase 4 | 5 | 6 | # For easier usage calculate the path relative to here. 7 | here = os.path.abspath(os.path.dirname(__file__)) 8 | get_path = partial(os.path.join, here) 9 | 10 | 11 | # Setup a plugin base for "example.modules" and make sure to load 12 | # all the default built-in plugins from the builtin_plugins folder. 13 | plugin_base = PluginBase(package='example.plugins', 14 | searchpath=[get_path('./builtin_plugins')]) 15 | 16 | 17 | class Application(object): 18 | """Represents a simple example application.""" 19 | 20 | def __init__(self, name): 21 | # Each application has a name 22 | self.name = name 23 | 24 | # And a dictionary where it stores "formatters". These will be 25 | # functions provided by plugins which format strings. 26 | self.formatters = {} 27 | 28 | # and a source which loads the plugins from the "app_name/plugins" 29 | # folder. We also pass the application name as identifier. This 30 | # is optional but by doing this out plugins have consistent 31 | # internal module names which allows pickle to work. 32 | self.source = plugin_base.make_plugin_source( 33 | searchpath=[get_path('./%s/plugins' % name)], 34 | identifier=self.name) 35 | 36 | # Here we list all the plugins the source knows about, load them 37 | # and the use the "setup" function provided by the plugin to 38 | # initialize the plugin. 39 | for plugin_name in self.source.list_plugins(): 40 | plugin = self.source.load_plugin(plugin_name) 41 | plugin.setup(self) 42 | 43 | def register_formatter(self, name, formatter): 44 | """A function a plugin can use to register a formatter.""" 45 | self.formatters[name] = formatter 46 | 47 | 48 | def run_demo(app, source): 49 | """Shows all formatters in demo mode of an application.""" 50 | print('Formatters for %s:' % app.name) 51 | print(' input: %s' % source) 52 | for name, fmt in sorted(app.formatters.items()): 53 | print(' %10s: %s' % (name, fmt(source))) 54 | print('') 55 | 56 | 57 | def main(): 58 | # This is the demo string we want to format. 59 | source = 'This is a cool demo text to show this functionality.' 60 | 61 | # Set up two applications. One loads plugins from ./app1/plugins 62 | # and the second one from ./app2/plugins. Both will also load 63 | # the default ./builtin_plugins. 64 | app1 = Application('app1') 65 | app2 = Application('app2') 66 | 67 | # Run the demo for both 68 | run_demo(app1, source) 69 | run_demo(app2, source) 70 | 71 | # And just to show how the import system works, we also showcase 72 | # importing plugins regularly: 73 | with app1.source: 74 | from example.plugins import secret 75 | print('Plugin module: %s' % secret) 76 | 77 | 78 | if __name__ == '__main__': 79 | main() 80 | -------------------------------------------------------------------------------- /pluginbase.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pluginbase 4 | ~~~~~~~~~~ 5 | 6 | Pluginbase is a module for Python that provides a system for building 7 | plugin based applications. 8 | 9 | :copyright: (c) Copyright 2014 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | import os 13 | import sys 14 | import uuid 15 | import errno 16 | import pkgutil 17 | import hashlib 18 | import threading 19 | 20 | from types import ModuleType 21 | from weakref import ref as weakref 22 | 23 | 24 | PY2 = sys.version_info[0] == 2 25 | if PY2: 26 | text_type = unicode 27 | string_types = (unicode, str) 28 | from cStringIO import StringIO as NativeBytesIO 29 | else: 30 | text_type = str 31 | string_types = (str,) 32 | from io import BytesIO as NativeBytesIO 33 | 34 | 35 | __version__ = '1.0.1' 36 | _local = threading.local() 37 | 38 | _internalspace = ModuleType(__name__ + '._internalspace') 39 | _internalspace.__path__ = [] 40 | sys.modules[_internalspace.__name__] = _internalspace 41 | 42 | 43 | def get_plugin_source(module=None, stacklevel=None): 44 | """Returns the :class:`PluginSource` for the current module or the given 45 | module. The module can be provided by name (in which case an import 46 | will be attempted) or as a module object. 47 | 48 | If no plugin source can be discovered, the return value from this method 49 | is `None`. 50 | 51 | This function can be very useful if additional data has been attached 52 | to the plugin source. For instance this could allow plugins to get 53 | access to a back reference to the application that created them. 54 | 55 | :param module: optionally the module to locate the plugin source of. 56 | :param stacklevel: defines how many levels up the module should search 57 | for before it discovers the plugin frame. The 58 | default is 0. This can be useful for writing wrappers 59 | around this function. 60 | """ 61 | if module is None: 62 | frm = sys._getframe((stacklevel or 0) + 1) 63 | name = frm.f_globals['__name__'] 64 | glob = frm.f_globals 65 | elif isinstance(module, string_types): 66 | frm = sys._getframe(1) 67 | name = module 68 | glob = __import__(module, frm.f_globals, 69 | frm.f_locals, ['__dict__']).__dict__ 70 | else: 71 | name = module.__name__ 72 | glob = module.__dict__ 73 | return _discover_space(name, glob) 74 | 75 | 76 | def get_searchpath(path, depth=float('inf'), followlinks=False): 77 | """This utility function returns a list directories suitable for use as the 78 | *searchpath* argument to :class:`PluginSource`. This will recursively add 79 | directories up to the specified depth. 80 | 81 | :param str path: The directory on the file system to start the search path 82 | at. It will be included in the result. 83 | :param int depth: The number of directories to recurse into while building 84 | the search path. By default the function will iterate into 85 | all child directories. 86 | :param bool followlinks: Whether or not to recurse into directories which 87 | are symbolic links. 88 | :return: A list of directories, including *path* and child directories. 89 | :rtype: list 90 | """ 91 | # os.walk implements a depth-first approach which results in unnecessarily 92 | # slow execution when *path* is a large tree and *depth* is a small number 93 | paths = [path] 94 | for dir_entry in os.listdir(path): 95 | sub_path = os.path.join(path, dir_entry) 96 | if not os.path.isdir(sub_path): 97 | continue 98 | if not followlinks and os.path.islink(sub_path): 99 | continue 100 | if depth: 101 | paths.extend(get_searchpath(sub_path, depth - 1, followlinks)) 102 | return paths 103 | 104 | 105 | def _discover_space(name, globals): 106 | try: 107 | return _local.space_stack[-1] 108 | except (AttributeError, IndexError): 109 | pass 110 | 111 | if '__pluginbase_state__' in globals: 112 | return globals['__pluginbase_state__'].source 113 | 114 | mod_name = globals.get('__name__') 115 | if mod_name is not None and \ 116 | mod_name.startswith(_internalspace.__name__ + '.'): 117 | end = mod_name.find('.', len(_internalspace.__name__) + 1) 118 | space = sys.modules.get(mod_name[:end]) 119 | if space is not None: 120 | return space.__pluginbase_state__.source 121 | 122 | 123 | def _shutdown_module(mod): 124 | members = list(mod.__dict__.items()) 125 | for key, value in members: 126 | if key[:1] != '_': 127 | setattr(mod, key, None) 128 | for key, value in members: 129 | setattr(mod, key, None) 130 | 131 | 132 | def _to_bytes(s): 133 | if isinstance(s, text_type): 134 | return s.encode('utf-8') 135 | return s 136 | 137 | 138 | class _IntentionallyEmptyModule(ModuleType): 139 | 140 | def __getattr__(self, name): 141 | try: 142 | return ModuleType.__getattr__(self, name) 143 | except AttributeError: 144 | if name[:2] == '__': 145 | raise 146 | raise RuntimeError( 147 | 'Attempted to import from a plugin base module (%s) without ' 148 | 'having a plugin source activated. To solve this error ' 149 | 'you have to move the import into a "with" block of the ' 150 | 'associated plugin source.' % self.__name__) 151 | 152 | 153 | class _PluginSourceModule(ModuleType): 154 | 155 | def __init__(self, source): 156 | modname = '%s.%s' % (_internalspace.__name__, source.spaceid) 157 | ModuleType.__init__(self, modname) 158 | self.__pluginbase_state__ = PluginBaseState(source) 159 | 160 | @property 161 | def __path__(self): 162 | try: 163 | ps = self.__pluginbase_state__.source 164 | except AttributeError: 165 | return [] 166 | return ps.searchpath + ps.base.searchpath 167 | 168 | 169 | def _setup_base_package(module_name): 170 | try: 171 | mod = __import__(module_name, None, None, ['__name__']) 172 | except ImportError: 173 | mod = None 174 | if '.' in module_name: 175 | parent_mod = __import__(module_name.rsplit('.', 1)[0], 176 | None, None, ['__name__']) 177 | else: 178 | parent_mod = None 179 | 180 | if mod is None: 181 | mod = _IntentionallyEmptyModule(module_name) 182 | if parent_mod is not None: 183 | setattr(parent_mod, module_name.rsplit('.', 1)[-1], mod) 184 | sys.modules[module_name] = mod 185 | 186 | 187 | class PluginBase(object): 188 | """The plugin base acts as a control object around a dummy Python 189 | package that acts as a container for plugins. Usually each 190 | application creates exactly one base object for all plugins. 191 | 192 | :param package: the name of the package that acts as the plugin base. 193 | Usually this module does not exist. Unless you know 194 | what you are doing you should not create this module 195 | on the file system. 196 | :param searchpath: optionally a shared search path for modules that 197 | will be used by all plugin sources registered. 198 | """ 199 | 200 | def __init__(self, package, searchpath=None): 201 | #: the name of the dummy package. 202 | self.package = package 203 | if searchpath is None: 204 | searchpath = [] 205 | #: the default search path shared by all plugins as list. 206 | self.searchpath = searchpath 207 | _setup_base_package(package) 208 | 209 | def make_plugin_source(self, *args, **kwargs): 210 | """Creates a plugin source for this plugin base and returns it. 211 | All parameters are forwarded to :class:`PluginSource`. 212 | """ 213 | return PluginSource(self, *args, **kwargs) 214 | 215 | 216 | class PluginSource(object): 217 | """The plugin source is what ultimately decides where plugins are 218 | loaded from. Plugin bases can have multiple plugin sources which act 219 | as isolation layer. While this is not a security system it generally 220 | is not possible for plugins from different sources to accidentally 221 | cross talk. 222 | 223 | Once a plugin source has been created it can be used in a ``with`` 224 | statement to change the behavior of the ``import`` statement in the 225 | block to define which source to load the plugins from:: 226 | 227 | plugin_source = plugin_base.make_plugin_source( 228 | searchpath=['./path/to/plugins', './path/to/more/plugins']) 229 | 230 | with plugin_source: 231 | from myapplication.plugins import my_plugin 232 | 233 | :param base: the base this plugin source belongs to. 234 | :param identifier: optionally a stable identifier. If it's not defined 235 | a random identifier is picked. It's useful to set this 236 | to a stable value to have consistent tracebacks 237 | between restarts and to support pickle. 238 | :param searchpath: a list of paths where plugins are looked for. 239 | :param persist: optionally this can be set to `True` and the plugins 240 | will not be cleaned up when the plugin source gets 241 | garbage collected. 242 | """ 243 | # Set these here to false by default so that a completely failing 244 | # constructor does not fuck up the destructor. 245 | persist = False 246 | mod = None 247 | 248 | def __init__(self, base, identifier=None, searchpath=None, 249 | persist=False): 250 | #: indicates if this plugin source persists or not. 251 | self.persist = persist 252 | if identifier is None: 253 | identifier = str(uuid.uuid4()) 254 | #: the identifier for this source. 255 | self.identifier = identifier 256 | #: A reference to the plugin base that created this source. 257 | self.base = base 258 | #: a list of paths where plugins are searched in. 259 | self.searchpath = searchpath 260 | #: The internal module name of the plugin source as it appears 261 | #: in the :mod:`pluginsource._internalspace`. 262 | self.spaceid = '_sp' + hashlib.md5( 263 | _to_bytes(self.base.package) + b'|' + 264 | _to_bytes(identifier), 265 | ).hexdigest() 266 | #: a reference to the module on the internal 267 | #: :mod:`pluginsource._internalspace`. 268 | self.mod = _PluginSourceModule(self) 269 | 270 | if hasattr(_internalspace, self.spaceid): 271 | raise RuntimeError('This plugin source already exists.') 272 | sys.modules[self.mod.__name__] = self.mod 273 | setattr(_internalspace, self.spaceid, self.mod) 274 | 275 | def __del__(self): 276 | if not self.persist: 277 | self.cleanup() 278 | 279 | def list_plugins(self): 280 | """Returns a sorted list of all plugins that are available in this 281 | plugin source. This can be useful to automatically discover plugins 282 | that are available and is usually used together with 283 | :meth:`load_plugin`. 284 | """ 285 | rv = [] 286 | for _, modname, ispkg in pkgutil.iter_modules(self.mod.__path__): 287 | rv.append(modname) 288 | return sorted(rv) 289 | 290 | def load_plugin(self, name): 291 | """This automatically loads a plugin by the given name from the 292 | current source and returns the module. This is a convenient 293 | alternative to the import statement and saves you from invoking 294 | ``__import__`` or a similar function yourself. 295 | 296 | :param name: the name of the plugin to load. 297 | """ 298 | if '.' in name: 299 | raise ImportError('Plugin names cannot contain dots.') 300 | with self: 301 | return __import__(self.base.package + '.' + name, 302 | globals(), {}, ['__name__']) 303 | 304 | def open_resource(self, plugin, filename): 305 | """This function locates a resource inside the plugin and returns 306 | a byte stream to the contents of it. If the resource cannot be 307 | loaded an :exc:`IOError` will be raised. Only plugins that are 308 | real Python packages can contain resources. Plain old Python 309 | modules do not allow this for obvious reasons. 310 | 311 | .. versionadded:: 0.3 312 | 313 | :param plugin: the name of the plugin to open the resource of. 314 | :param filename: the name of the file within the plugin to open. 315 | """ 316 | mod = self.load_plugin(plugin) 317 | fn = getattr(mod, '__file__', None) 318 | if fn is not None: 319 | if fn.endswith(('.pyc', '.pyo')): 320 | fn = fn[:-1] 321 | if os.path.isfile(fn): 322 | return open(os.path.join(os.path.dirname(fn), filename), 'rb') 323 | buf = pkgutil.get_data(self.mod.__name__ + '.' + plugin, filename) 324 | if buf is None: 325 | raise IOError(errno.ENOENT, 'Could not find resource') 326 | return NativeBytesIO(buf) 327 | 328 | def cleanup(self): 329 | """Cleans up all loaded plugins manually. This is necessary to 330 | call only if :attr:`persist` is enabled. Otherwise this happens 331 | automatically when the source gets garbage collected. 332 | """ 333 | self.__cleanup() 334 | 335 | def __cleanup(self, _sys=sys, _shutdown_module=_shutdown_module): 336 | # The default parameters are necessary because this can be fired 337 | # from the destructor and so late when the interpreter shuts down 338 | # that these functions and modules might be gone. 339 | if self.mod is None or self.mod.__name__ is None: 340 | return 341 | modname = self.mod.__name__ 342 | self.mod.__pluginbase_state__ = None 343 | self.mod = None 344 | try: 345 | delattr(_internalspace, self.spaceid) 346 | except AttributeError: 347 | pass 348 | prefix = modname + '.' 349 | # avoid the bug described in issue #6 350 | if modname in _sys.modules: 351 | del _sys.modules[modname] 352 | for key, value in list(_sys.modules.items()): 353 | if not key.startswith(prefix): 354 | continue 355 | mod = _sys.modules.pop(key, None) 356 | if mod is None: 357 | continue 358 | _shutdown_module(mod) 359 | 360 | def __assert_not_cleaned_up(self): 361 | if self.mod is None: 362 | raise RuntimeError('The plugin source was already cleaned up.') 363 | 364 | def __enter__(self): 365 | self.__assert_not_cleaned_up() 366 | _local.__dict__.setdefault('space_stack', []).append(self) 367 | return self 368 | 369 | def __exit__(self, exc_type, exc_value, tb): 370 | try: 371 | _local.space_stack.pop() 372 | except (AttributeError, IndexError): 373 | pass 374 | 375 | def _rewrite_module_path(self, modname): 376 | self.__assert_not_cleaned_up() 377 | if modname == self.base.package: 378 | return self.mod.__name__ 379 | elif modname.startswith(self.base.package + '.'): 380 | pieces = modname.split('.') 381 | return self.mod.__name__ + '.' + '.'.join( 382 | pieces[self.base.package.count('.') + 1:]) 383 | 384 | 385 | class PluginBaseState(object): 386 | __slots__ = ('_source',) 387 | 388 | def __init__(self, source): 389 | if source.persist: 390 | self._source = lambda: source 391 | else: 392 | self._source = weakref(source) 393 | 394 | @property 395 | def source(self): 396 | rv = self._source() 397 | if rv is None: 398 | raise AttributeError('Plugin source went away') 399 | return rv 400 | 401 | 402 | class _ImportHook(ModuleType): 403 | 404 | def __init__(self, name, system_import): 405 | ModuleType.__init__(self, name) 406 | self._system_import = system_import 407 | self.enabled = True 408 | 409 | def enable(self): 410 | """Enables the import hook which drives the plugin base system. 411 | This is the default. 412 | """ 413 | self.enabled = True 414 | 415 | def disable(self): 416 | """Disables the import hook and restores the default import system 417 | behavior. This effectively breaks pluginbase but can be useful 418 | for testing purposes. 419 | """ 420 | self.enabled = False 421 | 422 | def plugin_import(self, name, globals=None, locals=None, 423 | fromlist=None, level=None): 424 | if level is None: 425 | # set the level to the default value specific to this python version 426 | level = -1 if PY2 else 0 427 | import_name = name 428 | if self.enabled: 429 | ref_globals = globals 430 | if ref_globals is None: 431 | ref_globals = sys._getframe(1).f_globals 432 | space = _discover_space(name, ref_globals) 433 | if space is not None: 434 | actual_name = space._rewrite_module_path(name) 435 | if actual_name is not None: 436 | import_name = actual_name 437 | 438 | return self._system_import(import_name, globals, locals, 439 | fromlist, level) 440 | 441 | 442 | try: 443 | import __builtin__ as builtins 444 | except ImportError: 445 | import builtins 446 | import_hook = _ImportHook(__name__ + '.import_hook', builtins.__import__) 447 | builtins.__import__ = import_hook.plugin_import 448 | sys.modules[import_hook.__name__] = import_hook 449 | del builtins 450 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import sys 4 | 5 | base_directory = os.path.dirname(__file__) 6 | 7 | try: 8 | from setuptools import setup, find_packages 9 | except ImportError: 10 | print('This project needs setuptools in order to build. Install it using your package') 11 | print('manager (usually python-setuptools) or via pip (pip install setuptools).') 12 | sys.exit(1) 13 | 14 | try: 15 | with open(os.path.join(base_directory, 'README.rst')) as file_h: 16 | long_description = file_h.read() 17 | except OSError: 18 | sys.stderr.write('README.rst is unavailable, can not generate the long description\n') 19 | long_description = None 20 | 21 | with open(os.path.join(base_directory, 'pluginbase.py')) as file_h: 22 | match = re.search(r'^__version__\s*=\s*([\'"])(?P\d+(\.\d)*)\1$', file_h.read(), flags=re.MULTILINE) 23 | if match is None: 24 | raise RuntimeError('Unable to find the version information') 25 | version = match.group('version') 26 | 27 | DESCRIPTION = """\ 28 | PluginBase is a module for Python that enables the development of flexible \ 29 | plugin systems in Python.\ 30 | """ 31 | 32 | setup( 33 | name='pluginbase', 34 | author='Armin Ronacher', 35 | author_email='armin.ronacher@active-4.com', 36 | maintainer='Spencer McIntyre', 37 | maintainer_email='zeroSteiner@gmail.com', 38 | version=version, 39 | description=DESCRIPTION, 40 | long_description=long_description, 41 | url='http://github.com/mitsuhiko/pluginbase', 42 | py_modules=['pluginbase'], 43 | zip_safe=False, 44 | classifiers=[ 45 | 'Development Status :: 5 - Production/Stable', 46 | 'Environment :: Plugins', 47 | 'Intended Audience :: Developers', 48 | 'License :: OSI Approved :: BSD License', 49 | 'Operating System :: OS Independent', 50 | 'Programming Language :: Python', 51 | 'Programming Language :: Python :: 2.7', 52 | 'Programming Language :: Python :: 3', 53 | 'Programming Language :: Python :: 3.4', 54 | 'Programming Language :: Python :: 3.5', 55 | 'Programming Language :: Python :: 3.6', 56 | 'Programming Language :: Python :: 3.7', 57 | 'Programming Language :: Python :: 3.8', 58 | 'Programming Language :: Python :: 3.9', 59 | 'Programming Language :: Python :: Implementation :: PyPy', 60 | 'Topic :: Software Development :: Libraries :: Python Modules' 61 | ] 62 | ) 63 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import gc 2 | import pytest 3 | 4 | from pluginbase import PluginBase 5 | 6 | 7 | @pytest.fixture(scope='function') 8 | def base(): 9 | return PluginBase(package='dummy.plugins') 10 | 11 | 12 | @pytest.fixture(scope='function') 13 | def dummy_internal_name(): 14 | return 'pluginbase._internalspace._sp7bb7d8da1d24ae5a5205609c951b8be4' 15 | 16 | 17 | @pytest.fixture(scope='function') 18 | def source(base): 19 | return base.make_plugin_source(searchpath=['./plugins'], 20 | identifier='demo') 21 | 22 | 23 | @pytest.fixture(scope='function', autouse=True) 24 | def run_garbage_collection(): 25 | gc.collect() 26 | try: 27 | yield 28 | finally: 29 | gc.collect() 30 | -------------------------------------------------------------------------------- /tests/dummy.py: -------------------------------------------------------------------------------- 1 | # make sure there is a module we can base our modules against. 2 | -------------------------------------------------------------------------------- /tests/plugins/advanced.py: -------------------------------------------------------------------------------- 1 | from pluginbase import get_plugin_source 2 | 3 | 4 | def get_app(): 5 | rv = get_plugin_source(stacklevel=1) 6 | if rv is not None: 7 | return rv.app 8 | 9 | 10 | def get_app_name(): 11 | return get_app().name 12 | -------------------------------------------------------------------------------- /tests/plugins/hello.py: -------------------------------------------------------------------------------- 1 | def import_self(): 2 | from dummy.plugins import hello 3 | return hello 4 | 5 | 6 | def get_plugin_source(): 7 | from pluginbase import get_plugin_source 8 | return get_plugin_source() 9 | 10 | 11 | def demo_func(): 12 | return 42 13 | -------------------------------------------------------------------------------- /tests/plugins/hello2.py: -------------------------------------------------------------------------------- 1 | def awesome_stuff(): 2 | pass 3 | -------------------------------------------------------------------------------- /tests/plugins/withresources/__init__.py: -------------------------------------------------------------------------------- 1 | def foo(): 2 | pass 3 | -------------------------------------------------------------------------------- /tests/plugins/withresources/hello.txt: -------------------------------------------------------------------------------- 1 | I am a textfile. 2 | -------------------------------------------------------------------------------- /tests/shutdown.py: -------------------------------------------------------------------------------- 1 | from pluginbase import PluginBase 2 | 3 | base = PluginBase(package='dummy.modules') 4 | plugin_source = base.make_plugin_source( 5 | searchpath=['./plugins']) 6 | 7 | # This dangles around. This will be collected when the interpreter 8 | # shuts down. 9 | hello = plugin_source.load_plugin('hello') 10 | -------------------------------------------------------------------------------- /tests/test_advanced.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | def test_custom_state(base): 5 | class App(object): 6 | name = 'foobar' 7 | source = base.make_plugin_source(searchpath=['./plugins']) 8 | source.app = App() 9 | 10 | plg = source.load_plugin('advanced') 11 | assert plg.get_app_name() == 'foobar' 12 | 13 | 14 | def test_plugin_resources(source): 15 | with source.open_resource('withresources', 'hello.txt') as f: 16 | contents = f.read() 17 | assert contents == b'I am a textfile.\n' 18 | 19 | with pytest.raises(IOError): 20 | source.open_resource('withresources', 'missingfile.txt') 21 | -------------------------------------------------------------------------------- /tests/test_basics.py: -------------------------------------------------------------------------------- 1 | import gc 2 | import sys 3 | 4 | from pluginbase import get_plugin_source 5 | 6 | 7 | def test_basic_plugin(source, dummy_internal_name): 8 | # When the source is active the import gives us a module 9 | with source: 10 | from dummy.plugins import hello 11 | 12 | # Which because of a stable identifier has a predictable name. 13 | assert hello.__name__ == dummy_internal_name + '.hello' 14 | 15 | # And can continue to import from itself. 16 | assert hello.import_self() is hello 17 | 18 | # On the other hand without a source will fall flat on the floor. 19 | try: 20 | from dummy.plugins import hello 21 | except RuntimeError: 22 | pass 23 | else: 24 | assert False, 'Expected a runtime error but managed to ' \ 25 | 'import hello (%s)' % hello 26 | 27 | 28 | def test_fetching_plugin_source(source): 29 | # Finding the plugin source outside of a plugin and without a with 30 | # block of a plugin source returns None. 31 | assert get_plugin_source() is None 32 | 33 | # Inside a source block we can find the source through mere calling. 34 | with source: 35 | assert get_plugin_source() is source 36 | 37 | # A module can always find its own source as well (the hello module 38 | # calls get_plugin_source() itself). 39 | with source: 40 | from dummy.plugins import hello 41 | assert hello.get_plugin_source() is source 42 | 43 | # Last but not least the plugin source can be found by module names 44 | # (in a plugin source block by the import name and in any case by 45 | # the internal name) 46 | with source: 47 | assert get_plugin_source('dummy.plugins.hello') is source 48 | assert get_plugin_source(hello.__name__) is source 49 | 50 | # As well as by module object. 51 | assert get_plugin_source(hello) is source 52 | 53 | 54 | def test_cleanup(base): 55 | new_source = base.make_plugin_source(searchpath=['./plugins']) 56 | mod_name = new_source.mod.__name__ 57 | assert sys.modules.get(mod_name) is new_source.mod 58 | 59 | with new_source: 60 | from dummy.plugins import hello 61 | 62 | new_source = None 63 | gc.collect() 64 | assert sys.modules.get(mod_name) is None 65 | assert hello.import_self is None 66 | 67 | 68 | def test_persist(base): 69 | new_source = base.make_plugin_source(searchpath=['./plugins'], 70 | persist=True) 71 | mod_name = new_source.mod.__name__ 72 | assert sys.modules.get(mod_name) is new_source.mod 73 | 74 | with new_source: 75 | from dummy.plugins import hello 76 | 77 | new_source = None 78 | assert sys.modules.get(mod_name) is not None 79 | assert hello.import_self is not None 80 | sys.modules[mod_name].__pluginbase_state__.source.cleanup() 81 | assert sys.modules.get(mod_name) is None 82 | assert hello.import_self is None 83 | 84 | 85 | def test_list_plugins(source): 86 | plugins = source.list_plugins() 87 | hello_plugins = [x for x in plugins if x.startswith('hello')] 88 | assert hello_plugins == ['hello', 'hello2'] 89 | 90 | 91 | def test_load_plugin(source): 92 | hello = source.load_plugin('hello') 93 | assert hello.demo_func() == 42 94 | -------------------------------------------------------------------------------- /tests/test_shutdown.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import subprocess 4 | 5 | 6 | def test_clean_shutdown(): 7 | env = dict(os.environ) 8 | env['PYTHONPATH'] = '..:.' 9 | c = subprocess.Popen([sys.executable, '-c', 'import shutdown'], 10 | stdout=subprocess.PIPE, 11 | stderr=subprocess.PIPE, 12 | env=env) 13 | stdout, stderr = c.communicate() 14 | assert stdout == b'' 15 | assert stderr == b'' 16 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27,py34,py35,py36,py37,py38,py39,pypy 3 | 4 | [testenv] 5 | commands = make test 6 | deps = 7 | whitelist_externals = make 8 | --------------------------------------------------------------------------------