Last active
December 21, 2015 08:09
-
-
Save soasme/6276061 to your computer and use it in GitHub Desktop.
This file contains 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
# -*- coding: utf-8 -*- | |
from flask import Flask, make_response | |
from flask.ext.restful import Api, Resource | |
import json | |
app = Flask(__name__) | |
api = Api(app) | |
RESOURCE = { | |
'int': 1, | |
'float': 1.0, | |
'key': 'value', | |
'array': [1, 2, 3, ], | |
'dict': { | |
'key_in_dict': 'value_in_dict', | |
} | |
} | |
class MyResource(Resource): | |
def get(self, id): | |
return RESOURCE | |
@api.representation('application/vnd.example.v1+json') | |
def r(data, code, headers): | |
# 例如, 版本一不支持嵌套dict, 要打平数据结构. | |
data = dict(data) | |
dct = data.pop('dict') | |
data.update(dct) | |
resp = make_response(json.dumps(data), code) | |
resp.headers.extend(headers or {}) | |
return resp | |
@api.representation('application/vnd.example.v3+json') | |
def r3(data, code, headers): | |
# 版本三照常输出 | |
resp = make_response(json.dumps(data), code) | |
resp.headers.extend(headers or {}) | |
return resp | |
api.add_resource(MyResource, '/resources/<string:id>', endpoint='resource') | |
app.run(debug=True) | |
''' | |
~ % | |
~ % curl http://127.0.0.1:5000/resources/1 -H"Accept: application/vnd.example.v3+json" | |
{"int": 1, "array": [1, 2, 3], "float": 1.0, "dict": {"key_in_dict": "value_in_dict"}, "key": "value"}% | |
~ % | |
~ % curl http://127.0.0.1:5000/resources/1 -H"Accept: application/vnd.example.v1+json" | |
{"key_in_dict": "value_in_dict", "key": "value", "int": 1, "array": [1, 2, 3], "float": 1.0}% | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment