Flask 对应端点

Flask corresponding endpoints

我在一台机器上部署了两个 flask 端点以获取有关文件夹内容的信息:

@app.route('/info', methods=['GET'])
def get_info():
 
    files_number = int(request.args.get('files_number', default=5))
    directory = request.args.get('directory', default='C:\Admin')
    data = do_something(files_number, directory)
    return jsonify(data), 200 if data else 500
 
    
@app.route('/file', methods=['GET'])
def get_file(): 
    
    directory = request.args.get('directory', default='C:\Admin')
    file_path = request.args.get('file_path')
    data = send_file(file_path, attachment_filename=file_path)
    return data, 200 if data else 500

而且我还在另一台机器上部署了两个端点,它们必须从上面的两个端点获取信息并且return与上面的输出完全相同。

我的问题是如何写enpoints。我的尝试:

@app.route('/info2', methods=['GET'])
def get_info2():
 
    ip = request.args.get('ip')
    port = request.args.get('port')
    
    url = f'http://{ip}:{port}/info'
    
    req = requests.get(url)
    
    if req.status_code == 200:
        output = req.json()
        return output
 
    return None, 500
    
@app.route('/file2', methods=['GET'])
def get_file2(): 
 
    ip = request.args.get('ip')
    path = request.args.get('path')  
    port=5905  
    
    url = f'http://{ip}:{port}/file?path={path}'
    req = requests.get(url)
    
    if req.status_code == 200:
        output = req.json()
        return output
 
    return None, 500

想法是前两个端点与 soceon 代码段中的端点“对话”。

我会使用 request.base_url。 这 returns 调用的完整路径。

它应该是这样的:

@app.route('/info1', methods=['GET'])

def get_info1():

    ip = str(request.args.get('ip'))
    port = int(request.args.get('port'))

    url = f'http://{ip}:{port}/info

    req = requests.get(url)

    if req.status_code == 200:
        output = req.json()
        return jsonify(output)
 
    else:
        return None, 500

@app.route('/info2', methods=['GET'])

def get_(): 

    ip = str(request.args.get('ip'))
    port = int(request.args.get('port'))
    path = str(request.args.get('path'))  

    if path:
        url = f'http://{ip}:{port}/file?html_path={path}'

    req = requests.get(url)

    if req.status_code == 200:
        return redirect(url)

    else:
        return None, 500