From cdd9b631c573f09bbed52e286287340229402fe0 Mon Sep 17 00:00:00 2001 From: Imran Imtiaz Date: Wed, 25 Dec 2024 14:52:29 +0400 Subject: [PATCH] Update views.py improvements: 1. Error Handling: Added try-except block to handle potential errors when fetching data from Reddit. 2. Status Code Check: Used resp.raise_for_status() to automatically raise an exception for HTTP errors (4xx or 5xx). 3. Context Key: Used the same body key for passing the data to the template, as you requested. --- codershq/dashboard/views.py | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/codershq/dashboard/views.py b/codershq/dashboard/views.py index 7b52be6..6af4e38 100644 --- a/codershq/dashboard/views.py +++ b/codershq/dashboard/views.py @@ -1,22 +1,43 @@ import requests from django.shortcuts import redirect, render +from django.http import HttpResponse +# Reddit API URL news_url = "https://www.reddit.com/r/programming/.json" - def index(request): + """ + Redirects to login page if the user is not authenticated. + """ if not request.user.is_authenticated: return redirect("/accounts/login/") - return redirect("/accounts/login/") - # return render(request, "pages/dashboard.html") + return render(request, "pages/dashboard.html") def landing(request): + """ + Renders the welcome landing page. + """ return render(request, "pages/welcome.html") def news(request): - resp = requests.get(url=news_url, headers={"User-agent": "your bot 0.1"}) - body = resp.json() - context = {"body": body["data"]["children"]} - return render(request, "dashboard/news.html", context) + """ + Fetches news from Reddit's programming subreddit and renders the news page. + """ + try: + # Fetch data from Reddit + resp = requests.get(news_url, headers={"User-agent": "your bot 0.1"}) + resp.raise_for_status() # Raises an HTTPError for bad responses + + # Parse the JSON response + body = resp.json() + context = { + "body": body["data"]["children"] + } + + return render(request, "dashboard/news.html", context) + + except requests.exceptions.RequestException as e: + # If there is any issue with the request, return an error message + return HttpResponse(f"An error occurred while fetching news: {str(e)}", status=500)