diff --git a/docs/services.rst b/docs/services.rst index ef402214..e5f0571e 100644 --- a/docs/services.rst +++ b/docs/services.rst @@ -61,55 +61,7 @@ Pool Example ------- -.. code-block:: python - - import mitogen - import mitogen.service - - - class FileService(mitogen.service.Service): - """ - Simple file server, for demonstration purposes only! Use of this in - real code would be a security vulnerability as it would permit children - to read arbitrary files from the master's disk. - """ - handle = 500 - required_args = { - 'path': str - } - - def dispatch(self, args, msg): - with open(args['path'], 'r') as fp: - return fp.read() - - - def download_file(context, path): - s = mitogen.service.call(context, FileService.handle, { - 'path': path - }) - - with open(path, 'w') as fp: - fp.write(s) - - - @mitogen.core.takes_econtext - def download_some_files(paths, econtext): - for path in paths: - download_file(econtext.master, path) - - - @mitogen.main() - def main(router): - pool = mitogen.service.Pool(router, size=1, services=[ - FileService(router), - ]) - - remote = router.ssh(hostname='k3') - remote.call(download_some_files, [ - '/etc/passwd', - '/etc/hosts', - ]) - pool.stop() +.. literalinclude:: ../examples/service/self_contained.py Reference diff --git a/examples/service/self_contained.py b/examples/service/self_contained.py new file mode 100644 index 00000000..332aa24e --- /dev/null +++ b/examples/service/self_contained.py @@ -0,0 +1,52 @@ +import mitogen +import mitogen.service + + +class FileService(mitogen.service.Service): + """ + Simple file server, for demonstration purposes only! Use of this in + real code would be a security vulnerability as it would permit children + to read any file from the master's disk. + """ + + @mitogen.service.expose(policy=mitogen.service.AllowAny()) + @mitogen.service.arg_spec(spec={ + 'path': str + }) + def read_file(self, path): + with open(path, 'rb') as fp: + return fp.read() + + +def download_file(source_context, path): + s = source_context.call_service( + service_name=FileService, # may also be string 'pkg.mod.FileService' + method_name='read_file', + path=path, + ) + + with open(path, 'w') as fp: + fp.write(s) + + +def download_some_files(source_context, paths): + for path in paths: + download_file(source_context, path) + + +@mitogen.main() +def main(router): + pool = mitogen.service.Pool(router, services=[ + FileService(router), + ]) + + remote = router.ssh(hostname='k3') + remote.call(download_some_files, + source_context=router.myself(), + paths=[ + '/etc/passwd', + '/etc/hosts', + ] + ) + pool.stop() +