Add SQLAlchemy and database boilerplate code

This commit is contained in:
Lexi / Zoe 2022-04-02 01:06:59 +02:00
parent 2da6e43797
commit 31df889dcb
Signed by: binaryDiv
GPG key ID: F8D4956E224DA232
15 changed files with 454 additions and 60 deletions

View file

@ -1,28 +1,53 @@
from flask import Blueprint, jsonify
from flask import jsonify
from flask.views import MethodView
from sqlalchemy.orm import Session
from werkzeug.exceptions import NotFound
from tofu_api.common.rest import BaseBlueprint
from tofu_api.models import Task
class TaskApiBlueprint(Blueprint):
class TaskApiBlueprint(BaseBlueprint):
"""
Blueprint for the tasks REST API.
"""
def __init__(self):
super().__init__('rest_api_tasks', __name__, url_prefix='/tasks')
# Blueprint settings
name = 'rest_api_tasks'
import_name = __name__
url_prefix = '/tasks'
def init_blueprint(self) -> None:
"""
Register URL rules.
"""
db_session = self.app.dependencies.get_db_session()
self.add_url_rule(
'/',
view_func=TaskCollectionView.as_view(TaskCollectionView.__name__),
'',
view_func=self.create_view_func(TaskCollectionView, db_session=db_session),
methods=['GET', 'POST'],
)
self.add_url_rule(
'/<int:task_id>',
view_func=TaskItemView.as_view(TaskItemView.__name__),
view_func=self.create_view_func(TaskItemView, db_session=db_session),
methods=['GET', 'PATCH', 'DELETE'],
)
class TaskCollectionView(MethodView):
class TaskBaseView(MethodView):
"""
Base class for view classes for the `/tasks` endpoint.
"""
# TODO: Use a handler class instead of accessing the database session directly
db_session: Session
def __init__(self, *, db_session: Session):
self.db_session = db_session
class TaskCollectionView(TaskBaseView):
"""
View class for `/tasks` endpoint.
"""
@ -31,28 +56,26 @@ class TaskCollectionView(MethodView):
"""
Get list of all tasks.
"""
# TODO: Get actual data
task_list = self.db_session.query(Task).all()
return jsonify({
'count': 1,
'items': [
{
'id': 1,
'title': 'Do stuff',
'description': '',
'status': 'open',
},
],
'count': len(task_list),
'items': [task.to_dict() for task in task_list],
}), 200
def post(self):
"""
Create a new task.
"""
# TODO: Implement
raise NotImplementedError
# TODO: Parse request data and create real data
new_task = Task(
title='Do stuff'
)
self.db_session.add(new_task)
self.db_session.commit()
return jsonify(new_task.to_dict()), 201
class TaskItemView(MethodView):
class TaskItemView(TaskBaseView):
"""
View class for `/tasks/<int:task_id>` endpoint.
"""
@ -61,13 +84,10 @@ class TaskItemView(MethodView):
"""
Get a single task by ID.
"""
# TODO: Get actual data
return jsonify({
'id': task_id,
'title': 'Do stuff',
'description': '',
'status': 'open',
}), 200
task = self.db_session.query(Task).get(task_id)
if task is None:
raise NotFound(f'Task with ID {task_id} not found!')
return jsonify(task.to_dict()), 200
def patch(self, task_id: int):
"""