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

如何仅为网站已存在用户生成/profile/路径下的个人主页?

解决思路与代码修改方案

Got it, let's fix this issue step by step. Your core problem is that you're not checking if the requested username actually exists in the database before trying to load their profile, and right now your code will throw an error (instead of returning a 404) when a non-existent username is requested. Here's how to fix it:

1. 先校验用户是否存在

Before fetching the user's elo, first run a query to check if the username exists. If the query returns an empty result, we'll immediately return a 404 error.

2. 用Flask的abort()返回404

Flask has a built-in abort() function that lets you send standard HTTP error codes. You'll need to import it first.

修改后的完整代码

from flask import abort  # Don't forget to import this!

# Note: If you need real-time user list updates, move this query inside the route
users = db.execute("SELECT username FROM users")

@app.route("/profile/<username>")
def profile(username):
    # Query for the user's elo data
    user_data = db.execute("SELECT elo from users WHERE username = :username", username=username)
    
    # Check if the user exists
    if not user_data:
        abort(404)  # Return 404 page if no user found
    
    # Extract elo if user exists
    elo = user_data[0]["elo"]
    return render_template('profile.html', users=users, user=username, elo=elo)

额外优化建议

  • Custom 404 Page: If you want a user-friendly 404 page instead of Flask's default, add an error handler:
    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404
    
  • Real-Time User List: Your global users variable is only queried once when the app starts. If new users are added while the app is running, they won't show up. Move the db.execute("SELECT username FROM users") line inside the profile function if you need the list to update in real time.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:03:30