Skip to content

Commit 721b352

Browse files
authored
Merge pull request #95 from labthings/docs_improvements
Docs improvements
2 parents 6c176c1 + eba356c commit 721b352

File tree

13 files changed

+268
-89
lines changed

13 files changed

+268
-89
lines changed

.github/workflows/test.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,10 @@ jobs:
9797
if: success() || failure()
9898
run: pytest --cov=src --cov-report=lcov
9999

100+
- name: Check quickstart, including installation
101+
if: success() || failure()
102+
run: bash ./docs/source/quickstart/test_quickstart_example.sh
103+
100104
coverage:
101105
runs-on: ubuntu-latest
102106
needs: [base_coverage, test]

docs/source/dependencies.rst

Lines changed: 0 additions & 30 deletions
This file was deleted.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
2+
Dependencies
3+
============
4+
5+
Simple actions depend only on their input parameters and the :class:`~labthings_fastapi.thing.Thing` on which they are defined. However, it's quite common to need something else, for example accessing another :class:`~labthings_fastapi.thing.Thing` instance on the same LabThings server. There are two important principles to bear in mind here:
6+
7+
* Other :class:`~labthings_fastapi.thing.Thing` instances should be accessed using a :class:`~labthings_fastapi.client.in_server.DirectThingClient` subclass if possible. This creates a wrapper object that should work like a :class:`~labthings_fastapi.client.ThingClient`, meaning your code should work either on the server or in a client script. This makes the code much easier to debug.
8+
* LabThings uses the FastAPI "dependency injection" mechanism, where you specify what's needed with type hints, and the argument is supplied automatically at run-time. You can see the `FastAPI documentation`_ for more information.
9+
10+
LabThings provides a shortcut to create the annotated type needed to declare a dependency on another :class:`~labthings_fastapi.thing.Thing`, with the function :func:`~labthings_fastapi.dependencies.thing.direct_thing_client_dependency`. This generates a type annotation that you can use when you define your actions, that will supply a client object when the action is called.
11+
12+
:func:`~labthings_fastapi.dependencies.thing.direct_thing_client_dependency` takes a :func:`~labthings_fastapi.thing.Thing` class and a path as arguments: these should match the configuration of your LabThings server. Optionally, you can specify the actions that you're going to use. The default behaviour is to make all actions available, however it is more efficient to specify only the actions you will use.
13+
14+
Dependencies are added recursively - so if you depend on another Thing, and some of its actions have their own dependencies, those dependencies are also added to your action. Using the ``actions`` argument means you only need the dependencies of the actions you are going to use, which is more efficient.
15+
16+
.. literalinclude:: example.py
17+
:language: python
18+
19+
In the example above, the :func:`increment_counter` action on :class:`TestThing` takes a :class:`MyThing` as an argument. When the action is called, the ``my_thing`` argument is supplied automatically. The argument is not the :class:`MyThing` instance, instead it is a wrapper class (a dynamically generated :class:`~labthings_fastapi.client.in_server.DirectThingClient` subclass). The wrapper should have the same signature as a :class:`~labthings_fastapi.client.ThingClient`. This means any dependencies of actions on the :class:`MyThing` are automatically supplied, so you only need to worry about the arguments that are not dependencies. The aim of this is to ensure that the code you write for your :class:`Thing` is as similar as possible to the code you'd write if you were using it through the Python client module.
20+
21+
If you need access to the actual Python object (e.g. you need to access methods that are not decorated as actions), you can use the :func:`~labthings_fastapi.dependencies.raw_thing.raw_thing_dependency` function instead. This will give you the actual Python object, but you will need to supply all the arguments of the actions, including dependencies, yourself.
22+
23+
.. _`FastAPI documentation`: https://fastapi.tiangolo.com/tutorial/dependencies/

