烧瓶错误:AttributeError:'NoneType'对象没有属性'get'

时间:2019-03-23 19:48:19

标签: python rest flask flask-restful flask-login

我正在使用Flask开发宁静的API。我正在编写pytest案例来测试/ api / users路径。在测试时,我遇到错误。 我正在使用SQL Alchemy。我对Flask比较陌生。任何帮助将不胜感激

烧瓶API:

@app.route('/api/users', methods=['POST'])
def new_user():
    username = request.json.get('username')
    password = request.json.get('password')
    user = User(username = username)
    user.hash_password(password)
    db.session.add(user)
    db.session.commit()
    return ("user")

最坏的情况:

@pytest.fixture
def client():
    db_fd, app.config['DATABASE'] = tempfile.mkstemp()
    app.config['TESTING'] = True
    client = app.test_client()

    yield client

    os.close(db_fd)
    os.unlink(app.config['DATABASE'])

@pytest.fixture
def user():
    return {
    'username': 'test_username',
    'password': 'test_password',
    'email': 'test_email'
    }



def _new_user(client, user):
    return client.post('/api/users', json.dumps(user))


# REGISTER USER
def test_new_user(client, user):
    res = _new_user(client, user)

    assert res.status_code == 201
    assert 'user' in json.loads(res.get_data())

运行测试用例时,出现错误

    @app.route('/api/users', methods=['POST'])
    def new_user():
>       username = request.json.get('username')
E       AttributeError: 'NoneType' object has no attribute 'get'

apa/routes.py:20: AttributeError

2 个答案:

答案 0 :(得分:1)

问题在于您如何发布json。您需要修改以下行:

def _new_user(client, user):
    return client.post('/api/users', json.dumps(user))

成为:

def _new_user(client, user):
    return client.post('/api/users', json=json.dumps(user))

如果您未将json指定为参数,则会将其放入request.data属性而不是request.json.

通常,如果您试图从发布到API的json中获取密钥,则最好将try / except换行,因为如果密钥不存在或不存在,则会出现服务器500错误json已发布。使用Web API,即使帖子格式错误,也希望能够将响应返回给客户端,这有助于更复杂的API和调试。

答案 1 :(得分:0)

我认为您应该使用request.get_json()方法。

了解详情,request.get_json

相关问题