21

一行代码搞定各种头像,Flask Avatars 了解一下

 4 years ago
source link: https://foofish.net/flask-avatars.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

原谅我这个标题党,内容是纯正干货,就是希望你们能打开学习了解一下。

二十次幂网站的用户注册,当时并没有要求上传头像,所有人使用的是一个默认头像。

这几天花时间把这块优化了,现在每个人都有唯一的头像了。使用的模块就是 Flask-Avatars 提供的功能。

发现这个库非常强大,集成了很多功能在里面,各种各样的头像生成方案,有Identicon、 monsterid、Robohash 甚至是社交平台的头像,另外还支持裁减,这篇文章就来详细具体介绍一下。

安装

$ pip install flask-avatars

初始化

from flask import Flask
from flask_avatars import Avatars
app = Flask(__name__)

avatars = Avatars(app)

生成 Gravatar 头像

Gravatar是 Globally Recognized Avatar的缩写,是 gravatar 网站推出的一项服务,意为“全球通用头像”。GitHub、Stack Overflow、V2EX 等平台使用它作为用户默认的头像。

from flask import render_template
...

@app.route("/")
def hello():
    import hashlib
    avatar_hash = hashlib.md5("lzjun567@qq".lower().encode('utf-8')).hexdigest()
    avatar_hash = avatars.gravatar(avatar_hash, default="wavatar")
    return render_template("index.html", avatar_hash=avatar_hash)

if __name__ == '__main__':
    app.run(port=8000)

在index.html模板中可以直接引用 avatars 实例

<html lang="en">
<body>
<img src="{{ avatars.gravatar(avatar_hash) }}">
</body>
</html>

bauaIrm.png!web

这个头像的链接是来自于Gravatar网站,每个emai对应l唯一一个头像。

生成默认头像

<img src="{{ avatars.default() }}">

FFryI3R.png!web

生成Robohash头像

Robohash 头像是一种随机的机器人头像,可以直接使用 avatars.robohash() 生成 URL

<img src="{{ avatars.robohash('mark') }}">

AzEvmu3.png!web

生成社交媒体头像

如果你在某些社交平台有自己的账号,那么只要指定自己的用户名可以拿到头像了。我们找一个在Twitter有账号的人试一下,例如:Fenng老师

<img src="{{ avatars.social_media('Fenng', platform='twitter') }}">

BB3IjaR.png!web

支持的平台包括Twiiter,Facebook,还有 Instagram。

以上头像资源都保存在第三方平台,如果你想自己生成头像,并将它保存在本地,那么你可以使用 Identicon 类

哈希头像生成器

Identicon 基于用户信息的哈希值生成图像,通常使用用户登录时的邮箱地址作为输入值,并作为生成新建用户时的初始化头像用于保护用户隐私。

from flask_avatars import Identicon

@app.route("/")
def hello():
    avatar = Identicon()
    filenames = avatar.generate(text="lzjun")
    return render_template("index.html", filenames=filenames)


if __name__ == '__main__':
    app.config['AVATARS_SAVE_PATH'] = "./static/"
    app.run(port=8000)

index.thml

{% for file in filenames %}
<img src="{{ url_for('static', filename=file)}}">
{% endfor %}

最后生成的图像效果:

3qYjQjn.png!web

另外,Flask Avatar 还支持裁剪。类似这样的效果

7b6bIn7.png!web

有没有觉得很强大,同意的点个在看。

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

vQremuy.jpg!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK