Devices API

The chapter9_6.py file starts with the necessary imports. Note that the following request import is the request object from the client and not the requests package that we have been using in the previous chapters:

from flask import Flask, url_for, jsonify, request
from flask_sqlalchemy import SQLAlchemy
# The following is deprecated but still used in some examples
# from
flask.ext.sqlalchemy import SQLAlchemy

We declared a database object with its ID as the primary key and string fields for hostname, loopback, management IP, role, vendor, and OS:

class Device(db.Model):
__tablename__ = 'devices'
id = db.Column(db.Integer, primary_key=True)
hostname = db.Column(db.String(64), unique=True)
loopback = db.Column(db.String(120), unique=True)
mgmt_ip = db.Column(db.String(120), unique=True)
role = db.Column(db.String(64))
vendor = db.Column(db.String(64))
os = db.Column(db.String(64))

The get_url() function returns a URL from the url_for() function. Note that the get_device() function called is not defined just yet under the '/devices/<int:id>' route:

def get_url(self):
return url_for('get_device', id=self.id, _external=True)

The export_data() and import_data() functions are mirror images of each other. One is used to get the information from the database to the user (export_data()), such as when we use the GET method. The other is to put information from the user to the database (import_data()), such as when we use the POST or PUT method:

def export_data(self):
return {
'self_url': self.get_url(),
'hostname': self.hostname,
'loopback': self.loopback,
'mgmt_ip': self.mgmt_ip,
'role': self.role,
'vendor': self.vendor,
'os': self.os
}

def import_data(self, data):
try:
self.hostname = data['hostname']
self.loopback = data['loopback']
self.mgmt_ip = data['mgmt_ip']
self.role = data['role']
self.vendor = data['vendor']
self.os = data['os']
except KeyError as e:
raise ValidationError('Invalid device: missing ' + e.args[0])
return self

With the database object in place as well as import and export functions created, the URL dispatch is straightforward for devices operations. The GET request will return a list of devices by querying all the entries in the devices table and also return the URL of each entry. The POST method will use the import_data() function with the global request object as the input. It will then add the device and commit to the database:

@app.route('/devices/', methods=['GET'])
def get_devices():
return jsonify({'device': [device.get_url()
for device in Device.query.all()]})

@app.route('/devices/', methods=['POST'])
def new_device():
device = Device()
device.import_data(request.json)
db.session.add(device)
db.session.commit()
return jsonify({}), 201, {'Location': device.get_url()}

If you look at the POST method, the returned body is an empty JSON body, with the status code 201 (created) as well as extra headers:

HTTP/1.0 201 CREATED
Content-Length: 2
Content-Type: application/json
Date: ...
Location: http://172.16.1.173:5000/devices/4
Server: Werkzeug/0.9.6 Python/3.5.2

Let's look at the API that queries and returns information pertaining to individual devices.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.131.255