烧瓶-防止重新加载功能?

时间:2019-04-15 19:07:10

标签: python-3.x flask

我不确定如何解释该问题,但是我试图让flask一次加载我的main()函数,然后在用户单击按钮时将该函数“保留”在该函数内。

我有一张图像名称(例如20190101.jpg20190111.jpg20190323.jpg)的列表,它们以YYYYMMDD.jpg格式无格式显示。

当我第一次加载网站时,我希望它显示所有图像。但是,我还添加了一个日历选择器,允许用户选择一个日期,在选择日期时,我的routes.py仅查找该范围内的图像,然后将其返回以供查看。

我可以做到这一点,没问题。问题是当用户单击“下一张照片” /“上一张照片” /“随机”按钮,或从我的表格列表中选择图像时。当他们这样做时,将加载默认的照片列表,而不是已过滤的照片列表。

据我所知,这是因为在按钮单击时调用了main(),并且在顶部有_images = image_urls,因此它可以有效地重置列表。

如何编写我的函数以一次加载_images = image_urls,然后保留该列表并仅根据用户的指示进行更新?

index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{{ title }}</title>
    <link rel="stylesheet" type="text/css" href= "{{ url_for('static',filename='styles/index.css') }}">
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
{% extends "layout.html" %}
{% block content %}
    <h3>Index: {{ photo_index }}</h3>
    <h3>Filename: {{ image }}</h3>
    {% include "/HTML Snippets/calendar.html" %}
    <div class='image-container' id='image'>
        {% include "/HTML Snippets/favorite_button.html" %}
        <img src="{{ url_for('images.static', filename=image) }} " id="the-photo">
    </div>
    <div class='button-container' id='buttons'>
        <form action="" method="post">
            <input type="hidden" name="prev-next-buttons">
            <input type="submit" value="Prev photo" name='prev-photo'>
            <input type="submit" value="Next photo" name='next-photo'>
            <input type="submit" value="Random photo" name='random-photo'>
            <br/>
            <button type='button' id='rotate-button' onclick="rotateMeCounterClockwise('#the-photo')">Rotate Photo CounterClockwise</button>
            <button type='button' id='rotate-button' onclick="rotateMeClockwise('#the-photo')">Rotate Photo Clockwise</button>
        </form>
        <h3>Choose image from list:</h3>
        <form method="post">
            <input type="hidden" name="photo-select">
            <select name="select-image" onfocus='this.size=5;' onblur='this.size=1' onchange="this.size=1;  this.blur(); this.form.submit()">
                {% for eimage in image_list %}
                    <option 
                    {% if eimage == image %} 
                        selected 
                    {% endif %}
                    value = {{ eimage }}
                    >
                        {{eimage}}
                    </option>
                {% endfor %}
            </select>
        </form>
    </div>
    <div class='table-container'>
        <table id='image-list' name='select-from-table'>
            {% for image_row in image_list | batch(3) %}
            <tr>
                {% for image in image_row %}
                <td><a href="{{ url_for('main', chosen_image=image) }}"> {{ image }} </a></td>
                {% endfor %}
            </tr>
            {% endfor %}
        </table>
    </div>
{% endblock %}
</body>
</html>

calendar.html

{% block topscripts %}
    <link rel="stylesheet" type="text/css" href= "{{ url_for('static',filename='styles/calendar.css') }}">
    <script>
        $(function() {
            $("#datepicker").datepicker();
        });
    </script>    
{% endblock %}

{% block content %}
<form method="post">
<p>Date: <input type="text" id="datepicker"  name='go-to-date'></p>
    <input type="hidden" name="calendar-form">
    <input type="submit">
</form>
{% endblock %}

{% block endscripts %}

{% endblock %}

routes.py

[imports and misc]
images = os.listdir(IMAGE_FOLDER)


def create_urls(files):
    image_urls = []
    for file in files:
        if file.endswith(".jpg"):
            image_urls.append(file)
    return image_urls


