Hướng dẫn how do i save a flask file in python? - làm cách nào để lưu tệp bình trong python?

À đúng rồi, vấn đề cũ của tải lên tệp. Ý tưởng cơ bản của tải lên tệp thực sự khá đơn giản. Về cơ bản nó hoạt động như thế này:

  1. Một thẻ <form> được đánh dấu bằng enctype=multipart/form-data<input type=file> được đặt ở dạng đó.

  2. Ứng dụng truy cập tệp từ từ điển

    def allowed_file(filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
    
    @app.route('/', methods=['GET', 'POST'])
    def upload_file():
        if request.method == 'POST':
            # check if the post request has the file part
            if 'file' not in request.files:
                flash('No file part')
                return redirect(request.url)
            file = request.files['file']
            # if user does not select file, browser also
            # submit an empty part without filename
            if file.filename == '':
                flash('No selected file')
                return redirect(request.url)
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                return redirect(url_for('uploaded_file',
                                        filename=filename))
        return '''
        <!doctype html>
        <title>Upload new File</title>
        <h2>Upload new File</h2>
        <form method=post enctype=multipart/form-data>
          <input type=file name=file>
          <input type=submit value=Upload>
        </form>
        '''
    
    0 trên đối tượng yêu cầu.

  3. Sử dụng phương thức

    def allowed_file(filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
    
    @app.route('/', methods=['GET', 'POST'])
    def upload_file():
        if request.method == 'POST':
            # check if the post request has the file part
            if 'file' not in request.files:
                flash('No file part')
                return redirect(request.url)
            file = request.files['file']
            # if user does not select file, browser also
            # submit an empty part without filename
            if file.filename == '':
                flash('No selected file')
                return redirect(request.url)
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                return redirect(url_for('uploaded_file',
                                        filename=filename))
        return '''
        <!doctype html>
        <title>Upload new File</title>
        <h2>Upload new File</h2>
        <form method=post enctype=multipart/form-data>
          <input type=file name=file>
          <input type=submit value=Upload>
        </form>
        '''
    
    1 của tệp để lưu tệp vĩnh viễn ở đâu đó trên hệ thống tập tin.

Giới thiệu nhẹ nhàng

Hãy để bắt đầu với một ứng dụng rất cơ bản để tải tệp lên một thư mục tải lên cụ thể và hiển thị một tệp cho người dùng. Hãy cùng xem mã bootstrapping cho ứng dụng của chúng tôi:

import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

Vì vậy, trước tiên chúng ta cần một vài nhập khẩu. Hầu hết nên đơn giản,

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h2>Upload new File</h2>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
2 được giải thích một chút sau đó.
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h2>Upload new File</h2>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
3 là nơi chúng tôi sẽ lưu trữ các tệp đã tải lên và
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h2>Upload new File</h2>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
4 là tập hợp các phần mở rộng tệp được phép.

Tại sao chúng ta giới hạn các phần mở rộng được cho phép? Bạn có thể không muốn người dùng của bạn có thể tải lên mọi thứ ở đó nếu máy chủ trực tiếp gửi dữ liệu cho máy khách. Bằng cách đó, bạn có thể đảm bảo rằng người dùng không thể tải lên các tệp HTML sẽ gây ra sự cố XSS (xem tập lệnh chéo trang (XSS)). Ngoài ra, hãy đảm bảo không cho phép các tệp

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h2>Upload new File</h2>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
5 nếu máy chủ thực thi chúng, nhưng ai đã cài đặt PHP trên máy chủ của họ, phải không? :)Cross-Site Scripting (XSS)). Also make sure to disallow
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h2>Upload new File</h2>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
5 files if the server executes them, but who has PHP installed on their server, right? :)

Tiếp theo các chức năng kiểm tra xem tiện ích mở rộng có hợp lệ không và tải lên tệp và chuyển hướng người dùng đến URL cho tệp đã tải lên:

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h2>Upload new File</h2>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''

Vậy chức năng

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h2>Upload new File</h2>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
6 đó thực sự làm gì? Bây giờ vấn đề là có nguyên tắc gọi là không bao giờ tin tưởng vào đầu vào của người dùng. Điều này cũng đúng với tên tệp của một tệp được tải lên. Tất cả dữ liệu biểu mẫu được gửi có thể được giả mạo và tên tệp có thể nguy hiểm. Đối với thời điểm chỉ cần nhớ: Luôn luôn sử dụng chức năng đó để bảo mật tên tệp trước khi lưu trữ trực tiếp trên hệ thống tệp.

Thông tin cho các chuyên gia

Vì vậy, bạn có thể quan tâm đến những gì chức năng

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h2>Upload new File</h2>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
6 làm và vấn đề là gì nếu bạn không sử dụng nó? Vì vậy, chỉ cần tưởng tượng ai đó sẽ gửi các thông tin sau dưới dạng tệp cho ứng dụng của bạn:

filename = "../../../../home/username/.bashrc"

Giả sử số lượng

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h2>Upload new File</h2>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
8 là chính xác và bạn sẽ tham gia vào đó với
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h2>Upload new File</h2>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
3 Người dùng có thể có khả năng sửa đổi một tệp trên hệ thống tập tin của máy chủ mà người đó không nên sửa đổi. Điều này đòi hỏi một số kiến ​​thức về ứng dụng trông như thế nào, nhưng tin tôi, tin tặc kiên nhẫn :)

Bây giờ, hãy để xem xét chức năng đó hoạt động như thế nào:

>>> secure_filename('../../../../home/username/.bashrc')
'home_username_.bashrc'

Bây giờ một điều cuối cùng bị thiếu: phần phục vụ của các tệp đã tải lên. Trong

filename = "../../../../home/username/.bashrc"
0, chúng tôi chuyển hướng người dùng đến
filename = "../../../../home/username/.bashrc"
1, nghĩa là
filename = "../../../../home/username/.bashrc"
2. Vì vậy, chúng tôi viết hàm
filename = "../../../../home/username/.bashrc"
3 để trả về tệp của tên đó. Theo bình 0,5, chúng tôi có thể sử dụng một chức năng làm điều đó cho chúng tôi:

from flask import send_from_directory

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

Ngoài ra, bạn có thể đăng ký upload_file dưới dạng quy tắc build_only và sử dụng

filename = "../../../../home/username/.bashrc"
4. Điều này cũng hoạt động với các phiên bản cũ hơn của bình:

from werkzeug.middleware.shared_data import SharedDataMiddleware
app.add_url_rule('/uploads/<filename>', 'uploaded_file',
                 build_only=True)
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
    '/uploads':  app.config['UPLOAD_FOLDER']
})

Nếu bây giờ bạn chạy ứng dụng, mọi thứ sẽ hoạt động như mong đợi.

Cải thiện tải lên

Thay đổi

Mới trong phiên bản 0.6.

Vậy chính xác thì Flask xử lý tải lên như thế nào? Vâng, nó sẽ lưu trữ chúng trong bộ nhớ của WebServer nếu các tệp hợp lý nhỏ nếu không ở một vị trí tạm thời (như được trả về bởi

filename = "../../../../home/username/.bashrc"
5). Nhưng làm thế nào để bạn chỉ định kích thước tệp tối đa sau đó tải lên bị hủy bỏ? Bình mặc định sẽ vui vẻ chấp nhận tải lên tệp lên một lượng bộ nhớ không giới hạn, nhưng bạn có thể giới hạn điều đó bằng cách đặt khóa cấu hình
filename = "../../../../home/username/.bashrc"
6:

from flask import Flask, Request

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

Mã trên sẽ giới hạn tải trọng cho phép tối đa đến 16 megabyte. Nếu một tệp lớn hơn được truyền, bình sẽ tăng ngoại lệ

