aghad
aghad

Reputation: 29

Replacing embedded data with a URL in Python

I have this working Python code.

from flask import Flask, jsonify

    app = Flask(__name__)

tasks = [
    {
        'id': 1,
        'title': 'Public',
        'description': 'Available to download',
        'done': False
    },
    {
        'id': 2,
        'title': 'Non-Public',
        'description': 'Not available to download',
        'done': False
    },
     {
        'id': 3,
        'title': 'Restricted-Public',
        'description': 'got to',
        'done': False
    }
]

@app.route('/api/PDL/<int:task_id>', methods=['GET'])
def get_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    return jsonify({'task': task[0]})

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

I am trying to replace the following to read from an external data.json:

tasks = [
        {
            'id': 1,
            'title': 'Public',
            'description': 'Available to download',
            'done': False
        },
        {
            'id': 2,
            'title': 'Non-Public',
            'description': 'Not available to download',
            'done': False
        },
         {
            'id': 3,
            'title': 'Restricted-Public',
            'description': 'got to',
            'done': False
        }
    ]

I tried using tasks = open("/myproject/test.json"), but I get the following Python error.

TypeError: string indices must be integers

How can I fix this problem?

Upvotes: 0

Views: 77

Answers (1)

Celeo
Celeo

Reputation: 5682

When you load the file with open, you're reading the contents as a string into tasts. You need to convert to a Python dictionary object in order to be able use it as you are in your previous code.

Try JSON. To set the proper string in the file to start, do:

import json

tasks = [
    {
        'id': 1,
        'title': 'Public',
        'description': 'Available to download', 
        'done': False
    },
    {
        'id': 2,
        'title': 'Non-Public',
        'description': 'Not available to download', 
        'done': False
    },
    {
        'id': 3,
        'title': 'Restricted-Public',
        'description': 'got to', 
        'done': False
    }
]

with open('/myproject/test.json', 'w') as f:
    f.write(json.dumps(tasks))

Then, to load the contents of the file as a Python dictionary:

import json

with open('/myproject/test.json') as f:
    tasks = json.loads(f.read())

Upvotes: 1

Related Questions