Skip to content

Instantly share code, notes, and snippets.

@kristianperkins
Last active May 21, 2017 00:41
Show Gist options
  • Save kristianperkins/0cfcd2d125705a3773434e03eeb2de91 to your computer and use it in GitHub Desktop.
Save kristianperkins/0cfcd2d125705a3773434e03eeb2de91 to your computer and use it in GitHub Desktop.
Display of python `requests` responses in jupyter notbooks
from IPython.display import display_html, display_javascript
import uuid
from jinja2 import Environment, BaseLoader
def display_request(r):
rq_id = str(uuid.uuid4())
rs_id = str(uuid.uuid4())
template = Environment(loader=BaseLoader()).from_string("""<div class='dr'>
{% if r.ok %}
<div class='dr_status dr_success' style='height: 24px; width: 100%; background-color: lightgreen;'>Successful response {{r.status_code}} for {{r.request.url}}</div>
{% else %}
<div class='dr_status dr_error' style='height: 24px; width: 100%; background-color: goldenrod;'>Received response {{r.status_code}} for {{r.request.url}}</div>
{% endif %}
<h4>Request</h4>
<div id="{{rq_id}}" style="max-height: 600px; width:100%;"><pre>{{r.request.body}}</pre></div>
<h4>Response</h4>
<div id="{{rs_id}}" style="max-height: 600px; width:100%;"><pre>{{r.text}}</pre></div>
</div>
""")
display_html(template.render(r=r, rq_id=rq_id, rs_id=rs_id), raw=True)
js_template = Environment(loader=BaseLoader()).from_string("""
require(["https://rawgit.com/caldwell/renderjson/master/renderjson.js"], function() {
{% if r.request.headers['Content-Type'] == 'application/json' %}
document.getElementById('{{rq_id}}').innerHTML = '';
document.getElementById('{{rq_id}}').appendChild(renderjson({{r.request.body}}));
{% endif %}
{% if r.headers['Content-Type'] == 'application/json' %}
document.getElementById('{{rs_id}}').innerHTML = '';
document.getElementById('{{rs_id}}').appendChild(renderjson({{r.text}}));
{% endif %}
});""")
display_javascript(js_template.render(r=r, rq_id=rq_id, rs_id=rs_id), raw=True)
r = requests.post('http://httpbin.org/post', data = {'key':'value'})
display_request(r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment