CodeSamples icon indicating copy to clipboard operation
CodeSamples copied to clipboard

Python/AppDev/app/myApi.py

Open i4o opened this issue 3 years ago • 0 comments

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

i4o avatar Oct 04 '22 17:10 i4o