Exemple #1
0
def code2session(code):
    """
    code to session
    """
    try:
        response = requests.get(
            CODE2SESSION_URL.format(appid=getConfig("wechat", "appid"),
                                    secret=getConfig("wechat", "secret_key"),
                                    js_code=code))
    except:
        log.logger.warning("网络错误")
        return _Return_Error_Post(code=NETWORK_ERROR, message='网络错误')

    log.logger.info('微信code2session成功: ' + response.json())
    return _Return_Post(data=response.json(), message='微信code2session成功')
 def find_face_owner(self, face_code):
     results = list(mongo.find(getConfig('mongodb', 'user_collection'), {}))
     know_face_codes = [result['face'] for result in results]
     face_compare_result = face_recognition.compare_faces(
         know_face_codes, face_code)
     # 这里可能会出现非常相似的人脸(双胞胎) 不考虑
     try:
         user_index = face_compare_result.index(True)
     except ValueError:
         return {'code': 404, 'data': None}
     user = results[user_index]
     return {'code': 0, 'data': user}
def upload_face():
    """
    用户更新人脸
    :return:
    """
    uid = request.form.get('uid', None)

    if not uid:
        log.logger.warning('更新人脸,缺少用户ID')
        return _Return_Error_Post(code=USERID_LOST, message='缺少用户id')

    user_collection = getConfig('mongodb', 'user_collection')

    # 获取人脸编码
    face_stream = request.files.get('face').read()
    face_code = FaceTool(face_stream).encode()

    if not face_code:
        log.logger.info('获取人脸编码失败,照片上不存在人脸')
        return _Return_Error_Post(code=FACE_LOST, message='获取人脸编码失败,照片上不存在人脸')

    # 保存人脸照片到七牛云
    filename = f'{uid}-{shortuuid.uuid()}.png'
    qiniu.upload_file(filename, face_stream)

    if not mongo.select_one(user_collection, {'uid': uid}):
        # 不存在用户
        if mongo.insert(user_collection, UserModelMongo(uid, face_code).get(), ['uid']):
            data = {
                'uid': uid,
                'face': face_code
            }
            log.logger.info('更新人脸成功 %s' % uid)
            return _Return_Post(data=data, message='更新人脸数据成功')
    else:
        # 更新人脸
        if mongo.update(user_collection, {'uid': uid}, UserModelMongo(uid, face_code).get()):
            log.logger.info('更新人脸成功 %s' % uid)
            return _Return_Post(data=uid, message='更新人脸数据成功')
        else:
            log.logger.warning('更新人脸失败')
            return _Return_Error_Post(code=UNKNOWN_ERROR, message='更新人脸失败')
Exemple #4
0
def decrypt():
    """
    解密微信反馈的信息
    session_key, encrypted_data, iv 必需
    :return: unionid
    """

    data = request.json or {}

    session_key = data.get('session_key', None)
    encrypted_data = data.get('encryptedData', None)
    iv = data.get('iv', None)

    # 缺少参数
    if not bool(session_key and encrypted_data and iv):
        log.logger.warning("微信解密信息缺少参数")
        return _Return_Error_Post(code=WECHAT_DECRYPT_LOST_PARAM,
                                  message="微信解密信息缺少参数")

    result = wx_decrypt(getConfig("wechat", "appid"), session_key,
                        encrypted_data, iv)

    log.logger.info('解密微信信息成功: ' + result)
    return _Return_Post(data=result, message='微信解密信息成功')
        c = self.db[collection]
        try:
            c.update(item, {"$set": update_kvs})
            return True
        except Exception as e:
            print(e)
            return False

    def delete(self, collection, item):
        """
        删除文档
        :param collection:
        :param item:
        :return:
        """
        return self.db[collection].delete_one(item)


if __name__ == '__main__':
    mongo = MongoTools(
        getConfig('mongodb', 'db'),
        "mongodb://%s:%s@%s:%s" % (
            getConfig('mongodb', 'user'),
            getConfig('mongodb', 'pwd'),
            getConfig('mongodb', 'host'),
            getConfig('mongodb', 'port')
        )
    )

    print(mongo.insert('asd', {'1': 1}))
