
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
웹개발 종합반을 2회독하고 혼자서 연습을 하는 도중에 서버 오류가 생겼습니다.
KeyError가 발생했다고 하는데, 어떤 부분에서 잘못된 건지 구글링을 해도 찾기 어렵더라고요...
웹개발 종합반에서 배운 내용을 그대로 활용했는데 계속 오류가 납니다...
작성한 코드 및 에러 메세지
<에러 메시지>
127.0.0.1 - - [23/Dec/2022 20:10:46] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [23/Dec/2022 20:10:46] "GET /static/style.css HTTP/1.1" 304 -
127.0.0.1 - - [23/Dec/2022 20:10:46] "GET /work HTTP/1.1" 200 -
127.0.0.1 - - [23/Dec/2022 20:10:52] "POST /work HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/hansebin/Desktop/prec/toDo/venv/lib/python3.8/site-packages/flask/app.py", line 2548, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/hansebin/Desktop/prec/toDo/venv/lib/python3.8/site-packages/flask/app.py", line 2528, in wsgi_app
response = self.handle_exception(e)
File "/Users/hansebin/Desktop/prec/toDo/venv/lib/python3.8/site-packages/flask/app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "/Users/hansebin/Desktop/prec/toDo/venv/lib/python3.8/site-packages/flask/app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/hansebin/Desktop/prec/toDo/venv/lib/python3.8/site-packages/flask/app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/hansebin/Desktop/prec/toDo/venv/lib/python3.8/site-packages/flask/app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "/Users/hansebin/Desktop/prec/toDo/app.py", line 18, in work_post
work_receive = request.form['work_give']
File "/Users/hansebin/Desktop/prec/toDo/venv/lib/python3.8/site-packages/werkzeug/datastructures.py", line 375, in __getitem__
raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'work_give'
127.0.0.1 - - [23/Dec/2022 20:10:54] "GET /static/style.css HTTP/1.1" 304 -
<작성한 코드 app.py>
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://test:sparta@cluster0.g8d0ssb.mongodb.net/?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
@app.route('/')
def home():
return render_template('index.html')
@app.route("/work", methods=["POST"])
def work_post():
work_receive = request.form['work_give']
work_list = list(db.mywork.find({}, {'_id': False}))
count = len(work_list) + 1
doc = {
'num': count,
'work': work_receive,
'done': 0
}
db.mywork.insert_one(doc)
# print(request.form)
return jsonify({'msg': '작성 완료!'})
@app.route("/work", methods=["GET"])
def work_get():
return jsonify({'msg': 'get 연결 완료!'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
<작성한 코드 index.html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<link href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Gowun+Batang&family=Jua&family=Playfair+Display&display=swap"
rel="stylesheet">
<link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet">
<title>📓To Do List</title>
<script>
$(document).ready(function (){
show_work();
});
function show_work(){
$.ajax({
type: "GET",
url: "/work",
date: {},
success: function (response){
alert(response['msg'])
}
});
}
function save_work(){
let work = $('#work').val()
$.ajax({
type: "POST",
url: "/work",
date: {work_give: work},
success: function (response){
alert(response['msg'])
}
});
}
</script>
</head>
<body>
<div class="mytitle">
<h1>📓 TO DO LIST</h1>
</div>
<div class="myinput">
<div class="input-box">
<div class="input-group mb-3" id="mystyle">
<span class="input-group-text" id="basic-addon1">DATE</span>
<input type="text" class="form-control" placeholder="INPUT date -> ex) 2022.12.21"
aria-label="Username" aria-describedby="basic-addon1">
</div>
<button type="button" class="btn btn-outline-danger" id="btn-color">Enter</button>
</div>
<div class="input-box">
<div class="input-group mb-3" id="mystyle">
<span class="input-group-text" id="basic-addon1">TO DO</span>
<input id="work" type="text" class="form-control" placeholder="INPUT to do" aria-label="Username" aria-describedby="basic-addon1">
</div>
<button onclick="save_work()" type="button" class="btn btn-outline-danger" id="btn-color">Enter</button>
</div>
</div>
<!--id=work-date-->
<div id="work-date" class="mydate">
<h3>2022.12.21 to do list</h3>
</div>
<!--id = work-post-->
<div id="work-post" class="post-list">
<li>
<h4>👉🏻 flask 웹 페이지 제작 연습하기</h4>
<button type="button" class="btn btn-outline-danger" id="btn-color">Done!</button>
</li>
<li>
<h4 class="done">👉🏻 html, css 기획</h4>
</li>
</div>
<!--id = delete-->
<div id="delete"><h4>Delete All!</h4></div>
</body>
</html>
