0.页面展示效果
1.设置用户头像–后端代码
# coding:utf-8from . import api
from ihome.utils.commons import login_required
from flask import g, current_app, jsonify, request, session
from ihome.utils.response_code import RET
from ihome.utils.image_storage import storage
from ihome.models import User
from ihome import db, constants@api.route("/users/avatar", methods=["POST"])
@login_required
def set_user_avatar():"""设置用户的头像参数: 图片(多媒体表单格式) 用户id (g.user_id)"""# 装饰器的代码中已经将user_id保存到g对象中,所以视图中可以直接读取user_id = g.user_id# 获取图片image_file = request.files.get("avatar")if image_file is None:return jsonify(errno=RET.PARAMERR, errmsg="未上传图片")image_data = image_file.read()# 调用七牛上传图片, 返回文件名try:file_name = storage(image_data)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")# 保存文件名到数据库中try:User.query.filter_by(id=user_id).update({"avatar_url": file_name})db.session.commit()except Exception as e:db.session.rollback()current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="保存图片信息失败")avatar_url = constants.QINIU_URL_DOMAIN + file_name# 保存成功返回return jsonify(errno=RET.OK, errmsg="保存成功", data={"avatar_url": avatar_url})
2.设置用户头像–前端代码
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"><title>爱家-个人信息</title><link href="/static/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet"><link href="/static/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet"><link href="/static/css/reset.css" rel="stylesheet"><link href="/static/plugins/bootstrap-datepicker/css/bootstrap-datepicker.min.css" rel="stylesheet"><link href="/static/css/ihome/main.css" rel="stylesheet"><link href="/static/css/ihome/profile.css" rel="stylesheet">
</head>
<body><div class="container"><div class="top-bar"><div class="nav-bar"><h3 class="page-title">个人信息</h3><a class="nav-btn fl" href="/my.html"><span><i class="fa fa-angle-left fa-2x"></i></span></a></div></div><div class="menus-con"><ul class="menus-list"><li><div class="menu-title"><h3>头像</h3></div><div class="menu-content"><img id="user-avatar" src=""><div class="menu-text"><form id="form-avatar" enctype="multipart/form-data">选择头像:<input type="file" accept="image/*" name="avatar"><input type="submit" class="btn btn-success" value="上传"></form></div></div></li><li><div class="menu-title"><h3>用户名</h3></div><div class="menu-content"><form id="form-name" action="/api/profile/name" method="post"><input type="text" name="name" id="user-name"><input type="submit" class="btn btn-success" value="保存"></form><div class="error-msg"><i class="fa fa-exclamation-circle"></i>用户名已存在,请重新设置</div></div></li></ul></div><div class="popup_con"><div class="popup"><p>保存成功!</p></div><div class="mask"></div></div><div class="footer"><p><span><i class="fa fa-copyright"></i></span>爱家租房 享受家的温馨</p></div> </div><script src="/static/js/jquery.min.js"></script><script src="/static/js/jquery.form.min.js"></script><script src="/static/plugins/bootstrap/js/bootstrap.min.js"></script><script src="/static/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script><script src="/static/plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js"></script><script src="/static/js/ihome/profile.js"></script>
</body>
</html>
3.设置用户头像–js代码
function showSuccessMsg() {//fadeIn--使用淡入效果来显示$('.popup_con').fadeIn('fast', function() {setTimeout(function(){$('.popup_con').fadeOut('fast',function(){}); },1000) });
}function getCookie(name) {var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");return r ? r[1] : undefined;
}$(document).ready(function () {$("#form-avatar").submit(function (e) {// 阻止表单的默认行为e.preventDefault();// 利用jquery.form.min.js提供的ajaxSubmit对表单进行异步提交$(this).ajaxSubmit({url: "/api/v1.0/users/avatar",type: "post",dataType: "json",headers: {"X-CSRFToken": getCookie("csrf_token")},success: function (resp) {if (resp.errno == "0") {// 上传成功var avatarUrl = resp.data.avatar_url;$("#user-avatar").attr("src", avatarUrl);} else if (resp.errno == "4101") {location.href = "/login.html";} else {alert(resp.errmsg);}}})});
4.修改用户名–后端代码
@api.route("/users/name", methods=["PUT"])
@login_required
def change_user_name():"""修改用户名"""# 使用了login_required装饰器后,可以从g对象中获取用户user_iduser_id = g.user_id# 获取用户想要设置的用户名req_data = request.get_json()if not req_data:return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")name = req_data.get("name") # 用户想要设置的名字if not name:return jsonify(errno=RET.PARAMERR, errmsg="名字不能为空")# 保存用户昵称name,并同时判断name是否重复(利用数据库的唯一索引)try:User.query.filter_by(id=user_id).update({"name": name})db.session.commit()except Exception as e:current_app.logger.error(e)db.session.rollback()return jsonify(errno=RET.DBERR, errmsg="设置用户错误")# 修改session数据中的name字段session["name"] = namereturn jsonify(errno=RET.OK, errmsg="OK", data={"name": name})
5.修改用户名–前端代码
详细代码见本文第二部分。
6.修改用户名–js代码
//修改用户名的js代码$("#form-name").submit(function(e){e.preventDefault();// 获取参数var name = $("#user-name").val();if (!name) {alert("请填写用户名!");return;}$.ajax({url:"/api/v1.0/users/name",type:"PUT",data: JSON.stringify({name: name}),contentType: "application/json",dataType: "json",headers:{"X-CSRFTOKEN":getCookie("csrf_token")},success: function (data) {if ("0" == data.errno) {$(".error-msg").hide();showSuccessMsg();} else if ("4001" == data.errno) {$(".error-msg").show();} else if ("4101" == data.errno) {location.href = "/login.html";}}});})
7.获取用户信息–后端代码
@api.route("/user", methods=["GET"])
@login_required
def get_user_profile():"""获取用户信息"""user_id = g.user_id# 查询数据库获取个人信息try:user = User.query.get(user_id)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="获取用户信息失败")if user is None:return jsonify(errno=RET.NODATA, errmsg="无效操作")return jsonify(errno=RET.OK, errmsg="OK", data=user.to_dict())