Я не уверен, как объяснить проблему, но я пытаюсь заставить колбу загрузить мою функцию main()
один раз, а затем оставаться "внутри" этой функции, когда пользователь нажимает кнопки.
У меня есть список имен изображений (например, 20190101.jpg
, 20190111.jpg
, 20190323.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)
(Я старался, чтобы route.py показывал только необходимый минимум, но если вы хотите увидеть какие-либо функции, пожалуйста, дайте мне знать).
Вот пример того, что я имею в виду - при загрузке он показывает все изображения. Затем я могу выбрать дату, и routs.py обновляет список _images
, чтобы включить только тех, кто на эту дату (ура!). Но , когда я нажимаю «следующее изображение», вместо перехода к следующему изображению в новом _images
, оно перезагружает изображения из image_urls
. Я так понимаю, потому что первая строка в main()
это _images = image_urls
. (Я изучаю Flask, поэтому я также понимаю, что мои функции немного глупы).
У меня вопрос, как мне сначала правильно их настроить, но потом после того, как main вызывается в первый раз, использовать _images
, как установлено в коде?