How to upload via CalDAV a ICS with Python `requests`?
Feb 25, 10:33pm
To upload an .ics (iCalendar) file to a CalDAV server using Python’s requests library, you need to send an HTTP PUT request to the appropriate CalDAV endpoint. Here’s a step-by-step guide and a code example:
Prerequisites
Install the requests library if you haven’t already:
bash
pip install requests
Ensure you have the CalDAV server URL, your credentials, and the path where you want to upload the .ics file.
Steps to Upload an ICS File via CalDAV
Authenticate with the CalDAV server (usually Basic Auth or Digest Auth).
Send a PUT request with the .ics file content to the target URL.
Python Code Example
python
import requests
from requests.auth import HTTPBasicAuth
# CalDAV server details
caldav_url = "https://your.caldav.server/calendar/path/event.ics"
username = "your_username"
password = "your_password"
# Path to your local .ics file
ics_file_path = "path/to/your/event.ics"
# Read the .ics file
with open(ics_file_path, "r") as f:
ics_content = f.read()
# Set headers
headers = {
"Content-Type": "text/calendar; charset=utf-8",
"If-None-Match": "*",
}
# Send the PUT request
response = requests.put(
caldav_url,
data=ics_content,
headers=headers,
auth=HTTPBasicAuth(username, password)
)
# Check the response
if response.status_code in (200, 201, 204):
print("Event uploaded successfully!")
else:
print(f"Failed to upload event. Status code: {response.status_code}")
print(response.text)
Key Points
URL Structure: The caldav_url should point to the exact location where you want to create the event (e.g., https://example.com/caldav/calendar/event.ics).
Authentication: Use HTTPBasicAuth or HTTPDigestAuth depending on your server.