猿问

无论如何使用 JavaScript 查询 SQLAlchemy

我正在创建一个以 Flask 作为后端的网站,我希望我的 JavaScript 查询我的 SQLAlchemy 数据库以检查是否有任何具有相同名称的用户,如果是,则显示一条消息,如果没有,则继续路径,任何帮助将不胜感激,谢谢


我也不想泄露我所有的用户名


我的烧瓶代码注册用户名


@app.route("/reg/", methods=["POST", "GET"]);

def reg():

    if request.method == "POST":

        username = request.form["username"]

        

        check = db.query.filter_by(username=username).first()

        

        if check is None:

            add = db(username=username)

            udb.session.add(add)

            udb.session.commit()

            

            return render_template("login.html")


        else:

            return ('' ,304) # instead of this I want JavaScript to check and send a message that user already exists   

    else:

        return render_template("login.html")

我的表单 HTML


<form action="#" method="POST">

<input type="text" placeholder="Enter Username" name="username">

<input type="submit" name="submit">

</form>


阿晨1998
浏览 116回答 2
2回答

扬帆大鱼

Javascript 做不到!但如果我以另一种方式理解你,你可以启动一个 SQLAlchemy 对象并将它传递给模板上下文,如下所示:query = Users.queryreturn render_template('folder/mytemplate.html', user=query)在您的模板中,您也可以在HTML 标记中根据需要过滤查询<script>。<script>&nbsp; &nbsp; var x = '{{ user.first().name }}' // here you can play with query<script>

隔江千里

async store(req, res){&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const { username } = req.body;&nbsp; &nbsp; const userExists = await Dev.findOne({ user: username });&nbsp; &nbsp; if(userExists){&nbsp; &nbsp; &nbsp; &nbsp; return res.json(userExists);&nbsp; &nbsp; }&nbsp; &nbsp; const response = await axios.get(`https://api.github.com/users/${username}`);&nbsp; &nbsp; const { name, bio, avatar_url: avatar } = response.data;&nbsp; &nbsp; const dev = await Dev.create({&nbsp; &nbsp; &nbsp; &nbsp; name,&nbsp; &nbsp; &nbsp; &nbsp; user: username,&nbsp; &nbsp; &nbsp; &nbsp; bio,&nbsp; &nbsp; &nbsp; &nbsp; avatar&nbsp; &nbsp; });&nbsp; &nbsp; return res.json(dev);}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答