Skip to content

Examples

Runnable scripts ship inside the package. Each one is a short, complete program you can copy as a starting point.

pyhive examples                          # list them
pyhive examples show program_tree        # print one
pyhive examples run program_tree 2       # run one against the server

pyhive examples run signs in the same way as every other pyhive command (see Signing in) and passes extra arguments on to the example. Run as a plain script (python program_tree.py), an example signs in through the browser instead.

Every example defines main(client, *args), so you can also call one from your own code or a notebook:

from pyhive import examples
examples.load("program_tree").main(client, "2")
Example What it does
connect Every way to sign in to Hive, then print the server version and what you can see.
program_tree Print the course tree — program, subjects, modules, exercises — with counts.
find_student Find a student by name or number and show their mentor, classes and progress.
assignments_csv Export assignments as CSV — student, subject, module, exercise, status, submissions.
class_roster Print every class (rooms and student groups) with its members.
weekly_schedule Print the schedule for the next seven days, grouped by day.
open_help_requests List open help requests: who asked, about which exercise, and when it was last answered.
build_module Create a subject, a module and its exercises from a plain Python outline.

The source of each example is below. (Reading this file raw, as an agent does, the source appears as a --8<-- include line: print it with pyhive examples show NAME.)

connect

"""Every way to sign in to Hive, then print the server version and what you can see.

Run:  pyhive examples run connect
"""

import os

from pyhive import HiveClient

HIVE_URL = "https://hive.org"


def connect_with_sso() -> HiveClient:
    # Opens a browser for Hive's SSO page; the token refreshes itself afterwards.
    return HiveClient.from_sso(HIVE_URL, verify=False)


def connect_with_password(username: str, password: str) -> HiveClient:
    return HiveClient(username, password, HIVE_URL, verify=False)


def connect_with_token() -> HiveClient:
    # A bare token cannot be refreshed: once it expires, build a new client.
    # Get one with `pyhive token`.
    return HiveClient.from_api_token(os.environ["HIVE_ACCESS_TOKEN"], HIVE_URL)


def main(client: HiveClient, *_args: str) -> None:
    print(f"Hive version: {client.get_hive_version()}")
    print(f"Server time:  {client.get_server_time()}")
    print(f"Programs:     {[program.name for program in client.get_programs()]}")


if __name__ == "__main__":
    with connect_with_sso() as hive:
        main(hive)

program_tree

"""Print the course tree — program, subjects, modules, exercises — with counts.

Run:  pyhive examples run program_tree [PROGRAM_ID]
"""

from collections import defaultdict

from pyhive import HiveClient
from pyhive.types import Exercise, Module


def main(client: HiveClient, *args: str) -> None:
    programs = (
        [client.get_program(int(args[0]))] if args else list(client.get_programs())
    )
    for program in programs:
        # One request per level, grouped locally, instead of one request per
        # subject and per module through subject.get_modules().
        program_filter = [program.id]
        subjects = sorted(client.get_subjects(parent_program__id__in=program_filter))
        modules: dict[int, list[Module]] = defaultdict(list)
        for module in client.get_modules(
            parent_subject__parent_program__id__in=program_filter
        ):
            modules[module.parent_subject_id].append(module)
        exercises: dict[int, list[Exercise]] = defaultdict(list)
        for exercise in client.get_exercises(
            parent_module__parent_subject__parent_program__id__in=program_filter
        ):
            exercises[exercise.parent_module_id].append(exercise)

        print(f"{program.name} (#{program.id})")
        for subject in subjects:
            print(f"  [{subject.symbol}] {subject.name} (#{subject.id})")
            for module in sorted(modules[subject.id], key=lambda m: m.order):
                count = len(exercises[module.id])
                print(f"    {module.order:>3}. {module.name} — {count} exercises")
                for exercise in sorted(exercises[module.id], key=lambda e: e.order):
                    print(f"         - {exercise.name} (#{exercise.id})")


