[英]Flask Error - AttributeError 'NoneType' object has no attribute 'isatty'
[英]Flask error : AttributeError: 'NoneType' object has no attribute 'get'
我正在使用Flask開發寧靜的API。 我正在編寫pytest案例來測試/ api / users路徑。 在測試時,我遇到錯誤。 我正在使用SQL Alchemy。 我對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中獲取密鑰,那么最好將try / except換行,因為如果密鑰不存在或未發布json,則會收到服務器500錯誤。 使用Web API,即使帖子格式錯誤,也希望能夠將響應返回給客戶端,這有助於更復雜的API和調試。
我認為您應該使用request.get_json()方法。
請參閱此以獲取更多詳細信息request.get_json
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.