Skip to content

Bugayong #6

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

Open
wants to merge 4 commits 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
Binary file added app/app.db
Binary file not shown.
74 changes: 73 additions & 1 deletion app/routes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from flask import render_template, request, redirect
from flask import render_template, request, redirect, jsonify
from app import app, db
from app.models import Entry

Expand Down Expand Up @@ -86,6 +86,78 @@ def turn(id):

return "of the jedi"



@app.route('/api/entries', methods=['GET'])
def api_get_entries():
entries = Entry.query.all()
return jsonify([{
'id': e.id,
'title': e.title,
'description': e.description,
'status': e.status
} for e in entries]), 200

@app.route('/api/entries', methods=['POST'])
def api_create_entry():
data = request.get_json()
if not data or not data.get('title') or not data.get('description'):
return jsonify({'error': 'Missing data'}), 400
entry = Entry(
title=data['title'],
description=data['description'],
status=data.get('status', False)
)
db.session.add(entry)
db.session.commit()
return jsonify({
'id': entry.id,
'title': entry.title,
'description': entry.description,
'status': entry.status
}), 201

@app.route('/api/entries/<int:id>', methods=['GET'])
def api_get_entry(id):
entry = Entry.query.get(id)
if not entry:
return jsonify({'error': 'Not found'}), 404
return jsonify({
'id': entry.id,
'title': entry.title,
'description': entry.description,
'status': entry.status
}), 200

@app.route('/api/entries/<int:id>', methods=['PUT'])
def api_update_entry(id):
entry = Entry.query.get(id)
if not entry:
return jsonify({'error': 'Not found'}), 404
data = request.get_json()
if not data:
return jsonify({'error': 'Missing data'}), 400
entry.title = data.get('title', entry.title)
entry.description = data.get('description', entry.description)
entry.status = data.get('status', entry.status)
db.session.commit()
return jsonify({
'id': entry.id,
'title': entry.title,
'description': entry.description,
'status': entry.status
}), 200

@app.route('/api/entries/<int:id>', methods=['DELETE'])
def api_delete_entry(id):
entry = Entry.query.get(id)
if not entry:
return jsonify({'error': 'Not found'}), 404
db.session.delete(entry)
db.session.commit()
return '', 204


# @app.errorhandler(Exception)
# def error_page(e):
# return "of the jedi"
7 changes: 6 additions & 1 deletion crudapp.py
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
from app import app
from app import app, db

db.create_all()

if __name__ == "__main__":
app.run(debug=True)
78 changes: 78 additions & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Flask Final Laboratory: Entry Manager with REST API

## Overview

This Final laboratory a Flask web application for managing entries (with title, description, and status).
It features both a traditional web interface and a fully functional REST API for CRUD operations.

## Features

- Web interface for adding, viewing, updating, and deleting entries
- REST API with full CRUD support:
- Create, Read, Update, Delete entries via JSON
- Proper HTTP status codes and error handling
- Unit tests for all API endpoints (positive and negative cases)
- Database migrations using Flask-Migrate

## REST API Endpoints

| Method | Endpoint | Description |
|--------|-------------------------|----------------------------|
| GET | `/api/entries` | List all entries |
| POST | `/api/entries` | Create a new entry |
| GET | `/api/entries/<id>` | Get entry by ID |
| PUT | `/api/entries/<id>` | Update entry by ID |
| DELETE | `/api/entries/<id>` | Delete entry by ID |


### Error Responses

- `400 Bad Request` — Missing or invalid data
- `404 Not Found` — Entry does not exist

## How to Run

1. **Clone the repository:**

git clone https://github.com/your-username/Flask_Final_Laboratory.git
cd Flask_Final_Laboratory


2. **Install dependencies:**

pip install -r requirements.txt


3. **Set up the database:**

flask db upgrade


4. **Run the app:**

python crudapp.py


5. **Run tests:**
python -m pytest

## Testing

- All API endpoints are covered by unit tests in `tests/test_api.py`

## Enhancements

- REST API added for entries
- Added Unittest
- Improved error handling and status codes

## API Documentation

- See the table above for endpoints.
- All endpoints accept and return JSON.

## Author & Credits

- Forked and enhanced by [Marie Cristel Bugayong](https://github.com/Kuriseteru0)
- Original project by [Gürkan Akdeniz](https://github.com/gurkanakdeniz)

50 changes: 50 additions & 0 deletions migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# A generic, single database configuration.

[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false


# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic,flask_migrate

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[logger_flask_migrate]
level = INFO
handlers =
qualname = flask_migrate

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
91 changes: 91 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
from __future__ import with_statement

import logging
from logging.config import fileConfig

from flask import current_app

from alembic import context

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
config.set_main_option(
'sqlalchemy.url',
str(current_app.extensions['migrate'].db.get_engine().url).replace(
'%', '%%'))
target_metadata = current_app.extensions['migrate'].db.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def run_migrations_offline():
"""Run migrations in 'offline' mode.

This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.

Calls to context.execute() here emit the given string to the
script output.

"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url, target_metadata=target_metadata, literal_binds=True
)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online():
"""Run migrations in 'online' mode.

In this scenario we need to create an Engine
and associate a connection with the context.

"""

# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')

connectable = current_app.extensions['migrate'].db.get_engine()

with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args
)

with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
24 changes: 24 additions & 0 deletions migrations/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}


def upgrade():
${upgrades if upgrades else "pass"}


def downgrade():
${downgrades if downgrades else "pass"}
38 changes: 38 additions & 0 deletions migrations/versions/7a7a4d91d467_entries_table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""entries table

Revision ID: 7a7a4d91d467
Revises:
Create Date: 2025-05-24 11:34:05.303791

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '7a7a4d91d467'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('entry',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=64), nullable=False),
sa.Column('description', sa.String(length=120), nullable=False),
sa.Column('status', sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_entry_description'), 'entry', ['description'], unique=False)
op.create_index(op.f('ix_entry_title'), 'entry', ['title'], unique=False)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_entry_title'), table_name='entry')
op.drop_index(op.f('ix_entry_description'), table_name='entry')
op.drop_table('entry')
# ### end Alembic commands ###
Loading