我是 Flask 新手,正在创建一个 Web 应用程序,该应用程序将通过我们的 API 的回调 URL 监听和监控状态更新。如果执行特定事件,应用程序将以 pdf 格式下载文件。
应用程序将使用用户的集成 key 来访问管理控制台。该应用程序会将用户引导至选择屏幕,用户可以在其中选择下载选项。
@app.route('/tool', methods=['GET', 'POST'])
def tool():
# Empty dict
agreement_list = {}
# Iterate through session cookies to extract out the name & agreement ID
for agreement in session['agreementID']['userAgreementList']:
if agreement['esign'] == True and agreement['status'] != 'SIGNED':
agreement_list[agreement['name']] = agreement['agreementId']
# If the user clicks the download button
if request.method == 'POST':
# extract the data from the selection field
session['config_selected'] = request.form.get('select_name')
# Store into session
session['agreements'] = agreement_list
return redirect(url_for('scan'))
return render_template('tool.html', agreements=agreement_list)
单击按钮后,应用程序会将用户引导到一个页面,在该页面中它将监视更新并在有更新时下载文件。
@app.route('/scan', methods=['Get'])
def scan():
def createPDF(file_selected, agreementID, config_selected):
"""
This sub function will create a pdf requested by the user. It will use an API call
depending on which file is selected. It does both single and multiple pdf creations.
:param page_id: A list of selected downloading option the user selected
:param agreementID: Agreement ID that the user selected
:param select: name of the selected file use to help name pdf
:return: N/A
"""
# Iterate through the list of selected options that the user selected
for file in file_selected:
# API request
r = requests.get('Some request url from API' + agreementID + file,
headers=session['header'])
file_name = config_selected + ' - ' + id[1:] + '.pdf'
file_name = file_name.replace(' ', '_')
# Write file to pdf
with open(file_name, 'wb') as f:
f.write(r.content)
f.close()
# call createPDF here
return render_template('scan.html')
尝试
经过研究,我发现我应该使用套接字在服务器和客户端之间进行通信。我尝试实现 Flask-SocketIO 并让它运行。
@socketio.on('message')
def handleMessage(msg):
print('Message: ' + msg)
send(msg, broadcast=True)
当前该应用程序正在我的本地计算机上运行,并且当前能够在该特定页面上进行轮询。
$(document).ready(function () {
var socket = io.connect('http://127.0.0.1:5000');
socket.on('connect', function () {
socket.send('User has connected!');
});
// socket.on('message', function () {
// socket.send('Scanning')
// });
});
问题:
当最终用户执行我正在寻找的任务时,我如何获取实时回调更新?我是否必须将套接字连接到 API 服务器才能进行回调?或者是否有其他方法可以使用集成 key 获取回调更新,因为我可以使用 HTTP 请求访问管理 UI。
最佳答案
我终于弄清楚出了什么问题以及为什么我没有从 API 服务器收到任何事件 ping。事实证明,我的本地主机需要可公开访问才能从服务器接收事件更改。我的解决方案是让 ngrok 创建一条从本地主机到公共(public)端点的安全隧道。完成此操作后,我添加了回调 url,这反过来又允许服务器通过事件更改来 ping 我。
关于python - Flask API 回调监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49291739/