Skip to content

Instantly share code, notes, and snippets.

@cyli
Last active August 29, 2015 14:24
Show Gist options
  • Save cyli/1f6b1f832c2e3f4d79f6 to your computer and use it in GitHub Desktop.
Save cyli/1f6b1f832c2e3f4d79f6 to your computer and use it in GitHub Desktop.
Local request bin that handles arbitrary paths. Run "twistd -n web --resource-path=requestbin.py" with twisted >= 15.2.1
"""
A request bin.
"""
import json
from twisted.logger import Logger
from twisted.web.resource import Resource
log = Logger('requestbin')
class RequestBin(Resource):
"""
A resource just records all requests.
"""
isLeaf = True
def __init__(self, code=200):
"""
:param istubs: a :obj:`IStringResponseStubs` provider.
"""
Resource.__init__(self)
self.code = code
def getChild(self, name, request):
"""
Required due to some peculiarity with resource scripts not
actually expecting to be at the root.
"""
return self
def render(self, request):
"""
Produce a response according to the stubs provided.
"""
# The incoming request does not have the absoluteURI property, because
# an incoming request is a IRequest, not an IClientRequest, so it
# the absolute URI needs to be synthesized.
# But request.URLPath() only returns the scheme and hostname, because
# that is the URL for this resource (because this resource handles
# everything from the root on down).
# So we need to add the request.path (not request.uri, which includes
# the query parameters)
absoluteURI = str(request.URLPath().click(request.path))
data = request.content.read()
try:
loaded = json.loads(data)
except:
pass
else:
data = json.dumps(loaded, indent=2)
if not data:
data = repr(data)
log.info("\n\n{method} {url}\n\n{headers}\n\n{params}\n\n{data}\n\n",
headers=dict(request.requestHeaders.getAllRawHeaders()),
params=request.args, data=data,
url=absoluteURI, method=request.method)
request.setResponseCode(self.code)
return ""
resource = RequestBin(200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment