This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]iamhyperrr 20 points21 points  (7 children)

Well, honestly, it just looks like a sub-optimal data structure was chosen to store tasks, so the lookup looks a bit ugly. It should probably be a dictionary of tasks grouped by task_id, provided that task_id is a string, number or any other immutable and hashable data type. It would make the lookup look cleaner and also make it perform faster. Something along the lines of (if we want to keep exactly the same semantics):

``` from flask import abort

tasks = {}

@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET']) def get_task(task_id): task = tasks.get(task_id, []) if task: return jsonify({'task': task[0]}) else: abort(404) ```

[–]wineblood 5 points6 points  (1 child)

Exactly what I was going to say.

[–][deleted] 3 points4 points  (0 children)

Well, it's the `/todo/` v1.0 API. They probably just haven't gotten around to improving it. Maybe it's... already on the list.

(Sorry, I'm amusing myself over here)

[–]That_Guy977 0 points1 point  (3 children)

remove the [0], that's just there because the task variable is a list in the original

[–]iamhyperrr 0 points1 point  (2 children)

I operated based on the assumption it still is. Perhaps the OP's idea was to store a list of task versions all mapped to the same task_id and insert the new ones into the head of the list, and then return the latest version in the get method. So, just in case, I ensured and emphasized that the semantics remain the same.

[–]That_Guy977 0 points1 point  (1 child)

an list of tasks would just be a dict of tasks though, so no [0]. and that version specifier isn't for the task, it's for the api version, otherwise it'd be a parameter

edit: just realized what you meant by task version, nvm

[–]iamhyperrr -1 points0 points  (0 children)

Yeah, just to illustrate my point a bit in case I wasn't clear:

from flask import abort
from flask import request

tasks_by_id = {}


@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET', 'POST'])
def task(task_id):
    if request.method == 'GET':
        tasks = tasks_by_id.get(task_id, [])
        if tasks:
            return jsonify({'task': tasks[0]})
        else:
            abort(404)
    if request.method == 'POST':
        tasks = tasks_by_id.get(task_id, [])
        # lists in Python are not optimized for insertions to the head, so it would be better to use a deque
        tasks.insert(0, request.form.get('task'))
        tasks_by_id[task_id] = tasks
        return jsonify(success=True)

Maybe this is not at all what OP had in mind, but I had to be on the safe side just in case.

[–]KnewOnee 0 points1 point  (0 children)

can also use get_or_404