sourcecode

플라스크 - 잘못된 요청 브라우저(또는 프록시)가 이 서버가 이해할 수 없는 요청을 보냈습니다.

codebag 2023. 7. 12. 23:45
반응형

플라스크 - 잘못된 요청 브라우저(또는 프록시)가 이 서버가 이해할 수 없는 요청을 보냈습니다.

파일 업로드 및 플라스크를 사용하여 MongoDB에 데이터 입력 작업을 하려고 하는데 양식을 작성하고 이미지를 업로드할 때 다음 오류가 발생했습니다.

잘못된 요청 - 브라우저(또는 프록시)가 이 서버가 인식할 수 없는 요청을 보냈습니다.

내 HTML 코드

    <form class="form-check form-control" method="post" enctype="multipart/form-data" action="{{ url_for('index') }}">      
          <label>Full Name*</label></td>
          <input name="u_name" type="text" class="text-info my-input" required="required" />
          <label>Email*</label>
          <input name="u_email" type="email" class="text-info my-input" required="required" />
          <label>Password*</label>
          <input name="u_pass" type="password" class="text-info my-input" required="required" />
          <label>Your Image*</label>
          <input name="u_img" type="file" class="text-info" required="required" /></td>
          <input name="btn_submit" type="submit" class="btn-info" />
    </form>

내 파이썬 코드:

from flask import Flask, render_template, request, url_for
from flask_pymongo import PyMongo
import os
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'flask_assignment'
app.config['MONGO_URI'] = 'mongodb://<user>:<pass>@<host>:<port>/<database>'
mongo = PyMongo(app)
app_root = os.path.dirname(os.path.abspath(__file__))


@app.route('/', methods=['GET', 'POST'])
def index():
    target = os.path.join(app_root, 'static/img/')
    if not os.path.isdir(target):
        os.mkdir(target)
    if request.method == 'POST':
        name = request.form['u_name']
        password = request.form['u_pass']
        email = request.form['u_email']
        file_name = ''
        for file in request.form['u_img']:
            file_name = file.filename
            destination = '/'.join([target, file_name])
            file.save(destination)
        mongo.db.employee_entry.insert({'name': name, 'password': password, 'email': email, 'img_name': file_name})
        return render_template('index.html')
    else:
        return render_template('index.html')

app.run(debug=True)

오류는 다음과 같이 발생합니다.BadRequestKeyError존재하지 않는 키에 대한 액세스 때문에request.form.

ipdb> request.form['u_img']
*** BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

업로드된 파일은 다음과 같이 입력됩니다.request.files그리고 아닌request.form사전.또한 값이 아래에 입력되므로 루프를 잃어야 합니다.u_img의 예입니다.FileStorage그리고 주목할 만합니다.

@app.route('/', methods=['GET', 'POST'])
def index():
    target = os.path.join(app_root, 'static/img/')
    if not os.path.isdir(target):
        os.makedirs(target)
    if request.method == 'POST':
        ...
        file = request.files['u_img']
        file_name = file.filename or ''
        destination = '/'.join([target, file_name])
        file.save(destination)
        ...
    return render_template('index.html')

언급URL : https://stackoverflow.com/questions/48780324/flask-bad-request-the-browser-or-proxy-sent-a-request-that-this-server-could

반응형