代码拉取完成,页面将自动刷新
# 实现了 server 端用于接收客户端发送的数据,并对数据进行大写处理后返回给客户端
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import time
import grpc
from concurrent import futures
from loguru import logger
import reque_pb2
import reque_pb2_grpc
import math_problems_new# 自己编写的构建响应数据的模块,具体代码在后面,可以参考
import poems_problems
import English_problems
import AI_problems
import http_client
ONE_DAY_IN_SECONDS = 60 * 60 * 24
# 实现一个派生类,重写rpc中的接口函数.自动生成的grpc文件中比proto中的服务名称多了一个Servicer
class Decode(reque_pb2_grpc.QuestionServiceServicer):
# 重写接口函数.输入和输出都是proto中定义的Data类型
def GetQuestions(self, request, context):
logger.info('enter interface func')
grade = request.keyword.grade
subject = request.keyword.subject
topic = request.keyword.topic
difficulty = request.keyword.difficulty
quantity = request.quantity
print(type(request))
print("grade: ", grade)
print("subject: ", subject)
print("topic: ", topic)
print(type(topic))
print("difficulty: ", difficulty)
print("quantity: ", quantity)
addr = {'ip': 'localhost', 'port': '9000'}
request = {
'quantity': quantity,
'keyword': {
'grade': grade,
'subject': subject,
'topic': int(topic),
'difficulty': difficulty
}
}
res = http_client.ClientRecall(addr, request)
# if subject == '数学':
# question = math_problems_new.get_request(grade, quantity, difficulty)
# elif subject == '语文' and topic != '3':
# question = poems_problems.get_request(grade, quantity, difficulty)
# elif subject == '英语' and topic != '3':
# question = English_problems.get_request(grade, topic, quantity, difficulty)
# elif subject != '数学' and topic == '3':
# question = AI_problems.get_request(subject, grade, topic, quantity, difficulty)
problems = reque_pb2.GetQuestionsResponse()
que = []
for q in res:
print(q)
problem = reque_pb2.Question()
problem.question_text = q['question_text']
problem.answer = q['answer']
# print(q[0])
que.append(problem)
problems.questions.extend(que)
# question = bytes(question)
# print(type(reque_pb2.GetQuestionsResponse.FromString(question)))
# return reque_pb2.GetQuestionsResponse.FromString(question) # 返回结果
return problems
def server():
server_port = 9090 # 设置监听的端口
# 定义服务器并设置最大连接数,corcurrent.futures是一个并发库,类似于线程池的概念
grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) # 创建一个服务器
reque_pb2_grpc.add_QuestionServiceServicer_to_server(Decode(), grpcServer) # 在服务器中添加派生的接口服务(自己实现了处理函数)
grpcServer.add_insecure_port('[::]:%s' % server_port) # 添加监听端口
grpcServer.start() # 启动服务器
logger.info('grpc server started at: %s...' % str(server_port))
try:
while True:
time.sleep(ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
grpcServer.stop(0) # 关闭服务器
logger.info('grpc server end')
if __name__ == '__main__':
import datetime
import os
now_time = datetime.datetime.now().strftime('%Y%m%d')
BASE_DIR = '保存日志文件的根目录,自行设定'
logger.add(f'{BASE_DIR}/msg{now_time}.log', rotation="50 MB") # 记录日志
logger.info('start process')
server()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。