另一种方法是将应用程序和 API 放在同一个 Flask(-RESTful) 实例中。然后,您可以让应用程序在内部调用 API 方法/函数(不使用 HTTP)。让我们考虑一个管理服务器上文件的简单应用程序:
# API. Returns filename/filesize-pairs of all files in 'path'  
@app.route('/api/files/',methods=['GET'])
def get_files():
    files=[{'name':x,'size':sys.getsizeof(os.path.join(path,x))} for x in os.listdir(path)]
    return jsonify(files)
# app. Gets all files from the API, uses the API data to render a template for the user 
@app.route('/app/files/',methods=['GET'])
def app_get_files():
    response=get_files() # you may verify the status code here before continuing  
    return render_template('files.html',files=response.get_json())
您可以推送所有请求(从 API 到应用程序并返回),而无需将它们包含在您的函数调用中,因为 Flask 的请求对象是global。例如,对于处理文件上传的应用程序资源,您可以简单地调用:
@app.route('/app/files/post',methods=['POST'])
def app_post_file():
   response=post_file()
   flash('Your file was uploaded succesfully') # if status_code==200
   return render_template('home.html')
相关的 API 资源是:
@app.route('/api/files/',methods=['POST'])
def post_file():
   file=request.files['file']
   ....
   ....
   return jsonify({'some info about the file upload'})
但是,对于大量应用程序数据,包装/解包 JSON 的开销使得 Miguel 的第二个解决方案更受欢迎。
在你的情况下,你会想在你的控制器中调用它:
response=FooAPI().post(id)