app.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 ip_from_name(db, machine):
  7. cur = db.execute('SELECT ip FROM machines where name=?', (machine,))
  8. row = cur.fetchone()
  9. if row is None:
  10. return None
  11. return row[0]
  12. def next_port(db, ip):
  13. BASE_PORT=8000
  14. cur = db.execute('SELECT port FROM domains where ip=? order by port desc limit 1', (ip,))
  15. row = cur.fetchone()
  16. if row is None:
  17. return BASE_PORT
  18. return row[0]+1
  19. def turn_me_to_json(cursor,res):
  20. out = []
  21. for row in res:
  22. v = {}
  23. for i, val in enumerate(row):
  24. v[cursor.description[i][0]]=val
  25. out.append(v)
  26. return out
  27. @route('/machines/', method='GET')
  28. def get_machines(db):
  29. c = db.execute('SELECT mgroup,name,ip FROM machines')
  30. out = turn_me_to_json(c,c.fetchall())
  31. response.content_type = "application/json"
  32. return json.dumps(out)
  33. @route('/machines/<group>/<name>/<ip>', method='PUT')
  34. def put_machines(db, group, name, ip):
  35. c = db.execute('UPDATE machines set mgroup=? and name=? where ip=?', (group,name,ip))
  36. if c.rowcount == 0:
  37. c = db.execute('INSERT INTO machines (mgroup,name,ip) values(?,?,?)', (group,name,ip))
  38. @route('/domains/', method='GET')
  39. def get_domains(db):
  40. c = db.execute('SELECT ip,port,domain,subdomain,user FROM domains')
  41. out = turn_me_to_json(c,c.fetchall())
  42. response.content_type = "application/json"
  43. return json.dumps(out)
  44. @route('/domains/<machine>', method='PUT')
  45. def put_domain(db, machine ):
  46. if request.json is None or \
  47. "domain" not in request.json or \
  48. "user" not in request.json or \
  49. "subdomain" not in request.json:
  50. response.status=400
  51. return
  52. ip = ip_from_name(db,machine)
  53. if ip is None:
  54. response.status=400
  55. return
  56. port = next_port(db,ip)
  57. domain = request.json["domain"]
  58. user = request.json["user"]
  59. sub = request.json["subdomain"]
  60. print(domain)
  61. c = db.execute('UPDATE domains set domain = ?, user = ? where ip=? and subdomain=?',
  62. (domain,user,ip,sub))
  63. if c.rowcount == 0:
  64. print("inserting!")
  65. c = db.execute('INSERT INTO domains(domain,subdomain,user,port,ip) VALUES (?,?,?,?,?)',
  66. (domain,sub,user,port,ip))
  67. else:
  68. print("updating! %d" % c.rowcount)
  69. print(domain,port,user,ip,sub)
  70. run(host='localhost', port=8080)