modify

Modifying requests and responses via middleware is simply a matter of using the modify function decorator.

import requests
from hoverpy import modify

@modify(middleware="python examples/modify/middleware.py")
def get_modified_time():
    print(requests.get("http://time.ioloop.io?format=json").json())

get_modified_time()
$ python examples/modify/modify.py

Output:

{u'date': u'2017-02-17', u'epoch': 101010, u'time': u'21:22:38'}

As you can see, the epoch has been successfully modified by the middleware script.

Middleware

Middleware is required, and can be written in any language that is supported in your development environment.

# middleware.py

import sys
import logging
import json

logging.basicConfig(filename='middleware.log', level=logging.DEBUG)

data = sys.stdin.readlines()
payload = data[0]
doc = json.loads(payload)

logging.debug(json.dumps(doc, indent=4, separators=(',', ': ')))

if "request" in doc:
  doc["request"]["headers"]["Accept-Encoding"] = ["identity"]

if "response" in doc and doc["response"]["status"] == 200:
  if doc["request"]["destination"] == "time.ioloop.io":
    body = json.loads(doc["response"]["body"])
    body["epoch"] = 101010
    doc["response"]["body"] = json.dumps(body)
    doc["response"]["headers"]["Content-Length"] = [str(len(json.dumps(body)))]

print(json.dumps(doc))