Home > Blockchain >  Can't get information from codeforces API in Django
Can't get information from codeforces API in Django

Time:12-09

in my project, I need to show the name of the contest site. I can't hardcode the name as I have to load the name & details of various websites as per user need. I need to show the Contest site name, contest name, contest date & time(found in UNIX format in the API which has to be converted), contest URL (which is in the list of return items but not showing while I open the API)

I am so new in Django and working for the first time with API

I wrote the function in views.py

def homepage(request):
    response = pip._vendor.requests.get('https://codeforces.com/api/contest.list').json()
    return render(request,'home.html',response)

and in HTML I did this to get the name of all contests

<div >
                {% for i in response %}
                {{i.name}}
                {% endfor %} 
        </div>

CodePudding user response:

I think the problem is not related to Django but to how do you handle JSON in particular, in your view the API from request(I presume you are using the requests package) will return JSON

let's take a look at what the API returning:

{
  "status": "OK",
  "result": [
    {
      "id": 1768,
      "name": "Codeforces Round (Div. 2)",
      "type": "CF",
      "phase": "BEFORE",
      "frozen": false,
      "durationSeconds": 7200,
      "startTimeSeconds": 1672929300,
      "relativeTimeSeconds": -2433104
    },
    {
      "id": 1770,
      "name": "Good Bye 2022",
      "type": "CF",
      "phase": "BEFORE",
      "frozen": false,
      "durationSeconds": 9000,
      "startTimeSeconds": 1672410900,
      "relativeTimeSeconds": -1914704
    },
    ...
  ]
}

so in the JSON response, the detail you need is the value of result, this value is an array of dictionaries. Looping through the list and you can get the value

from django.utils.timezone import make_aware
from datetime import datetime

def homepage(request):
    response = pip._vendor.requests.get('https://codeforces.com/api/contest.list').json()
    # convert timestamp to readable datetime string
    for contest in response.result:
        contest["start_time"] = make_aware(datetime.fromtimestamp(contest["startTimeSeconds"]))
    return render(request,'home.html',response)

and in your template:

<div >
   {% for i in response.result %}
        <h3>Name</h3>: <p>{{ i.name }}</p>
        <h3>Date and time</h3>: <p>{{ i.start_time|date:'Y-m-d H:i' }}</p>
    {% endfor %} 
</div>

for the date time format, follow the Django docs

I don't see anything related to contest URL in your API though

  • Related