Python烧瓶:查看其他图像在按钮上单击

发布于 2025-02-07 07:03:13 字数 1557 浏览 2 评论 0原文

我是学习Python和使用API​​的新手单击按钮时的图像。

当我单击按钮时,我在控制台上获得HTML 200代码,但图像不更改

这是我的主

    ''' 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()
'''

 ''' <!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>


 '''

I am new to learning python and working with APIs, I am trying to retrieve a random image from an API endpoint and render to a webpage, using Python flask, I am able to do that, I just need the image to update to a new image when I click a button.

When I click the button, I get a html 200 code on the console but the image don't change

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()
'''

my html code

 ''' <!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>


 '''

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

囍孤女 2025-02-14 07:03:13

您的next_image()对API进行调用,该代码大概返回图像列表,而您的代码始终选择列表中的第一个 - Response> response_api.json()[0] < /code> ie您的索引是0,这是列表中的第一个项目。

使用当前的代码,您获得不同的映像的唯一方法是,如果每个调用API返回不同的图像列表或图像的排序订购方式不同。

如果您的API调用返回相同的列表,则需要使用类似全局索引值之类的内容来确定要返回的图像IE的内容IE

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)

,这只是一个示例。还有其他方法(可能更有效)解决这个问题

Your code for next_image() makes a call to an API which presumably returns a list of images and your code always picks the first one in the list - response_api.json()[0] i.e. your index is 0 which is the first item in the list.

With your current code, the only way you will get different images is if each call to your API returns a different list of images or the images are ordered differently.

If your API call is returning the same list, then you will need to use something like a global index value to determine which image to return i.e. something like this

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)

Note: This is just an example. There are other ways (might be more efficient) to tackle this

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文