"""
  @author: LinTao
  @time: 2022/10/30 14:51
  @desc: Redis 相关
"""
import re
from datetime import datetime

import redis

from common.database import dbconnect
from common.utility import model_list
from module.article import Article
from module.users import Users


def redis_connect():
    pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True,
                                db=0, password='redis666')
    red = redis.Redis(connection_pool=pool)
    return red


# def redis_mysql_string():
#     from common.database import dbconnect
#
#     red = redis_connect()
#
#     dbsession, md, DBase = dbconnect()
#     result = dbsession.query(Users).all()
#     json = model_list(result)
#     red.set('users', str(json))


def redis_mysql_string():
    from common.database import dbconnect

    red = redis_connect()

    dbsession, md, DBase = dbconnect()
    result = dbsession.query(Users).all()
    user_list = model_list(result)
    for user in user_list:
        red.set(user['username'], str(user['password']))


def redis_mysql_hash():
    from common.database import dbconnect

    red = redis_connect()

    dbsession, md, DBase = dbconnect()
    result = dbsession.query(Users).all()
    user_list = model_list(result)
    for user in user_list:
        red.hset('users_hash', user['username'], str(user))


def redis_article_zsort():
    dbsession, md, DBase = dbconnect()
    result = dbsession.query(Article, Users.nickname).join(Users, Users.userid == Article.userid).all()

    list = []
    for article, nickname in result:
        dict = {}
        for k, v in article.__dict__.items():
            if not k.startswith('_sa_instance_state'):
                # 如果某个字段的值是 datetime 类型，则将其格式转为字符串
                if isinstance(v, datetime):
                    v = v.strftime('%Y-%m-%d %H:%M:%S')
                elif k == 'content':
                    # 将文章内容的HTML和不可见字符删除，再截取前面80个字符
                    pattern = re.compile(r'<[^>]+>')
                    temp = pattern.sub('', v)
                    temp = temp.replace('&nbsp;', '')
                    temp = temp.replace('\r', '')
                    temp = temp.replace('\n', '')
                    temp = temp.replace('\t', '')
                    v = temp.strip()[0:80]
                dict[k] = v
        dict['nickname'] = nickname
        list.append(dict)

    red = redis_connect()
    for row in list:
        # 参数：(键名, {值: 排序依据})
        red.zadd('article', {str(row): row['articleid']})


if __name__ == '__main__':
    redis_article_zsort()
    # redis_mysql_hash()

