简体   繁体   English

Python:具有访问令牌的动态Facebook图片网址的最佳做法

[英]Python: best practice for a dynamic Facebook picture url with access token

I've got a Django app where users can sign up with facebook. 我有一个Django应用,用户可以在其中注册Facebook。 I'm using facebook-sdk to query the Facebook Graph API. 我正在使用facebook-sdk查询Facebook Graph API。 I'm running into a problem when constructing a profile picture url for a given user. 在为给定用户构造个人资料图片网址时,我遇到了一个问题。

According to various sources, I can render the user's picture at various widths using the following: 根据各种来源,我可以使用以下方法以各种宽度渲染用户的图片:

<img src="https://graph.facebook.com/{{facebookUserId}}/picture?type=square&width=500">

That way, I don't have to store the user's picture when they sign up. 这样,当用户注册时,我不必存储用户的图片。 However, if the user's picture is private, I need to append an access token like so: 但是,如果用户的图片是私人的,则需要添加访问令牌,如下所示:

<img src="https://graph.facebook.com/{{facebookUserId}}/picture?type=square&width=500&access_token={{accessToken}}">

The problem is that the access token will eventually expire. 问题在于访问令牌最终将过期。 I can convert a short access token (from the facebook javascript SDK) to a long-lived access token via the Graph API, but eventually even that token will expire, and at that point I won't be able to render the image anymore. 我可以通过Graph API将短访问令牌(从facebook javascript SDK转换为长寿命的访问令牌),但是最终即使该令牌也将过期,到那时我将无法再渲染图像。

I can store the expiry date of the token on the user model to check when it's expired: 我可以将令牌的到期日期存储在用户模型上,以检查其过期时间:

class User(models.Model):
    accessToken = models.CharField(...)
    accessTokenExpires = models.DateTimeField(...)

But then I have to check whether the access token is expired every time I need to render the picture, which probably means I should use a URL from my own backend, like /picture/<userId>?size=500 which would redirect to graph.facebook.com/<userIdGoesHere>/picture?type=square&width=500&access_token=<accessTokenGoesHere> with the stored accessToken, but at that point I lose the speed of using Facebook's CDN to render the image. 但是然后我必须每次访问图片时都要检查访问令牌是否过期,这可能意味着我应该使用自己后端的URL,例如/picture/<userId>?size=500 ,它将重定向到graph.facebook.com/<userIdGoesHere>/picture?type=square&width=500&access_token=<accessTokenGoesHere>和已存储的accessToken,但那时候我失去了使用Facebook CDN渲染图像的速度。

I suppose I could try to update the tokens of all my users with a cron'd worker task, but that doesn't seem ideal as the number of users grows and I'm wondering if there's a better way. 我想我可以尝试通过cron'd worker任务更新所有用户的令牌,但是随着用户数量的增加,这似乎并不理想,我想知道是否有更好的方法。

What's the best practice for keeping these tokens up to date while still dynamically rendering an image URL? 在仍动态呈现图像URL的同时保持这些标记为最新的最佳实践是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM