Skip to content

Instantly share code, notes, and snippets.

@cdpath
Created January 24, 2018 07:28
Show Gist options
  • Select an option

  • Save cdpath/6fc2e1914157ebbc5010a82c7d437bb3 to your computer and use it in GitHub Desktop.

Select an option

Save cdpath/6fc2e1914157ebbc5010a82c7d437bb3 to your computer and use it in GitHub Desktop.
requests with msgpack
import msgpack
from flask import Flask, request, jsonify
from flask.wrappers import Request
class RequestWithMsgPackSupport(Request):
@property
def is_msgpack(self):
return self.mimetype == 'application/msgpack'
def get_msgpack(self):
if not self.is_msgpack:
return None
try:
return msgpack.unpackb(self.get_data(), encoding='utf-8')
except msgpack.exceptions.UnpackException:
return None
def prepare_resp(obj):
msgpack_type = 'application/msgpack'
if request.headers.get('accept', None) == msgpack_type:
return app.response_class(
msgpack.packb(obj),
mimetype=msgpack_type
)
return jsonify(obj)
app = Flask(__name__)
app.request_class = RequestWithMsgPackSupport
@app.route('/', methods=['POST'])
def index():
data = request.get_msgpack()
return prepare_resp(data)
if __name__ == '__main__':
app.debug = True
app.run()
import requests
url = 'http://127.0.0.1:5000'
data = {'title': 'Pale Blue Dot', 'author': 'Carl Sagan'}
resp = requests.post(
url,
data=msgpack.packb(data),
headers={
'Content-type': 'application/msgpack',
'Accept': 'application/msgpack'
}
)
print msgpack.unpackb(resp.content)
resp = requests.post(
url,
data=msgpack.packb(data),
headers={
'Content-type': 'application/msgpack',
}
)
print resp.json()
@cdpath
Copy link
Copy Markdown
Author

cdpath commented Jan 25, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment