烧瓶静止,具有get / id并在同一类中使用json发布 [英] flask-restful having a get/<id> and post with json in the same class

查看:98
本文介绍了烧瓶静止,具有get / id并在同一类中使用json发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果#api.add_resource(User,‘/ user /’)
行未注释,而另一个api.add_resource是注释,则对用户的get方法起作用。
要使post方法起作用,则相反。

The get method on user works if the # api.add_resource(User, '/user/') line is uncommented, and the other api.add_resource is. The inverse of that is true to make the post method work.

我如何才能同时使用这两种路径?

How can I get both of these paths to work?

from flask import Flask, request
from flask.ext.restful import reqparse, abort, Api, Resource
import os
# set the project root directory as the static folder, you can set others.
app = Flask(__name__)
api = Api(app)

class User(Resource):

    def get(self, userid):
        print type(userid)
        if(userid == '1'):
            return {'id':1, 'name':'foo'}
        else:
            abort(404, message="user not found")

    def post(self):
        # should just return the json that was posted to it
        return request.get_json(force=True)

api.add_resource(User, '/user/')
# api.add_resource(User, '/user/<string:userid>')

if __name__ == "__main__":
    app.run(debug=True)


推荐答案

Flask-Restful 支持为单个资源注册多个URL 。当您注册 User 资源时,只需提供两个URL:

Flask-Restful supports registering multiple URLs for a single resource. Simply provide both URLs when you register the User resource:

api.add_resource(User, '/user/', '/user/<userid>')

这篇关于烧瓶静止,具有get / id并在同一类中使用json发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