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:
requests library if you haven’t already:
bashpip install requests
.ics file.Content-Type: text/calendarIf-None-Match: * (to avoid overwriting existing events)PUT request with the .ics file content to the target URL.pythonimport 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)
caldav_url should point to the exact location where you want to create the event (e.g., https://example.com/caldav/calendar/event.ics).HTTPBasicAuth or HTTPDigestAuth depending on your server.Content-Type: text/calendar is required.If-None-Match: * prevents overwriting existing resources.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.403 or 404, double-check the URL and your permissions.response.text to see the server’s error message.