【问题标题】:Flask-SQLAlchemy Check if row existsFlask-SQLAlchemy 检查行是否存在
【发布时间】:2019-04-12 03:06:06
【问题描述】:

我已经看过this SO question,到目前为止还没有帮助。

所以我正在尝试使用 Flask-SQLAlchemy 检查表中是否存在一行,但到目前为止没有任何帮助。

我当前的代码:

@app.route('/guilds/<guildid>')
def guildsettings(guildid):
    discord = make_session(token=session.get('oauth2_token'))
    user = discord.get(API_BASE_URL + '/users/@me').json()
    guilds = discord.get(API_BASE_URL + '/users/@me/guilds').json()
    row = Settings.query.all()
    exists = Settings.query.filter_by(db.exists().where(Settings.guildid==guildid)).scalar()
    print(exists)
    if exists == True:
        info = Settings.query.filter_by(guildid=guildid).first()
        return render_template("guild.html", id=guildid, guilds=guilds, User=user, prefix=info.prefix, logschannel=info.logschannel, modrole=info.modrole, adminrole=info.adminrole, welcomechannel=info.welcomechannel, welcomemessage=info.welcomemessage, dadbot=info.dadbot, music=info.music, funcmds=info.funcmds, weather=info.weather, wapikey=info.wapikey)
    else:
        return render_template("notinserver.html", guildid=guildid, link="https://discordapp.com/api/oauth2/authorize?client_id=xxxxxx&permissions=8&redirect_uri=xxxxxxx%2Fme&scope=bot&guild_id={}".format(guildid))

我不知道现在该做什么。任何帮助表示赞赏。

【问题讨论】:

  • 您的代码发生了什么?为什么它不起作用?

标签: python python-3.x flask flask-sqlalchemy


【解决方案1】:

如果需要正好是一个结果:

try:
    Settings.query.filter_by(db.exists().where(Settings.guildid==guildid)).one()
except sqlalchemy.orm.exc.NoResultFound:
    return False
except sqlalchemy.orm.exc.MultipleResultsFound:
    #do what ever you want to do if there is more than one result
return True

【讨论】:

  • 我需要它来检查具有特定guildid 的行是否存在。如果没有,那么它应该重定向到链接。如果是,它应该呈现guild.html 模板。
  • 只需将 flase/true 替换为重定向/渲染。有效果还是你还需要帮助?
猜你喜欢
  • 2016-01-01
  • 2017-03-31
  • 1970-01-01
  • 2017-11-22
  • 2022-01-24
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 2016-09-20
相关资源
最近更新 更多