양식 전송 오류, Flask
두 개의 형태가 <input type="submit">
있습니다. 하지만 내가 보낼 때 두 번째 제출하면 오류가 발생합니다.
레이아웃 :
<form action="{{ url_for('index') }}" method="post">
<input type="submit" name="add" value="Like">
<input type="submit" name="remove" value="Dislike">
</form>
main.py :
...
if request.method == 'POST':
if request.form['add']:
return redirect(url_for('index'))
elif request.form['remove']:
return redirect(url_for('index'))
...
첫 번째 제출 (추가)은 잘 작동하지만 두 번째 (제거) ... :
잘못된 요청 브라우저 (또는 프록시)가이 서버가 이해할 수없는 요청을 보냈습니다.
이 오류를 어떻게 해결할 수 있습니까?
UPD :
매우 간단했습니다. request.form은 ImmutableMultiDict를 반환합니다.
...
if 'Like' in request.form.values():
...
elif 'Dislike' in request.form.values():
...
@Blubber가 지적했듯이 문제는 Flask가 args
및 form
사전 에서 키를 찾지 못하면 HTTP 오류를 발생 시킨다는 것 입니다. Flask가 기본적으로 가정하는 것은 특정 키를 요청하는 경우 해당 키 가 없으면 요청에서 누락 된 부분이 있고 전체 요청이 유효하지 않다는 것입니다.
상황을 처리하는 다른 두 가지 좋은 방법이 있습니다.
사용
request.form
의.get
방법 :if request.form.get('add', None) == "Like": # Like happened elif request.form.get('remove', None) == "Dislike": # Dislike happened
name
두 제출 요소에 동일한 속성을 사용하십시오 .<input type="submit" name="action" value="Like"> <input type="submit" name="action" value="Dislike"> # and in your code if request.form["action"] == "Like": # etc.
'add'
및 'remove'
키가 request.form
dict에 있는지 확인해야합니다 .
if request.method == 'POST':
if 'add' in request.form:
return redirect(url_for('index'))
elif 'remove' in request.form:
return redirect(url_for('index'))
Like 를 클릭 하면 첫 번째 조건이 충족되어 실패하지 않으므로 두 번째 조건은 확인되지 않습니다. 그러나 싫어요 버튼을 클릭하면 라는 키가 포함되어 있지 않기 KeyError
때문에 첫 번째 조건에서 예외 가 발생합니다 .request.form
'add'
참조 URL : https://stackoverflow.com/questions/8552675/form-sending-error-flask
'IT TIP' 카테고리의 다른 글
인라인 모델 양식 또는 폼셋이있는 django 클래스 기반 뷰 (0) | 2021.01.07 |
---|---|
Pusher에 대한 오픈 소스 대안 (0) | 2021.01.07 |
Java에서 HashMap과 Map의 차이점 ..? (0) | 2021.01.07 |
node.js의 가비지 수집기를 실행하도록 요청하는 방법은 무엇입니까? (0) | 2021.01.07 |
UICollectionView-동적 셀 높이? (0) | 2021.01.07 |