image_urls = create_urls(images)
image_urls.append('favicon.ico')
# Subtract 2 below, so you don't include the
# favicon.ico
num_images = len(image_urls) - 2


class Photo_Index():
    def __init__(self, index=0):
        self.index = index

    def increase_number(self):
        if self.index == num_images:
            self.index = 0
        else:
            self.index = self.index + 1
        return self.index

    def decrease_number(self):
        if self.index == 0:
            self.index = num_images
        else:
            self.index = self.index - 1
        return self.index

    def random_number(self):
        self.index = random.randint(0, num_images)
        return self.index

    def set_number(self, number):
        self.index = number
        return self.index

...

def day_month_year(filename):
    """
    Takes a string `20190212` and pulls out Year, Month, Date
    """
    year = filename[:4]
    month = filename[4:6]
    day = filename[6:8]
    return str(year + "-" + month + "-" + day)


def get_files_on(specific_date):
    _files = []
    print("\nLooking for files on:", specific_date, "\n")
    for file in image_urls:
        # print(file, day_month_year(file))
        if day_month_year(file) == specific_date:
            _files.append(file)
    return _files


photo_index_obj = Photo_Index()
fav_photo_index = Photo_Index()


def update_index(rqst, indx_obj):
    if 'prev-photo' in rqst.form:
        indx_obj.decrease_number()
    elif 'next-photo' in rqst.form:
        indx_obj.increase_number()
    elif 'random-photo' in rqst.form:
        indx_obj.random_number()
    return indx_obj


@app.route("/", methods=["GET", "POST"])
@app.route("/<chosen_image>", methods=["GET", "POST"])
def main(chosen_image=None):
    _images = image_urls
    if request.method == "POST":
        if 'go-to-date' in request.form:
            spec_date = request.form['go-to-date']
            spec_date = datetime.datetime.strptime(spec_date, "%m/%d/%Y").strftime("%Y-%m-%d") # noqa
            _images = get_files_on(spec_date)
        elif 'prev-next-buttons' in request.form:
            update_index(request, photo_index_obj)
        elif 'photo-select' in request.form:
            img = request.form.get("select-image")
            photo_index_obj.set_number(_images.index(str(img)))
        elif 'favorite-photo' in request.form:
            add_to_favorites(_images[photo_index_obj.index])
        elif 'un-favorite-photo' in request.form:
            remove_from_favorites(_images[photo_index_obj.index])
    if request.method == "GET":
        if chosen_image is not None:
            photo_index_obj.set_number(_images.index(chosen_image))
    favorite = is_favorite(_images[photo_index_obj.index])
    return render_template('index.html',
                           title="Local Image Viewer",
                           photo_index=photo_index_obj.index,
                           image=_images[photo_index_obj.index],
                           image_list=_images,
                           favorite=favorite)

(我试图保留routes.py以仅显示所需的最小值,但是如果您想查看特定功能,请告诉我。)

Here's an example of what I mean-加载时显示所有图像。然后,我可以选择一个日期,routes.py将更新_images列表,使其仅包含该日期的那些(是的!)。 但是,当我单击“下一张图片”时,它会从_images重新加载图像,而不是转到 new image_urls中的下一张图片。我了解这是因为main()中的第一行是_images = image_urls。 (我正在学习Flask,所以我也了解我的功能有点笨拙。)

我的问题是,首先应该如何正确设置这些设置,但是第一次调用 之后,请使用代码中设置的_images

1 个答案:

答案 0 :(得分:1)

您要的内容与URL过滤器和分页非常相似。广泛的实践(您可以在大多数基于php的博客/ e-shops / etc上看到它)是单击日期,然后应用日期过滤器,因此前端会发出诸如GET localhost?date=1.1.2019和您的Flask应用应提取该日期并根据该过滤器返回图像。默认情况下,应该返回该列表的第一张图像,并且当您单击下一个照片按钮时,您会发出类似GET localhost?date=1.1.2019&offset=2的请求。偏移表示您需要从所有过滤结果中获取第二张图像(或页面)。