app.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env python3
  2. from bottle import route, run, request, install, response
  3. from bottle_sqlite import SQLitePlugin
  4. import json
  5. install(SQLitePlugin(dbfile='test.db'))
  6. def turn_me_to_json(cursor,res):
  7. out = []
  8. for row in res:
  9. v = {}
  10. for i, val in enumerate(row):
  11. v[cursor.description[i][0]]=val
  12. out.append(v)
  13. return out
  14. @route('/machines/', method='GET')
  15. def get_machines(db):
  16. c = db.execute('SELECT mgroup,name,ip FROM machines')
  17. out = turn_me_to_json(c,c.fetchall())
  18. response.content_type = "application/json"
  19. return json.dumps(out)
  20. @route('/machines/<group>/<name>/<ip>', method='PUT')
  21. def put_machines(db, group, name, ip):
  22. c = db.execute('UPDATE machines set mgroup=? and name=? where ip=?', (group,name,ip))
  23. if c.rowcount == 0:
  24. c = db.execute('INSERT INTO machines (mgroup,name,ip) values(?,?,?)', (group,name,ip))
  25. @route('/domain/', method='GET')
  26. def get_domains(db):
  27. c = db.execute('SELECT ip,port,domain,subdomain FROM domains')
  28. out = turn_me_to_json(c,c.fetchall())
  29. response.content_type = "application/json"
  30. return json.dumps(out)
  31. @route('/domain/<ip>', method='PUT')
  32. def put_domain(db, ip="Mystery Domain" ):
  33. if request.json is None or "domain" not in request.json or "subdomain" not in request.json or "port" not in request.json:
  34. response.status=400
  35. return
  36. c = db.execute('UPDATE domains set domain=? and subdomain=? and port=? where ip=?',
  37. (request.json["domain"],request.json["subdomain"],request.json["port"],ip))
  38. if c.rowcount == 0:
  39. c = db.execute('INSERT INTO user_machines (ip,name) values(?,?)', (request.json["ip"],name))
  40. return
  41. run(host='localhost', port=8080)