Skip to content
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

Overall cleanup #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions superweb/database.py → superweb/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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
59 changes: 28 additions & 31 deletions superweb/resources.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,48 @@
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:
tasks_list.append(model_to_dict(t))

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):
Expand All @@ -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/')
Expand All @@ -72,15 +69,15 @@ 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/')


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))
Expand All @@ -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)

Expand All @@ -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))
Expand All @@ -127,17 +124,17 @@ 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()
resp.status = falcon.HTTP_OK

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'))
Expand All @@ -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
Expand Down
13 changes: 13 additions & 0 deletions superweb/rest.py
Original file line number Diff line number Diff line change
@@ -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)
9 changes: 0 additions & 9 deletions superweb/base.py → superweb/tpl.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import datetime
from pathlib import Path

from jinja2 import Environment, FileSystemLoader, select_autoescape
Expand All @@ -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
6 changes: 3 additions & 3 deletions utils/db_create.py
Original file line number Diff line number Diff line change
@@ -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)