Skip to content

Instantly share code, notes, and snippets.

@madsmtm
Last active December 9, 2018 23:42
Show Gist options
  • Save madsmtm/bd3537cdfd853b6557ee37268fe176f0 to your computer and use it in GitHub Desktop.
Save madsmtm/bd3537cdfd853b6557ee37268fe176f0 to your computer and use it in GitHub Desktop.
Rudimentary, Sans-IO `https://httpbin.org/get`, with a syncronous implementation on the side
import json
import h11
from urllib.parse import urlencode
class Get:
"""Sans-IO implementation of `/get`"""
def __init__(self, params):
self.params = params
def to_send(self):
target = "/get{}{}".format("?" if self.params else "", urlencode(self.params))
return [
h11.Request(method="GET", target=target, headers=[("Host", "httpbin.org")]),
h11.EndOfMessage(),
]
def parse(self, events):
data = b""
for event in events:
if isinstance(event, h11.Data):
data += event.data
return json.loads(data.decode("utf-8"))["args"]
import h11
from httpbin_sansio_get import Get
# This client is the functions from h11's example client, as a class.
# See https://gist.github.com/madsmtm/5f3d0b9b5f68e41ff13cb5eaa15868a7
from h11_sync_client import Client
def get(params):
"""Call `/get` with URL-encoded parameters."""
client = Client("httpbin.org")
getter = Get(params)
for event in getter.to_send():
client.send(event)
events = []
while True:
event = client.next_event()
events.append(event)
if isinstance(event, h11.EndOfMessage):
break
return getter.parse(events)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment