Skip to content

Commit 0a02146

Browse files
Better documentation for start_server() method (Fixes miguelgrinberg#252)
1 parent 482ab6d commit 0a02146

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

docs/intro.rst

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,34 @@ handler functions can be defined as ``async def`` or ``def`` functions, but
8282
``async def`` functions are recommended for performance.
8383

8484
The :func:`run() <microdot.Microdot.run>` method starts the application's web
85-
server on port 5000 by default. This method blocks while it waits for
86-
connections from clients.
85+
server on port 5000 by default, and creates its own asynchronous loop. This
86+
method blocks while it waits for connections from clients.
87+
88+
For some applications it may be necessary to run the web server alongside other
89+
asynchronous tasks, on an already running loop. In that case, instead of
90+
``app.run()`` the web server can be started by invoking the
91+
:func:`start_server() <microdot.Microdot.start_server>` coroutine as shown in
92+
the following example::
93+
94+
import asyncio
95+
from microdot import Microdot
96+
97+
app = Microdot()
98+
99+
@app.route('/')
100+
async def index(request):
101+
return 'Hello, world!'
102+
103+
async def main():
104+
# start the server in a background task
105+
server = asyncio.create_task(app.start_server())
106+
107+
# ... do other asynchronous work here ...
108+
109+
# cleanup before ending the application
110+
await server
111+
112+
asyncio.run(main())
87113

88114
Running with CPython
89115
^^^^^^^^^^^^^^^^^^^^
@@ -145,8 +171,9 @@ changed by passing the ``port`` argument to the ``run()`` method.
145171
Web Server Configuration
146172
^^^^^^^^^^^^^^^^^^^^^^^^
147173

148-
The :func:`run() <microdot.Microdot.run>` method supports a few arguments to
149-
configure the web server.
174+
The :func:`run() <microdot.Microdot.run>` and
175+
:func:`start_server() <microdot.Microdot.start_server>` methods support a few
176+
arguments to configure the web server.
150177

151178
- ``port``: The port number to listen on. Pass the desired port number in this
152179
argument to use a port different than the default of 5000. For example::

pyproject.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ classifiers = [
1414
"Operating System :: OS Independent",
1515
]
1616
requires-python = ">=3.8"
17+
dependencies = [
18+
]
1719

1820
[project.readme]
1921
file = "README.md"
@@ -24,6 +26,8 @@ Homepage = "https://github.com/miguelgrinberg/microdot"
2426
"Bug Tracker" = "https://github.com/miguelgrinberg/microdot/issues"
2527

2628
[project.optional-dependencies]
29+
dev = [
30+
]
2731
docs = [
2832
"sphinx",
2933
"pyjwt"

0 commit comments

Comments
 (0)