【问题标题】:How to access post data in flask using blueprints and restfull如何使用蓝图和restful访问flask中的post数据
【发布时间】:2016-06-11 00:06:00
【问题描述】:

究竟如何使用蓝图和 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

【问题讨论】:

    标签: flask flask-restful


    【解决方案1】:

    这是对您的示例的改编。根据您的进口,看起来您走在正确的轨道上。我的示例仅采用 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
    

    【讨论】:

      【解决方案2】:

      我就是这样做的。

      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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-23
        • 2018-12-02
        • 1970-01-01
        • 2012-01-01
        • 2014-06-13
        • 2021-06-25
        • 2018-06-24
        相关资源
        最近更新 更多