Created
January 24, 2018 07:28
-
-
Save cdpath/6fc2e1914157ebbc5010a82c7d437bb3 to your computer and use it in GitHub Desktop.
requests with msgpack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
reference Msgpack in Flask-RESTful | Kendrick Tan