带函数返回的烧瓶render_template - python

我最近在研究Flask。
我对此有疑问。

我的脚本如下所示:

@app.route('/')
def index():
    // execute
    return render_template('index.html', body=body, block=block)
@app.route('/api/')
def api():
    // execute
    return 'api'

函数apiindex完全相同。

我认为是要创建一个两个页面都可以调用并表示相同内容的函数。

有没有可能实现这一目标的方法?

参考方案

TL; DR在这种情况下,我想我会选择使用我提出的第四个选项

我将介绍4个选项,其中一些选项可能比其他选项更可行。

如果您担心execute表示的代码的代码重复(DRY),则可以简单地定义两个路由都可以调用的函数:

def execute():
    # execute, return a value if needed
    pass

@app.route('/')
def index():
    execute()
    return render_template('index.html', body=body, block=block)

@app.route('/api/')
def api():
    execute()
    return 'api'

这可能就是您的意思并正在寻找。

但是,如果您想实际提供两条到达同一功能的路由,也可以这样做,只要记住它们是从上到下进行扫描的。显然,使用这种方法无法返回2个不同的值。

@app.route('/')
@app.route('/api/')
def index():
    # execute
    return render_template('index.html', body=body, block=block)

第三种选择,对于您正在寻找的东西似乎有些过分(和/或繁琐),但是为了完整起见,我会提到它。

您可以使用带有可选值的单个路由,然后确定要返回的内容:

@app.route('/')
@app.route('/<path:address>/')
def index(address=None):
    # execute
    if address is None:
        return render_template('index.html', body=body, block=block)
    elif address == 'api':
        return 'api'
    else:
        return 'invalid value'  # or whatever else you deem appropriate

第四个(最后一个,我保证)选项是将2条路由定向到相同的功能,然后使用request对象查找客户端请求的路由:

from flask import Flask, request

@app.route('/')
@app.route('/api')
def index():
    # execute
    if request.path == '/api':
        return 'api'
    return render_template('index.html', body=body, block=block)

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

通过Python使用FacePlusPlus API - python

我收到以下错误。'error_message': 'BAD_ARGUMENTS 当我执行此python代码时。import requests import json response = requests.post( 'https://api-us.faceplusplus.com/facepp/v3/detect&#…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

python JSON对象必须是str,bytes或bytearray,而不是'dict - python

在Python 3中,要加载以前保存的json,如下所示:json.dumps(dictionary)输出是这样的{"('Hello',)": 6, "('Hi',)": 5}当我使用json.loads({"('Hello',)": 6,…

Python-使用请求时发布请求失败 - python

使用外壳程序时,我可以通过运行以下命令成功创建新用户curl --user administrator:pasword "Content-Type: application/json" https://localhost:8080/midpoint/ws/rest/users -d @user.json但是,当我尝试使用请求在python…