You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask项目报错TypeError:address_finder()需0个参数却传入2个

解决Flask视图函数调用时的TypeError问题

你遇到的TypeError: address_finder() takes 0 positional arguments but 2 were given错误,核心原因是在Flask视图函数内部递归调用了自身:视图函数address_finder被设计为无额外参数(Flask路由视图函数默认仅接收路由匹配的参数,你的/directions路由未定义任何参数),但你传入了location和user_input.lower()两个参数,导致参数不匹配。

如果给视图函数强行添加两个参数,Flask会尝试从路由中获取对应变量,但你的路由没有定义变量,访问页面时又会触发参数缺失的TypeError。


修正后的代码实现

将地址查找逻辑从视图函数中抽离,单独封装成一个函数,让视图函数专注处理HTTP请求:

Python代码

from flask import Flask, render_template, request

location = {
    "673 Ayres Ave": ["acs building", "ACS building", "BLDG 750", "Soldier Support Center", "soldier support center"],
    "BLDG 683": ["Desmond Doss Health Clinic", "Desmond Doss", "desmond doss", "desmond doss health clinic"], 
    "694 McCornack Rd": ["PX", "Schofield Main Exchange", "Post Exchange", "px", "post exchange", "schofield main exchange"]
}

app = Flask(__name__)

# 独立处理地址匹配的函数
def find_target_address(location_dict, input_str):
    for address, aliases in location_dict.items():
        if input_str in aliases:
            return address
    # 未找到匹配项时返回原输入
    return input_str

@app.route("/directions", methods=['GET', 'POST'])
def address_finder():
    if request.method == 'POST':
        user_input = request.form['location']
        # 调用独立的查找函数,而非视图函数自身
        result = find_target_address(location, user_input.lower())

        if result != user_input:
            return f"The location for '{user_input}' is: {result}"
        else:
            return f"'{user_input}' not found in the dictionary"
    return render_template('inputpage.html')

if __name__ == '__main__':
    app.run(debug=True)

HTML模板(无需修改)

<!DOCTYPE html>
 <html>
 <head>
    <title>Address Finder</title>
  </head>
   <body>
     <h1>Address Finder</h1>
     <form method="POST">
         <label for="location">Enter the location you want to find:</label>
         <input type="text" name="location" id="location">
         <input type="submit" value="Find Address">
     </form>
   </body>
  </html>

关键修改点

  1. 新增find_target_address函数,专门负责遍历字典匹配地址,职责单一,避免与视图函数混淆。
  2. 视图函数address_finder仅处理GET/POST请求的分发,调用独立函数完成查找逻辑,不再递归调用自身,彻底解决参数不匹配问题。

内容的提问来源于stack exchange,提问作者dhud130

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:35:10