Dusty Boshoff
Dusty Boshoff

Reputation: 1061

Python flask_restful arguments

I'm creating the server end of a test API using flask_restful that will capture a request coming into the API with a ID, and 3 parameters. If the Id does not exists, then it is created and populated with the 3 data arguments. The Asset is created, however only the 3rd parameter is added to the dict.

Code I have:

from flask import Flask, request
from flask_restful import reqparse, abort, Api, Resource

app = Flask(__name__)
api = Api(app)
assets = {}

def abort_if_asset_doesnt_exist(asset_id):
    if asset_id not in assets:
        abort(404, message="Asset {} doesn't exist".format(asset_id))

parser = reqparse.RequestParser()
parser.add_argument('data1', type=str)
parser.add_argument('data2', type=str)
parser.add_argument('data3', type=str)

class Asset(Resource):
    def get(self, asset_id):
        return {asset_id: assets[asset_id]}
    def put(self, asset_id):
        assets[asset_id] = request.form['data1']
        assets[asset_id] = request.form['data2']
        assets[asset_id] = request.form['data3']
        return {asset_id: assets[asset_id]}
    def delete(self, asset_id):
        abort_if_todo_doesnt_exist(asset_id)
        del assets[asset_id]
        return '', 204

api.add_resource(Asset, '/api-v1.0/add/<string:asset_id>', methods=['PUT', 'GET'])

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

I want to take the id and create a 'instance' in the dictionary, with it's corresponding data fields attached to it. like below

What I want:

{
    "123456" {
              "data1":"Mydata1"
              "data2":"Mydata2"
              "data3":"Mydata3"
              }
}

With this I can call the asset and receive it's associated data fields.

The curl (PUT) command I use looks like this.

$ curl http://localhost:5000/api-v1.0/add/123456 -d "data1=Mydata1" -d "data2=Mydata2" -d "data3=Mydata3" -X PUT

Upvotes: 0

Views: 250

Answers (1)

Alasdair Colley
Alasdair Colley

Reputation: 36

This is because you're just assigning a value one after the other to the location specified by asset_id in your assets dict. Since the last value assigned to assets is the 3rd parameter this is the value that is contained at that key.

To fix this you need to change that code to create a dict for the asset_id that you want to store the form data against:

assets[asset_id] = dict()
assets[asset_id]['data1'] = request.form['data1']
assets[asset_id]['data2'] = request.form['data2']
assets[asset_id]['data3'] = request.form['data3']

Or even better use a defaultdict:

assets = defaultdict(dict)
...
assets[asset_id]['data1'] = request.form['data1']

Upvotes: 2

Related Questions