From ba9a5bf9948813d8c3cb1ed40cebf7be337c9ec0 Mon Sep 17 00:00:00 2001 From: Kuriseteru0 <115957758+Kuriseteru0@users.noreply.github.com> Date: Sat, 24 May 2025 11:45:02 +0800 Subject: [PATCH 1/4] statring project --- app/app.db | Bin 0 -> 24576 bytes app/routes.py | 16 ++- crudapp.py | 7 +- migrations/README | 1 + migrations/alembic.ini | 50 ++++++++++ migrations/env.py | 91 ++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../versions/7a7a4d91d467_entries_table.py | 38 ++++++++ 8 files changed, 225 insertions(+), 2 deletions(-) create mode 100644 app/app.db create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/7a7a4d91d467_entries_table.py diff --git a/app/app.db b/app/app.db new file mode 100644 index 0000000000000000000000000000000000000000..a53fe3c6d2cd675fb474d502bfaf9b876b96a3f3 GIT binary patch literal 24576 zcmeI(F>ljA6bJBgouqN3G}(^vRYGd4AVgbAC#1T;f~vuxZa{QEmXlni6S31Kmrw?V zcID$R@rf82VdQM$Dvm0cQ~gh}b7w!ly!+Y9$;s(STPi{4qj3}}+GTZS80>(EF=pwl zq_?aUbSK%eW@Mdzd|K@B>}$35n-#0ySgl(7z7cFN-9>`{1Rwwb2tWV=5P$##AOL~? z3mg|q+~$Um@jzV3t3bqR{5eok4Mo~5wS3pLs#s~Q^v>~HuN=Se?5UkQyYPj#G21&&@<9_7s_BFdJDs-ccuCSX z{?Tj4Kci#!j2d!aSL|!sSm({Aabu;`hC>ncWIvdR@kC234cBrrSUO3KiZ#D1h^NtQ zS-U&=s#+cIwCg*1&a{*vxcJzoT!{<$bgj?VO8lg0u=K`FE{A#*AB0miO2@%+vhAe< zrhd%I$)i?HcJ*Y31_1~_00Izz00bZa0SG_<0uX?}eHExA6T|xdzTRHU3jz>;00bZa z0SG_<0uX=z1R#(KWbglLKL7#&2tWV=5P$##AOHafKmY;|fWYbrJT!`IbH6NUIGPEr z2Yky?pJZReG8PnxNc8mo8nXBQwV$guLsSd_2tWV=5P$##AOHafKmY;|fIv>*fw^x* xG7jtJmUZ{~|5q*^0|-C>0uX=z1Rwwb2tWV=5P$##R$8EHZd$Tz^1nX@_ygx+-h%)D literal 0 HcmV?d00001 diff --git a/app/routes.py b/app/routes.py index ddc580f..9000819 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,20 @@ 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.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..0e04844 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. 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 ### From f92e71f2e63c621583dd0a8d1785140e9b4d27bf Mon Sep 17 00:00:00 2001 From: Kuriseteru0 <115957758+Kuriseteru0@users.noreply.github.com> Date: Sat, 24 May 2025 12:03:44 +0800 Subject: [PATCH 2/4] download some requirements and fix unittest --- app/routes.py | 58 +++++++++++++++++++++++++++++++++++++++++++++++ tests/test_api.py | 55 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 tests/test_api.py diff --git a/app/routes.py b/app/routes.py index 9000819..76d0f6e 100644 --- a/app/routes.py +++ b/app/routes.py @@ -98,6 +98,64 @@ def api_get_entries(): '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) diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000..05d48d4 --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,55 @@ +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): + # First, create an entry + 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 + # Confirm deletion + response = client.get(f'/api/entries/{entry.id}') + assert response.status_code == 404 \ No newline at end of file From 3a96015ac1ba34f79790a95011a340b2d506eb5c Mon Sep 17 00:00:00 2001 From: Kuriseteru0 <115957758+Kuriseteru0@users.noreply.github.com> Date: Mon, 26 May 2025 20:43:56 +0800 Subject: [PATCH 3/4] check status --- app/app.db | Bin 24576 -> 24576 bytes tests/test_api.py | 6 +++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/app.db b/app/app.db index a53fe3c6d2cd675fb474d502bfaf9b876b96a3f3..2a424bae8b7a9f41f9258746776c102836065951 100644 GIT binary patch delta 133 zcmZoTz}Rqrae_1>??f4AM&6AHEA<(#Y!(za#c!s?$jTt@%NbIhnVhQNmzkHUkeiyD zlv-4*P@Y+mp^%=RpQ2EfSzMZ!Q>@3u00aUI4E%S1dN1*-C^P$V64J9N;5R=j*mMA_ CASyWk delta 116 zcmZoTz}Rqrae_1>=R_H2M$U~1EA<(lZx$4|z;B?!$jYE-&XK8*lV6r94&;cdbC#56 zCa30Q=A|m+rsk$5r4|))F#v%80|Wnipsu_8k`m13oVl5Ki2}^(oG1!61^nh`1?vX@ Dap@t% diff --git a/tests/test_api.py b/tests/test_api.py index 05d48d4..ed238fc 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -27,7 +27,7 @@ def test_create_entry(client): assert json_data['description'] == 'Test Desc' def test_get_entry_by_id(client): - # First, create an entry + entry = Entry(title='Entry1', description='Desc1', status=True) db.session.add(entry) db.session.commit() @@ -50,6 +50,6 @@ def test_delete_entry(client): db.session.commit() response = client.delete(f'/api/entries/{entry.id}') assert response.status_code == 204 - # Confirm deletion response = client.get(f'/api/entries/{entry.id}') - assert response.status_code == 404 \ No newline at end of file + assert response.status_code == 404 + \ No newline at end of file From e41cd105c7fd96803dc69ca2b5bbbb3ff8ac5987 Mon Sep 17 00:00:00 2001 From: Kuriseteru0 <115957758+Kuriseteru0@users.noreply.github.com> Date: Mon, 26 May 2025 20:57:43 +0800 Subject: [PATCH 4/4] final check --- app/app.db | Bin 24576 -> 24576 bytes migrations/README | 79 +++++++++++++++++++++++++++++++++++++++++++++- tests/test_api.py | 7 +++- 3 files changed, 84 insertions(+), 2 deletions(-) diff --git a/app/app.db b/app/app.db index 2a424bae8b7a9f41f9258746776c102836065951..d745561a8dbc40423dba25959b203109fc2d91f4 100644 GIT binary patch delta 93 zcmZoTz}Rqrae_1>|3n#QM*fWnEA=;X2At-fe8pZ_n4OW8fuEnFxR{Fp2m}}y_??f4AM&6AHEA<(#Y!(za#XtFqy|S=ES!Qu*VotFh7XuIoFfj1n n0ZLxtpM1w(o(&?gnbF`f|HKJ$e7wwxoS7WV;+!GnnaQaD` | 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/tests/test_api.py b/tests/test_api.py index ed238fc..60ddedf 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -52,4 +52,9 @@ def test_delete_entry(client): assert response.status_code == 204 response = client.get(f'/api/entries/{entry.id}') assert response.status_code == 404 - \ No newline at end of file + +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'])