在 Microsoft Graph 中获取用户个人资料图片

Posted

技术标签:

【中文标题】在 Microsoft Graph 中获取用户个人资料图片【英文标题】:Get user profile picture in Microsoft Graph 【发布时间】:2021-03-09 23:11:19 【问题描述】:

我想使用 python 检索我的个人资料图片并将其显示在profiles.html上。

"...gif;base64,(变量)" >?

我认为我需要更改(可变)响应,但是我在转换它以及我应该将它转换为什么方面遇到了困难。

这是我尝试过的:

profiles.html:

% extends "tutorial/layout.html" %
% block content %
<h1>Profile</h1>
<img id="test" src="data:image/gif;base64,output_image" >
% endblock %

graph_helper.py

def get_profiles(token):
    graph_client = OAuth2Session(token=token)

    profiles = graph_client.get(f"graph_url/me/photo/$value", stream=True)
    return profiles.raw.read()

views.py

def profiles(request):

    token = get_token(request)

    profiles = get_profiles(token)

    return render(request, 'tutorial/profiles.html', "output_image": profiles)

但是我收到错误代码

无法访问此站点数据:image/gif;base64,b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00\x00\x00 \x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c\x0b\x0b \x0c\x19\x12\x13\x0f\x14\x1d\x1a\x1f\x1e\x1d\x1a\x1c\x1c $.' ",#\x1c\x1c(7),01444\x1f'9=82<.342 x00 x08 x97 xc5 err_invalid_url>

【问题讨论】:

您可以在 Microsoft Graph Explorer 中尝试上述 Graph API 调用,看看是否可以重现该问题? @Dev 感谢您的回复,它让我重新思考我应该如何提出这个问题,我将改变它以反映问题。我将如何将收到的代码转换为 .html 显示我的个人资料图片所需的正确代码? "...gif;base64,(插入代码)" >? 当您使用 /photo/$value 端点获取个人资料照片的二进制数据时,您需要将数据转换为 base-64 字符串才能将其添加为电子邮件附件。我看到您想在网页上显示图像,从图像创建一个内存对象,并使该对象成为图像元素的源。我记得一个 javascript 示例: const url = window.URL ||窗口.webkitURL;常量 blobUrl = url.createObjectURL(image.data); document.getElementById(imageElement).setAttribute("src", blobUrl); Graph 会将数据作为流返回给您,您需要将该流转换为 base64 以上内容对您的进步有帮助吗? 【参考方案1】:

感谢大家引导我走向正确的方向,这是我能够用来回答问题的确切代码。

在我的 graph_helper.py 中:

def get_profiles(token):
graph_client = OAuth2Session(token=token)

query_params = 
    "accept-encoding": "gzip, deflate"

photo_response = graph_client.get(f"graph_url/me/photo/$value", stream=True)
photo_status_code = photo_response.status_code
if photo_response.ok:
    photo = photo_response.raw.read()
    test = base64.b64encode(photo).decode('utf-8')
    # note we remove /$value from endpoint to get metadata endpoint
    metadata_response = graph_client.get(f"graph_url/me/photo/")
    content_type = metadata_response.json().get('@odata.mediaContentType', '')
else:
    photo = ''
    content_type = ''

return test

在profiles.html中

<img class="profile_pic" src="data:image/png;base64,output_image"  style="width:50%">

【讨论】:

以上是关于在 Microsoft Graph 中获取用户个人资料图片的主要内容,如果未能解决你的问题,请参考以下文章

在 facebook graph v2.2 中获取用户的个人资料图片

获取 Microsoft Graph API 的有效访问令牌

Microsoft Graph API - 列出用户登录的所有权限/范围

在 Microsoft Graph 中获取“logoUrl”和“homePageUrl”为空

在 Facebook Graph API 2.0 中获取用户名字段

Instagram Graph API - 当用户从个人账户切换到企业账户时获取媒体洞察指标