def stbu():
    """同步教务系统"""
    rbody = request.json or {}

    uid = rbody.get('uid', None)
    user = rbody.get('u', None)
    pwd = rbody.get('p', None)

    if not bool(uid and user and pwd):
        log.logger.warning('绑定教务系统缺少参数')
        return _Return_Error_Post(code=JW_LOST_PARAM, message='绑定教务系统缺少参数')

    # 开始同步,获取用户信息
    s = Stbu(rbody.get("u"), rbody.get("p"))
    stbu_user = s.sync()

    if stbu_user and (stbu_user != 0):
        # 把用户放到数据库里
        need_update_user = UserModelMySQL.query.get(uid)

        if not need_update_user:
            log.logger.warning('用户不存在')
            return _Return_Error_Post(code=USER_NOT_FOUND, message='用户不存在')

        # 更新用户信息 -> MySQL
        need_update_user.sid = stbu_user.get('sid')
        need_update_user.name = stbu_user.get('name')
        need_update_user.gender = get_gender_num(stbu_user.get('gender'))
        need_update_user.grade = stbu_user.get('grade')
        need_update_user.major = stbu_user.get('major')
        need_update_user.grade = stbu_user.get('grade')
        need_update_user.class_name = stbu_user.get('class_name')
        need_update_user.college = stbu_user.get('college')
        need_update_user.email = stbu_user.get('email')
        need_update_user.phone = stbu_user.get('phone')
        need_update_user.face_url = getConfig(
            'qiniu', 'domain') + "/" + stbu_user.get('face_url')
        need_update_user.is_bind_jw = True

        # 更新用户信息 -> MongoDB
        user_collection = getConfig('mongodb', 'user_collection')

        if not mongo.select_one(user_collection, {'uid': uid}):
            # 不存在则创建
            if mongo.insert(user_collection,
                            UserModelMongo(uid, stbu_user.get('face')).get(),
                            ['uid']):
                log.logger.info('绑定教务成功: %s' % uid)
                return _Return_Post(data=uid, message='绑定教务系统成功')
            else:
                log.logger.warning('绑定教务系统失败,在插入人脸数据出出错')
                return _Return_Error_Post(code=JW_FAILURE, message='账户或密码错误')
        else:
            # 存在则更新
            if mongo.update(user_collection, {'uid': uid},
                            UserModelMongo(uid, stbu_user.get('face')).get()):
                log.logger.info('绑定教务成功: %s' % uid)
                return _Return_Post(data=uid, message='绑定教务系统成功')
            else:
                log.logger.warning('绑定教务系统失败,在更新人脸数据出出错')
                return _Return_Error_Post(code=JW_FAILURE, message='账户或密码错误')
    else:
        log.logger.warning('绑定教务系统账户或密码错误')
        return _Return_Error_Post(code=JW_ACCOUNT_ERROR, message='账户或密码错误')
# -*- coding: utf-8 -*-

from apps.Config import getConfig

DEBUG = True

TEMPLATES_AUTO_RELOAD = True

SERVER_NAME = "facer.yingjoy.cn"

FILE_ALLOWED = ['image/png', 'image/jpg', 'image/jpeg']

SECRET_KEY = '\xca\x0c\x86\x04\x98@\x02b\x1b7\x8c\x88]\x1b\xd7"+\xe6px@\xc3#\\'

SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4".format(
    getConfig('mysql', 'user'), getConfig('mysql', 'pwd'),
    getConfig('mysql', 'host'), getConfig('mysql', 'port'),
    getConfig('mysql', 'db'))
root_path = os.path.split(os.path.split(os.path.split(os.path.abspath(__file__))[0])[0])[0]

log = Logger(
    os.path.join(
        root_path,
        'logs',
        'FaceR.log'
    ), level='debug'
)

# SQLAlchemy
db = SQLAlchemy()

# MongoDB
mongo = MongoTools(
    getConfig('mongodb', 'db'),
    "mongodb://%s:%s@%s:%s" % (
        getConfig('mongodb', 'user'),
        getConfig('mongodb', 'pwd'),
        getConfig('mongodb', 'host'),
        getConfig('mongodb', 'port')
    )
)

# 七牛云
qiniu = MyQiNiu(
    access_key=getConfig('qiniu', 'access_key'),
    secret_key=getConfig('qiniu', 'secret_key'),
    bucket_name=getConfig('qiniu', 'bucket_name'),
    domain=getConfig('qiniu', 'domain')
)