API get only assignments that are not submitted by current student

Jump to solution
BenediktMoore
Community Novice

i am trying to build a todo list app for personal use. however it returns assignments that i've already submitted and i can't find how i need to filter them

 

 

import requests
from datetime import datetime, timedelta
# Use a pipeline as a high-level helper
from transformers import pipeline

pipe = pipeline("summarization", model="Falconsai/text_summarization")
import re
# as per recommendation from @freylis, compile once only
CLEANR = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')

def cleanhtml(raw_html):
  cleantext = re.sub(CLEANR, '', raw_html)
  return cleantext
def sumtxt(input):
    if (len(input) > 512):
        #print('\n'+input+'\n')
        input = input.strip().replace("\n","")
        if (len(input) > 512):
            input = input[:510]
    return pipe(input,max_length=20,min_length=10,do_sample=False)[0]['summary_text']

def fetch_courses(token):
    url = "https://iusd.instructure.com/api/v1/courses?per_page=100"
    headers = {
        'Authorization': f'Bearer {token}'
    }
    response = requests.get(url, headers=headers)
    response.raise_for_status()  # Raise an error for bad responses
    return response.json()

def fetch_assignments(token, course_id):
    url = f"https://iusd.instructure.com/api/v1/courses/{course_id}/assignments?per_page=100?bucket=upcoming?include[]=submission"
   # url2 = f"https://iusd.instructure.com/api/v1/courses/{course_id}/students/submissions?per_page=100"
    
    headers = {
        'Authorization': f'Bearer {token}'
    }
    response = requests.get(url, headers=headers)
    #response2 = requests.get(url2, headers=headers)
    try:
        response.raise_for_status()  # Raise an error for bad responses
       #print(response.json())
        #print(response2.json())
        print(response.json())
        return response.json()
    except:
        return ""
import requests


def filter_and_sort_assignments(assignments):
    now = datetime.now()
    two_weeks_from_now = now + timedelta(weeks=2)
    two_weeks_from_now.replace(tzinfo=None)

    filtered_assignments = [
        assignment for assignment in assignments
        
        if assignment['due_at'] and datetime.fromisoformat(assignment['due_at'].replace('Z', '+00:00')).replace(tzinfo=None) <= two_weeks_from_now and not ('submission' in assignment )
    ]#or assignment['graded_submissions_exist']

    # Sort by due date
    filtered_assignments.sort(key=lambda x: datetime.fromisoformat(x['due_at'].replace('Z', '+00:00')))
    return filtered_assignments

def main():
    token = "SOMEEXAMPLETOKEN"
    
    try:
        courses = fetch_courses(token)
        all_assignments = []

        for course in courses:
            assignments = fetch_assignments(token, course['id'])
            all_assignments.extend(assignments)

        filtered_assignments = filter_and_sort_assignments(all_assignments)

        print("\nTodo List of Assignments:")
        filtered_assignments=[]
        for assignment in filtered_assignments:
            due_date = datetime.fromisoformat(assignment['due_at'].replace('Z', '+00:00')).strftime('%Y-%m-%d')
            print(assignment)
            print(f"{assignment['name']} - Due: {due_date} - Points: {assignment.get('points', 'N/A')} - Summary: {sumtxt(cleanhtml(assignment.get('description', 'no description available'))) + '...'}")

    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    #messages = [
    #{"role": "user", "content": "Who are you?"},
    #]
    #pipe = pipeline("text-generation", model="Qwen/Qwen2.5-1.5B-Instruct")
    #print(pipe(messages))
    main()

 

 

Labels (1)
0 Likes
1 Solution
BenediktMoore
Community Novice
Author

for anyone else the solution is to get the submissions and then filter assignments with same id as submissions like this

 

import requests
from datetime import datetime, timedelta
import time
# Use a pipeline as a high-level helper
from transformers import pipeline

pipe = pipeline("summarization", model="Falconsai/text_summarization")
import re
# as per recommendation from @freylis, compile once only
CLEANR = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')

def cleanhtml(raw_html):
  cleantext = re.sub(CLEANR, '', raw_html)
  return cleantext
def sumtxt(input):
    if (len(input) > 512):
        #print('\n'+input+'\n')
        input = input.strip().replace("\n","")
        if (len(input) > 512):
            input = input[:510]
    return pipe(input,max_length=20,min_length=10,do_sample=False)[0]['summary_text']

def fetch_courses(token):
    url = "https://iusd.instructure.com/api/v1/courses?per_page=100"
    headers = {
        'Authorization': f'Bearer {token}'
    }
    response = requests.get(url, headers=headers)
    response.raise_for_status()  # Raise an error for bad responses
    return response.json()

def fetch_assignments(token, course_id):
    url = f"https://iusd.instructure.com/api/v1/courses/{course_id}/assignments?per_page=100?bucket=upcoming?include[]=submission"
    url2 = f"https://iusd.instructure.com/api/v1/courses/{course_id}/students/submissions?per_page=100"
    
    headers = {
        'Authorization': f'Bearer {token}'
    }
    response = requests.get(url, headers=headers)
    response2 = requests.get(url2, headers=headers)
    try:
        response.raise_for_status()  # Raise an error for bad responses
        print(response.json())
        print(response2.json())

        return [response.json(),response2.json()]
    except:
        return [[],[]]
import requests


def filter_and_sort_assignments(assignments,submissions):
    now = datetime.now()
    two_weeks_from_now = now + timedelta(weeks=2)


    filtered_assignments = []

    for assignment in assignments:
        if assignment['due_at']:
            due_date = datetime.fromisoformat(assignment['due_at'].replace('Z', '+00:00')).replace(tzinfo=None)
            ct=True
            for i in submissions:
                if (i.get('assignment_id') == assignment.get('id')):
                    if (i.get('workflow_state') == 'unsubmitted'):
                        ct=True
                    else:
                        ct=False
                
            if due_date <= two_weeks_from_now and ct:
                filtered_assignments.append(assignment)
    # Sort by due date
    filtered_assignments.sort(key=lambda x: datetime.fromisoformat(x['due_at'].replace('Z', '+00:00')))
    return filtered_assignments

def main():
    token = "SOMEEXAMPLETOKEN"
    
    try:
        courses = fetch_courses(token)
        all_assignments = []
        all_submissions = []

        for course in courses:
            assignments = fetch_assignments(token, course['id'])
            all_assignments.extend(assignments[0])
            all_submissions.extend(assignments[1])

        filtered_assignments = filter_and_sort_assignments(all_assignments,all_submissions)

        print("\nTodo List of Assignments:")
        for assignment in filtered_assignments:
            due_date = datetime.fromisoformat(assignment['due_at'].replace('Z', '+00:00')).strftime('%Y-%m-%d')
            print(assignment)
            print(f"{assignment['name']} - Due: {due_date} - Points: {assignment.get('points', 'N/A')} - Summary: {sumtxt(cleanhtml(assignment.get('description', 'no description available'))) + '...'}")

    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    #messages = [
    #{"role": "user", "content": "Who are you?"},
    #]
    #pipe = pipeline("text-generation", model="Qwen/Qwen2.5-1.5B-Instruct")
    #print(pipe(messages))
    main()

 

View solution in original post

0 Likes