Package: tranquilizer
TranquilizerDeploy a REST API with one line by decorating your functions.InstallThe package is available for all Mac, Linux, and Windows on my conda channel. Python 2 is not supported.> conda install -c conda-forge tranquilizerQuick startTranquilizer can be used with either Jupyter Notebooks (.ipynb) or Python script files (.py).The decorated function below will be served as an end point calledorderwith the GET method. The
function must return a JSON serializable object.See thecomplete description of@tranquilize()below.fromtranquilizerimporttranquilize@tranquilize()deforder(cheese):'''I'd like to buy some cheese!'''return"I'm afraid we're fresh out of{}, Sir.".format(cheese)The REST API is served byFlaskandFlask-RESTXusing thetranquilizercommand.> tranquilizer cheese_shop.ipynb
 * Serving Flask app "tranquilizer.application" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:8086/ (Press CTRL+C to quit)Let's see if there is any Red Leicester.> curl -G http://localhost:8086/order --data-urlencode "cheese=Red Leicester"
"I'm afraid we're fresh out of Red Leicester, Sir."or using the Requests library in Python.In[1]:importrequestsIn[2]:response=requests.get('http://localhost:8086/order',params={'cheese':'Red Leicester'})In[3]:response.textOut[3]:'"I\'m afraid we\'re fresh out of cheddar, Sir."\n'ThetranquilizedAPI is documented withSwaggerand is accessible
in your web browser athttp://localhost:8086.Tranquilize DecoratorThe@tranqulizedecorator will assign the GET method by default. POST is also supported withmethod='post'.
Other methods are under consideration.By default atranquilizedfunction will receive all inputs as strings. This behavior can be modified by usingtype hints. When data is received by the Flask server it will use the provided
type function to transform the string to the requested data type. This avoids having to perform the conversion in yourtranquilizedfunction.Supported source formatsTranquilizer can serve functions written in Python source (.py) files or Jupyter Notebooks (.ipynb).When working interactively in Jupyter Notebooks the decorated functions will continue to operate as normal.
Note that all calls toJupyter Magicand Shell (!) commands will be ignored when the REST API is served.
Only those lines will be ignored, the rest of the cell will continue to run.Data TypesIn addition tobuiltintypesTranquilizer
provides specialized support for Lists, date/datetime, and files.TypeDescriptiondatetime.dateordatetime.datetimeConverts string withdateutil.parser.parseand returns specified type.listConvertsrepeatedarguments to a list of strings.typing.List[<type>]Convertsrepeatedarguments to a list; each value is converted to<type>.Listarguments are constructed using theaction='append'argument described in
theFlask RESTX documentation.
Any valid type can be used inList[].The following file-like types are handled bywerkzeugFileStorage.FileStorageis a file-like object that supports methods like.read()and.readlines().
These types support sending files with cURL using-F.TypeDescriptiontyping.BinaryIOFile-like object to read binary data.typing.TextIOConvertsFileStoragetype toio.StringIO().Further, specific support for Image and NumPy files are provided. The binary contents of the file are automatically converted.TypeDescriptionPIL.Image.ImageConvertsFileStoragetype to PIL Image.numpy.ndarrayConvertsFileStoragetype to NumPy array usingnp.load().Custom typesCustom type classes can be built...Type hints exampleThe example below usesint,datetime.datetime, andtyping.List.datetime.datetimesupport
has been built withdatetutiland will convert any compatible datetime string to adatetime.datetimeobject.typing.Listsupports specialization with[]and will transform allrepeatedarguments passed to the REST API into a list and convert
the type of each element.Finally, tranquilizer supports default arguments.fromtranquilizerimporttranquilizefromdatetimeimportdatefromtypingimportList@tranquilize(method='post')defconvert(string:str,date:date,items:List[float],factor:int=10):'''Let's convert strings to something useful'''new_items=[i*factorforiinitems]response={'string':string.upper(),'date':date.strftime('%c'),'items':new_items}returnresponseLet's see what happens when I POST to this REST API.In[1]:data={'string':'hello, world!','date':'4th July 1776','items':range(5)}In[2]:importrequestsIn[3]:response=requests.post('http://localhost:8086/convert',data=data)In[4]:response.json()Out[4]:{'date':'Thu Jul  4 00:00:00 1776','items':[0.0,10.0,20.0,30.0,40.0],'string':'HELLO, WORLD!'}In[5]:Securing the API with a bearer tokenIf you need to secure your tranquilized API with an Authorization Bearer token use the--secret-keycommand-line
flag. The supplied secret key is used to decrypt JWT tokens. When the tranquilizer server starts a bearer token
is printed to standard out that can be used to access the API. Here's an example of the output.NOTE: It is important that you keep your secret key safe and not share it as it is used to sign and verify bearer
tokens, not to access the API.> tranquilizer --secret-key <secret-key> cheese_shop.ipynb
-- This API secured with JWT using the HS256 algorithm. The following token can be used as an  Authorization Bearer token in the request header.

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTYzODc0MzkxNiwianRpIjoiNGY0YTdiZWYtMWJiZi00ZGUwLWI0MDMtOTVhNzY2Y2IxNWUyIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IlRyYW5xdWlsaXplZCBBUEkgdXNlciIsIm5iZiI6MTYzODc0MzkxNn0.pWoKvH_N9abFUYLzbzc02ewnPGPbvTjiFAVI3GlVltw

