在Flask-RESTful

时间:2015-07-03 11:14:07

标签: python flask flask-restful

我正在使用Flask-RESTful处理API。使用此API,我希望能够选择GET enpoint是否必须返回JSON或HTML。

当我在没有任何额外变量的情况下调用/shipments/ready时,我想返回一个JSON对象,其中所有货件的状态都设置为“就绪”。这没有任何问题。 但是我也希望能够在Javascript中调用这个相同的端点并给它一个format=html标志,在这种情况下,端点必须返回相同的数据,但是作为HTML字符串(使用Jinja2模板)。 / p>

我通过查看request.args并查看format标志是否已设置(见下面的代码)来实现此目的。但我也想使用@marshal_with来格式化JSON响应。当我使用此修饰符时,HTML响应不再起作用(具有shipments_fields中指定的字段的JSON对象,而是返回所有设置为null的对象)。 我能够通过将@marshal_with移动到单独的函数来创建变通方法,但我无法想象这是最好的方法。

有谁知道应该怎么做?

shipments_fields = {
    'id':                   fields.Integer,
    # etc...
}

@marshal_with(shipments_fields)
def marshal_shipments(result):
    return result

class Shipments_by_status(Resource):
    def get(self, status):
        shipments = models.Shipment.query.filter_by(status=status).all()

        # If asking for HTML
        try: # Try, to prevent errors when 'format' is not existing
            if request.args['format'] == 'html':
                return render_template("page_snippets/shipment.html",\
                shipments=shipments), 200
        except:
            pass

        shipments = marshal_shipments(shipments)
        return shipments

api.add_resource(Shipments_by_status,   '/shipments/<string:status>')

1 个答案:

答案 0 :(得分:0)

定义一个单独的函数来编组数据是一个好主意。但默认情况下,回复import static test.Selector.*; import static test.Util.*; public class Main { public static void main(String[] args) { getStartState() .methodLeftA() .methodRightA() .selectLeftType(B) .methodLeftB() .methodRightA() .selectRightType(B) .methodLeftB() .methodRightB() .selectLeftType(C) .methodLeftC() .methodRightB() .selectRightType(A) .methodLeftC() .methodRightA() .selectLeftType(B) .methodLeftB() .selectLeftType(A) .methodRightA(); } } Contenty-Type。要进行html响应,如果application/json标头在请求中有make_resonse,则必须通过调用Accept函数来创建响应对象。

并且您不必通过查询字符串来请求html输出,但您的请求text/html标题应包含Accept,这是浏览器的默认值。

text/html

如果您不想检查请求def get(self, status): shipments = models.Shipment.query.filter_by(status=status).all() accept = request.headers.get('Accept') if accept and 'text/html' in accept: return make_reponse(render_template("page_snippets/shipment.html", shipments=shipments), 200) return marshal_shipments(shipments) 标头以呈现不同媒体类型的正确输出,则必须为每种媒体类型定义单独的函数,并使用Accept装饰器注册它们。

api.representation