当我在烧瓶中传递参数时遇到问题

I have a problem when i pass a parameter in flask

提问人: 提问时间:7/15/2023 更新时间:7/16/2023 访问量:35

问:

我的代码即将在 Web 中制作一个徽标生成器,以便用户可以选择名称、行业、字体和颜色,并且 Web 应用程序使用 python 生成徽标。 因此,当我选择行业并显示在网址“http://localhost:5000/logo_fontslogo_name=r%27t&logo_colors=blue&logo_colors=purple&selected_industry=restaurant”中时,我会收到一条带有随机行业的错误消息:我在这里有错误和问题。错误是权限错误(静态/符号中有一个带有行业名称的文件夹,我现在没有我得到的权限错误),问题是随机行业(当用户选择一个行业时,程序在生成函数转到符号文件夹并在文件夹上搜索行业名称,然后它从行业文件夹中随机选择图标,但在这里它选择了随机文件夹中的一个随机文件夹symbols 文件夹)。 这是我的代码:PermissionError: [Errno 13] Permission denied: 'static/symbols\\interior design'

我的 app.py 文件:

@app.route('/logo_maker/logotype', methods=['POST', 'GET'])

def logotype():

    logo_name = session.get('logo_name')
    selected_colors = session.get('selected_colors')
    industries = [        
    {'name': 'مطعم', 'translate': 'restaurant', 'icon': 'fas fa-utensils'},
    {'name': 'التمويل', 'translate': 'finance', 'icon': 'fas fa-user-tie'},
    {'name': 'الصيدلة', 'translate': 'pharmacy', 'icon': 'fas fa-flask'},
    {'name': 'اللوجستيات', 'translate': 'logistics', 'icon': 'fas fa-truck-moving'},
    {'name': 'العقارات', 'translate': 'real estate', 'icon': 'fas fa-building'},
    {'name': 'تصميم الديكور', 'translate': 'interior design', 'icon': 'fas fa-paint-roller'},
    {'name': 'التعليم', 'translate': 'education', 'icon': 'fas fa-graduation-cap'},
    {'name': 'التكنولوجيا', 'translate': 'information technology', 'icon': 'fas fa-laptop'},
    {'name': 'الرعاية الصحية', 'translate': 'healthcare', 'icon': 'fas fa-hospital'},
    {'name': 'التجزئة', 'translate': 'retail', 'icon': 'fas fa-shopping-bag'},
    {'name': 'السيارات', 'translate': 'automotive', 'icon': 'fas fa-car'},
    {'name': 'الضيافة', 'translate': 'hospitality', 'icon': 'fas fa-coffee'},
    {'name': 'الأزياء', 'translate': 'fashion', 'icon': 'fas fa-tshirt'},
    {'name': 'وسائط الإعلام', 'translate': 'media', 'icon': 'fas fa-film'},
    {'name': 'الرياضة', 'translate': 'sports', 'icon': 'fas fa-football-ball'},
    {'name': 'البناء', 'translate': 'construction', 'icon': 'fas fa-hard-hat'},
    {'name': 'التجارة الإلكترونية', 'translate': 'e-commerce', 'icon': 'fas fa-shopping-cart'},
    {'name': 'الطيران', 'translate': 'aviation', 'icon': 'fas fa-plane'},
    {'name': 'الطاقة', 'translate': 'energy', 'icon': 'fas fa-bolt'},
    {'name': 'التسويق', 'translate': 'marketing', 'icon': 'fas fa-bullhorn'},
    {'name': 'أخرى', 'translate': 'other', 'icon': 'fas fa-question'}
            ]
    selected_industry = request.args.get('selected_industry')
    session['selected_industry'] = selected_industry
    return render_template('logotype.html', logo_name=logo_name, selected_colors=selected_colors, industries=industries, industry=selected_industry)
@app.route('/logo_fonts', methods=['POST', 'GET'])
def logo_fonts():
    logoname = session.get('logo_name')
    selected_colors = session.get('selected_colors')
    selected_industry = session.get('selected_industry')
    if request.method == 'POST':
        selected_fonts = request.form.get('selected_fonts')
        if selected_fonts:
            selected_fonts = json.loads(selected_fonts)
        else:
            selected_fonts = []

        print(selected_fonts)  # Print selected fonts to check the values
        session['selected_fonts'] = selected_fonts
        return redirect(url_for("loading"))

    return render_template('logo_fonts.html', fonts=fonts)

@app.route('/loading')
def loading():

    return render_template('load.html')


