Python Flask:点击按钮查看不同的图像



我是学习python和使用API的新手,我试图从API端点检索随机图像并渲染到网页,使用python flask,我能够做到这一点,我只需要图像更新到一个新的图像当我点击一个按钮。

当我点击按钮时,我在控制台上得到一个html 200代码但是图像没有改变

This is my main.py

''' from flask import Flask, render_template
import requests
i
app = Flask(__name__)
@app.route('/', methods=['GET'])
def next_image():
response_api = requests.get('https://api.thecatapi.com/v1/images/search?api_'
'key=API-KEY')
data = response_api.json()[0]['url']
return render_template("index.html", cat_image=data)

@app.route("/getimage")
def get_img():
cat_img = next_image()
return cat_img

if __name__ == '__main__':
app.run()
'''
我的HTML代码
''' <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Cats Images</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script>
</head>
<body>
<h1>Random Cat Images</h1>
<input type = "button" id = "mybutton" value = "View Next "/>
<div>
<img src="{{cat_image}}" id="myimg" alt="Cat Image">
</div>
</body>
<script>
$(document).ready(function() {
$('#mybutton').click(function(){
$.ajax({
url: "{{ url_for ('get_img') }}",
type: "GET",
success: function(response) {
$("#myimg").attr('src', response.url);
},
});
});
});
</script>
</html>

'''

您的next_image()代码调用API,该API可能返回图像列表,您的代码总是选择列表中的第一个-response_api.json()[0],即您的索引是0,这是列表中的第一个项目。

在你当前的代码中,你将获得不同图像的唯一方法是每次调用你的API返回不同的图像列表或图像顺序不同。

如果你的API调用返回相同的列表,那么你将需要使用类似全局索引值的东西来确定返回哪个图像,即像这样的东西

curr_index = 0
app = Flask(__name__)
def next_image():
global curr_index
response_api = requests.get('https://api.thecatapi.com/v1/images/search?api_'
'key=API-KEY')

data = response_api.json()

# If curr_index is outside of the list index, then raise an error
if curr_index == len(data):
return "Sorry, no more images"

# Use curr_index to pick which image in the list to return
data = data[curr_index]['url']
# Increment curr_index so that next time you call, you pick a different image in the list
curr_index = curr_index + 1
return render_template("index.html", cat_image=data)

注意:这只是一个例子。还有其他方法(可能更有效)来处理这个

最新更新