filename = "../../../../home/username/.bashrc"
7.

Vấn đề đặt lại kết nối

Khi sử dụng máy chủ phát triển cục bộ, bạn có thể gặp lỗi thiết lập lại kết nối thay vì phản hồi 413. Bạn sẽ nhận được phản hồi trạng thái chính xác khi chạy ứng dụng với máy chủ WSGI sản xuất.

Tính năng này đã được thêm vào bình 0.6 nhưng có thể đạt được trong các phiên bản cũ hơn bằng cách phân lớp đối tượng yêu cầu. Để biết thêm thông tin về việc tham khảo tài liệu Werkzeug về xử lý hồ sơ.

Tải lên các thanh tiến trình

Cách đây một thời gian, nhiều nhà phát triển đã có ý tưởng đọc tệp đến trong các phần nhỏ và lưu trữ tiến trình tải lên trong cơ sở dữ liệu để có thể bỏ phiếu tiến trình với JavaScript từ máy khách. Câu chuyện dài: Khách hàng hỏi máy chủ cứ sau 5 giây, nó đã truyền bao nhiêu. Bạn có nhận ra sự trớ trêu? Khách hàng đang yêu cầu một cái gì đó mà nó nên biết.

Một giải pháp dễ dàng hơn

Bây giờ có những giải pháp tốt hơn làm việc nhanh hơn và đáng tin cậy hơn. Có các thư viện JavaScript như jQuery có các plugin biểu mẫu để giảm bớt việc xây dựng thanh tiến trình.

Bởi vì mô hình phổ biến cho các tải lên tệp tồn tại gần như không thay đổi trong tất cả các ứng dụng liên quan đến tải lên, nên cũng có một tiện ích mở rộng bình gọi là các lớp tải bỏ Flask thực hiện cơ chế tải lên đầy đủ với các phần mở rộng màu trắng và đen và nhiều hơn nữa.

Làm cách nào để trả lại một tệp bình?

Truy cập trình duyệt và nhập loại HTTP: // LocalHost: 8000/get-files/..

Làm thế nào để bạn tải lên một tệp trong Python?

Phương pháp 1: Sử dụng mô-đun HĐH của Python: Ngoài ra, thuộc tính Enctype có giá trị "đa phần/dữ liệu hình thức" sẽ giúp biểu mẫu HTML tải lên tệp. Cuối cùng, chúng tôi cần thẻ đầu vào với thuộc tính tên tệp để tải lên tệp chúng tôi muốn. Cuối cùng, chúng tôi cần thẻ đầu vào với thuộc tính tên tệp để tải lên tệp chúng tôi muốn.Using the Python's os Module: Also, the enctype attribute with "multi-part/form-data" value will help the HTML form to upload a file. Lastly, we need the input tag with the filename attribute to upload the file we want. Lastly, we need the input tag with the filename attribute to upload the file we want.

Làm cách nào để tải lên và tải xuống bình?

Tuy nhiên, chúng tôi cũng truy cập các mẫu HTML, vì vậy chúng tôi tạo thư mục mẫu và truy cập ở đây ...
Từ bình nhập bình.Ứng dụng = Flask (__ name__, template_folder = 'Mẫu') ....
Upload_folder = 'tải lên/' app.config ['upload_folder'] = upload_folder.....
Nhập hệ điều hành.từ werkzeug.utils nhập secure_filename.....
@ứng dụng.....
Nhập hệ điều hành ..

Làm cách nào để thêm một tệp python vào bình?

Sử dụng nhập khẩu:..
Bọc những gì tập lệnh Python (ví dụ: trang web_generator.py) đang tạo thành một hàm ..
Đặt nó vào cùng thư mục với app.py hoặc flask.py của bạn ..
Sử dụng từ trang web_generator nhập chức năng_name trong flask.py ..
Chạy nó bằng function_name ().