From ef8955a29094f892a03229ca2707fcb58d3e0844 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Rogalski?= Date: Wed, 11 Oct 2017 19:26:18 +0200 Subject: [PATCH] Overall cleanup: - split superweb.base to superweb.tpl and superweb.rest - concise naming for top-level packages (database -> db) and some objects (e.g. db backend) - remove redundant (obvious) comments --- superweb/{database.py => db.py} | 6 ++-- superweb/resources.py | 59 ++++++++++++++++----------------- superweb/rest.py | 13 ++++++++ superweb/{base.py => tpl.py} | 9 ----- utils/db_create.py | 6 ++-- 5 files changed, 46 insertions(+), 47 deletions(-) rename superweb/{database.py => db.py} (89%) create mode 100644 superweb/rest.py rename superweb/{base.py => tpl.py} (66%) diff --git a/superweb/database.py b/superweb/db.py similarity index 89% rename from superweb/database.py rename to superweb/db.py index 20c0539..cdc3f03 100644 --- a/superweb/database.py +++ b/superweb/db.py @@ -6,7 +6,7 @@ # Tworzymy obiekt bazy danych DB_PATH = str(pathlib.Path(__file__).with_name('todo.db')) -db = SqliteDatabase(DB_PATH) +backend = SqliteDatabase(DB_PATH) class Task(Model): @@ -17,8 +17,6 @@ class Task(Model): completed_at = DateTimeField(null=True) deadline_at = DateTimeField(null=True) - - # Tutaj łączymy nasz model z bazą danych "db" zdefiniowaną wyżej. class Meta: - database = db + database = backend diff --git a/superweb/resources.py b/superweb/resources.py index 8ec37ce..26f839a 100644 --- a/superweb/resources.py +++ b/superweb/resources.py @@ -1,24 +1,21 @@ import json +import datetime from urllib import parse import falcon from playhouse.shortcuts import model_to_dict -from superweb import database -from superweb.base import render_template, json_serializer_handler - -import datetime +from superweb import db +from superweb.rest import json_dumps +from superweb.tpl import render_template +TEXT_HTML = 'text/html' APPLICATION_JSON = 'application/json' -def json_dumps(obj): - return json.dumps(obj, default=json_serializer_handler) - - class ToDoJsonList: def on_get(self, req, resp): - tasks = database.Task.select() + tasks = db.Task.select() tasks_list = [] for t in tasks: @@ -26,26 +23,26 @@ def on_get(self, req, resp): tasks_json = json_dumps(tasks_list) - resp.content_type = 'application/json' + resp.content_type = APPLICATION_JSON resp.body = tasks_json class ToDoList: def on_get(self, req, resp): - tasks = database.Task.select().where(database.Task.is_completed == False) + tasks = db.Task.select().where(db.Task.is_completed == False) tasks_list = [] for t in tasks: tasks_list.append(model_to_dict(t)) - resp.content_type = 'text/html' + resp.content_type = TEXT_HTML resp.body = render_template('todo_list.jinja2', {'tasks': tasks_list, 'now': datetime.datetime.now()}) class ToDo: def on_get(self, req, resp): resp.status = falcon.HTTP_200 - resp.content_type = 'text/html' + resp.content_type = TEXT_HTML resp.body = render_template('todo_add.jinja2') def on_post(self, req, resp): @@ -62,7 +59,7 @@ def on_post(self, req, resp): if deadline_at is not None: deadline_at = datetime.datetime.strptime(deadline_at, "%Y-%m-%S") # this will raise ValueError on format mismatch - database.Task.insert(title=title, description=description, + db.Task.insert(title=title, description=description, deadline_at=deadline_at).execute() raise falcon.HTTPSeeOther('/todo/') @@ -72,7 +69,7 @@ class ToDoComplete: def on_post(self, req, resp, task_id): task_id = int(task_id) - query = database.Task.update(is_completed=True, completed_at=datetime.datetime.now()).where(database.Task.id == task_id) + query = db.Task.update(is_completed=True, completed_at=datetime.datetime.now()).where(db.Task.id == task_id) query.execute() raise falcon.HTTPSeeOther('/todo/') @@ -80,7 +77,7 @@ def on_post(self, req, resp, task_id): class ToDoTaskCompleted: def on_get(self, req, resp): - completed_task = database.Task.select().where(database.Task.is_completed == True) + completed_task = db.Task.select().where(db.Task.is_completed == True) tasks_list = [] for t in completed_task: tasks_list.append(model_to_dict(t)) @@ -92,7 +89,7 @@ def on_get(self, req, resp): class JsonHello: def on_get(self, req, resp): resp.status = falcon.HTTP_200 - resp.content_type = 'application/json' + resp.content_type = APPLICATION_JSON content = {'message': 'Hello World!'} resp.body = json.dumps(content) @@ -109,16 +106,16 @@ class TodoTaskResource: # http://www.restapitutorial.com/lessons/httpmethods.html def on_post(self, req, resp, task_id): try: - database.Task.get(database.Task.id == task_id) - except database.DoesNotExist: + db.Task.get(db.Task.id == task_id) + except db.DoesNotExist: resp.status = falcon.HTTP_NOT_FOUND else: resp.status = falcon.HTTP_CONFLICT def on_get(self, req, resp, task_id): try: - item_to_get = database.Task.get(database.Task.id == task_id) - except database.DoesNotExist: + item_to_get = db.Task.get(db.Task.id == task_id) + except db.DoesNotExist: resp.status = falcon.HTTP_NOT_FOUND else: resp.body = json_dumps(model_to_dict(item_to_get)) @@ -127,8 +124,8 @@ def on_get(self, req, resp, task_id): def on_delete(self, req, resp, task_id): try: - item_to_delete = database.Task.get(database.Task.id == task_id) - except database.DoesNotExist: + item_to_delete = db.Task.get(db.Task.id == task_id) + except db.DoesNotExist: resp.status = falcon.HTTP_NOT_FOUND else: item_to_delete.delete_instance() @@ -136,8 +133,8 @@ def on_delete(self, req, resp, task_id): def on_put(self, req, resp, task_id): try: - item_to_update = database.Task.get(database.Task.id == task_id) - except database.DoesNotExist: + item_to_update = db.Task.get(db.Task.id == task_id) + except db.DoesNotExist: resp.status = falcon.HTTP_NOT_FOUND else: data = json.loads(req.stream.read().decode('utf-8')) @@ -159,18 +156,18 @@ def on_post(self, req, resp): title = data['title'] description = data['description'] deadline_at = data.get('deadline_at') - created_id = database.Task.insert(title=title, - description=description, - deadline_at=deadline_at).execute() + created_id = db.Task.insert(title=title, + description=description, + deadline_at=deadline_at).execute() resp.set_headers({'Location': '/api/todo_tasks/{}'.format(created_id)}) resp.status = falcon.HTTP_CREATED def on_get(self, req, resp): # TODO: pagination, filtering - database.Task.select() + db.Task.select() resp.status = falcon.HTTP_200 - resp.content_type = 'application/json' - resp.body = json_dumps([model_to_dict(t) for t in database.Task.select()]) + resp.content_type = APPLICATION_JSON + resp.body = json_dumps([model_to_dict(t) for t in db.Task.select()]) def on_delete(self, req, resp): resp.status = falcon.HTTP_METHOD_NOT_ALLOWED diff --git a/superweb/rest.py b/superweb/rest.py new file mode 100644 index 0000000..75af450 --- /dev/null +++ b/superweb/rest.py @@ -0,0 +1,13 @@ +import json +import datetime + + +def json_serializer_handler(obj): + if isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() + else: + return None + + +def json_dumps(obj): + return json.dumps(obj, default=json_serializer_handler) diff --git a/superweb/base.py b/superweb/tpl.py similarity index 66% rename from superweb/base.py rename to superweb/tpl.py index 0a2e558..8e2b416 100644 --- a/superweb/base.py +++ b/superweb/tpl.py @@ -1,4 +1,3 @@ -import datetime from pathlib import Path from jinja2 import Environment, FileSystemLoader, select_autoescape @@ -19,11 +18,3 @@ def render_template(name, context=None): rendered_template = template.render(context) return rendered_template - - -def json_serializer_handler(obj): - """Funkcja pozwalająca serializować do jsona obiekt datetime""" - if isinstance(obj, (datetime.datetime, datetime.date)): - return obj.isoformat() - else: - return None diff --git a/utils/db_create.py b/utils/db_create.py index 4fa3e17..59595a8 100644 --- a/utils/db_create.py +++ b/utils/db_create.py @@ -1,7 +1,7 @@ from superweb import database -database.db.connect() +database.backend.connect() tables = [database.Task] -database.db.drop_tables(tables) -database.db.create_tables(tables) +database.backend.drop_tables(tables) +database.backend.create_tables(tables)