Skip to content

Python/AppDev/app/myApi.py #5

@i4o

Description

@i4o

This script actually fails to search beyond first entry in db.txt.
I've wasted 15 mins figuring out what's wrong, instead of learning :).

As you can see below, if first record is match, OK found.
If 1st record is not match, it will return with "No match".
2nd record is never tried, function never continues looping, it returns after validation of 1st record...

for record in records:
                if record['hostname'] == hostname:
                    LOG.info('Routers returned')
                    return jsonify(record), 200
                if record['hostname'] != hostname:
                    LOG.warning('No matching router')
                    return jsonify({"response": "No match"}), 200

I did modify your script to work:

@app.route('/routers', methods=['GET'])
def getRouter():
    try:
        hostname = request.args.get('hostname')
        if (hostname is None) or (hostname == ""):
            LOG.warning('No hostname specified')
            raise ValueError
        with open(f'{script_dir}/db.txt', 'r') as f:
            data = f.read()
            records = json.loads(data)
            for record in records:
                print("Hostname: ", record['hostname'])
                if record['hostname'] == hostname:
                    LOG.info('Routers returned')
                    return jsonify(record), 200
                if record['hostname'] != hostname:
                    continue    
                    
            LOG.warning('No matching router')
            return jsonify({"response": "No match"}), 200
    except ValueError:
        LOG.error("NO HOSTNAME SPECIFIED")
        return jsonify({"error": "NO_HOSTNAME_SPECIFIED"}), 400
    except Exception as err:
        LOG.error(f'Error during GET {err}')
        return jsonify({"error": err}), 500

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions