Debian Codegraph @

docs/writing_plugins.rst

raw
1 .. _writing_plugins:
2
3 Writing plugins
4 ===============
5
6 You can write one-off plugins that apply to just one Datasette instance, or you can write plugins which can be installed using ``pip`` and can be shipped to the Python Package Index (`PyPI <https://pypi.org/>`__) for other people to install.
7
8 Want to start by looking at an example? The `Datasette plugins directory <https://datasette.io/plugins>`__ lists more than 90 open source plugins with code you can explore. The :ref:`plugin hooks <plugin_hooks>` page includes links to example plugins for each of the documented hooks.
9
10 .. _writing_plugins_one_off:
11
12 Writing one-off plugins
13 -----------------------
14
15 The quickest way to start writing a plugin is to create a ``my_plugin.py`` file and drop it into your ``plugins/`` directory. Here is an example plugin, which adds a new custom SQL function called ``hello_world()`` which takes no arguments and returns the string ``Hello world!``.
16
17 .. code-block:: python
18
19 from datasette import hookimpl
20
21
22 @hookimpl
23 def prepare_connection(conn):
24 conn.create_function(
25 "hello_world", 0, lambda: "Hello world!"
26 )
27
28 If you save this in ``plugins/my_plugin.py`` you can then start Datasette like this::
29
30 datasette serve mydb.db --plugins-dir=plugins/
31
32 Now you can navigate to http://localhost:8001/mydb and run this SQL::
33
34 select hello_world();
35
36 To see the output of your plugin.
37
38 .. _writing_plugins_cookiecutter:
39
40 Starting an installable plugin using cookiecutter
41 -------------------------------------------------
42
43 Plugins that can be installed should be written as Python packages using a ``setup.py`` file.
44
45 The quickest way to start writing one an installable plugin is to use the `datasette-plugin <https://github.com/simonw/datasette-plugin>`__ cookiecutter template. This creates a new plugin structure for you complete with an example test and GitHub Actions workflows for testing and publishing your plugin.
46
47 `Install cookiecutter <https://cookiecutter.readthedocs.io/en/stable/installation.html>`__ and then run this command to start building a plugin using the template::
48
49 cookiecutter gh:simonw/datasette-plugin
50
51 Read `a cookiecutter template for writing Datasette plugins <https://simonwillison.net/2020/Jun/20/cookiecutter-plugins/>`__ for more information about this template.
52
53 .. _writing_plugins_packaging:
54
55 Packaging a plugin
56 ------------------
57
58 Plugins can be packaged using Python setuptools. You can see an example of a packaged plugin at https://github.com/simonw/datasette-plugin-demos
59
60 The example consists of two files: a ``setup.py`` file that defines the plugin:
61
62 .. code-block:: python
63
64 from setuptools import setup
65
66 VERSION = "0.1"
67
68 setup(
69 name="datasette-plugin-demos",
70 description="Examples of plugins for Datasette",
71 author="Simon Willison",
72 url="https://github.com/simonw/datasette-plugin-demos",
73 license="Apache License, Version 2.0",
74 version=VERSION,
75 py_modules=["datasette_plugin_demos"],
76 entry_points={
77 "datasette": [
78 "plugin_demos = datasette_plugin_demos"
79 ]
80 },
81 install_requires=["datasette"],
82 )
83
84 And a Python module file, ``datasette_plugin_demos.py``, that implements the plugin:
85
86 .. code-block:: python
87
88 from datasette import hookimpl
89 import random
90
91
92 @hookimpl
93 def prepare_jinja2_environment(env):
94 env.filters["uppercase"] = lambda u: u.upper()
95
96
97 @hookimpl
98 def prepare_connection(conn):
99 conn.create_function(
100 "random_integer", 2, random.randint
101 )
102
103
104 Having built a plugin in this way you can turn it into an installable package using the following command::
105
106 python3 setup.py sdist
107
108 This will create a ``.tar.gz`` file in the ``dist/`` directory.
109
110 You can then install your new plugin into a Datasette virtual environment or Docker container using ``pip``::
111
112 pip install datasette-plugin-demos-0.1.tar.gz
113
114 To learn how to upload your plugin to `PyPI <https://pypi.org/>`_ for use by other people, read the PyPA guide to `Packaging and distributing projects <https://packaging.python.org/tutorials/distributing-packages/>`_.
115
116 .. _writing_plugins_static_assets:
117
118 Static assets
119 -------------
120
121 If your plugin has a ``static/`` directory, Datasette will automatically configure itself to serve those static assets from the following path::
122
123 /-/static-plugins/NAME_OF_PLUGIN_PACKAGE/yourfile.js
124
125 Use the ``datasette.urls.static_plugins(plugin_name, path)`` method to generate URLs to that asset that take the ``base_url`` setting into account, see :ref:`internals_datasette_urls`.
126
127 To bundle the static assets for a plugin in the package that you publish to PyPI, add the following to the plugin's ``setup.py``:
128
129 .. code-block:: python
130
131 package_data = (
132 {
133 "datasette_plugin_name": [
134 "static/plugin.js",
135 ],
136 },
137 )
138
139 Where ``datasette_plugin_name`` is the name of the plugin package (note that it uses underscores, not hyphens) and ``static/plugin.js`` is the path within that package to the static file.
140
141 `datasette-cluster-map <https://github.com/simonw/datasette-cluster-map>`__ is a useful example of a plugin that includes packaged static assets in this way.
142
143 .. _writing_plugins_custom_templates:
144
145 Custom templates
146 ----------------
147
148 If your plugin has a ``templates/`` directory, Datasette will attempt to load templates from that directory before it uses its own default templates.
149
150 The priority order for template loading is:
151
152 * templates from the ``--template-dir`` argument, if specified
153 * templates from the ``templates/`` directory in any installed plugins
154 * default templates that ship with Datasette
155
156 See :ref:`customization` for more details on how to write custom templates, including which filenames to use to customize which parts of the Datasette UI.
157
158 Templates should be bundled for distribution using the same ``package_data`` mechanism in ``setup.py`` described for static assets above, for example:
159
160 .. code-block:: python
161
162 package_data = (
163 {
164 "datasette_plugin_name": [
165 "templates/my_template.html",
166 ],
167 },
168 )
169
170 You can also use wildcards here such as ``templates/*.html``. See `datasette-edit-schema <https://github.com/simonw/datasette-edit-schema>`__ for an example of this pattern.
171
172 .. _writing_plugins_configuration:
173
174 Writing plugins that accept configuration
175 -----------------------------------------
176
177 When you are writing plugins, you can access plugin configuration like this using the ``datasette plugin_config()`` method. If you know you need plugin configuration for a specific table, you can access it like this::
178
179 plugin_config = datasette.plugin_config(
180 "datasette-cluster-map", database="sf-trees", table="Street_Tree_List"
181 )
182
183 This will return the ``{"latitude_column": "lat", "longitude_column": "lng"}`` in the above example.
184
185 If there is no configuration for that plugin, the method will return ``None``.
186
187 If it cannot find the requested configuration at the table layer, it will fall back to the database layer and then the root layer. For example, a user may have set the plugin configuration option like so::
188
189 {
190 "databases: {
191 "sf-trees": {
192 "plugins": {
193 "datasette-cluster-map": {
194 "latitude_column": "xlat",
195 "longitude_column": "xlng"
196 }
197 }
198 }
199 }
200 }
201
202 In this case, the above code would return that configuration for ANY table within the ``sf-trees`` database.
203
204 The plugin configuration could also be set at the top level of ``metadata.json``::
205
206 {
207 "title": "This is the top-level title in metadata.json",
208 "plugins": {
209 "datasette-cluster-map": {
210 "latitude_column": "xlat",
211 "longitude_column": "xlng"
212 }
213 }
214 }
215
216 Now that ``datasette-cluster-map`` plugin configuration will apply to every table in every database.
217
218 .. _writing_plugins_designing_urls:
219
220 Designing URLs for your plugin
221 ------------------------------
222
223 You can register new URL routes within Datasette using the :ref:`plugin_register_routes` plugin hook.
224
225 Datasette's default URLs include these:
226
227 - ``/dbname`` - database page
228 - ``/dbname/tablename`` - table page
229 - ``/dbname/tablename/pk`` - row page
230
231 See :ref:`pages` and :ref:`introspection` for more default URL routes.
232
233 To avoid accidentally conflicting with a database file that may be loaded into Datasette, plugins should register URLs using a ``/-/`` prefix. For example, if your plugin adds a new interface for uploading Excel files you might register a URL route like this one:
234
235 - ``/-/upload-excel``
236
237 Try to avoid registering URLs that clash with other plugins that your users might have installed. There is no central repository of reserved URL paths (yet) but you can review existing plugins by browsing the `plugins directory <https://datasette.io/plugins>`.
238
239 If your plugin includes functionality that relates to a specific database you could also register a URL route like this:
240
241 - ``/dbname/-/upload-excel``
242
243 Or for a specific table like this:
244
245 - ``/dbname/tablename/-/modify-table-schema``
246
247 Note that a row could have a primary key of ``-`` and this URL scheme will still work, because Datasette row pages do not ever have a trailing slash followed by additional path components.
248
249 .. _writing_plugins_building_urls:
250
251 Building URLs within plugins
252 ----------------------------
253
254 Plugins that define their own custom user interface elements may need to link to other pages within Datasette.
255
256 This can be a bit tricky if the Datasette instance is using the :ref:`setting_base_url` configuration setting to run behind a proxy, since that can cause Datasette's URLs to include an additional prefix.
257
258 The ``datasette.urls`` object provides internal methods for correctly generating URLs to different pages within Datasette, taking any ``base_url`` configuration into account.
259
260 This object is exposed in templates as the ``urls`` variable, which can be used like this:
261
262 .. code-block:: jinja
263
264 Back to the <a href="{{ urls.instance() }}">Homepage</a>
265
266 See :ref:`internals_datasette_urls` for full details on this object.