if __name__ == "__main__":
    with HiveClient.from_sso("https://hive.org", verify=False) as hive:
        main(hive)

find_student

"""Find a student by name or number and show their mentor, classes and progress.

Run:  pyhive examples run find_student "First Last"
      pyhive examples run find_student 1234
"""

from collections import Counter

from pyhive import HiveClient


def main(client: HiveClient, *args: str) -> None:
    if not args:
        print("Pass a student name or number. Students:")
        for each in client.get_students():
            print(f"  {each.number}  {each.display_name}")
        return

    query = args[0]
    student = (
        client.get_student(number=int(query))
        if query.isdigit()
        else client.get_student(name=query)
    )
    if student is None:
        print(f"No single student matches {query!r}.")
        return

    print(f"{student.display_name} (#{student.id}, number {student.number})")
    print(f"  status:  {student.status.value if student.status else '-'}")
    print(f"  program: {student.program.name if student.program else '-'}")
    print(f"  mentor:  {student.mentor.display_name if student.mentor else '-'}")
    print(f"  classes: {', '.join(c.name for c in student.classes) or '-'}")

    by_status = Counter(a.assignment_status.value for a in student.get_assignments())
    print("  assignments:")
    for status, count in by_status.most_common():
        print(f"    {status:<18} {count}")


if __name__ == "__main__":
    import sys

    with HiveClient.from_sso("https://hive.org", verify=False) as hive:
        main(hive, *sys.argv[1:])

assignments_csv

"""Export assignments as CSV — student, subject, module, exercise, status, submissions.

Run:  pyhive examples run assignments_csv > assignments.csv
      pyhive examples run assignments_csv MENTOR_USER_ID   (only that mentor's mentees)
"""

import csv
import sys

from pyhive import HiveClient
from pyhive.types import Exercise, User


def main(client: HiveClient, *args: str) -> None:
    assignments = (
        client.get_assignments(for_mentees_of=int(args[0]))
        if args
        else client.get_assignments()
    )

    # Fetch each lookup table once. assignment.user / assignment.exercise
    # would issue one request per assignment.
    users: dict[int, User] = {user.id: user for user in client.get_users()}
    exercises: dict[int, Exercise] = {ex.id: ex for ex in client.get_exercises()}

    writer = csv.writer(sys.stdout)
    writer.writerow(
        ["student", "subject", "module", "exercise", "status", "submissions"]
    )
    for assignment in assignments:
        student = users.get(assignment.user_id)
        exercise = exercises.get(assignment.exercise_id)
        writer.writerow(
            [
                student.display_name if student else assignment.user_id,
                exercise.parent_subject_name if exercise else "",
                exercise.parent_module_name if exercise else "",
                exercise.name if exercise else assignment.exercise_id,
                assignment.assignment_status.value,
                assignment.submission_count,
            ]
        )


if __name__ == "__main__":
    with HiveClient.from_sso("https://hive.org", verify=False) as hive:
        main(hive, *sys.argv[1:])

class_roster

"""Print every class (rooms and student groups) with its members.

Run:  pyhive examples run class_roster
"""

from pyhive import HiveClient
from pyhive.types import ClassTypeEnum


def main(client: HiveClient, *_args: str) -> None:
    # One users request instead of class.users, which fetches members one by one.
    users = {user.id: user for user in client.get_users()}

    for class_type in ClassTypeEnum:
        print(f"{class_type.value}s")
        for hive_class in client.get_classes(type_=class_type):
            members = [users[uid].display_name for uid in hive_class.user_ids]
            print(f"  {hive_class.name} (#{hive_class.id}) — {len(members)} members")
            for name in sorted(members):
                print(f"      {name}")


if __name__ == "__main__":
    with HiveClient.from_sso("https://hive.org", verify=False) as hive:
        main(hive)

weekly_schedule

"""Print the schedule for the next seven days, grouped by day.

Run:  pyhive examples run weekly_schedule
"""

