def get(self): # 接收请求参数 parser = RequestParser() parser.add_argument('channel_id', location='args', required=True, help='频道id int') args = parser.parse_args() # 通过rpc调用远端推荐系统的函数,返回响应对象(包含了推荐的文章) # 1.通过上下文环境链接rpc服务端 with grpc.insecure_channel('127.0.0.1:8888') as channel: # 2.实例化stub对象 stub = reco_pb2_grpc.UserRecommendStub(channel) # 3.通过stub调用远程函数获取结果 rpc_response = self._get_rpc_article_list(stub, g.user_id, channel_id=args.channel_id) # 构造数据并返回 recommends_list = [] for article in rpc_response.recommends: article_dict = {} article_dict['article_id'] = article.article_id article_dict['track'] = dict() article_dict['track']['click'] = article.track.click article_dict['track']['collect'] = article.track.collect article_dict['track']['share'] = article.track.share article_dict['track']['read'] = article.track.read recommends_list.append(article_dict) return { 'expousre': rpc_response.expousre, 'time_stamp': rpc_response.time_stamp, 'recommends': recommends_list }
def _feed_articles(self, channel_id, timestamp, feed_count): """ 获取推荐文章 :param channel_id: 频道id :param feed_count: 推荐数量 :param timestamp: 时间戳 :return: [{article_id, trace_params}, ...], timestamp """ user_request = reco_pb2.UserRequest() user_request.user_id = str(g.user_id) if g.user_id else 'anony' user_request.channel_id = channel_id user_request.article_num = feed_count user_request.time_stamp = timestamp stub = reco_pb2_grpc.UserRecommendStub(current_app.rpc_reco_channel) ret = stub.user_recommend(user_request) # ret -> ArticleResponse 对象 exposure = ret.exposure pre_timestamp = ret.time_stamp recommends = ret.recommends return recommends, pre_timestamp
def _feed_articles(self, channel_id, timestamp, feed_count): """ rpc调用获取推荐文章 :param channel_id: 频道id :param feed_count: 推荐数量 :param timestamp: 时间戳 :return: [{article_id, trace_params}, ...], timestamp """ # 创建用户进行rpc调用的工具 stub = reco_pb2_grpc.UserRecommendStub(current_app.rpc_reco) # 进行rpc调用 req = reco_pb2.UserRequest() req.user_id = str(g.user_id) if g.user_id else 'Anonymous' req.channel_id = channel_id req.article_num = feed_count req.time_stamp = timestamp ret = stub.user_recommend(req) # ret -> ArticleResponse 对象 pre_timestamp = ret.time_stamp feed_articles = ret.recommends return feed_articles, pre_timestamp
def _feed_articles(self, channel_id, timestamp, feed_count): """ 获取推荐文章 :param channel_id: 频道id :param feed_count: 推荐数量 :param timestamp: 时间戳 :return: [{article_id, trace_params}, ...], timestamp """ #构建辅助调用工具 stub = reco_pb2_grpc.UserRecommendStub(current_app.rpc_reco) #进行rpc调用 user_request = reco_pb2.UserRequest() # userid用字符串的原因,有匿名用户,不登录的 user_request.user_id = g.user_id or 'annoy' user_request.channel_id = channel_id # 频道 user_request.article_num = feed_count # 文章数量 user_request.time_stamp = round(time.time() * 1000) # 时间戳 #feeds = user_request.recommend #pre_timwstamp = user_request.time_stamp ret = stub.user_recommend(user_request) # ret->ArticleResponse 对象 return ret.recommends, ret.time_stamp