-- You can create more bearer tokens online at https://jwt.io using the secret-key you supplied on the command line.
 * Serving Flask app "tranquilizer.application" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:8086/ (Press CTRL+C to quit)A user can then utilize the supplied token in requests to the API, for example with curl> TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTYzODc0MzkxNiwianRpIjoiNGY0YTdiZWYtMWJiZi00ZGUwLWI0MDMtOTVhNzY2Y2IxNWUyIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IlRyYW5xdWlsaXplZCBBUEkgdXNlciIsIm5iZiI6MTYzODc0MzkxNn0.pWoKvH_N9abFUYLzbzc02ewnPGPbvTjiFAVI3GlVltw'
> curl -H 'Authorization: Bearer ${TOKEN}' http://localhost:8086/order?cheese=cheddar
"I'm afraid we're fresh out of cheddar, Sir."If the authorization header is not included in the request a 401 error is returned.> curl -i http://localhost:8086/order?cheese=cheddar
HTTP/1.0 401 UNAUTHORIZED
Content-Type: application/json
Content-Length: 43
Server: Werkzeug/1.0.1 Python/3.7.9
Date: Mon, 06 Dec 2021 15:46:19 GMT

{"message":"Missing Authorization Header"}Choosing functions to protect with authenticationBy default all@tranquilize()decorated functions will require authentication when using the--secret-keycommand
line argument. To disable authentication for specific functions use therequires_authentication=Falsekeyword
argument. For example in the tranquilized functions below thecheeses()function does not require theAuthorization: Bearer ${TOKEN}header, but theorder()function does require the header.Whenrequires_authentication=Noneor is not included in the decorator call the function will require authentication
when using the--secret-keyCLI argument. Ifrequires_authentication=Trueis used but tranquilizer is not started
with the--secret-keyargument aRuntimeErrorexception is raised.fromtranquilizerimporttranquilize@tranquilize()defcheeses(method='get',requires_authentication=False):'''List the available cheeses'''return['Red Leicester','Tilsit','Caerphilly','Bel Paese','Venezuelan Beaver Cheese']@tranquilize(method='post')deforder(cheese):'''I'd like to buy some cheese!'''return"I'm afraid we're fresh out of{}, Sir.".format(cheese)SwaggerWhen using--set-secretand the optionalrequires_authenticationkeyword argument the Swagger docs
are still accessible but in order totry outan endpoint that requires authentication you must first
click theAuthorizebutton at the top right. In the dialog box include the bearer token prepended byBeareras shown in the screenshot.