Я столкнулся со смешанным контентом ошибка в Chrome, когда я использую hx-post в форме, даже когда я указываю URL-адрес, содержащий https, или передаю _scheme функции url_for Flask.
Я пытаюсь создать простая веб-страница, которая позволяет пользователю чтобы загрузить входной шаблон, загрузите готовый шаблон, запустите сценарий на входе, а затем загрузите полученный файл.
Я использую Flask, сервер — Gunicorn, и он размещен в службах веб-приложений Azure.
Полный HTML-код веб-страницы:
My app
alt="Logo" width="384" height="192" />
Welcome to The App
1. Download the Input Template
Download
2. Select the Completed Input File
Upload
Конкретный раздел, вызывающий проблему:
2. Select the Completed Input File
Upload
Я также пробовал "{{ url_for('input_upload', _scheme='https', _external=True) }}" в поле hx-post и явный полный https-адрес страницы. Все выдают ошибку смешанного контента.
Я также пробовал без HTMX и получаю ошибку 400, которую я не понимаю:
2. Select the Completed Input File
Upload
Когда я проверяю страницу после попытки загрузки, я вижу полный URL-адрес https в поле hx-post при использовании url_for, но сообщение об ошибке смешанного контента показывает http:
Смешанное содержимое: страница «https:///» была загружена через HTTPS, но запросила небезопасную конечную точку XMLHttpRequest «http:///». input_upload'. Этот запрос заблокирован; контент должен передаваться через HTTPS.
Я не понимаю, что является причиной этого, поэтому буду благодарен за любую помощь.
П.С. вот app.py для веб-сайта:
import os
import logging
from werkzeug.utils import secure_filename
from flask import (
Flask,
redirect,
render_template,
request,
send_from_directory,
url_for,
)
# Sets logging level to DEBUG.
logging.basicConfig(filename="record.log", level=logging.DEBUG)
# Start and configure the Flask app.
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024 * 10 # 10 MB limit
app.config["UPLOAD_EXTENSIONS"] = [".xlsx", ".xlsm"]
app.config["UPLOAD_PATH"] = "uploads"
app.config["PREFERRED_URL_SCHEME"] = "https"
# Filesize validation. Automatically detected by Flask based on the configuration.
@app.errorhandler(413)
def too_large(e):
return "File is too large", 413
def allowed_file(filename):
return (
"." in filename
and filename.rsplit(".", 1)[1].lower() in app.config["UPLOAD_EXTENSIONS"]
)
# App Page Routing.
@app.route("/")
def index():
app.logger.debug("Request for index page received")
return render_template("index.html")
@app.route("/favicon.ico")
def favicon():
app.logger.debug("Request for favicon received")
return send_from_directory(
os.path.join(app.root_path, "static"),
"favicon.ico",
mimetype="image/vnd.microsoft.icon",
)
@app.route("/template_download", methods=["POST"])
def template_download():
app.logger.debug("Request for template download received")
return send_from_directory(
os.path.join(app.root_path, "static"),
".xlsm",
mimetype="application/vnd.ms-excel.sheet.macroEnabled.12",
)
@app.route("/input_upload", methods=["POST"])
def input_upload():
app.logger.debug("Request for input upload received")
if request.files:
input_file = request.files["input_file"]
if input_file.filename == "":
app.logger.debug("No file selected")
return redirect(request.url)
else:
if allowed_file(input_file.filename):
# Gets the username from the email address in header.
name = request.headers["X-MS-CLIENT-PRINCIPAL-NAME"].split("@")[0]
# Creates a folder for the user if it doesn't exist.
os.makedirs(
os.path.join(app.config["UPLOAD_PATH"], name), exist_ok=True
)
# Saves the file to the user's folder. Always overwrites prior input.
input_file.save(
os.path.join(
app.config["UPLOAD_PATH"], name, "input.xlsx"
) # Always save as .xlsx.
)
app.logger.debug(f"User {name} input saved")
return redirect(request.url)
else:
app.logger.debug("File type not allowed")
return redirect(request.url)
@app.route("/output_download", methods=["POST"])
def output_download():
app.logger.debug("Request for output download received")
pass
if __name__ == "__main__":
app.run(
# debug=True,
)
Подробнее здесь: https://stackoverflow.com/questions/791 ... tent-error