diff --git a/app/app.db b/app/app.db new file mode 100644 index 0000000..d745561 Binary files /dev/null and b/app/app.db differ diff --git a/app/routes.py b/app/routes.py index ddc580f..76d0f6e 100644 --- a/app/routes.py +++ b/app/routes.py @@ -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 @@ -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/', 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/', 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/', 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" \ No newline at end of file diff --git a/crudapp.py b/crudapp.py index e524e69..7d99868 100644 --- a/crudapp.py +++ b/crudapp.py @@ -1 +1,6 @@ -from app import app \ No newline at end of file +from app import app, db + +db.create_all() + +if __name__ == "__main__": + app.run(debug=True) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..dd6087d --- /dev/null +++ b/migrations/README @@ -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/` | Get entry by ID | +| PUT | `/api/entries/` | Update entry by ID | +| DELETE | `/api/entries/` | 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) + diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 0000000..ec9d45c --- /dev/null +++ b/migrations/alembic.ini @@ -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 diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..68feded --- /dev/null +++ b/migrations/env.py @@ -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() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..2c01563 --- /dev/null +++ b/migrations/script.py.mako @@ -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"} diff --git a/migrations/versions/7a7a4d91d467_entries_table.py b/migrations/versions/7a7a4d91d467_entries_table.py new file mode 100644 index 0000000..d1491ac --- /dev/null +++ b/migrations/versions/7a7a4d91d467_entries_table.py @@ -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 ### diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000..60ddedf --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,60 @@ +import pytest +from app import app, db +from app.models import Entry + +@pytest.fixture +def client(): + app.config['TESTING'] = True + app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' + with app.test_client() as client: + with app.app_context(): + db.create_all() + yield client + with app.app_context(): + db.drop_all() + +def test_get_entries_empty(client): + response = client.get('/api/entries') + assert response.status_code == 200 + assert response.get_json() == [] + +def test_create_entry(client): + data = {'title': 'Test Entry', 'description': 'Test Desc', 'status': True} + response = client.post('/api/entries', json=data) + assert response.status_code == 201 + json_data = response.get_json() + assert json_data['title'] == 'Test Entry' + assert json_data['description'] == 'Test Desc' + +def test_get_entry_by_id(client): + + entry = Entry(title='Entry1', description='Desc1', status=True) + db.session.add(entry) + db.session.commit() + response = client.get(f'/api/entries/{entry.id}') + assert response.status_code == 200 + assert response.get_json()['title'] == 'Entry1' + +def test_update_entry(client): + entry = Entry(title='Old', description='Old', status=False) + db.session.add(entry) + db.session.commit() + data = {'title': 'New', 'description': 'New', 'status': True} + response = client.put(f'/api/entries/{entry.id}', json=data) + assert response.status_code == 200 + assert response.get_json()['title'] == 'New' + +def test_delete_entry(client): + entry = Entry(title='ToDelete', description='DeleteMe', status=False) + db.session.add(entry) + db.session.commit() + response = client.delete(f'/api/entries/{entry.id}') + assert response.status_code == 204 + response = client.get(f'/api/entries/{entry.id}') + assert response.status_code == 404 + +def test_get_entry_not_found(client): + response = client.get('/api/entries/999') + assert response.status_code == 404 + assert response.get_json()['error'] == 'Not found' + print("404 error message:", response.get_json()['error'])