#python #flask
#python #flask
Вопрос:
странная проблема, с которой я сталкиваюсь в своем приложении. Надеюсь, кто-нибудь сможет помочь!
У меня есть upload.py файл, который позволяет пользователю отправлять документы для последующей обработки. Цель состоит в том, чтобы другие сценарии python запускались по мере прохождения определенного рабочего процесса, и сейчас я нахожусь в процессе прикрепления этих файлов и выяснения того, как все работает!
Однако, когда я импортирую функцию из другого локального файла (того же каталога), она генерирует ошибку субъекта в flask.
Если я открою оболочку python, я смогу импортировать все без каких-либо проблем, поэтому я предполагаю, что это проблема с Flask. У меня есть другие файлы python, использующие тот же импорт, которые не генерируют никаких ошибок при работе на python. Это говорит мне о том, что путь не является проблемой.
В любом случае, вот текущие файлы, о которых идет речь.
upload.py (the file being served by flask)
import os from flask import Flask, flash, request, redirect, url_for, send_from_directory, render_template from werkzeug.utils import secure_filename from update_sku import update_sku app = Flask(__name__) UPLOAD_FOLDER = 'uploads/' ALLOWED_EXTENSIONS = {'xlsx'} app.config['SECRET_KEY'] = 'secret' app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000 #16MB file size limit app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/uploads/lt;namegt;') def download_file(name): return send_from_directory(app.config["UPLOAD_FOLDER"], name) @app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'curfile' not in request.files or 'newfile' not in request.files: flash("Sorry, the upload didn't send all of the data!") return redirect(request.url) curfile = request.files["curfile"] newfile = request.files["newfile"] # If the user does not select a file, the browser submits an # empty file without a filename. if curfile.filename == "" or newfile.filename == "": flash('You need to upload 2 files!') return redirect(request.url) if (curfile and allowed_file(curfile.filename)) and (newfile and allowed_file(newfile.filename)): curfilename = secure_filename(curfile.filename) curfile.save(os.path.join(app.config['UPLOAD_FOLDER'], curfilename)) newfilename = secure_filename(newfile.filename) newfile.save(os.path.join(app.config['UPLOAD_FOLDER'], newfilename)) update_sku(curfilename, newfilename) #since files are good, let's send them to the next step - finding new skus #return redirect(url_for('download_file', name=curfilename)) return render_template("upload.html") if __name__ == '__main__': app.run(debug=True)
upload.html (template file being filled out by upload.py)
lt;!DOCTYPE htmlgt; lt;headgt; lt;titlegt;Titlelt;/titlegt; lt;/headgt; lt;htmlgt; lt;bodygt; lt;form method="post" enctype="multipart/form-data"gt; lt;h2gt;Upload Current (XLSX)lt;/h2gt; lt;input type="file" name="curfile"gt; lt;h2gt;Upload New (XLSX)lt;/h2gt; lt;input type="file" name="newfile"gt; lt;pgt;lt;/pgt; lt;input type="submit" value="Upload"gt; lt;/formgt; {% with messages = get_flashed_messages() %} {% if messages %} lt;ul class="flashes"gt; {% for message in messages %} lt;div class="message_flash"gt;{{ message }}lt;/divgt; {% endfor %} lt;/ulgt; {% endif %} {% endwith %} lt;/bodygt; lt;/htmlgt;
update_sku.py (other file that will perform operations on said documents)
import pandas as pd from column_fixer import column_fixer def update_sku(curfilename, newfilename): newcolname = "upc" curcolname = "upc" # define spreadsheet locations to compare # load current spreadsheet dfcur = pd.read_excel("uploads/" curfilename, dtype={'ID': str,'VPN': str,'Category': str,'Description': str,'Brand': str,'Color': str,'Size': str, 'UPC': str,'CaseQty': str,'cost': str,'msrp': str, 'IsNonInventory': str,'StyleNumber': str, 'StyleName': str, 'Year': str, 'Gender': str, 'Season': str, 'MPN': str, 'eCommerce': str, 'CaseQty': str, 'CaseUPC': str, 'CaseMSRP':str}) # load new spreadsheet dfnew = pd.read_excel("uploads/" newfilename, dtype={'ID': str,'PartNo': str,'MfgrPartNo': str,'Description': str,'Brand': str,'Color': str,'Size': str, 'upc': str,'CaseQty': str,'cost': str,'msrp': str}) # convert all column names to lowercase and strip away any spaces before and after dfnew.columns = dfnew.columns.str.strip().str.lower() dfcur.columns = dfcur.columns.str.strip().str.lower() # Fix column names column_fixer(dfcur, dfnew) # define a dataset from our current vendor information set_cur = set(dfcur[curcolname]) dfout = pd.DataFrame(columns=dfnew.columns) # compare new sheet values to current sheet values for i in range(len(dfnew.index)): # if item is not in the current sheet, add it to the bottom of the current sheet if not dfnew[newcolname][i] in set_cur: dfout.loc[len(dfout)] = dfnew.iloc[i] # if item is in the current sheet, update as specified below else: id = dfnew[newcolname][i] idx=dfcur[dfcur[curcolname]==id].index.values[0] dfcur.at[idx,"cost"] = dfnew.at[i,"cost"] dfcur.at[idx,"msrp"] = dfnew.at[i,"msrp"] # append the current sheet with the new information (both new unmatched items and updated info on matched items) dfcur=dfcur.append(dfout) # create a new xlsx file with the final information #dfout.to_excel("data/importfile.xlsx", index=False)