IT TIP

양식 전송 오류, Flask

itqueen 2021. 1. 7. 20:17
반응형

양식 전송 오류, 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가 argsform사전 에서 키를 찾지 못하면 HTTP 오류를 발생 시킨다는 것 입니다. Flask가 기본적으로 가정하는 것은 특정 키를 요청하는 경우 해당 키 가 없으면 요청에서 누락 된 부분이 있고 전체 요청이 유효하지 않다는 것입니다.

상황을 처리하는 다른 두 가지 좋은 방법이 있습니다.

  1. 사용 request.form.get방법 :

    if request.form.get('add', None) == "Like":
        # Like happened
    elif request.form.get('remove', None) == "Dislike":
        # Dislike happened
    
  2. 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.formdict에 있는지 확인해야합니다 .

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

반응형