Last active
December 21, 2017 00:38
-
-
Save platisd/6fa83f217cde154e1be3cc156e37b70b to your computer and use it in GitHub Desktop.
A simple REST server written in Python and Flask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A very simple REST server using Python and Flask. | |
Install dependencies: | |
* pip3 install flask flask-jsonpify flask-sqlalchemy flask-restful | |
Usage: | |
GET movement and light for <node id>: http://localhost:5000/node/<node id> | |
POST movement and light for <node id>: http://localhost:5000/node/<node id>/<movement>/<light> | |
""" | |
from flask import Flask, request, jsonify | |
from flask_restful import Resource, Api | |
from sqlalchemy import create_engine | |
from json import dumps | |
# Set up the database and the Flask app | |
db_connect = create_engine('sqlite:///medtech-iot.db') | |
app = Flask("medtech-iot") | |
# Create the table with our nodes | |
conn = db_connect.connect() | |
conn.execute("create table IF NOT EXISTS nodes(node_id integer PRIMARY_KEY UNIQUE, movement boolean NOT NULL, light boolean NOT NULL)") | |
# Set up the REST API | |
api = Api(app) | |
@app.route('/node/<node_id>', methods=['GET']) | |
def get_node(node_id): | |
conn = db_connect.connect() | |
query = conn.execute("select * from nodes where node_id = %s" % node_id) | |
result = {'data': [dict(zip(tuple(query.keys()), i)) for i in query.cursor]} | |
return jsonify(result) | |
@app.route('/node/<node_id>/<movement>/<light>', methods=['POST']) | |
def set_node(node_id, movement, light): | |
conn = db_connect.connect() | |
trans = conn.begin() | |
conn.execute("replace into nodes(node_id, movement, light) values(%s, %s, %s)" % (node_id, movement, light)) | |
trans.commit() # We need to commit the transaction since we are inserting | |
return jsonify({'status': 'success'}) | |
def main(): | |
app.run() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment