1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
| from django.shortcuts import render
from rest_framework.generics import ListAPIView from article.models import Article from .serializers import ArticleListModelSerializer from .paginations import HomeArticlePageNumberPagination from tablestore import * from django.conf import settings from users.models import User from datetime import datetime from renranapi.utils.ItemCF import ItemCF class ArticleListAPIView(ListAPIView): serializer_class = ArticleListModelSerializer pagination_class = HomeArticlePageNumberPagination
@property def client(self): return OTSClient(settings.OTS_ENDPOINT, settings.OTS_ID, settings.OTS_SECRET, settings.OTS_INSTANCE)
def get_queryset(self): week_timestamp = datetime.now().timestamp() - 7 * 86400 week_date = datetime.fromtimestamp(week_timestamp) queryset = Article.objects.filter(pub_date__gte=week_date).exclude(pub_date=None,).order_by("-reward_count","-comment_count","-like_count","-id")
user = self.request.user
if isinstance(user, User): queryset1 = [] start_sequence_id = self.get_start_sequence_id(user.id) message_id_list = self.get_feed_message(user.id, start_sequence_id) if len(message_id_list) >= 10: queryset = queryset.filter(id__in=message_id_list) limit_num = 0 else: message_id_list = self.get_message_by_itemCF(user.id) if len(message_id_list) > 0: queryset1 = queryset.filter(id__in=message_id_list) queryset1 = list(queryset1)
queryset2 = self.check_user_message_log(user, queryset) queryset2 = list(queryset2) queryset = queryset1 + queryset2 queryset = list(set(queryset))[:10] if len(queryset)>0: article_id_list = [] for item in queryset: article_id_list.append(item.id) self.push_log(user.id, article_id_list)
return queryset
def get_user_read_history(self,user_id): """查找用户最近1个月的浏览历史记录""" table_name = "user_message_log_table" inclusive_start_primary_key = [ ('user_id', user_id), ('message_id', INF_MIN) ]
exclusive_end_primary_key = [ ('user_id', user_id), ('message_id', INF_MAX) ]
columns_to_get = []
cond = CompositeColumnCondition(LogicalOperator.AND)
cond.add_sub_condition(SingleColumnCondition("is_push", True, ComparatorType.EQUAL)) cond.add_sub_condition(SingleColumnCondition("is_read", True, ComparatorType.EQUAL))
consumed, next_start_primary_key, row_list, next_token = self.client.get_range( table_name, Direction.FORWARD, inclusive_start_primary_key, exclusive_end_primary_key, columns_to_get, column_filter=cond, max_version=1 )
data = [] if len(row_list) == 0: return data
for row in row_list: data.append(row.primary_key[1][1]) return data
def get_user_by_message_id(self,message_id): """根据文章ID获取用户列表""" table_name = "user_message_log_table" inclusive_start_primary_key = [ ('user_id', INF_MIN), ('message_id', message_id) ]
exclusive_end_primary_key = [ ('user_id', INF_MAX), ('message_id', message_id) ]
columns_to_get = []
cond = CompositeColumnCondition(LogicalOperator.AND)
cond.add_sub_condition(SingleColumnCondition("is_push", True, ComparatorType.EQUAL)) cond.add_sub_condition(SingleColumnCondition("is_read", True, ComparatorType.EQUAL))
consumed, next_start_primary_key, row_list, next_token = self.client.get_range( table_name, Direction.FORWARD, inclusive_start_primary_key, exclusive_end_primary_key, columns_to_get, column_filter=cond, max_version=1 )
data = set() if len(row_list) == 0: return list(data)
for row in row_list: data.add(row.primary_key[0][1]) return list(data)
def find_user_by_history(self, message_list): """根据阅读文章列表的记录查询出阅读这些文章的用户""" users =[] for message_id in message_list: users += self.get_user_by_message_id(message_id) users = list(set(users)) return users
def find_message_by_user(self, users): allUserItemsStarList=[] messages = [] users_message = [] for user_id in users: ret = self.get_user_read_history(user_id) messages += ret users_message.append(ret) messages = list(set(messages)) for item_user_message in users_message: message_list = [] for msg in messages: message_list.append( 1 if(msg in item_user_message) else 0) allUserItemsStarList.append(message_list)
return allUserItemsStarList, messages
def get_message_by_itemCF(self, user_id): """基于物品的协同过滤获取Feed内容""" current_user_history_list = self.get_user_read_history(user_id)
if len(current_user_history_list) == 0: return []
users = self.find_user_by_history(current_user_history_list) if len(users) == 0: return []
allUserItemsStarList, messages = self.find_message_by_user(users) if len(allUserItemsStarList) < 1 or len(messages) < 1: return []
cf = ItemCF(users, messages, allUserItemsStarList)
return cf.calrecommendMoive(user_id)
def get_feed_message(self,user_id, start_sequence_id): """获取同步库中的数据""" table_name = "user_message_table"
inclusive_start_primary_key = [ ('user_id', user_id), ('sequence_id', start_sequence_id), ('sender_id', INF_MIN), ('message_id', INF_MIN) ]
exclusive_end_primary_key = [ ('user_id', user_id), ('sequence_id', INF_MAX), ('sender_id', INF_MAX), ('message_id', INF_MAX), ]
columns_to_get = [] limit = 10
consumed, next_start_primary_key, row_list, next_token = self.client.get_range( table_name, Direction.FORWARD, inclusive_start_primary_key, exclusive_end_primary_key, columns_to_get, limit, max_version=1 )
message_id_list = [] for item in row_list: message_id_list.append( item.primary_key[3][1] )
try: self.set_start_sequence_id(user_id, start_sequence_id, next_start_primary_key[1][1]) except: pass
return message_id_list
def set_start_sequence_id(self, user_id,old_start_sequence_id, next_start_primary_key): table_name = "user_message_session_table" try: primary_key = [('user_id', user_id), ('last_sequence_id', old_start_sequence_id)] row = Row(primary_key) consumed, return_row = self.client.delete_row(table_name, row, None) except: pass
primary_key = [('user_id', user_id), ('last_sequence_id', next_start_primary_key)] attribute_columns = [] row = Row(primary_key, attribute_columns) consumed, return_row = self.client.put_row(table_name, row) print(return_row) return return_row
def get_start_sequence_id(self,user_id): """获取最后读取的Feed流id""" table_name = "user_message_session_table"
inclusive_start_primary_key = [ ('user_id', user_id), ('last_sequence_id', INF_MIN) ]
exclusive_end_primary_key = [ ('user_id', user_id), ('last_sequence_id', INF_MAX) ]
columns_to_get = [] limit = 1
consumed, next_start_primary_key, row_list, next_token = self.client.get_range( table_name, Direction.FORWARD, inclusive_start_primary_key, exclusive_end_primary_key, columns_to_get, limit, max_version=1 )
if len(row_list) < 1: return INF_MIN else: return row_list[0].primary_key[1][1]
def check_user_message_log(self, user, queryset): """判断系统是否曾经推送过文章给用户""" columns_to_get = [] rows_to_get = [] for article in queryset: primary_key = [('user_id', user.id), ('message_id', article.id)] rows_to_get.append(primary_key) request = BatchGetRowRequest() table_name = "user_message_log_table"
cond = CompositeColumnCondition(LogicalOperator.OR) cond.add_sub_condition(SingleColumnCondition("is_read", True, ComparatorType.EQUAL)) cond.add_sub_condition(SingleColumnCondition("is_like", True, ComparatorType.EQUAL))
request.add(TableInBatchGetRowItem(table_name, rows_to_get, columns_to_get,column_filter=cond, max_version=1)) result = self.client.batch_get_row(request) table_result = result.get_result_by_table(table_name) push_id_list = [] for item in table_result: if item.row is not None: push_id_list.append(item.row.primary_key[1][1])
return queryset.exclude(id__in=push_id_list)
def push_log(self, user_id, article_id_list): """推送文章给用户的记录""" table_name = "user_message_log_table"
put_row_items = []
for i in article_id_list: primary_key = [ ('user_id', user_id), ("message_id", i), ]
attribute_columns = [('is_push', True), ('is_read', False), ('is_like', False), ('is_reward',False), ('is_comment',False)]
row = Row(primary_key, attribute_columns) condition = Condition(RowExistenceExpectation.IGNORE) item = PutRowItem(row, condition) put_row_items.append(item)
request = BatchWriteRowRequest() request.add(TableInBatchWriteRowItem(table_name, put_row_items)) result = self.client.batch_write_row(request) return result.is_all_succeed()
|