python - Avatar problem of flasky project of <flask web>
某草草
某草草 2017-06-12 09:22:28
0
1
865

How to change to a customized local avatar? Is there any implemented code? Please give me a link. Thank you

Local image address: ./static/avatar/1.jpg-9.jpg

My code is like this:

def gravatar(self, size=100, default='identicon', rating='g'):
    import random
    return '%d.jpg' % random.randint(1, 9)
    

The call is like this:
<img class="img-rounded profile-thumbnail" src="{{ url_for('static', filename='avatar/') }}{{ current_user.avatar_hash } }">

The picture cannot be loaded after I modified it like this. Why?

某草草
某草草

reply all(1)
女神的闺蜜爱上我

Welcome to communicate, I am also learning Flask, but I didn’t use the gavatar example in the book, so I don’t know where your problem lies...

Regarding local avatars, I have a semi-finished product written by myself for reference, which implements ajax asynchronous uploading of avatars to the server. User A avatar field is added to the model to store the url path corresponding to the avatar routing, by accessing the avatar The route obtains the avatar file. The uploaded avatar is stored in /static/img/avatr/n/ according to the user's id. Each AVATARS_PER_FOLDER avatar file is stored in /static/img/avatr/n/, and the file name is

u{id}.jpg

.


I can’t explain it in detail due to time constraints, welcome to communicate~

backend blueprint -

app/backend/views.py

:

Handle avatar upload and return avatar

@backend.route("/avatar/<int:id>", methods=["GET", "POST"])
def avatar(id):
    # 设置头像存储路径
    avatar_folder = current_app.config["UPLOAD_FOLDER"] + "avatar/"
    # 按照 id 计算头像存储位置
    r = id // current_app.config["AVATARS_PER_FOLDER"]
    save_location = avatar_folder + str(r)
    # jpg
    filename = "u{}.jpg".format(id)

    # 处理头像上传
    # TODO: CSRF 保护
    if request.method == "POST" and request.is_xhr:
        # base64 -> img
        img_b64 = request.form.get("img")
        img_b64 = re.sub(r"data:image/.+;base64,", "", img_b64)
        img = Image.open(BytesIO(base64.b64decode(img_b64)))
        # 保存文件
        if not os.path.exists(save_location):
            os.mkdir(save_location)
        img.save(os.path.join(save_location, filename))
        # 更新数据库
        u = User.query.get_or_404(id)
        u.avatar = url_for("backend.avatar", id=id)
        db.session.add(u)
        # 返回响应
        return jsonify(result="success")

return send_from_directory(save_location, filename)
html page -

app/templates/user_settings.html

:

Handle avatar upload and update display through ajax

<p class="settings_avatar">
    <a class="avatar" href="#">
        <img alt="头像" class="img-circle" src="{{ current_user.avatar }}">
    </a>
    <input id="upload_avatar" type="file" accept="image/*">
</p>
The localResizeIMG plug-in is used here to compress the image, get the base64 encoding of the image, and pass in the

upload_avatar()🎜 function to upload asynchronously. If the upload is successful, the avatar display is updated🎜
<script>
    $(function() {
        var URL_ROOT = {{ request.url_root | tojson | safe }};
        var id = {{ current_user.id }}
    
        $("#upload_avatar").on("change", function() {
            // 使用了
            lrz(this.files[0])
            .then(function (rst)
                upload_avatar(URL_ROOT, id, rst);
            })
            .catch(function (err) {
                alert(err);
            })
            .always(function () {});
        })
    })
    function upload_avatar(URL_ROOT, id, rst) {
        r = "backend/avatar/" + id;
        $.post(
            URL_ROOT+r,
            {
                img: rst.base64,
            },
            function(data) {
                if (data.result === "success") {
                    $(".settings_avatar .avatar .img-circle").attr("src", rst.base64);
                }
            }
        )
    }
</script>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!