### Copy Example .env File Source: https://github.com/erseco/python-moodle/blob/main/docs/getting-started/configuration.md Copy the example .env file to start configuring your credentials. ```bash cp .env.example .env ``` -------------------------------- ### Run Example Script Source: https://github.com/erseco/python-moodle/blob/main/README.md Execute the main example script to understand library usage. Ensure a valid .env file and installed dependencies. ```bash python example_script.py ``` -------------------------------- ### Install and Run python-moodle CLI Source: https://github.com/erseco/python-moodle/blob/main/README.md Install the library using pip, copy the example environment file, and configure your Moodle URL and credentials. Then, run a basic command to list courses. ```bash pip install python-moodle cp .env.example .env # Edit .env with your Moodle URL and credentials py-moodle courses list ``` -------------------------------- ### Docker Development Setup Source: https://github.com/erseco/python-moodle/blob/main/docs/development.md Commands for starting the Docker development instance and running local tests. ```bash docker-compose up -d MOODLE_LOCAL_URL=http://localhost:8080 make test-local ``` -------------------------------- ### Install python-moodle Source: https://context7.com/erseco/python-moodle/llms.txt Install the package using pip. Copy the example environment file to configure your Moodle instance credentials. ```bash pip install python-moodle ``` ```bash cp .env.example .env ``` -------------------------------- ### Install MkDocs and Build Documentation Source: https://github.com/erseco/python-moodle/blob/main/README.md Install necessary packages for building documentation and then build the MkDocs site strictly. ```bash pip install mkdocs 'mkdocstrings[python]' mkdocs build --strict ``` -------------------------------- ### Start Local Moodle and Verify CLI Source: https://context7.com/erseco/python-moodle/llms.txt Use Docker Compose to start a local Moodle instance for testing. Verify the CLI installation by listing courses. ```bash # Start a local Moodle for testing docker-compose up -d # Verify the CLI works py-moodle courses list ``` -------------------------------- ### Clone and Set Up Development Environment Source: https://github.com/erseco/python-moodle/blob/main/docs/development.md Clone the repository, create a virtual environment, and install the project in development mode. ```bash git clone https://github.com/erseco/python-moodle.git cd py-moodle # Create virtual environment python -m venv env source env/bin/activate # On Windows: env\Scripts\activate # Install in development mode pip install -e . ``` -------------------------------- ### Example .env.example Configuration Source: https://github.com/erseco/python-moodle/blob/main/AGENTS.md This example shows the typical environment variables required for Moodle connection, including URL, username, and password. ```dotenv MOODLE_URL=https://sandbox.moodledemo.net MOODLE_USERNAME=admin MOODLE_PASSWORD=sandbox24 # CAS_URL=https://cas.your-institution.org/cas ``` -------------------------------- ### Development Environment Variables Source: https://github.com/erseco/python-moodle/blob/main/docs/development.md Example environment variables for local development setup. ```env MOODLE_LOCAL_URL=http://localhost:8080 MOODLE_LOCAL_USERNAME=admin MOODLE_LOCAL_PASSWORD=admin DEBUG=true ``` -------------------------------- ### Install python-moodle from PyPI Source: https://github.com/erseco/python-moodle/blob/main/README.md Use pip to install the library from the Python Package Index. This is the recommended installation method. ```bash pip install python-moodle ``` -------------------------------- ### Start Local Moodle Stack with Make Source: https://github.com/erseco/python-moodle/blob/main/docs/troubleshooting.md Use the `make upd` command to start the local Moodle stack. This is often required when the local Moodle host is unreachable. ```bash make upd ``` -------------------------------- ### Install python-moodle from Source Source: https://github.com/erseco/python-moodle/blob/main/README.md Clone the repository and install the library locally. This is useful for development or when you need the latest unreleased changes. ```bash git clone https://github.com/erseco/python-moodle.git cd python-moodle pip install . ``` -------------------------------- ### CLI Command Examples Source: https://github.com/erseco/python-moodle/blob/main/AGENTS.md Demonstrates common command-line interface operations for managing courses and modules within Moodle. ```sh # List all courses py-moodle courses list ``` ```sh # Show details for a specific course py-moodle courses show ``` ```sh # Create a new course py-moodle courses create --fullname "My New Course" --shortname "mynewcourse" ``` ```sh # Delete a course py-moodle courses delete ``` ```sh # Add a new label to a course section py-moodle modules add label --name "My Label" --intro "Label content" ``` -------------------------------- ### Verify py-moodle Installation Source: https://github.com/erseco/python-moodle/blob/main/docs/getting-started/installation.md Run this command after installation to confirm that py-moodle is correctly installed and accessible. It should display the main help screen. ```bash py-moodle --help ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/erseco/python-moodle/blob/main/docs/development.md Install essential tools for development, including linters, formatters, and documentation generators. ```bash # Core development tools pip install black isort flake8 pytest # Documentation tools pip install mkdocs mkdocs-material mkdocstrings[python] ``` -------------------------------- ### Install py-moodle from Source Source: https://github.com/erseco/python-moodle/blob/main/docs/getting-started/installation.md Clone the repository and install py-moodle locally. This method is useful if you want to contribute to the project or need a version not yet released on PyPI. ```bash git clone https://github.com/erseco/python-moodle.git cd py-moodle pip install . ``` -------------------------------- ### Get Help with py-moodle Source: https://github.com/erseco/python-moodle/blob/main/docs/getting-started/quickstart.md Use the --help flag to get detailed information about the py-moodle CLI or specific commands. ```bash py-moodle --help ``` ```bash py-moodle COMMAND --help ``` -------------------------------- ### Create Course and Add Welcome Label Source: https://github.com/erseco/python-moodle/blob/main/docs/recipes.md A minimal end-to-end content bootstrap workflow. Replace the example course ID with the ID returned by the create command in your environment. ```bash # 1. Create the course. py-moodle courses create \ --fullname "Automation Demo" \ --shortname "automation-demo" ``` ```bash # 2. Create a section if you need one beyond the default course layout. py-moodle sections create 2 --name "Getting Started" ``` ```bash # 3. Add a welcome label to the first section. py-moodle modules add label \ --course-id 2 \ --section-id 1 \ --name "Welcome" \ --intro "

Welcome to the course.

" ``` -------------------------------- ### Configure Moodle Credentials Source: https://github.com/erseco/python-moodle/blob/main/README.md Copy the example environment file and edit it with your Moodle instance credentials. Ensure this file is not committed to version control. ```bash cp .env.example .env # Now, edit the .env file with your credentials ``` -------------------------------- ### Example .env file for Moodle Credentials Source: https://github.com/erseco/python-moodle/blob/main/README.md This is an example of how your .env file should be structured to store Moodle instance credentials and optional CAS SSO configuration. ```env # Production environment credentials MOODLE_PROD_URL=https://your.moodle.site MOODLE_PROD_USERNAME=your_admin_user MOODLE_PROD_PASSWORD=your_super_secret_password # Optional: CAS SSO URL # MOODLE_PROD_CAS_URL=https://cas.your-institution.org/cas # Optional: Predefined webservice token (required for CAS) # MOODLE_PROD_WS_TOKEN=your_webservice_token ``` -------------------------------- ### Install py-moodle from PyPI Source: https://github.com/erseco/python-moodle/blob/main/docs/getting-started/installation.md Use this command to install the latest stable version of py-moodle from the Python Package Index. This is the recommended method for most users. ```bash pip install py-moodle ``` -------------------------------- ### Automated Course Setup with py-moodle Library Source: https://github.com/erseco/python-moodle/blob/main/docs/examples.md This Python script automates the creation of a new course, adds a welcome label, and creates a materials folder using the py-moodle library. It requires initialization of a MoodleSession and uses functions for course creation and module additions. ```python from py_moodle import MoodleSession from py_moodle.course import create_course, list_courses from py_moodle.module import add_label, add_folder # Initialize session ms = MoodleSession.get() # Create a new course course_data = { 'fullname': 'Automated Course Setup Demo', 'shortname': 'auto-demo-001', 'categoryid': 1 } course = create_course(ms.session, ms.settings.url, course_data, token=ms.token) print(f"Created course: {course['id']}") # Add welcome content add_label( ms.session, ms.settings.url, course_id=course['id'], section_id=1, name="Course Welcome", intro="

Welcome!

This course was created automatically.

", token=ms.token ) # Add a materials folder add_folder( ms.session, ms.settings.url, course_id=course['id'], section_id=1, name="Course Materials", intro="All course materials will be stored here.", token=ms.token ) print("Course setup completed!") ``` -------------------------------- ### Configure Moodle Credentials Source: https://github.com/erseco/python-moodle/blob/main/docs/getting-started/quickstart.md Copy the example .env file and edit it with your Moodle instance URL, username, and password. This file is used to authenticate your commands. ```bash cp .env.example .env ``` ```env MOODLE_PROD_URL=https://your-moodle-site.com MOODLE_PROD_USERNAME=your-username MOODLE_PROD_PASSWORD=your-password # Optional: CAS URL and token # MOODLE_PROD_CAS_URL=https://cas.your-institution.org/cas # MOODLE_PROD_WS_TOKEN=your_webservice_token ``` -------------------------------- ### Start Local Moodle Stack with Docker Compose Source: https://github.com/erseco/python-moodle/blob/main/docs/troubleshooting.md Alternatively, use `docker compose up -d` to start the local Moodle stack. This command is useful for managing Docker containers directly. ```bash docker compose up -d ``` -------------------------------- ### Moodle Course Configuration Example Source: https://github.com/erseco/python-moodle/blob/main/docs/examples.md A JSON configuration file structure for defining a Moodle course, including its sections and content items like labels and SCORM packages. ```json { "course": { "fullname": "Introduction to Python Programming", "shortname": "python-intro-2024", "categoryid": 1 }, "sections": [ { "id": 1, "content": [ { "type": "label", "name": "Course Introduction", "intro": "

