Skip to content

Instantly share code, notes, and snippets.

@0atman
Last active September 4, 2021 19:35
Show Gist options
  • Save 0atman/36574328fdb2d390834c1d878ac4c32f to your computer and use it in GitHub Desktop.
Save 0atman/36574328fdb2d390834c1d878ac4c32f to your computer and use it in GitHub Desktop.
Native literate programming in python through doctests. This is either the best or the worst thing I have ever written.

Imports

First the imports, this demo requires the flask_restful package. Then we set up the Flask wsgi application object, app and the api wrapper, api.

>>> from flask import Flask
>>> from flask_restful import Resource, Api

>>> app = Flask(__name__)
>>> api = Api(app)

Flask Restful resources

We define a single HelloWorld resource, that responds with a simple json object on a GET request.

>>> class HelloWorld(Resource):
...     def get(self):
...         return {'hello': 'world'}

Routing

api.add_resource() wires the Resource class HelloWorld into the flask router at /.

>>> api.add_resource(HelloWorld, '/')

Run Server

After we have created everything, we run the flask werkzeug server.

>>> if __name__ == '__main__':
...     app.run()
@0atman
Copy link
Author

0atman commented May 12, 2017

Running without doctest's verbose mode looks like a normal flask server:

$ python -m doctest lit.md

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

With verbose mode:

$ python -m doctest -v lit.md

Trying:
    from flask import Flask
Expecting nothing
ok
Trying:
    from flask_restful import Resource, Api
Expecting nothing
ok
Trying:
    app = Flask(__name__)
Expecting nothing
ok
Trying:
    api = Api(app)
Expecting nothing
ok
Trying:
    class HelloWorld(Resource):
        def get(self):
            return {'hello': 'world'}
Expecting nothing
ok
Trying:
    api.add_resource(HelloWorld, '/')
Expecting nothing
ok
Trying:
    if __name__ == '__main__':
        app.run()
Expecting nothing
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

@0atman
Copy link
Author

0atman commented May 12, 2017

Or for maximum hackery, add this extended shebang to make the .md file executable!

#!/usr/bin/env python
import doctest, sys; doctest.testfile(sys.argv[0])
#
"""
# markdown here
"""

You now can execute it:

$ ./lit.md
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment