定义返回的数据格式
# Restful API
from flask import jsonifyclass HttpCode(object):# 响应正常ok = 200# 没有登陆错误unloginerror = 401# 没有权限错误permissionerror = 403# 客户端参数错误paramserror = 400# 服务器错误servererror = 500def _restful_result(code, message, data):return ({"message": message or "", "data": data or {}, "code": code})def ok(message=None, data=None):return _restful_result(code=HttpCode.ok, message=message, data=data)def unlogin_error(message="没有登录!"):return _restful_result(code=HttpCode.unloginerror, message=message, data=None)def permission_error(message="没有权限访问!"):return _restful_result(code=HttpCode.paramserror, message=message, data=None)def params_error(message="参数错误!"):return _restful_result(code=HttpCode.paramserror, message=message, data=None)def server_error(message="服务器开小差啦!"):return _restful_result(code=HttpCode.servererror, message=message or '服务器内部错误', data=None)
默认头像
存储头像的文件
pip install flask-avatars
app.py
avatars = Avatars(app)
socket 跨域解决
socketio = SocketIO(app, cors_allowed_origins="*")
说明:这里做成轻量级的,数据不存储在数据库中,存储在内存中
后端 登录完整代码
from flask import Flask, request, send_from_directory, url_forfrom flask_socketio import SocketIO
from flask_avatars import Avatars, Identicon
from utils import restful
from hashlib import md5
import osBASE_DIR = os.path.dirname(__file__)app = Flask(__name__)
app.config['AVATARS_SAVE_PATH'] = os.path.join(BASE_DIR, "media", "avatars")
socketio = SocketIO(app, cors_allowed_origins="*")
avatars = Avatars(app)# 全局变量,用来存储用户信息
online_users = []@app.route('/meadia/avatars/<path:filename>')
def get_avatar(filename):return send_from_directory(app.config['AVATARS_SAVE_PATH'], filename)@socketio.on('connect')
def connect():print('ip:' + request.remote_addr)print('sid:' + request.sid)@socketio.on('login')
def login(data):username = data.get('username')if not username:return restful.params_error("请传入用户名")for user in online_users:if user['username'] == username:return restful.params_error("此用户名已存在")filenames = Identicon().generate(md5(username.encode("utf-8")).hexdigest())# 获取大头像avatar_name = filenames[2]# 获取头像路径# "/media/avatars/"+avatar_nameavatar_url = url_for("get_avatar", filename=avatar_name)user = {"username": username,"ip": request.remote_addr,'avatar': avatar_url,"sid": request.sid}online_users.append(user)return restful.ok(data=user)if __name__ == '__main__':socketio.run(app)