-
我拥有的
我在 Flask 中有一个客户端/服务器。客户端将 JSON 格式的查询发送到服务器,服务器创建一个 JSON 文件。还有另一个工具可以接受此查询,在数据库上执行它并将结果写入 results.txt 文件。服务器定期检查“结果”目录中的 .txt 文件,如果发现新文件,则会提取结果。对于定期检查部分,我使用了 APS。
-
我想做的事现在我想将从服务器从 .txt 文件中提取的数据(queryResult)发送回客户端。
这就是我到目前为止所做的。
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)
谁能帮助我如何将此查询结果发送回客户?
编辑:我希望服务器每次在工具目录中遇到新文件时将 queryResult 发送回客户端,即每次找到新文件时,它都会提取结果(当前正在执行此操作)并发送它返回给客户端。
你想做的事情叫做Web Worker Architecture
.
传递实时摘要queryResult
从后台作业到客户端应用程序,您可以使用消息队列(推荐 Kafka,RabbitMQ 也可以)和 Web-Socket 的组合。当客户端发送请求到/data
端点,您应该返回一些唯一的令牌(如果您的用户是匿名的,则返回 UUID,如果经过身份验证,则返回用户 ID)。您应该将相同的标记添加到生成的文件的名称中。当后台工作程序处理完文件后,它使用令牌(来自文件名)创建 Kafka 或 RabbitMQ 主题,例如topic_for_user_id_1337
or topic_for_uuid_jqwfoj-123qwr
,并发布queryResult
作为一条消息。
同时,你的客户端应该建立一个 Web 套接字连接(Flask 对于 Web 套接字来说非常糟糕,但是很少有好的库可以做到这一点,比如 socketio),并将令牌通过它传递到你的后端,这样就可以了我们将创建一个消息队列订阅者,使用令牌名称订阅主题,以便当后台作业完成时,Web 后端将接收消息并通过 Web 套接字将其传递给用户。
附:如果听起来过于复杂,您可以避免使用 MQ 和 WS,而将queryResult
进入数据库并创建一个端点来检查它是否存在于数据库中。如果不是,你会返回类似的东西not ready yet
如果准备就绪,客户端会在几秒钟内重试 - 您返回queryResult
来自数据库。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)