聊天系统登录后端实现

定义返回的数据格式
聊天系统登录后端实现_第1张图片

# Restful API
from flask import jsonify


class HttpCode(object):
  # 响应正常
  ok = 200
  # 没有登陆错误
  unloginerror = 401
  # 没有权限错误
  permissionerror = 403
  # 客户端参数错误
  paramserror = 400
  # 服务器错误
  servererror = 500


def _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)

聊天系统登录后端实现_第2张图片

socket 跨域解决
socketio = SocketIO(app, cors_allowed_origins="*")

说明:这里做成轻量级的,数据不存储在数据库中,存储在内存中

后端 登录完整代码

from flask import Flask, request, send_from_directory, url_for

from flask_socketio import SocketIO
from flask_avatars import Avatars, Identicon
from utils import restful
from hashlib import md5
import os

BASE_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/')
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_name
    avatar_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)

在这里插入图片描述

你可能感兴趣的:(Flask,python,开发语言)