async def user_browse_history_add(ns={}): # ns = { # 'userid': '9KVhsVCJsW_29q3hRhMAr', # 用户ID # 'product_id': 'p2s2YPPU7uquza3gGw9k2', # 产品ID # 'ip_address': '192.168.1.1', # IP地址 # 'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/98.0.4758.102' # 用户代理 # } # 必要参数校验 if not ns.get('userid') or not ns.get('product_id'): return { 'status': False, 'msg': 'userid and product_id are required' } db = DBPools() async with db.sqlorContext('kboss') as sor: try: # 根据timestamp时间字段:browse_time去重 查找10个小时内是否存在 browse_time = datetime.datetime.now() - datetime.timedelta(hours=10) check_sql = """ SELECT * FROM user_browse_history WHERE userid = '%s' AND product_id = '%s' AND del_flg = '0' AND browse_time >= '%s'; """ % (ns.get('userid'), ns.get('product_id'), browse_time) check_result = await sor.sqlExe(check_sql, {}) if check_result: return { 'status': False, 'msg': 'The user has browsed this product within the last 10 hours' } # 生成记录ID record_id = uuid() # 插入浏览记录 insert_sql = """ INSERT INTO user_browse_history ( id, userid, product_id, ip_address, user_agent, del_flg ) VALUES ('%s', '%s', '%s', '%s', '%s', '0'); """ % (record_id, ns.get('userid'), ns.get('product_id'), ns.get('ip_address', ''), ns.get('user_agent', '')) await sor.sqlExe(insert_sql, {}) return { 'status': True, 'msg': 'Browse history recorded successfully', 'data': {'record_id': record_id} } except Exception as e: return { 'status': False, 'msg': 'Failed to record browse history, %s' % str(e) } ret = await user_browse_history_add(params_kw) return ret