docs/source/dependencies/example.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from labthings_fastapi.thing import Thing
2+
from labthings_fastapi.decorators import thing_action
3+
from labthings_fastapi.dependencies.thing import direct_thing_client_dependency
4+
from labthings_fastapi.example_things import MyThing
5+
from labthings_fastapi.server import ThingServer
6+
7+
MyThingDep = direct_thing_client_dependency(MyThing, "/mything/")
8+
9+
10+
class TestThing(Thing):
11+
"""A test thing with a counter property and a couple of actions"""
12+
13+
@thing_action
14+
def increment_counter(self, my_thing: MyThingDep) -> None:
15+
"""Increment the counter on another thing"""
16+
my_thing.increment_counter()
17+
18+
19+
server = ThingServer()
20+
server.add_thing(MyThing(), "/mything/")
21+
server.add_thing(TestThing(), "/testthing/")
22+
23+
if __name__ == "__main__":
24+
import uvicorn
25+
26+
uvicorn.run(server.app, port=5000)

docs/source/index.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ Welcome to labthings-fastapi's documentation!
1111
:caption: Contents:
1212

1313
core_concepts.rst
14-
quickstart.rst
15-
dependencies.rst
14+
quickstart/quickstart.rst
15+
dependencies/dependencies.rst
1616

1717
apidocs/index
1818

docs/source/quickstart.rst

Lines changed: 0 additions & 57 deletions
This file was deleted.

docs/source/quickstart/counter.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import time
2+
from labthings_fastapi.thing import Thing
3+
from labthings_fastapi.decorators import thing_action
4+
from labthings_fastapi.descriptors import PropertyDescriptor
5+
6+
7+
class TestThing(Thing):
8+
"""A test thing with a counter property and a couple of actions"""
9+
10+
@thing_action
11+
def increment_counter(self) -> None:
12+
"""Increment the counter property
13+
14+
This action doesn't do very much - all it does, in fact,
15+
is increment the counter (which may be read using the
16+
`counter` property).
17+
"""
18+
self.counter += 1
19+
20+
@thing_action
21+
def slowly_increase_counter(self) -> None:
22+
"""Increment the counter slowly over a minute"""
23+
for i in range(60):
24+
time.sleep(1)
25+
self.increment_counter()
26+
27+
counter = PropertyDescriptor(
28+
model=int, initial_value=0, readonly=True, description="A pointless counter"
29+
)
30+
31+
32+
if __name__ == "__main__":
33+
from labthings_fastapi.server import ThingServer
34+
import uvicorn
35+
36+
server = ThingServer()
37+
38+
# The line below creates a TestThing instance and adds it to the server
39+
server.add_thing(TestThing(), "/counter/")
40+
41+
# We run the server using `uvicorn`:
42+
uvicorn.run(server.app, port=5000)
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from labthings_fastapi.client import ThingClient
2+
3+
counter = ThingClient.from_url("http://localhost:5000/counter/")
4+
5+
v = counter.counter
6+
print(f"The counter value was {v}")
7+
8+
counter.increment_counter()
9+
10+
v = counter.counter
11+
print(f"After incrementing, the counter value was {v}")
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"things": {
3+
"example": "labthings_fastapi.example_things:MyThing"
4+
}
5+
}

