Flask:如何将上传的文件作为输入传递给方法?AttributeError:“\u io.BytesIO”对象没有属性“lower”

2024-06-07 15:37:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我对flask完全陌生(事实上我今天早上才开始),到目前为止,我只实现了一个基本的上传功能(取自flask文档)。文件上传工作正常,但我似乎不知道如何将文件传递到另一种方法(挖掘)。当我这样做时,我总是会收到错误消息:AttributeError:“\u io.BytesIO”对象没有属性“lower”。接受任何形式的帮助对我来说都是非常重要的!提前谢谢大家

def mining(xes):
    log = xes_importer.apply(xes)
    tracefilter_log_pos = attributes_filter.apply_events(log, ["complete"], parameters={attributes_filter.Parameters.ATTRIBUTE_KEY: "lifecycle:transition", attributes_filter.Parameters.POSITIVE: True})
    variants = pm4py.get_variants_as_tuples(tracefilter_log_pos)
    Alpha(variants.keys())
    Heuristic(variants.keys(), 1, 0.5)


UPLOAD_FOLDER = '/Users/jenny/processmining_lab/uploads'
ALLOWED_EXTENSIONS = set(['xes'])

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


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 the user does not select a file, the browser submits an
        # empty file without a 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 mining(file)
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''

Here is the traceback


Tags: thelogappreturnifrequestdeffolder
1条回答
网友
1楼 · 发布于 2024-06-07 15:37:48

这取决于mining函数的外观

file是一个^{} object,它有自己的各种方法

所以(没有看到)你的mining函数应该是这样的:

def mining(file_obj):

    lower_fname = file_obj.filename.lower()
    data = file_obj.read()

    # Do something

你提到的AttributeError听起来像是试图运行某个不返回字符串的lower方法

作为旁注:很难知道代码中的位置,因为您从未发布过完整的回溯,所以没有发生此异常


编辑

My mining function is actually at the top of the code I've inserted. I've also now included the traceback.

看起来您正在使用PM4Py,此文档对此声明:

from pm4py.objects.log.importer.xes import importer as xes_importer
log = xes_importer.apply('<path_to_xes_file.xes>') 

因此,您需要向挖掘函数实际传递一个文件路径

我建议将主代码更改为:

        if file and allowed_file(file.filename):
            sfilename = secure_filename(file.filename)
            output_path = os.path.join(app.config['UPLOAD_FOLDER'], sfilename)

            # Now save to this `output_path` and pass that same var to your mining function
            file.save(output_path)
            return mining(output_path)

相关问题 更多 >

    热门问题