The device ID API

The route for individual devices specifies that the ID should be an integer, which can act as our first line of defense against a bad request. The two endpoints follow the same design pattern as our /devices/ endpoint, where we use the same import and export functions:

@app.route('/devices/<int:id>', methods=['GET'])def get_device(id):    return jsonify(Device.query.get_or_404(id).export_data())@app.route('/devices/<int:id>', methods=['PUT'])def edit_device(id):    device = Device.query.get_or_404(id)    device.import_data(request.json)    db.session.add(device)    db.session.commit()    return jsonify({})

Note the query_or_404() method; it provides a convenient way for returning 404 (not found) if the database query returns negative for ...

Get Mastering Python Networking - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.