我有一个带有连接到我的数据库的搜索栏的页面,我正在创建一个按钮,用户可以通过上传 .xlsx 文件来更新数据库。
我编写了脚本和函数,但是当我单击提交按钮时出现此错误:
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'product'
当我从 PyCharm 运行 python 函数时,或者当我在 main.py 中删除 search_bar
函数然后运行该函数时,一切正常,但如果我有 search_bar
函数,它根本不起作用。
知道为什么它不起作用吗?
main.py
from flask import Flask, render_template, request, redirect, url_for, session, send_file, send_from_directory, flash
from werkzeug.utils import secure_filename
from flask_mysqldb import MySQL
import MySQLdb.cursors
import os
from compare import upload_excel_to_sql
app = Flask(__name__)
@app.route('/content)
def content():
# Check if user is loggedin
if 'loggedin' in session:
# User is loggedin show them the home page
return render_template('content.html', username=session['username'])
# User is not loggedin redirect to login page
return redirect(url_for('login'))
# SEARCH IN DATABASE
@app.route('/content', methods=['GET', 'POST'])
def search_bar():
if 'loggedin' in session:
if request.method == "POST":
cursor = connection.cursor(buffered=True)
product = request.form['product']
# search by project name or title or brand
cursor.execute("USE content_repository")
cursor.execute("""SELECT upload_date,
product_code,
Project_name,
Country,
Brand,
Category,
Title,
Bullet_Points,
Description,
version
FROM product WHERE Project_name LIKE %s OR Title LIKE %s OR Brand LIKE %s""",
(product, product, product))
connection.commit()
data = cursor.fetchall()
# all in the search box will return all the tuples
if len(data) == 0 and product == 'all':
cursor.execute("""SELECT upload_date,
product_code,
Project_name,
Country,
Brand,
Category,
Title,
Bullet_Points,
Description,
version
FROM product""")
connection.commit()
data = cursor.fetchall()
return render_template('content.html', data=data)
return render_template('content.html')
return redirect((url_for('content')))
# UPLOADING AND PROCESSING FILE
UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'
DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/'
# Allow user to upload only xlsx files'
ALLOWED_EXTENSIONS = {'xlsx'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER
# Set up the maximum size of the file, in this case it is 10 mb
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
# Functions that check if an extension is valid
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/content_repository', 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(UPLOAD_FOLDER, filename))
# we call process_file function and pass the uploaded file path as an argument
filename = upload_excel_to_sql(os.path.join(UPLOAD_FOLDER, filename), UPLOAD_FOLDER)
return redirect(url_for('content', filename=filename))
return render_template('content.html', username=session['username'])
if __name__ == '__main__':
app.run(debug=True)
比较.py
from sqlalchemy import create_engine
import pymysql
import pandas as pd
from aifc import Error
import os
def upload_excel_to_sql(file_path, upload_folder):
"""
Load data from excel to sql database
:param path: path to excel with dataset (str)
:return: True if everything is correct
"""
output_path = os.path.join(upload_folder, file_path)
df_scrapped_data = pd.read_excel(output_path)
for column in df_scrapped_data.columns:
if column.startswith("Unnamed"):
df_scrapped_data.drop([column], inplace=True, axis=1)
engine = create_engine("mysql+pymysql://{user}:{psw}@localhost/{db}".format(user="root", psw="root", db="content"))
df_scrapped_data.to_sql('product', con=engine, if_exists='append', index=False)
return engine
内容.html 带有搜索栏以及上传和提交元素的表单元素。
<form method="POST" action="">
<input type="search" placeholder="Search" aria-label="Search" name="product">
<button type="submit">Search</button>
</form>
<form method="POST" action="" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit" value="Submit"></p>
</form>