【问题标题】:How to handle missing parameters in URL with Flask/Python 3 [duplicate]如何使用 Flask/Python 3 处理 URL 中缺少的参数 [重复]
【发布时间】:2016-08-27 12:07:23
【问题描述】:

目前,我的网站上有两个下拉框,其值在提交表单后会转换为两个 URL 参数“myState”和“myShelter”。例如:

https://www.atweather.org/forecast?myState=CT&myShelter=181

我现在添加了第三个框,并且将有第三个对应的参数称为“myTrail”。我的问题是:我怎样才能做到,如果有人直接提交一个只有两个参数的 URL,浏览器就不会因为错误的请求而出错?我希望用户看到的页面好像“myState”和“myShelter”被选中,但“myTrail”只是未被选中。

我尝试查看herehere,但我认为这些情况与我所询问的情况不同。我在 Python 3 下使用 Flask,目前像这样处理这条路线:

@app.route('/forecast', methods = ['GET'])
def forecast(loc_state = None, loc_id = None):

    """
    Handles rendering of page after a location has been selected
    """

    loc_state = request.args['myState']
    loc_id = int(request.args['myShelter'])

    ...and a bunch of other logic for rendering the page...

提前感谢您的任何见解!

【问题讨论】:

    标签: python-3.x flask url-parameters


    【解决方案1】:

    request.args.get() 方法允许获取参数(如果存在)。

    # return None if the argument doesn't exist
    trail = request.args.get('myTrail')
    
    # return 'x' if the argument doesn't exist
    trail = request.args.get('myTrail', 'x')
    

    在此之后,只需处理值以返回您想要的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-30
      • 2023-03-26
      • 2020-07-16
      • 2017-09-10
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多