我正在使用 Flask 开发 restful API。我正在编写 pytest 案例来测试/api/users 路径。在测试时我遇到了以下错误。 我正在使用 SQL 炼金术。我对 Flask 比较陌生。任何帮助将不胜感激
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 案例:
@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
最佳答案
问题在于您如何发布 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 中获取 key ,最好包装在 try/except 中,因为如果 key 不存在或不存在,您将收到服务器 500 错误json 已发布。使用 Web API,即使帖子格式不正确,也希望能够向客户端返回响应,这有助于更复杂的 API 和调试。
关于python - flask 错误 : AttributeError: 'NoneType' object has no attribute 'get' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55317712/