如何使用蓝图和restfull访问烧瓶中的帖子数据

时间:2016-05-18 08:25:27

标签: flask flask-restful

我如何使用蓝图和flask-restfull从烧瓶应用中获取发布数据?为什么这么难?

在我的views.py文件中

 api.add_resource(register, '/api/driver/register')

在我的资源档案中:

from flask_restful import fields, marshal_with, reqparse, Resource
class register(Resource):
    def post(self):
        ACCESS MY POST DATA!!!!!!!!!!!!!
        return 'omg' 



curl -H "Content-Type: application/json" -X POST -d '{"f":"xyz","u":"xyz"}' http://0.0.0.0:5000/api/driver/register

2 个答案:

答案 0 :(得分:0)

以下是您的示例的改编。根据您的导入情况,您似乎走在正确的轨道上。我的示例只接受2个JSON参数,电子邮件和移动设备,并以JSON格式回送它们。您可以使用args['email']args['mobile']来参考处理和业务逻辑的值。

from flask_restful import fields, marshal_with, reqparse, Resource
class register(Resource):
    def post(self):
        reqparse = reqparse.RequestParser()
        reqparse.add_argument('email', type=str)
        reqparse.add_argument('mobile', type=int)
        args = reqparse.parse_args()
        response = {'email': args['email'], 'mobile': args['mobile']}
        response_fields = {'email': fields.String, 'mobile': fields.Integer}
        return marshal(response, response_fields), 200

答案 1 :(得分:0)

这就是我的方式。

from flask_restful import fields, marshal_with, reqparse, Resource


class Register(Resource):

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('field_data_one', type=str, required=True, location='json')
        self.reqparse.add_argument('field_data_two', type=str, required=True, location='json')
        ...

    def post(self):
        args = self.reqparse.parse_args()

        obj = {
            'field_data_one': args['field_data_one'],
            'field_data_two': args['field_data_two']
        }

        return {'omg': obj}, 201

        # ACCESS MY POST DATA!!!!!!!!!!!!!
        # return 'omg'
相关问题