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
Steps to Upload an ICS File via CalDAV
- Authenticate with the CalDAV server (usually Basic Auth or Digest Auth).
- Set the correct headers:
Content-Type: text/calendar
If-None-Match: * (to avoid overwriting existing events)
- Send a
PUT request with the .ics file content to the target URL.
Python Code Example
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.
- Headers:
Content-Type: text/calendar is required.
If-None-Match: * prevents overwriting existing resources.
- Response Codes:
201 Created or 204 No Content means success.
401 Unauthorized means authentication failed.
403 Forbidden or 404 Not Found means the URL or permissions are incorrect.
Troubleshooting
- If you get a
403 or 404, double-check the URL and your permissions.
- For debugging, print
response.text to see the server’s error message.