首页 > 解决方案 > 使用 Django、Requests 和 Microsoft Graph 将数据发布到 Outlook 日历

问题描述

我有一个功能,我正在尝试使用 Microsoft 的 Graph API 向我的 Outlook 日历发出发布请求。

def create_calendar_event(token, payload, **kwargs):
    """
    Creates a new calendar event
    :param payload: json str
    :param token: str
    :return: dict
    """
    graph_client = OAuth2Session(token=token)
    url_endpoint = "https://graph.microsoft.com/v1.0/me/events"
    events = graph_client.post(url=url_endpoint, json=payload)

    return events.json()

在我看来,我正在使用表单从用户那里获取数据,这样我就可以将用户数据发布到我的 Outlook 日历中。表单看起来像这样:

class CalendarFormView(TemplateView):
    template_name = "event-form.html"

    def get(self, request, **kwargs):
        form = CalendarEventForm()
        return render(request, self.template_name, {"form": form})

    def post(self, request):
        form = CalendarEventForm(request.POST)
        token = client.get_token(request)  # does get the token correctly

        if form.is_valid():
            subject = form.cleaned_data["subject"]
            content = form.cleaned_data["body_content"]
            start = form.cleaned_data["start"]
            end = form.cleaned_data["end"]
            location = form.cleaned_data["location"]
            is_all_day = form.cleaned_data["is_all_day"]

            payload = {
                "subject": subject,
                "body": {"contentType": "html", "content": content},
                “start”: {
                    "dateTime": start.strftime("%Y-%m-%dT%H:%M:%S.%f"),
                    "timeZone": "UTC",
                },
                "end": {
                    "dateTime": end.strftime("%Y-%m-%dT%H:%M:%S.%f"),
                    "timeZone": "UTC",
                },
                "location": {"displayName": location},
                "isAllDay": is_all_day,
            }
            event = create_calendar_event(token, json.dumps(payload))
            print(event)

            return render(request, self.template_name, context=event)

        return render(request, "event-form.html", {"form": form})

access_token将表单数据正确传递到有效负载字典中,但是,当我打印出来时,event我收到以下错误消息:

{u'error': {u'innerError': {u'date': u'2020-01-20T21:59:24', u'request-id': u'fxbxd5c1-myxx-reqx-idxx-1xxxxab91a'}, u'message': u'Empty Payload. JSON content expected.', u'code': u'BadRequest'}}

一切都在 Azure/Microsoft Graph 端正确设置。当我使用Microsoft Graph Explorer时,我能够获取我的日历事件和 POST 请求。问题仅在于从我的 Django 应用程序向我的日历发布事件。

关于我可能出错的地方有什么想法吗?

标签: pythondjangopython-requestsmicrosoft-graph-apimicrosoft-graph-calendar

解决方案


我永远不会明白为什么要花时间在 stackoverflow 上写一篇文章,然后才能神奇地找到答案。

问题出在我的帖子功能中:

event = create_calendar_event(token, json.dumps(payload))

我应该传入一个 dict 而不是 json 作为有效负载。替换json.dumps(payload)forpayload就可以了。事件应如下所示:

event = create_calendar_event(token, payload)  # remove json.dumps from payload

推荐阅读