@app.route('/generate', methods=['POST', 'GET'])
def generate():
    selected_fonts = session.get('selected_fonts') or []
    print(selected_fonts)  # Print selected fonts to check the values
    logo_name = session.get('logo_name')
    selected_colors = session.get('selected_colors') or []
    selected_industry = session.get('selected_industry') or ""
    image_list = []
    folder_name = generate_unique_folder_name()

    # Create the directory for storing the images
    folder_path = f"static/generated_images/{folder_name}"
    os.makedirs(folder_path, exist_ok=True)

    def generate_logo_with_icon(color1: str, color2: str, selected_industry: str):
        # Set the size of the image
        width = 900
        height = 500

        # Create an image object
        img = Image.new("RGB", (width, height), (255, 255, 255))

        # Get drawing context
        draw = ImageDraw.Draw(img)

        # Set font size
        font_size = 70

        # Get a random font folder from selected_fonts
        font_folder = random.choice(selected_fonts)

        # Search for the font folder in the "static/Fonts" directory
        font_folder_path = os.path.join("static/Fonts", font_folder)

        # Check if the font folder exists
        if os.path.isdir(font_folder_path):
            # Get a random font file from the font folder
            font_files = os.listdir(font_folder_path)
            font_file = random.choice(font_files)
            font_file_path = os.path.join(font_folder_path, font_file)

            # Load the selected font file
            font = ImageFont.truetype(font_file_path, font_size)

            # Get text size
            text_width, text_height = draw.textsize(logo_name or '', font=font)

            # Calculate x, y position of text in center of image
            x = (width - text_width) / 2
            y = (height - text_height) / 2

            # Draw rectangle around the text
            rect_width = text_width + 20
            rect_height = text_height + 10
            rect_x1 = x - 10
            rect_y1 = y - 5
            rect_x2 = x + rect_width + 20
            rect_y2 = y + rect_height + 10

            draw.rectangle((rect_x1, rect_y1, rect_x2, rect_y2), fill=color2)

            # Get random industry icon
            industry_icons_path = os.path.join("static/symbols", selected_industry)
            industry_icons = os.listdir(industry_icons_path)
            icon_file = random.choice(industry_icons)
            icon_path = os.path.join(industry_icons_path, icon_file)

            # Resize and place the icon on the image
            icon_size = (100, 100)
            icon = Image.open(icon_path).resize(icon_size)
            icon_x = x - icon_size[0] - 20
            icon_y = (height - icon_size[1]) / 2
            img.paste(icon, (int(icon_x), int(icon_y)), mask=icon)

            # Draw text on image
            draw.text((x, y), logo_name or '', fill=color1, font=font)
        else:
            print(f"Font folder '{font_folder_path}' does not exist")
            # Return a default image
            default_img = Image.new("RGB", (width, height), (255, 255, 255))
            draw = ImageDraw.Draw(default_img)
            draw.text((10, 10), "Font folder not found", fill="black")
            img = default_img

        return img
    email = request.cookies.get('email')
    user = User.query.filter_by(email=email).first()

    if user is not None:
        if selected_colors:
            color1 = random.choice(selected_colors)
            print(selected_colors)
            print(color1)
            color2 = random.choice(selected_colors)
            if color1 == color2:
                color2 = "white"
        else:
            return redirect(url_for('logo_maker'))

        for _ in range(10):
            filename = f"{folder_path}/{os.urandom(5).hex()}.png"
            logo_image = generate_logo_with_icon(color1=color1, color2=color2, selected_industry=selected_industry)
            if logo_image is not None:
                logo_image.save(filename)
                image_list.append(filename)

        return render_template('show.html', image_list=image_list, name=user.name, folder_name=folder_name)
    else:
        return redirect(url_for('login'))

def generate_unique_folder_name():
    while True:
        folder_name = ''.join(random.choices(string.ascii_lowercase, k=5))
        folder_path = f"static/generated_images/{folder_name}"
        if not os.path.exists(folder_path):
            return folder_name

我的标识.html文件:

 <body>
    <div class="header">
        <a href="{{url_for('home')}}">
            <img src="{{ url_for('static', filename='img/logotrans1.png') }}" alt="Logo">
        </a>
        <div class="progress-bar-container">
            <div class="progress-bar-fill"></div>
        </div>
    </div>

    <div class="container">
        {% with messages = get_flashed_messages(with_categories=true) %}
        {% for category, message in messages %}
        {% if category == 'error' %}
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
            {{ message }}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        {% endif %}
        {% endfor %}
        {% endwith %}

        <div class="container">
            <h2 style="color: rgb(83, 64, 255);">الخطوة الثالثة</h2>
            <h1>اختر مجالا</h1>
            <small>سوف نقوم بتوليد شعارات اعتمادًا على اختيارك للمجال</small>
            <div class="industry-cards">
                <div class="industry-cards">
                    {% for industry in industries %}
                    <a class="a1" href="{{ url_for('logo_fonts', logo_name=logo_name, logo_colors=selected_colors, selected_industry=industry.translate) }}">
                        <div class="industry-card" data-industry="{{ industry.translate }}">
                            <div class="industry-icon"><i class="{{ industry.icon }}"></i></div>
                            <div class="industry-name">{{ industry.name }}</div>
                        </div>
                    </a>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/js/all.min.js"></script>
    <script>
        function toggleSelection(card) {
            card.classList.toggle('selected');
            updateContinueButtonVisibility(); // Call the function to update the visibility of the Continue button
        }

        function updateContinueButtonVisibility() {
            const selectedCards = document.querySelectorAll('.industry-card.selected');
            const continueButton = document.querySelector('.continue-button');

            // If at least one card is selected, show the Continue button; otherwise, hide it
            if (selectedCards.length > 0) {
                continueButton.style.display = 'block';
            } else {
                continueButton.style.display = 'none';
            }
        }

        function redirectToSelectedIndustryPage(selectedIndustry) {
            window.location.href = "{{ url_for('logo_fonts', selected_industry='') }}" + selectedIndustry;
        }
    </script>
</body>

这是一个客户项目,请帮忙。

python-3.x flask jinja2 参数传递

评论


答:

0赞 Thrilok Kumar Pallaki 7/16/2023 #1

在共享的 URL 中,路径之后和查询参数之前缺少一个。http://localhost:5000/logo_fontslogo_name=r%27t&logo_colors=blue&logo_colors=purple&selected_industry=restaurant?

它应该是http://localhost:5000/logo_fonts?logo_name=r%27t&logo_colors=blue&logo_colors=purple&selected_industry=restaurant