使用 FlaskWTF

问题描述

简介

嗨。在此应用程序中,我正在使用flask_login、fetch() 和flask_cors 来预测正在预测的服装。一切正常,直到我尝试使用注册用户帐户登录


问题

所以目前,我已经创建了一个用户帐户,他可以在该帐户中进行任何他想做的预测。所以在这里我有一段代码,当用户点击 ID 为 #startbutton 的预测按钮时,它会向我的烧瓶后端发送一个 POST,预测并返回预测结果。

$("#startbutton").on("click",function(){
    let img = webcam.snap()
    $('#result').text( 'Predicting...');

    $.ajax({
        type: "POST",url:  "http://localhost:5000/predict",data: img,success: function(data){
            $('#result').text('Predicted Output: ' + data);
        }
    });
});

在我的后端,我创建了一个 API 路由来处理来自我的 javascript 的数据,并将记录添加到我的数据库中。在这里,我使用 @login_required 来验证登录用户并将他的数据发布到数据库。我还添加@cross_origin 以便我可以从我的 ajax 调用获取数据。

@app.route('/predict',methods=['GET','POST'])
@login_required
@cross_origin(origin='localhost',headers=['Content-Type','Authorization'],supports_credentials=True)
def predict():
    if request.method == 'POST':
        # get data from drawing canvas and save as image
        fileName,filePath = parseImage(request.get_data())
    
        # Decoding and pre-processing base64 image
        img = image.img_to_array(image.load_img(filePath,color_mode="grayscale",target_size=(28,28))) / 255.
        # reshape data to have a single channel
        img = img.reshape(1,28,1)
    
        predictions = make_prediction(img)
    
        ret = ""
        for i,pred in enumerate(predictions):
            ret = "{}".format(np.argmax(pred))
            response = results[int(ret)]

            # dump new entry into db
            new_entry = Entry(user_id=current_user.id,filename=fileName,prediction=response,predicted_on=datetime.utcNow())
            add_entry(new_entry)

            return response
    return render_template("index.html",index=True,nav=True)

在我声明我的应用程序和 CORS 的 _init_.py 中,我添加supports_credentials=True 以便 CORS 支持我的应用程序的凭据。

app = Flask(__name__)
CORS(app,supports_credentials=True)

但是,当我尝试调试并尝试在本地主机中运行我的应用程序时,我使用现有用户帐户登录并尝试进行预测。但我总是以 Error 401(Unauthorized) 错误消息结束,当我进入 google chrome 控制台查看错误时,我看到它把我识别为匿名用户

jquery-3.5.1.js:10099 POST http://localhost:5000/predict 401 (UNAUTHORIZED)
send @ jquery-3.5.1.js:10099
ajax @ jquery-3.5.1.js:9682
(anonymous) @ index.js:49 <------- HERE
dispatch @ jquery-3.5.1.js:5429
elemData.handle @ jquery-3.5.1.js:5233

研究

我试图找出是否有人遇到过同样的问题,并且我设法找到了一篇与我目前的情况类似的 SO 帖子。 Link here。我试图理解它,但无法看到(或理解)他的最终决定。


编辑

好的,所以我尝试将我当前的 ajax 代码重新制定到 Mozilla fetch() 中,据说它支持 cookie(我猜?),但最终还是收到了未经授权的消息。

$("#startbutton").on("click",function(){
    let img = webcam.snap()
    $('#result').text( 'Predicting...');

    fetch("http://localhost:5000/predict",{
      method: "POST",ContentType: 'application/json',credentials: 'include'
    })
    .then(function(data) {
      $('#result').text('Predicted Output: ' + data);
    }).catch((err) => {
      console.log(err)
    })
});

如果有人能帮助我,我真的真的,真的感激不尽! :(谢谢!:)

解决方法

所以经过 3 天的痛苦之后,我看到一篇文章说 ajax 调用默认是异步的,所以为了获取 cookie,我只需要将 async 设置为 False .所以我将我的 ajax 代码修改为下面的代码片段:

$("#startbutton").on("click",function(){
    let img = webcam.snap()
    $('#result').text( 'Predicting...');

    $.ajax({
        type: "POST",url:  "http://localhost:5000/predict",data: img,crossDomain: true,async: false,success: function(data){
            $('#result').text('Predicted Output: ' + data);
        }
    });
});

我知道这不是最佳解决方案(或者它是 lmao),所以我愿意看到其他替代方案。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...