Update controllers to return JSON and fix parameter handling

- Fix decorator parameter order issues with @with_session
- Return JSON responses instead of HTML fragments
- Add proper error handling with JSON error responses
- Fix route parameter conflicts in delete and update endpoints
This commit is contained in:
2026-01-27 13:05:01 +13:00
parent c56739c5fa
commit a7e921805a
3 changed files with 156 additions and 163 deletions

View File

@@ -7,9 +7,29 @@ controller = Microdot()
profiles = Profile()
@controller.get('')
async def list_profiles(request):
"""List all profiles."""
return json.dumps(profiles), 200, {'Content-Type': 'application/json'}
@with_session
async def list_profiles(request, session):
"""List all profiles with current profile info."""
profile_list = profiles.list()
current_id = session.get('current_profile')
# If no current profile in session, use first one
if not current_id and profile_list:
current_id = profile_list[0]
session['current_profile'] = str(current_id)
session.save()
# Build profiles object
profiles_data = {}
for profile_id in profile_list:
profile_data = profiles.read(profile_id)
if profile_data:
profiles_data[profile_id] = profile_data
return json.dumps({
"profiles": profiles_data,
"current_profile_id": current_id
}), 200, {'Content-Type': 'application/json'}
@controller.get('/current')
@with_session
@@ -27,8 +47,13 @@ async def get_current_profile(request, session):
return json.dumps({"error": "No profile available"}), 404
@controller.get('/<id>')
async def get_profile(request, id):
@with_session
async def get_profile(request, id, session):
"""Get a specific profile by ID."""
# Handle 'current' as a special case
if id == 'current':
return await get_current_profile(request, session)
profile = profiles.read(id)
if profile:
return json.dumps(profile), 200, {'Content-Type': 'application/json'}
@@ -53,7 +78,8 @@ async def create_profile(request):
profile_id = profiles.create(name)
if data:
profiles.update(profile_id, data)
return json.dumps(profiles.read(profile_id)), 201, {'Content-Type': 'application/json'}
profile_data = profiles.read(profile_id)
return json.dumps({profile_id: profile_data}), 201, {'Content-Type': 'application/json'}
except Exception as e:
return json.dumps({"error": str(e)}), 400