一尘不染

检查flask中的request.method时出错

flask

我目前正在学习Flask。

$.ajax()使用jQuery 发送数据后,type='post'当我检查时,服务器端会给出错误消息request.method。也会发生同样的情况type='get'

错误

builtins.ValueError
ValueError: View function did not return a response

Traceback (most recent call last)
  File "C:\Python33\lib\site-packages\flask\app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Python33\lib\site-packages\flask\app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "C:\Python33\lib\site-packages\flask\app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python33\lib\site-packages\flask\_compat.py", line 33, in reraise 
    raise value 
  File "C:\Python33\lib\site-packages\flask\app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python33\lib\site-packages\flask\app.py", line 1478, in full_dispatch_request
    response = self.make_response(rv)
  File "C:\Python33\lib\site-packages\flask\app.py", line 1566, in make_response
    raise ValueError('View function did not return a response')
ValueError: View function did not return a response

python代码

if request.method=='psot': #**Error occur when i check**
    req = request.get_json()
    ck=query_db("select * from users where username=?",[req['u']])
    if ck:
        if check_password_hash(ck[0]['password'],req['p']):
            session['username']=req['u']
            return jsonify({'result':'1234'})
        else:
            return jsonify({'result':'noo'})
    else:
            return jsonify({'result':'noo'})

jQuery

$.ajax({
    type:'post',
    contentType: 'application/json',
    url:"/login",
    data:JSON.stringify({'u':luser.val(),'p':lpass.val()}),
    dataType:'json',
    success:function(data)
    {
        if(data.result=='1234')
        {
            window.location.href='/profile';
        }
        else
        {
            $('#log3s').html('username or password not correct').css('color','red');
            return false;
        }
    }
});

阅读 719

收藏
2020-04-07

共1个答案

一尘不染

你需要确保使用正确的方法注册了查看路线:

@app.route('/login', methods=['GET', 'POST'])

同时允许GET和POST请求,或使用:

@app.route('/login', methods=['POST'])

只 允许POST这条路线。

要测试请求方法,请使用大写文本进行测试:

if request.method == 'POST':

但请确保你始终返回响应。如果request.method是不等于'POST'你还需要返回一个有效的响应。

2020-04-07