from collections import defaultdict
from datetime import date, datetime, timedelta, timezone

from pyhive import HiveClient
from pyhive.types import ScheduleEvent


def main(client: HiveClient, *_args: str) -> None:
    start = datetime.now(timezone.utc).replace(
        hour=0, minute=0, second=0, microsecond=0
    )
    end = start + timedelta(days=7)

    days: dict[date, list[ScheduleEvent]] = defaultdict(list)
    # Hive 8.0.0+ filters on start__lt/end__gt, older releases on start__gte/end__lte;
    # each ignores the other's.
    events = client.get_schedule_events(
        start__lt=end, end__gt=start, start__gte=start, end__lte=end
    )
    for event in events:
        days[event.start.date()].append(event)

    if not days:
        print(f"No events between {start:%Y-%m-%d} and {end:%Y-%m-%d}.")
    for day in sorted(days):
        print(f"{day:%A %Y-%m-%d}")
        for event in sorted(days[day], key=lambda e: e.start):
            category = f" [{event.category_name}]" if event.category_name else ""
            print(f"  {event.start:%H:%M}-{event.end:%H:%M}  {event.title}{category}")


if __name__ == "__main__":
    with HiveClient.from_sso("https://hive.org", verify=False) as hive:
        main(hive)

open_help_requests

"""List open help requests: who asked, about which exercise, and when it was last answered.

Run:  pyhive examples run open_help_requests
"""

from pyhive import HiveClient
from pyhive.types import HelpStatusEnum


def main(client: HiveClient, *_args: str) -> None:
    requests = list(
        client.get_help_requests(
            help_status__in=[HelpStatusEnum.OPEN.value], ordering="-id"
        )
    )
    print(f"{len(requests)} open help requests")
    for request in requests:
        exercise = request.for_exercise
        about = f" — {exercise.name}" if exercise else ""
        print(f"#{request.id} [{request.help_type.value}] {request.title}{about}")
        print(f"    asked by {request.user.display_name}")
        responses = list(client.get_help_responses(request))
        if responses:
            print(
                f"    {len(responses)} replies, last on {responses[-1].date:%Y-%m-%d}"
            )


if __name__ == "__main__":
    with HiveClient.from_sso("https://hive.org", verify=False) as hive:
        main(hive)

build_module

"""Create a subject, a module and its exercises from a plain Python outline.

Writes to the server. Everything it creates is deleted again at the end unless
you pass --keep.

Run:  pyhive examples run build_module PROGRAM_ID [--keep]
"""

import random
import string

from pyhive import HiveClient

OUTLINE = {
    "Python Basics": [
        "Variables and types",
        "Conditionals",
        "Loops",
        "Functions",
    ],
}


def main(client: HiveClient, *args: str) -> None:
    if not args:
        print("Pass a program id, e.g.: pyhive examples run build_module 2")
        return
    program = client.get_program(int(args[0]))
    keep = "--keep" in args

    symbol = "".join(random.choices(string.ascii_uppercase, k=2))
    subject = program.create_subject(
        symbol=symbol, name="PyHive example", color="#3F51B5"
    )
    print(f"Created subject [{subject.symbol}] {subject.name} (#{subject.id})")
    try:
        for order, (module_name, exercise_names) in enumerate(OUTLINE.items(), 1):
            module = subject.create_module(name=module_name, order=order)
            print(f"  module {module.name} (#{module.id})")
            for ex_order, exercise_name in enumerate(exercise_names, 1):
                exercise = module.create_exercise(
                    name=exercise_name, order=ex_order, expected_duration="45:00"
                )
                print(f"    exercise {exercise.name} (#{exercise.id})")
    finally:
        if not keep:
            # Deleting a subject deletes its modules and exercises with it.
            subject.delete()
            print("Deleted everything again (pass --keep to keep it).")


if __name__ == "__main__":
    import sys

    with HiveClient.from_sso("https://hive.org", verify=False) as hive:
        main(hive, *sys.argv[1:])