-
Notifications
You must be signed in to change notification settings - Fork 0
HTTP api #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
HTTP api #1
Changes from 9 commits
485e0d0
ce90890
6a4556a
f8dc052
a2eb8c9
950e82d
0b4e66e
8abc830
cc2ee8a
d8a8095
f0d0fca
02a32cc
f7967a4
eff9f7b
250e722
721fc62
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| *.py[co] | ||
| __pycache__/ | ||
| venv/ | ||
| config.py | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| #!/usr/bin/env python3 | ||
|
|
||
| import config | ||
| from gateserver import db | ||
|
|
||
| def db_create_tables(): | ||
| print('Creating DB tables...', end='') | ||
| with open('./tables.sql', 'r') as f: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Hmm, od suboru s koncovkou .sql by som cakal korektne sql. Tu su to sql fragmenty s |
||
| if not db.conn: db.connect(config.db_url) | ||
| for line in f: | ||
| line = line.split('#')[0].strip() | ||
| if line: db.exec_sql('CREATE TABLE IF NOT EXISTS ' + line) | ||
| print(' OK') | ||
|
|
||
| def all(): | ||
| db_create_tables() | ||
|
|
||
| if __name__ == '__main__': | ||
| all() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| """The server configuration.""" | ||
|
|
||
| http_api = { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Co ja viem ci dicty. Co takto rovno |
||
| 'port': 5047, | ||
| } | ||
|
|
||
| controller_api = { | ||
| 'port': 5042, | ||
| } | ||
|
|
||
| db_url = 'postgresql://user:password@host/dbname' | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| """The UDP server that provides the API for the controllers.""" | ||
|
|
||
| def serve(config): | ||
| # TODO | ||
| print('controller_api would start serving') |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| """Holds the (global) connection to the DB.""" | ||
| # TODO maybe use a connection pool one beautiful day | ||
|
|
||
| import config | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Jop, je, sorry. |
||
| import psycopg2 | ||
|
|
||
| conn = None | ||
|
|
||
| def connect(db_url): | ||
| global conn | ||
| conn = psycopg2.connect(db_url) | ||
| conn.autocommit=True | ||
|
|
||
| def exec_sql(query, args=(), ret=False): | ||
| """Execute the query, returning the result as a list if `ret` is set.""" | ||
| with conn.cursor() as cur: | ||
| cur.execute(query, args) | ||
| if ret: return cur.fetchall() | ||
|
|
||
| # thrown when constraints aren't satisfied | ||
| IntegrityError = psycopg2.IntegrityError | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| """Defines the REST API for CRUD and management.""" | ||
|
|
||
| from . import db | ||
| import nacl.raw as nacl | ||
| import cherrypy | ||
|
|
||
| class MountPoint: | ||
| """Represents a mount point, or path prefix, for attaching resources to.""" | ||
| pass | ||
|
|
||
| class Resource(MountPoint): | ||
| """Represents a REST resource.""" | ||
| exposed = True | ||
|
|
||
| class CRUDResource(Resource): | ||
| """Represents a REST resource that exposes a DB table's CRUD methods.""" | ||
| def __init__(self, tbl, put_columns, get_columns, on_save=lambda x: x): | ||
| assert(tbl.isidentifier()) | ||
| self.table = tbl | ||
| self.put_columns = put_columns | ||
| self.get_columns = get_columns | ||
| self.on_save = on_save | ||
|
|
||
| @cherrypy.tools.json_out() | ||
| def GET(self, id=None): | ||
| cols = list(self.get_columns) | ||
| q = 'SELECT {} FROM {}'.format(','.join(cols), self.table) | ||
| if id: q += ' WHERE id = %s' | ||
| rs = [ dict(zip(cols, r)) for r in db.exec_sql(q, (id,), ret=True) ] | ||
| if id: | ||
| if len(rs) < 1: raise cherrypy.HTTPError('404 Not Found') | ||
| return rs[0] | ||
| else: return rs | ||
|
|
||
| @cherrypy.tools.json_in() | ||
| @cherrypy.tools.json_out() | ||
| def PUT(self, id): | ||
| json = self.on_save(dict(cherrypy.request.json, id=id)) | ||
| print(json) | ||
| cols, values, ps = [], [], [] | ||
| for c in self.put_columns: | ||
| cols.append(c) | ||
| values.append(json.get(c)) | ||
| ps.append('%s') | ||
| q = 'INSERT INTO controller ({}) VALUES ({})'.format(','.join(cols), | ||
| ','.join(ps)) | ||
| try: | ||
| db.exec_sql(q, values) | ||
| except db.IntegrityError as e: | ||
| raise cherrypy.HTTPError('400 Bad Request', e.pgerror) | ||
| return { 'url': cherrypy.url() } | ||
|
|
||
| # TODO POST | ||
|
|
||
| def DELETE(self, id): | ||
| db.exec_sql('DELETE FROM {} WHERE id = %s'.format(self.table), (id,)) | ||
|
|
||
| ################################################################################ | ||
|
|
||
| api_root = MountPoint() | ||
| api_root.controller = CRUDResource('controller', | ||
| get_columns={'id', 'ip', 'name'}, | ||
| put_columns={'id', 'ip', 'key', 'name'}, | ||
| on_save=lambda ctrl: | ||
| dict(ctrl, key=nacl.randombytes(nacl.crypto_secretbox_KEYBYTES))) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Hmm, detaily tabuliek by som cakal v inom subore nez vseobecne triedy vyssie.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Toto chce byť o tom, že "čo vidno v HTTP API". (Skutočný obsah tabuliek sú nadmnožiny toho, čo je tuto.) V jednom súbore je to preto, že všetko (vrátane tých všeobecných tried) to definuje, ako vyzerá HTTP API. Ale som ukecateľná na rozdelenie. A vlastne to aj tak idem celé prepísať... :D |
||
|
|
||
| ################################################################################ | ||
|
|
||
| cherrypy_conf = { | ||
| '/': { | ||
| 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), | ||
| } | ||
| } | ||
| cherrypy.tree.mount(api_root, '/', cherrypy_conf) | ||
|
|
||
| def serve(config): | ||
| cherrypy.config.update({'server.socket_port': config['port']}) | ||
| cherrypy.engine.start() | ||
|
|
||
| def stop(): | ||
| cherrypy.engine.exit() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,3 @@ | ||
| CherryPy==3.6.0 | ||
| psycopg2==2.5.4 | ||
| https://github.com/warner/python-tweetnacl/tarball/b48a25a33f |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| #!/usr/bin/env python3 | ||
| """Gate server runner.""" | ||
|
|
||
| from gateserver import db, controller_api, http_api | ||
| import config | ||
|
|
||
| def serve(): | ||
| db.connect(config.db_url) | ||
| controller_api.serve(config.controller_api) | ||
| http_api.serve(config.http_api) | ||
|
|
||
| if __name__ == '__main__': | ||
| serve() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| controller (id macaddr PRIMARY KEY, ip inet UNIQUE NOT NULL, key bytea NOT NULL, name text) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, slohni .gitignore z fmfi-svt/gate, vyhod
__pycache__a pridaj.*a!.git*.