python - <flask web>的flasky項目的頭像問題
問題描述
怎么換成自定義的本地頭像呢? 有沒有實現的代碼 給個鏈接看看 謝謝
本地的圖片地址:./static/avatar/1.jpg-9.jpg
我的代碼是這樣的:
def gravatar(self, size=100, default=’identicon’, rating=’g’): import random return ’%d.jpg’ % random.randint(1, 9)
調用是這樣的:<img src='http://www.cgvv.com.cn/wenda/{{ url_for(’static’, filename=’avatar/’) }}{{ current_user.avatar_hash }}'>
我這樣修改后 圖片是加載不出來的 為什么呢?
問題解答
回答1:歡迎交流, 也在學 Flask, 不過我沒用書上 gavatar 的例子, 所以我也不太知道你的問題出在哪里...
關于本地頭像, 我這邊有個自己寫的半成品供參考, 實現了 ajax 異步上傳頭像到服務器. User 模型里添加了一個 avatar 字段, 存放頭像路由相應的 url 路徑, 通過訪問頭像路由得到頭像文件. 上傳的頭像根據用戶 id 每 AVATARS_PER_FOLDER 個頭像文件存放在 /static/img/avatr/n/ 中, 文件名是 u{id}.jpg.
時間關系我解釋的不太詳細, 歡迎交流~
backend 藍圖 - app/backend/views.py:
處理頭像上傳和返回頭像
@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 -> imgimg_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 頁面 - app/templates/user_settings.html:
通過 ajax 處理頭像上傳和更新顯示
<p class='settings_avatar'> <a href='http://www.cgvv.com.cn/wenda/9710.html#'><img alt='頭像' src='http://www.cgvv.com.cn/wenda/{{ current_user.avatar }}'> </a> <input type='file' accept='image/*'></p>
這里使用 localResizeIMG 插件來壓縮圖像, 得到圖像的 base64 編碼, 傳入 upload_avatar() 函數異步上傳, 如果上傳成功, 更新頭像顯示
<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>
相關文章:
1. android - webview 自定義加載進度條2. 為什么我ping不通我的docker容器呢???3. javascript - 微信小程序限制加載個數4. 并發模型 - python將進程池放在裝飾器里為什么不生效也沒報錯5. mysql - 怎么讓 SELECT 1+null 等于 16. python 怎樣用pickle保存類的實例?7. linux - openSUSE 上,如何使用 QQ?8. 大家好,請問在python腳本中怎么用virtualenv激活指定的環境?9. linux - 升級到Python3.6后GDB無法正常運行?10. Python中, 仿照經典代碼實現單例, 卻出現了不是單例的的狀態, 代碼哪里出錯了 ?
