如何使用 Flask/Python 3 处理 URL 中缺少的参数

Pat*_*nes 5 url-parameters flask python-3.x

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

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

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

我尝试查看此处此处,但我认为这些情况与我所问的情况并不完全相同。我在 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...
Run Code Online (Sandbox Code Playgroud)

预先感谢您的任何见解!

iur*_*vio 4

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')
Run Code Online (Sandbox Code Playgroud)

之后,只需处理该值即可以您想要的方式返回。