docs/source/quickstart/quickstart.rst

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
Quick start
2+
===========
3+
4+
You can install `labthings-fastapi` using `pip`. We recommend you create a virtual environment, for example:
5+
6+
7+
.. literalinclude:: quickstart_example.sh
8+
:language: bash
9+
:start-after: BEGIN venv
10+
:end-before: END venv
11+
12+
then install labthings with:
13+
14+
.. literalinclude:: quickstart_example.sh
15+
:language: bash
16+
:start-after: BEGIN install
17+
:end-before: END install
18+
19+
To define a simple example ``Thing``, paste the following into a python file, ``counter.py``:
20+
21+
.. literalinclude:: counter.py
22+
:language: python
23+
24+
``counter.py`` defines the ``TestThing`` class, and then runs a LabThings server in its ``__name__ == "__main__"`` block. This means we should be able to run the server with:
25+
26+
27+
.. literalinclude:: quickstart_example.sh
28+
:language: bash
29+
:start-after: BEGIN serve
30+
:end-before: END serve
31+
32+
Visiting http://localhost:5000/counter/ will show the thing description, and you can interact with the actions and properties using the Swagger UI at http://localhost:5000/docs/.
33+
34+
You can also interact with it from another Python instance, for example by running:
35+
36+
.. literalinclude:: counter_client.py
37+
:language: python
38+
39+
It's best to write ``Thing`` subclasses in Python packages that can be imported. This makes them easier to re-use and distribute, and also allows us to run a LabThings server from the command line, configured by a configuration file. An example config file is below:
40+
41+
.. literalinclude:: example_config.json
42+
:language: JSON
43+
44+
Paste this into ``example_config.json`` and then run a server using:
45+
46+
.. code-block:: bash
47+
48+
labthings-server -c example_config.json
49+
50+
Bear in mind that this won't work if `counter.py` above is still running - both will try to use port 5000.
51+
52+
As before, you can visit http://localhost:5000/docs or http://localhost:5000/example/ to see the OpenAPI docs or Thing Description, and you can use the Python client module with the second of those URLs.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
echo "Setting up environemnt"
2+
# BEGIN venv
3+
python -m venv .venv --prompt labthings
4+
source .venv/bin/activate # or .venv/Scripts/activate on Windows
5+
# END venv
6+
echo "Installing labthings-fastapi"
7+
# BEGIN install
8+
pip install labthings-fastapi[server]
9+
# END install
10+
echo "running example"
11+
# BEGIN serve
12+
python counter.py
13+
# END serve
14+
echo $! > example_server.pid
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# cd to this directory
2+
cd "${BASH_SOURCE%/*}/"
3+
rm -rf .venv
4+
# Override the virtual environment so we use the package
5+
# from this repo, not from pypi
6+
python -m venv .venv
7+
source .venv/bin/activate
8+
pip install ../../..
9+
# Run the quickstart code in the background
10+
bash "quickstart_example.sh" 2>&1 &
11+
quickstart_example_pid=$!
12+
echo "Spawned example with PID $quickstart_example_pid"
13+
14+
function killserver {
15+
# Stop the server that we spawned.
16+
children=$(ps -o pid= --ppid "$quickstart_example_pid")
17+
kill $children
18+
echo "Killed spawned processes: $children"
19+
20+
wait
21+
}
22+
trap killserver EXIT
23+
24+
# Wait for it to respond
25+
# Loop until the command is successful or the maximum number of attempts is reached
26+
ret=7
27+
attempt_num=0
28+
while [[ $ret == 7 ]]; do # && [ $attempt_num -le 50 ]
29+
# Execute the command
30+
ret=0
31+
curl -sf -m 10 http://localhost:5000/counter/counter || ret=$?
32+
if [[ $ret == 7 ]]; then
33+
echo "Curl didn't connect on attempt $attempt_num"
34+
35+
# Check the example process hasn't died
36+
ps $quickstart_example_pid > /dev/null
37+
if [[ $? != 0 ]]; then
38+
echo "Child process (the server example) died without responding."
39+
exit -1
40+
fi
41+
42+
attempt_num=$(( attempt_num + 1 ))
43+
sleep 1
44+
fi
45+
done
46+
echo "Final return value $ret on attempt $attempt_num"
47+
48+
if [[ $ret == 0 ]]; then
49+
echo "Success"
50+
else
51+
echo "Curl returned $ret, likely something went wrong."
52+
exit -1
53+
fi
54+
55+
# Check the Python client code
56+
echo "Running Python client code"
57+
(source .venv/bin/activate && python counter_client.py)
58+
if [[ $? != 0 ]]; then
59+
echo "Python client code did not run OK."
60+
exit -1
61+
fi

tests/test_docs.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from pathlib import Path
2+
from runpy import run_path
3+
from test_server_cli import MonitoredProcess
4+
from fastapi.testclient import TestClient
5+
from labthings_fastapi.client import ThingClient
6+
7+
8+
this_file = Path(__file__)
9+
repo = this_file.parents[1]
10+
docs = repo / "docs" / "source"
11+
12+
13+
def run_quickstart_counter():
14+
# A server is started in the `__name__ == "__main__" block`
15+
run_path(docs / "quickstart" / "counter.py")
16+
17+
18+
def test_quickstart_counter():
19+
"""Check we can create a server from the command line"""
20+
p = MonitoredProcess(target=run_quickstart_counter)
21+
p.run_monitored(terminate_outputs=["Application startup complete"])
22+
23+
24+
def test_dependency_example():
25+
globals = run_path(docs / "dependencies" / "example.py", run_name="not_main")
26+
with TestClient(globals["server"].app) as client:
27+
testthing = ThingClient.from_url("/testthing/", client=client)
28+
testthing.increment_counter()

0 commit comments

Comments
 (0)