Repository: ucfopen/canvasapi

Issue:
Canvas.list_calendar_events should accept datetime instances
The `Canvas.list_calendar_events` method feeds its parameters down to a `GET /api/v1/calendar_events` request. [That request](https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.index) accepts `start_date` and `end_date` parameters, which “should be formatted as: yyyy-mm-dd or ISO 8601 YYYY-MM-DDTHH:MM:SSZ.” When using these parameters from Python, it would be convenient to provide values as Python `datetime` instances. For example, to list events between a course’ start and end dates:

```python
from datetime import datetime, timedelta
soon = datetime.today() + timedelta(weeks=2)
events = canvas.list_calendar_events(end_date=soon)
```

This seems like an obvious way to make the call, but iterating over the result fails using version 0.6.0 of `canvasapi`:

```
canvasapi.exceptions.BadRequest: {'end_date': 'Invalid date or invalid datetime for end_date'}'}
```

The call works if I convert the date into a suitably-formatted (ISO 8601) string:

```python
from datetime import datetime, timedelta
soon = datetime.today() + timedelta(weeks=2)
soon_iso = soon.isoformat()
events = canvas.list_calendar_events(end_date=soon_iso)
```

It would be very convenient if `Canvas.list_calendar_events` could accept parameters in the standard `datetime` a Python programmer would naturally expect to use, and would handle the ISO 8601 conversion internally.

Of course, dates and times appear in many other places in the Canvas API. I am reporting this against `Canvas.list_calendar_events` because that is where it is affecting me right now. But perhaps the best fix would be at a lower level within `canvasapi` so that *every* `datetime` instance is converted using `.isoformat` whenever given as the value of any request parameter. Is there a single, centralized place where that could be done?

Discussion:

Patch:
diff --git a/canvasapi/requester.py b/canvasapi/requester.py
index 2388493..0c09669 100644
--- a/canvasapi/requester.py
+++ b/canvasapi/requester.py
@@ -1,4 +1,5 @@
 from __future__ import absolute_import, division, print_function, unicode_literals
+from datetime import datetime
 
 import requests
 
@@ -58,6 +59,20 @@ class Requester(object):
             auth_header = {'Authorization': 'Bearer %s' % (self.access_token)}
             headers.update(auth_header)
 
+        # Convert kwargs into list of 2-tuples and combine with _kwargs.
+        _kwargs = [] if _kwargs is None else _kwargs
+        for kw, arg, in kwargs.items():
+            _kwargs.append((kw, arg))
+
+        # Do any final argument processing before sending to request method.
+        for i, kwarg in enumerate(_kwargs):
+            kw, arg = kwarg
+
+            # Convert any datetime objects into ISO 8601 formatted strings.
+            if isinstance(arg, datetime):
+                _kwargs[i] = (kw, arg.isoformat())
+
+        # Determine the appropriate request method.
         if method == 'GET':
             req_method = self._get_request
         elif method == 'POST':
@@ -67,13 +82,10 @@ class Requester(object):
         elif method == 'PUT':
             req_method = self._put_request
 
-        # Convert kwargs into list of 2-tuples and combine with _kwargs.
-        _kwargs = [] if _kwargs is None else _kwargs
-        for kw, arg, in kwargs.items():
-            _kwargs.append((kw, arg))
-
+        # Call the request method
         response = req_method(full_url, headers, _kwargs)
 
+        # Raise for status codes
         if response.status_code == 400:
             raise BadRequest(response.json())
         elif response.status_code == 401:


Test patch:
diff --git a/tests/test_requester.py b/tests/test_requester.py
index 0fabb9f..d65f2d4 100644
--- a/tests/test_requester.py
+++ b/tests/test_requester.py
@@ -1,7 +1,10 @@
 from __future__ import absolute_import, division, print_function, unicode_literals
+from datetime import datetime
 import unittest
 
+import requests
 import requests_mock
+from six.moves.urllib.parse import quote
 
 from canvasapi import Canvas
 from canvasapi.exceptions import (
@@ -26,12 +29,42 @@ class TestRequester(unittest.TestCase):
         response = self.requester.request('GET', 'fake_get_request')
         self.assertEqual(response.status_code, 200)
 
+    def test_request_get_datetime(self, m):
+        date = datetime.today()
+
+        def custom_matcher(request):
+            match_query = 'date={}'.format(quote(date.isoformat()).lower())
+            if request.query == match_query:
+                resp = requests.Response()
+                resp.status_code = 200
+                return resp
+
+        m.add_matcher(custom_matcher)
+
+        response = self.requester.request('GET', 'test', date=date)
+        self.assertEqual(response.status_code, 200)
+
     def test_request_post(self, m):
         register_uris({'requests': ['post']}, m)
 
         response = self.requester.request('POST', 'fake_post_request')
         self.assertEqual(response.status_code, 200)
 
+    def test_request_post_datetime(self, m):
+        date = datetime.today()
+
+        def custom_matcher(request):
+            match_text = 'date={}'.format(quote(date.isoformat()))
+            if request.text == match_text:
+                resp = requests.Response()
+                resp.status_code = 200
+                return resp
+
+        m.add_matcher(custom_matcher)
+
+        response = self.requester.request('POST', 'test', date=date)
+        self.assertEqual(response.status_code, 200)
+
     def test_request_delete(self, m):
         register_uris({'requests': ['delete']}, m)