【问题标题】:Flask server error 400 Bad Request ...... KeyError: 'file'Flask 服务器错误 400 Bad Request ...... KeyError: 'file'
【发布时间】:2021-04-15 07:26:27
【问题描述】:

我打算使用从 android 应用程序发送的发布请求将视频发送到烧瓶服务器。我收到此错误

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'file'

以下是烧瓶服务器的 python 代码。请注意,我正在尝试使用 for 循环获取文件(MultiDict)的内容以进行调试。我在 powershell 窗口上没有输出。另外,由于错误是KeyError: 'file',我知道files变量为空?

from flask import Flask, request, jsonify

path_upload_folder = 'C:\\Users\\vishw\\Desktop\\cse535a3_uploads\\uploads'

app = Flask(__name__)
app.config['path_upload_folder'] = path_upload_folder
@app.route('/mainapp', methods=['GET', 'POST'])
def upload_video():
    print('Started')
    if request.method == 'POST':
        keys = request.files.keys()
        for each in keys:
            print(each)
        sent_file = request.files['file']
        sent_file.save(app.config['path_upload_folder'] + '\\' + secure_filename(sent_file.filename))
        return jsonify(operation_status="true")
    return jsonify(operation_status="false")

app.run(host="0.0.0.0", port=5000, debug=True)

这里是android应用的相关代码

public class ExampleGesture extends AppCompatActivity {
    private final int VIDEO_CAPTURE = 1;
    private VideoView example_gesture;
    private boolean captured_video = false;
    private MediaType object_mediatype;
    private Intent intent_record_video;
    private File file_media;
    private String name_file;
    private String gesture_received;
    private String address_server_ipv4;
    private String port_number;
    private String posturl;
    private int count_files = -1;
    private int [] count_practice; //= ((MainApplication)getApplication()).count_practice;
    private HashMap links;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example_gesture);
//        Log.i("APP: ", getApplication().getClass().getSimpleName());
        Log.i("EG: ", "Under Super");
        Log.i("EXAMACTTHREAD: ", String.valueOf((Thread.currentThread()).getId()));
        Context context_current = getApplicationContext();
        new Thread(new Runnable() {
            public void run() {
              Log.i("EXAMACTTHREADNEW: ", String.valueOf((Thread.currentThread()).getId()));
//                Log.i("EG: ", "Setting COntent View");
                count_practice = ((MainApplication)getApplication()).count_practice;
                Intent intent_current = getIntent();
                String gesture = intent_current.getStringExtra("EXTRA_GESTURE");
                gesture_received = gesture;
                ArrayAdapter<CharSequence> arrayAdapter_gestures = ArrayAdapter.createFromResource(context_current,
                        R.array.list_gestures,
                        android.R.layout.simple_spinner_item);
//              Log.i("ARRAY: ", String.valueOf(arrayAdapter_gestures.getCount()));
                links = new HashMap();
                for (int index = 0; index < arrayAdapter_gestures.getCount(); ++index) {
//                  Log.i("ARRAY: ", (arrayAdapter_gestures.getItem(index)).toString());
                    if (!((arrayAdapter_gestures.getItem(index)).toString().equals("Select Gesture"))) {
                        links.put((arrayAdapter_gestures.getItem(index)).toString(), 0);
                    }
                }
//              Log.i("GESTURE: ", gesture);
                String path_file = "/sdcard/Movies/";
                if (gesture == "FanUp") {
                    path_file = path_file + "H-IncreaseFanSpeed.mp4";
                } else if (gesture == "FanDown") {
                    path_file = path_file + "H-DecreaseFanSpeed.mp4";
                } else path_file = path_file + "H-" + gesture + ".mp4";
                Uri u1 = Uri.fromFile(new File(path_file));
                example_gesture = (VideoView)findViewById(R.id.videoView_gesture);
                example_gesture.setVideoURI(u1);
                example_gesture.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer arg_mp) { example_gesture.start(); }
                });
                example_gesture.start();
                Button button_record = (Button) findViewById(R.id.button_record);
                button_record.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg_view) {
                        intent_record_video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        intent_record_video.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 5);
                        File k = new File("/storage/self/primary/DCIM/Camera/");
                        count_files = (k.list()).length;
                        startActivityForResult(intent_record_video, VIDEO_CAPTURE);

                    }
                });
                Button button_previous_screen = (Button) findViewById(R.id.button_previous_screen);
                button_previous_screen.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg_view) {
                        startActivity(new Intent(getApplicationContext(), MainActivity.class));
                    }
                });
                Button button_upload = (Button) findViewById(R.id.button_upload);
                button_upload.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg_view) {
                        if (name_file.length() > 0) {
                            RequestBody postbody = RequestBody.create(object_mediatype, file_media);
                            OkHttpClient client = new OkHttpClient();

                            Request request = new Request.Builder()
                                    .url(posturl)
                                    .post(postbody)
                                    .build();
                            
                            Log.i("REQUEST: ", "Throwing a request");
                            client.newCall(request).enqueue(new Callback() {
                                @Override
                                public void onFailure(final Call call, final IOException e) {
                                    call.cancel();
                                    Log.i("REQUEST: ", "Call canceled");
                                }

                                @Override
                                public void onResponse(Call call, final Response response) throws IOException {
                                }
                            });
                            name_file = "";
                        }
                    }
                });
                address_server_ipv4 = "192.168.0.113";
                port_number = "5000";
                posturl = "http://" + address_server_ipv4 + ":" + port_number + "/mainapp";
                Thread.currentThread().interrupt();
            }
        }).start();
    }
    @Override
    protected void onResume() {
        super.onResume();

                Log.i("THREAD: ", "ran the resume thread");
        File file = new File("/storage/self/primary/DCIM/Camera/");
        String[] list_files = file.list();
        if (list_files.length > count_files && count_files != -1) {
            captured_video = true;
            count_files = list_files.length;
        }
        if (!example_gesture.isPlaying()) {
            example_gesture.start();
        }
        if (captured_video) {

//          File file = new File("/storage/self/primary/DCIM/Camera/");
//          String[] list_files = file.list();
            for (int index = 0; index < list_files.length; ++index) {
                if ((list_files[index]).charAt(0) == 'V') {
                    File f = new File(file.getPath() +'/' + list_files[index]);
                    name_file = file.getPath() + '/' + gesture_received
                            + "_PRACTICE_"
                            + count_practice[(int) links.get(gesture_received)] + "_desai.mp4";
                    File f2 = new File(name_file);
                    boolean result = f.renameTo(f2);
                    file_media = f2;
                    ++count_practice[(int) links.get(gesture_received)];
                    break;
                }
            }
            captured_video = false;
            object_mediatype = MediaType.parse("video/mp4");
        }
    }
}

正如我之前提出的,请求中的文件变量是否为空?即文件没有被发送?另外,请就我是否以正确的方式发送视频文件提出您的意见。如果我也弄错了,请告诉我正确的方法。

【问题讨论】:

    标签: python flask


    【解决方案1】:

    自从分配截止日期后忘记立即回答它,但您希望专注于您在该请求中发送的文件的名称以及您在烧瓶程序中使用的名称。我现在能记得的就这些了。

    编辑:
    sent_file = request.files['file'],这里的'file'应该是RequestBody中发送的信息的'name'

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 2010-12-13
      • 1970-01-01
      • 2013-04-20
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      相关资源
      最近更新 更多