Welcome to Python Programming!

This course will teach you the basics of Python.

" }, { "type": "scorm", "name": "Python Basics Interactive", "file": "./scorm/python-basics.zip" } ] } ] } ``` -------------------------------- ### Development Installation of py-moodle Source: https://github.com/erseco/python-moodle/blob/main/docs/getting-started/installation.md Install py-moodle in editable mode for development. Changes made to the source code will be immediately reflected without needing reinstallation. ```bash git clone https://github.com/erseco/python-moodle.git cd py-moodle pip install -e . ``` -------------------------------- ### CLI: Get Site Info Source: https://context7.com/erseco/python-moodle/llms.txt Command to retrieve general site information from Moodle. Use --env to select the target environment. ```bash py-moodle admin site-info ``` -------------------------------- ### Upload Multiple Files to a Course Folder with py-moodle CLI Source: https://github.com/erseco/python-moodle/blob/main/docs/examples.md This example shows how to first create a folder in a course section using the py-moodle CLI, and then upload all PDF files from the current directory into that folder. Note that the folder ID needs to be obtained from the folder creation output before uploading files. ```bash # Upload all PDFs in a directory to a course folder course_id=2 section_id=1 folder_name="Course Materials" # Create the folder first py-moodle modules add folder --course-id $course_id --section-id $section_id --name "$folder_name" # Upload files (you'll need to get the folder ID from the output above) for file in *.pdf; do py-moodle files upload --course-id $course_id --file "$file" done ``` -------------------------------- ### Python Function with Google-Style Docstring Source: https://github.com/erseco/python-moodle/blob/main/docs/development.md Example of a Python function demonstrating Google-style docstrings, including Args, Returns, Raises, and an Example section. Type hints are encouraged. ```python def create_course(session: requests.Session, url: str, course_data: dict, token: str = None) -> dict: """Create a new course in Moodle. Args: session: Authenticated requests session url: Base Moodle URL course_data: Dictionary containing course information token: Optional session token Returns: Dictionary containing the created course information Raises: requests.RequestException: If the request fails ValueError: If course_data is invalid Example: >>> course_data = { ... 'fullname': 'My Course', ... 'shortname': 'my-course', ... 'categoryid': 1 ... } >>> course = create_course(session, url, course_data) >>> print(course['id']) 42 """ # Implementation here pass ``` -------------------------------- ### Build Documentation Source: https://github.com/erseco/python-moodle/blob/main/README.md Build the MkDocs site. ```bash make docs ``` -------------------------------- ### Test Configuration by Listing Courses Source: https://github.com/erseco/python-moodle/blob/main/docs/getting-started/configuration.md Run a command like 'courses list' to verify that your configuration is correct and credentials are valid. ```bash py-moodle courses list ``` -------------------------------- ### Build Documentation with MkDocs Source: https://github.com/erseco/python-moodle/blob/main/docs/development.md Commands to build, serve, and deploy documentation using MkDocs. ```bash make docs mkdocs serve mkdocs gh-deploy ``` -------------------------------- ### Verify Environment and Login Source: https://github.com/erseco/python-moodle/blob/main/docs/recipes.md Use this command first when setting up a new .env profile or switching to a different Moodle environment. It confirms credentials, session bootstrap, and base URL are working together. ```bash # Use the environment from MOODLE_ENV or pass one explicitly. py-moodle --env local site info ``` -------------------------------- ### Python Test Case for Course Creation Source: https://github.com/erseco/python-moodle/blob/main/docs/development.md Example of a pytest test function that verifies successful course creation using the `create_course` function and Moodle fixtures. ```python def test_create_course_success(moodle_session): """Test successful course creation.""" course_data = { 'fullname': 'Test Course', 'shortname': 'test-001', 'categoryid': 1 } course = create_course( moodle_session.session, moodle_session.settings.url, course_data, token=moodle_session.token ) assert course['fullname'] == 'Test Course' assert course['shortname'] == 'test-001' assert 'id' in course ``` -------------------------------- ### Create a New Course Source: https://github.com/erseco/python-moodle/blob/main/docs/getting-started/quickstart.md Create a new course in Moodle by providing a full name and a short name. ```bash py-moodle courses create --fullname "Test Course" --shortname "test-001" ``` -------------------------------- ### Add Labels to Course Sections with py-moodle CLI Source: https://github.com/erseco/python-moodle/blob/main/docs/examples.md This example demonstrates how to add a 'label' module to multiple sections within a specific course using the py-moodle CLI. It iterates through a range of section IDs and adds a welcome message to each. ```bash # Add welcome labels to all sections of a course course_id=2 for section in {1..5}; do py-moodle modules add label \ --course-id $course_id \ --section-id $section \ --name "Section $section Welcome" \ --intro "

Welcome to Section $section

This section covers important topics.

" done ``` -------------------------------- ### Manage Moodle Sessions Source: https://context7.com/erseco/python-moodle/llms.txt Use `MoodleSession.get(env)` to get a thread-safe session manager. It handles lazy login, caches sessions, and provides access to the underlying requests session, sesskey, token, and Moodle version. Supports direct REST webservice calls. ```python from py_moodle import MoodleSession, MoodleSessionError try: ms = MoodleSession.get("local") # returns cached session for "local" env # Lazy login is triggered on first property access: session = ms.session # requests.Session with cookies set sesskey = ms.sesskey # e.g. "aB3xK9pL..." (required for AJAX) token = ms.token # webservice token, or None if unavailable version = ms.moodle_version # MoodleVersion(raw="4.5.2+ (Build: 20241001)") # Call any Moodle REST webservice function directly: site_info = ms.call("core_webservice_get_site_info") print(site_info["sitename"]) # "My Moodle Site" # CAS/SSO login — credentials and CAS URL come from .env ms_sso = MoodleSession.get("staging") # MOODLE_STAGING_CAS_URL triggers CAS flow except MoodleSessionError as e: print(f"Login failed: {e}") ``` -------------------------------- ### CLI: Create Course Source: https://context7.com/erseco/python-moodle/llms.txt Command to create a new course with specified full name, short name, and category ID. Environment can be selected using --env or MOODLE_ENV. ```bash py-moodle courses create --fullname "My Course" --shortname "mc-01" --category-id 1 ``` -------------------------------- ### Select Environment using --env Option Source: https://github.com/erseco/python-moodle/blob/main/docs/getting-started/configuration.md Alternatively, use the --env command-line option to specify the Moodle environment. ```bash py-moodle --env prod courses list ``` -------------------------------- ### Generic Moodle Webservice API Call Source: https://context7.com/erseco/python-moodle/llms.txt Execute any Moodle REST webservice function directly by name using a valid webservice token. This method automatically raises MoodleSessionError for Moodle-side errors. It's useful for performing various actions like getting site info, enrolling users, or searching courses. ```python from py_moodle import MoodleSession, MoodleSessionError ms = MoodleSession.get() try: # Get site information info = ms.call("core_webservice_get_site_info") print(info["sitename"], info["release"]) # Enrol a user in a course (roleid 5 = student) ms.call("enrol_manual_enrol_users", { "enrolments[0][roleid]": 5, "enrolments[0][userid]": 55, "enrolments[0][courseid]": 42, }) print("User enrolled.") # Search for courses by keyword results = ms.call("core_course_search_courses", { "criterianame": "search", "criteriavalue": "python", }) for course in results.get("courses", []): print(course["id"], course["fullname"]) except MoodleSessionError as e: print(f"API error: {e}") ``` -------------------------------- ### Complete Course Deployment from JSON with py-moodle Source: https://github.com/erseco/python-moodle/blob/main/docs/examples.md This Python script demonstrates a more advanced automation scenario where an entire course, including its structure and modules, is deployed based on a configuration loaded from a JSON file. It uses functions to create the course and then proceeds to add various modules. ```python import json from py_moodle import MoodleSession from py_moodle.course import create_course from py_moodle.module import add_label, add_resource, add_scorm # Load course configuration from JSON with open('course_config.json', 'r') as f: config = json.load(f) ms = MoodleSession.get() # Create the course course = create_course(ms.session, ms.settings.url, config['course'], token=ms.token) print(f"Created course: {course['shortname']}") ``` -------------------------------- ### CLI Reference Source: https://context7.com/erseco/python-moodle/llms.txt The py-moodle command-line interface exposes all library operations. The --env flag selects the environment profile. ```APIDOC ## CLI Reference The `py-moodle` command-line interface exposes all library operations. The `--env` flag selects the environment profile. ```bash # Select environment via flag or MOODLE_ENV variable export MOODLE_ENV=staging # --- Courses --- py-moodle courses list py-moodle courses show 42 py-moodle courses create --fullname "My Course" --shortname "mc-01" --category-id 1 py-moodle courses delete 42 # --- Sections --- py-moodle sections create --course-id 42 py-moodle sections delete --course-id 42 --section-id 15 # --- Modules --- py-moodle modules add label --course-id 42 --section-id 15 --name "Intro" --intro "

Hello

" py-moodle modules add assign --course-id 42 --section-id 15 --name "Assignment 1" py-moodle modules add scorm --course-id 42 --section-id 15 --name "Module 1" --path ./scorm.zip py-moodle modules show 87 py-moodle modules delete 87 # --- Categories --- py-moodle categories list py-moodle categories create --name "Science" --parent 0 py-moodle categories delete 12 # --- Users --- py-moodle users list --course-id 42 py-moodle users create --username jdoe --password "Abc123!" --firstname Jane --lastname Doe --email jdoe@example.com # --- Admin utilities --- py-moodle admin site-info py-moodle --env prod courses list # use the "prod" .env profile ``` ``` -------------------------------- ### Create a new Moodle course via CLI Source: https://github.com/erseco/python-moodle/blob/main/README.md Use the 'py-moodle courses create' command with --fullname and --shortname flags to programmatically create a new course. ```bash py-moodle courses create --fullname "My New Automated Course" --shortname "auto-course-01" ``` -------------------------------- ### CLI: List Categories Source: https://context7.com/erseco/python-moodle/llms.txt Command to list all available course categories. Environment selection can be done via --env or MOODLE_ENV. ```bash py-moodle categories list ``` -------------------------------- ### Fetch Course Details with Sections and Modules Source: https://context7.com/erseco/python-moodle/llms.txt Provides a normalized, ready-to-use dict structure with course details, including sections and their modules. Also shows how to fetch raw section and module data. ```python from py_moodle import MoodleSession from py_moodle.course import get_course, get_course_with_sections_and_modules ms = MoodleSession.get() course_id = 42 # Normalized full structure course = get_course_with_sections_and_modules( ms.session, ms.settings.url, ms.sesskey, course_id, token=ms.token ) print(course["fullname"]) for section in course["sections"]: print(f" Section {section['section']}: {section['name']}") for mod in section["modules"]: print(f" [{mod['modname']}] {mod['name']} (cmid={mod['id']})") # Raw list of sections (webservice or AJAX): raw = get_course(ms.session, ms.settings.url, ms.sesskey, course_id, token=ms.token) ``` -------------------------------- ### Add API Documentation Source: https://github.com/erseco/python-moodle/blob/main/docs/development.md Steps to add new API documentation using mkdocstrings. ```markdown # Module Name ::: py_moodle.module_name ``` -------------------------------- ### CLI: Select Environment Source: https://context7.com/erseco/python-moodle/llms.txt Demonstrates how to select an environment profile for CLI commands, either by exporting the MOODLE_ENV variable or using the --env flag. ```bash # Select environment via flag or MOODLE_ENV variable export MOODLE_ENV=staging # --- Courses --- py-moodle courses list py-moodle courses show 42 py-moodle courses create --fullname "My Course" --shortname "mc-01" --category-id 1 py-moodle courses delete 42 # --- Sections --- py-moodle sections create --course-id 42 py-moodle sections delete --course-id 42 --section-id 15 # --- Modules --- py-moodle modules add label --course-id 42 --section-id 15 --name "Intro" --intro "

Hello

" py-moodle modules add assign --course-id 42 --section-id 15 --name "Assignment 1" py-moodle modules add scorm --course-id 42 --section-id 15 --name "Module 1" --path ./scorm.zip py-moodle modules show 87 py-moodle modules delete 87 # --- Categories --- py-moodle categories list py-moodle categories create --name "Science" --parent 0 py-moodle categories delete 12 # --- Users --- py-moodle users list --course-id 42 py-moodle users create --username jdoe --password "Abc123!" --firstname Jane --lastname Doe --email jdoe@example.com # --- Admin utilities --- py-moodle admin site-info py-moodle --env prod courses list # use the "prod" .env profile ``` -------------------------------- ### Debug Moodle Session Issues Source: https://github.com/erseco/python-moodle/blob/main/docs/examples.md Initializes a Moodle session, prints session details, and attempts to list courses to verify session validity. Catches and prints any exceptions encountered during the process. ```python from py_moodle import MoodleSession # Enable debug mode ms = MoodleSession.get() print(f"Session URL: {ms.settings.url}") print(f"Session token: {ms.token[:10]}..." if ms.token else "No token") # Test session validity try: from py_moodle.course import list_courses courses = list_courses(ms.session, ms.settings.url, token=ms.token) print(f"Session valid - found {len(courses)} courses") except Exception as e: print(f"Session error: {e}") ``` -------------------------------- ### Project Structure Overview Source: https://github.com/erseco/python-moodle/blob/main/AGENTS.md Illustrates the directory layout for the py-moodle project, including source code, tests, and configuration files. ```tree python-moodle/ ├── src/ │ └── py_moodle/ │ ├── __init__.py │ ├── __main__.py │ ├── cli/ │ │ ├── __init__.py │ │ ├── app.py │ │ └── ... # CLI modules │ ├── auth.py │ ├── course.py │ ├── folder.py │ ├── label.py │ ├── scorm.py │ ├── draftfile.py │ └── ... # Other modules ├── tests/ │ ├── test_auth.py │ ├── test_course.py │ └── ... # One test file per module ├── README.md ├── LICENSE ├── pyproject.toml ├── .env.example ``` -------------------------------- ### Run All Tests Source: https://github.com/erseco/python-moodle/blob/main/README.md Execute all configured test environments. ```bash make test ``` -------------------------------- ### CLI: Create User Source: https://context7.com/erseco/python-moodle/llms.txt Command to create a new user in Moodle. Requires username, password, first name, last name, and email address. ```bash py-moodle users create --username jdoe --password "Abc123!" --firstname Jane --lastname Doe --email jdoe@example.com ``` -------------------------------- ### CLI: List Users in Course Source: https://context7.com/erseco/python-moodle/llms.txt Command to list users enrolled in a specific course. Requires the course ID. Environment can be specified using --env or MOODLE_ENV. ```bash py-moodle users list --course-id 42 ``` -------------------------------- ### Run Staging Integration Tests Source: https://github.com/erseco/python-moodle/blob/main/README.md Execute the integration test suite against the staging Moodle environment. ```bash make test-staging ``` -------------------------------- ### Create a New Course in Moodle Source: https://context7.com/erseco/python-moodle/llms.txt Creates a course by posting to the Moodle web form. Returns a dict with at minimum `id`, `fullname`, and `shortname`. Requires the user to have the 'manager' role. ```python from py_moodle import MoodleSession from py_moodle.course import create_course, MoodleCourseError import time ms = MoodleSession.get() ts = int(time.time()) try: course = create_course( ms.session, ms.settings.url, ms.sesskey, fullname=f"Automated Course {ts}", shortname=f"auto-{ts}", categoryid=1, visible=1, summary="

Created by py-moodle.

", numsections=4, ) print(course["id"], course["shortname"]) # 42 auto-1718000000 except MoodleCourseError as e: # e.g. "Shortname already in use. Please use a unique shortname for the course." print(f"Error: {e}") ``` -------------------------------- ### Run Unit and Integration Tests Source: https://github.com/erseco/python-moodle/blob/main/docs/development.md Execute unit tests quickly or opt-in for Moodle-backed integration tests using `make` commands or `pytest`. ```bash # Fast smoke tests that do not require Moodle make test-unit pytest tests/unit # Moodle-backed integration tests (opt in) make test-local make test-staging pytest --integration --moodle-env local -m integration -n auto # Full local workflow (starts Docker, then runs integration tests) make test ``` -------------------------------- ### Run Local Integration Tests Source: https://github.com/erseco/python-moodle/blob/main/README.md Execute the Docker-backed integration test suite against a local Moodle environment. ```bash make test-local ``` -------------------------------- ### Format and Lint Code Source: https://github.com/erseco/python-moodle/blob/main/docs/development.md Use `make` commands or manual execution of `black` and `isort` for code formatting, and `flake8` for linting. ```bash # Format code make format # Or manually: black src/ tests/ isort src/ tests/ ``` ```bash # Run linter make lint # Or manually: flake8 src/ tests/ ``` -------------------------------- ### CLI: Create Section Source: https://context7.com/erseco/python-moodle/llms.txt Command to create a new section within a specified course. The course ID and environment must be provided. ```bash py-moodle sections create --course-id 42 ``` -------------------------------- ### Inspect Course Before Changes Source: https://github.com/erseco/python-moodle/blob/main/docs/recipes.md Use these commands together to confirm IDs and current state before creating or deleting content. This reduces the chance of targeting the wrong course or section. ```bash # Find the course ID you want to work with. py-moodle courses list ``` ```bash # Inspect one course in detail. py-moodle courses show 2 ``` ```bash # List its sections before adding modules. py-moodle sections list 2 ``` -------------------------------- ### Common Makefile Commands Source: https://github.com/erseco/python-moodle/blob/main/docs/development.md Utility commands for formatting, linting, testing, and cleaning the project. ```bash make format make lint make test make docs make clean ``` -------------------------------- ### Batch User Enrollment with py-moodle Library Source: https://github.com/erseco/python-moodle/blob/main/docs/examples.md This Python script enrolls multiple users into a specified course. It first retrieves all users to create an email-to-ID mapping, then iterates through a list of target user emails to perform the enrollment using the `enroll_user` function. ```python from py_moodle import MoodleSession from py_moodle.user import list_users from py_moodle.course import enroll_user ms = MoodleSession.get() # List of users to enroll user_emails = ['student1@example.com', 'student2@example.com', 'student3@example.com'] course_id = 2 # Get all users users = list_users(ms.session, ms.settings.url, token=ms.token) # Create email to user ID mapping email_to_id = {user['email']: user['id'] for user in users} # Enroll users for email in user_emails: if email in email_to_id: user_id = email_to_id[email] enroll_user(ms.session, ms.settings.url, course_id, user_id, token=ms.token) print(f"Enrolled {email} in course {course_id}") else: print(f"User {email} not found") ``` -------------------------------- ### Run Unit Tests Source: https://github.com/erseco/python-moodle/blob/main/README.md Execute the fast, unit test suite. This does not require a Moodle service to be running. ```bash make test-unit ``` -------------------------------- ### Create Multiple Courses with py-moodle CLI Source: https://github.com/erseco/python-moodle/blob/main/docs/examples.md Use the py-moodle CLI to create multiple courses from a list of names. Short names are generated by converting full names to lowercase and replacing spaces with hyphens. ```bash # Create courses from a list for course in "Math 101" "Physics 201" "Chemistry 301"; do py-moodle courses create --fullname "$course" --shortname "$(echo $course | tr ' ' '-' | tr '[:upper:]' '[:lower:]')" done ``` -------------------------------- ### Show Course Details Source: https://github.com/erseco/python-moodle/blob/main/docs/getting-started/quickstart.md Retrieve and display detailed information for a specific course using its ID. ```bash py-moodle courses show 2 ``` -------------------------------- ### Load Environment Configuration Source: https://context7.com/erseco/python-moodle/llms.txt Load Moodle settings from environment variables using `load_settings`. It supports different environments and raises a ValueError if required variables are missing. ```python from py_moodle.settings import Settings, load_settings # Load the "local" profile (reads MOODLE_LOCAL_* vars) cfg = load_settings("local") print(cfg.url) # http://localhost:8080 print(cfg.username) # admin print(cfg.use_cas) # False — set to True if MOODLE_LOCAL_CAS_URL is present # Load the "prod" profile explicitly prod_cfg = load_settings("prod") # Raises ValueError if URL / USERNAME / PASSWORD are missing: # ValueError: Missing required environment variable: MOODLE_PROD_URL ``` -------------------------------- ### Manage Moodle Users Source: https://context7.com/erseco/python-moodle/llms.txt This snippet demonstrates how to create, delete, and list users in Moodle. User creation and deletion support both webservice (token) and form-based (sesskey) methods, with a fallback to form-based if webservice permissions are insufficient. ```python from py_moodle import MoodleSession from py_moodle.user import create_user, delete_user, list_course_users, MoodleUserError ms = MoodleSession.get() try: # Create a user (webservice; falls back to form if token lacks permission) user = create_user( ms.session, ms.settings.url, token=ms.token, username="jdoe", password="Secret#42!", # must meet Moodle password policy firstname="Jane", lastname="Doe", email="jdoe@example.com", sesskey=ms.sesskey, # used if webservice access is denied ) print(user) # {"id": 55, "username": "jdoe"} # List all enrolled users in a course users = list_course_users(ms.session, ms.settings.url, ms.token, course_id=42) for u in users: print(u["id"], u["fullname"], u["email"]) # Delete the user (admin role required) delete_user(ms.session, ms.settings.url, ms.token, user_id=55, sesskey=ms.sesskey) except MoodleUserError as e: print(f"Error: {e}") ``` -------------------------------- ### Add Content to Moodle Course Source: https://github.com/erseco/python-moodle/blob/main/docs/examples.md Iterates through a configuration to add labels and SCORM packages to a Moodle course section. Requires a pre-defined course and configuration dictionary. ```python for section_config in config['sections']: section_id = section_config['id'] # Add section content for content in section_config['content']: if content['type'] == 'label': add_label( ms.session, ms.settings.url, course_id=course['id'], section_id=section_id, name=content['name'], intro=content['intro'], token=ms.token ) elif content['type'] == 'scorm': add_scorm( ms.session, ms.settings.url, course_id=course['id'], section_id=section_id, name=content['name'], scorm_file=content['file'], token=ms.token ) print("Course deployment completed!") ``` -------------------------------- ### Define Course Creation Command Source: https://github.com/erseco/python-moodle/blob/main/AGENTS.md This defines the CLI command for creating a new course using Typer. It integrates with the core logic and session management. ```python # commands/courses.py import typer from py_moodle.course import create_course from py_moodle.session import MoodleSession app = typer.Typer(help="Manage courses.") @app.command("create") def create_new_course( ctx: typer.Context, fullname: str = typer.Option(..., "--fullname"), shortname: str = typer.Option(..., "--shortname"), ): """Creates a new course.""" ms = MoodleSession.get(ctx.obj["env"]) course = create_course(ms.session, fullname, shortname) typer.echo(f"Course created: {course['id']}") ``` -------------------------------- ### load_settings Source: https://context7.com/erseco/python-moodle/llms.txt Loads environment configuration from .env file based on the specified environment name. It reads Moodle URL, username, and password, along with optional CAS URL and webservice token. ```APIDOC ## load_settings(env: str = None) ### Description Loads environment configuration from environment variables (e.g., `MOODLE__URL`, `MOODLE__USERNAME`, `MOODLE__PASSWORD`). Optionally supports CAS/SSO configuration (`MOODLE__CAS_URL`, `MOODLE__WS_TOKEN`). The `env` parameter defaults to the `MOODLE_ENV` environment variable, which itself defaults to "local". ### Parameters #### Path Parameters None #### Query Parameters - **env** (str) - Optional - The environment profile to load (e.g., "local", "prod"). Defaults to `MOODLE_ENV` environment variable or "local". ### Returns - **Settings** - A frozen dataclass containing the loaded configuration. ### Raises - **ValueError** - If required environment variables (URL, USERNAME, PASSWORD) are missing for the specified environment. ### Example ```python from py_moodle.settings import Settings, load_settings # Load the "local" profile cfg = load_settings("local") print(cfg.url) print(cfg.username) print(cfg.use_cas) # Load the "prod" profile explicitly prod_cfg = load_settings("prod") ``` ``` -------------------------------- ### Run Contributor Validation Loop Source: https://github.com/erseco/python-moodle/blob/main/docs/recipes.md This sequence provides the quickest feedback with existing repository tooling when changing code or documentation. Use `make test-local` only when Docker-backed integration coverage against the local Moodle environment is needed. ```bash # Fast smoke tests with no live Moodle requirement. make test-unit ``` ```bash # Static checks used by CI. make lint ``` ```bash # Rebuild the documentation site, including generated CLI docs. make docs ``` -------------------------------- ### CLI: Show Module Details Source: https://context7.com/erseco/python-moodle/llms.txt Command to display details of a specific module, identified by its ID. Ensure the correct environment is selected. ```bash py-moodle modules show 87 ``` -------------------------------- ### CLI: Show Course Details Source: https://context7.com/erseco/python-moodle/llms.txt Command to display detailed information about a specific course, identified by its ID. The --env flag can be used to specify the environment. ```bash py-moodle courses show 42 ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/erseco/python-moodle/llms.txt Fill in your Moodle instance URL, username, and password in the .env file. Optional CAS/SSO URLs and webservice tokens can also be configured. ```env # .env — one section per environment, e.g. "local", "staging", "prod" MOODLE_LOCAL_URL=http://localhost:8080 MOODLE_LOCAL_USERNAME=admin MOODLE_LOCAL_PASSWORD=Admin1234! # Optional CAS/SSO # MOODLE_LOCAL_CAS_URL=https://cas.example.org/cas # MOODLE_LOCAL_WS_TOKEN=your_prebuilt_webservice_token # Select the active environment (default: "local") MOODLE_ENV=local ``` -------------------------------- ### CLI: Create Category Source: https://context7.com/erseco/python-moodle/llms.txt Command to create a new course category. Requires a name for the category and the ID of its parent category. ```bash py-moodle categories create --name "Science" --parent 0 ``` -------------------------------- ### CLI: Add Label Module Source: https://context7.com/erseco/python-moodle/llms.txt Command to add a 'label' type module to a course section. Requires course ID, section ID, module name, and HTML content for the introduction. ```bash py-moodle modules add label --course-id 42 --section-id 15 --name "Intro" --intro "

Hello

" ``` -------------------------------- ### create_course Source: https://context7.com/erseco/python-moodle/llms.txt Creates a course by posting to the Moodle web form (`/course/edit.php`). Returns a dict with at minimum `id`, `fullname`, and `shortname`. Decorated with `@requires_role("manager")`. ```APIDOC ## `create_course` — Create a New Course Creates a course by posting to the Moodle web form (`/course/edit.php`). Returns a dict with at minimum `id`, `fullname`, and `shortname`. Decorated with `@requires_role("manager")`. ```python from py_moodle import MoodleSession from py_moodle.course import create_course, MoodleCourseError import time ms = MoodleSession.get() ts = int(time.time()) try: course = create_course( ms.session, ms.settings.url, ms.sesskey, fullname=f"Automated Course {ts}", shortname=f"auto-{ts}", categoryid=1, visible=1, summary="

Created by py-moodle.

", numsections=4, ) print(course["id"], course["shortname"]) # 42 auto-1718000000 except MoodleCourseError as e: # e.g. "Shortname already in use. Please use a unique shortname for the course." print(f"Error: {e}") ``` ``` -------------------------------- ### Upload and Create a SCORM Package Source: https://context7.com/erseco/python-moodle/llms.txt The `add_scorm` function uploads a SCORM package and creates an activity. A webservice token is required for this method. `add_scorm_ajax` can be used as a fallback if only a session is available. A `progress_callback` can be provided to monitor upload progress. ```python from py_moodle import MoodleSession from py_moodle.scorm import add_scorm, MoodleScormError ms = MoodleSession.get() def on_progress(bytes_sent: int): print(f" Uploaded {bytes_sent} bytes...") try: cmid = add_scorm( ms.session, ms.settings.url, ms.sesskey, course_id=42, section_id=15, name="Introduction to Python SCORM", file_path="./packages/python_intro.zip", intro="

Interactive SCORM module.

", visible=1, progress_callback=on_progress, ) print(f"SCORM cmid: {cmid}") # 105 except MoodleScormError as e: # e.g. "A webservice token is required for this upload method" print(f"Error: {e}") ``` -------------------------------- ### Implement Course Creation Logic Source: https://github.com/erseco/python-moodle/blob/main/AGENTS.md This function handles the core logic for creating a new Moodle course. It requires a session object and course details. ```python # py_moodle/course.py def create_course(session: requests.Session, fullname: str, shortname: str) -> dict: """Creates a new course.""" # ... implementation ... return course_data ```