Python—将查询结果从服务器返回到Flask中的客户端
我拥有的 我在Flask中有一个客户机/服务器。客户端向服务器发送JSON格式的查询,服务器创建JSON文件。还有另一个工具,它接受这个查询,在数据库上执行它,并将结果写入results.txt文件。服务器定期检查“results”目录中的.txt文件,如果发现新文件,则提取结果。对于定期检查部分,我使用了APSPython—将查询结果从服务器返回到Flask中的客户端,python,json,rest,flask,client-server,Python,Json,Rest,Flask,Client Server,我拥有的 我在Flask中有一个客户机/服务器。客户端向服务器发送JSON格式的查询,服务器创建JSON文件。还有另一个工具,它接受这个查询,在数据库上执行它,并将结果写入results.txt文件。服务器定期检查“results”目录中的.txt文件,如果发现新文件,则提取结果。对于定期检查部分,我使用了APS 我想做什么 现在我想将服务器从.txt文件中提取的数据(queryResult)发送回客户端 这就是我到目前为止所做的 服务器代码: 有谁能帮我把这个查询结果发送回客户吗 编
- 服务器代码:
编辑:我希望服务器在每次遇到工具目录中的新文件时将查询结果发送回客户机,即,每次它找到新文件时,它都会提取结果(当前正在执行的操作)并将其发送回客户机。您要做的事称为
Web Worker体系结构
要将实时摘要queryResult
从后台作业传递到客户端应用程序,您可以使用消息队列(建议使用Kafka,RabbitMQ也可以)和Web套接字的组合。当客户端向/data
端点发送请求时,您应该返回一些唯一的令牌(例如,如果您的用户是匿名的,则返回UUID;如果用户是经过身份验证的,则返回用户id)。您应该将相同的标记添加到结果文件的名称中。当您的后台工作人员处理完文件后,它使用令牌(来自文件名)创建Kafka或RabbitMQ主题,如用户id为1337的topic\u或用户id为jqwfoj-123qwr的topic\u,并以消息形式发布queryResult
同时,您的客户端应该建立一个web套接字连接(Flask对于web套接字来说是非常糟糕的,但不管怎样,很少有好的lib可以这样做,比如socketio),并将令牌通过它传递到后端,这样它将创建一个消息队列订阅者,订阅一个带有令牌名称的主题,以便在后台作业完成时,web后端将接收消息并通过web套接字将其传递给用户
注意:如果听起来过于复杂,您可以避免使用MQ和WS,将queryResult
放入数据库,并创建一个端点来检查它是否存在于数据库中。如果没有,您将返回类似于尚未就绪
的内容,客户端将在几秒钟内重试,如果就绪,您将从DB返回查询结果
。我不知道Kafka/Rabbit MQ和Web套接字方法,因此我实施了一种类似于您所提到的解决方法。我只是将queryResult写入一个文件,而不是db,服务器检查该文件的内容是否为“无”。如果是,则等待并重试,如果不是,则返回给客户端。但谢谢你提到另一种方法。我会调查的。
app = Flask(__name__)
api = Api(app)
# Variable to store the result file count in the Tool directory
fileCount = 0
# Variable to store the query result generated by the Tool
queryResult = 0
# Method to read .txt files generated by the Tool
def readFile():
global fileCount
global queryResult
# Path where .txt files are created by the Tool
path = "<path>"
tempFileCount = len(fnmatch.filter(os.listdir(path), '*.txt'))
if (fileCount != tempFileCount):
fileCount = tempFileCount
list_of_files = glob.iglob(path + '*.txt')
latest_file = max(list_of_files, key=os.path.getctime)
print("\nLast modified file: " + latest_file)
with open(latest_file, "r") as myfile:
queryResult = myfile.readlines()
print(queryResult) # I would like to return this queryResult to the client
scheduler = BackgroundScheduler()
scheduler.add_job(func=readFile, trigger="interval", seconds=10)
scheduler.start()
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
# Method to write url parameters in JSON to a file
def write_file(response):
time_stamp = str(time.strftime("%Y-%m-%d_%H-%M-%S"))
with open('data' + time_stamp + '.json', 'w') as outfile:
json.dump(response, outfile)
print("JSON File created!")
class GetParams(Resource):
def get(self):
response = json.loads(list(dict(request.args).keys())[0])
write_file(response)
api.add_resource(GetParams, '/data') # Route for GetJSON()
if __name__ == '__main__':
app.run(port='5890', threaded=True)
data = {
'query': 'SELECT * FROM table_name'
}
url = 'http://127.0.0.1:5890/data'
session = requests.Session()
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
resp = session.get(url, params=json.dumps(data))
print(resp)