아이오닉 웹앱 클라이언트 챕터에서
웹앱 웹서비스 테스트를 수행하고 있는데요.
아이오닉 로컬호스트에서는 실행이 잘되는데,
플라스크 실행해서 플라스크 서버를 들어가면 문제가 생깁니다.
크롬으로 플라스크 서버 192.168.0.10:5000을 입력해서 들어가면,
(저는 이상하게 0.0.0.0으로 app run을 해도 192.168.0.10:5000으로 호스트가 뜹니다.)
Method Not Allowed
The method is not allowed for the requested URL.
이런 메세지가 나오구요.
@app.route('/dnn/yolo', methods=['POST'])
위 코드를
@app.route('/dnn/yolo', methods=['GET', 'POST'])
으로 바꾸면, key error 'model'이 나오는데요...
뭔가 틀렸나싶어 예제코드를 아무리 붙여봐도 안되는데.ㅠㅠ
뭐가 잘못되었는지를 모르겠습니다...
flask 버전을 1.1.1로 바꿔도 안되고...
브라우저를 웨일이나 인터넷익스플로러로 해도 안되고...
몇시간째 헤매고 있네요..ㅠ
key error 모델에러는 다음과 같이 나구요..
werkzeug.exceptions.BadRequestKeyError
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'model'
Traceback (most recent call last)
-
File "D:\web-dnn\Lib\site-packages\flask\app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
-
File "D:\web-dnn\Lib\site-packages\flask\app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
-
File "D:\web-dnn\Lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
-
File "D:\web-dnn\Lib\site-packages\flask\app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
-
File "D:\web-dnn\Lib\site-packages\flask\_compat.py", line 39, in reraise
-
File "D:\web-dnn\Lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
-
File "D:\web-dnn\Lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
-
File "D:\web-dnn\Lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
-
File "D:\web-dnn\Lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
-
File "D:\web-dnn\Lib\site-packages\flask\_compat.py", line 39, in reraise
-
File "D:\web-dnn\Lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
-
File "D:\web-dnn\Lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
-
File "D:\web-yolo\flask\main.py", line 18, in main
model = request.form['model']
-
File "D:\web-dnn\Lib\site-packages\werkzeug\datastructures.py", line 377, 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: 'model'
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.
You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:
dump()
shows all variables in the frame
dump(obj)
dumps all that's known about the object
아래는 flask main.py 코드입니다.
from flask import Flask, request, Response, jsonify
import base64
from flask_cors import CORS
import numpy as np
import cv2
from PIL import Image
from io import BytesIO
confthres=0.5
nmsthres=0.1
app = Flask(__name__)
CORS(app)
@app.route('/dnn/yolo', methods=['GET', 'POST'])
def main():
model = request.form['model']
if model == 'apple':
labelsPath="./model/classes.names"
configpath="./model/apple-train-yolo.cfg"
weightspath="./model/apple-train-yolo_final.weights"
else:
labelsPath="./model/coco.names"
configpath="./model/yolov3.cfg"
weightspath="./model/yolov3.weights"
print("[INFO] loading ", model.upper(), " models...")
LABELS = open(labelsPath).read().strip().split("\n")
net = cv2.dnn.readNetFromDarknet(configpath, weightspath)
file = request.form['image']
starter = file.find(',')
image_data = file[starter+1:]
image_data = bytes(image_data, encoding="ascii")
img = Image.open(BytesIO(base64.b64decode(image_data)))
#img = cv2.imread('./dog.jpg')
npimg=np.array(img)
image=npimg.copy()
image=cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
(H, W) = image.shape[:2]
ln = net.getLayerNames()
ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416),
swapRB=True, crop=False)
net.setInput(blob)
layerOutputs = net.forward(ln)
boxes = []
confidences = []
classes = []
results = []
for output in layerOutputs:
for detection in output:
scores = detection[5:]
classID = np.argmax(scores)
confidence = scores[classID]
if confidence > confthres:
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classes.append({ 'id': int(classID), 'name': LABELS[classID] })
idxs = cv2.dnn.NMSBoxes(boxes, confidences, confthres,
nmsthres)
if len(idxs) > 0:
for i in idxs.flatten():
results.append({ 'class': classes[i], 'confidence': confidences[i], 'bbox': boxes[i] })
return jsonify(results)
# start flask app
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')