Flask API回调监听器

时间:2018-03-15 04:42:44

标签: python flask web-applications flask-socketio

我是Flask的新手,正致力于创建一个Web应用程序,该应用程序将使用我们的API中的回调URL来监听和监控状态更新。如果执行特定事件,应用程序将以pdf格式下载文件。

应用程序将使用用户的集成键访问管理控制台。该应用程序将用户路由到选择屏幕,用户可以在下载选项之间进行选择。

@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服务器以进行回调?或者是否有另一种方法可以使用集成密钥获得回调更新,因为我可以使用HTTP请求访问管理UI。

1 个答案:

答案 0 :(得分:1)

我终于弄清楚出了什么问题以及为什么我没有从API服务器获取任何事件。事实证明,我的localhost需要公开访问才能从服务器接收事件更改。我的解决方案是让我们ngrok创建一个从我的localhost到公共端点的安全隧道。一旦实现,我添加了回调网址,这反过来允许服务器通过更改事件来ping我。