【问题标题】:How to move data between HTML and Flask in real time?如何在 HTML 和 Flask 之间实时移动数据?
【发布时间】:2021-03-05 02:58:46
【问题描述】:

我正在构建一个基本的 python 应用程序,它可以提取新闻数据,现在只是文章名称和图片,并以刷卡的方式显示它们,类似于 Tinder 的格式。我的应用程序只包含一个用于获取新闻数据的 python 脚本、一个烧瓶应用程序和一个 HTML 文件。但是,我不确定如何从我的 python 应用程序文件中实时提取文章图像并将它们显示在 HTML 页面上。 这是HTML文件中处理卡片内容(图片)的js函数:

push() {

                let card = document.createElement('div')

                card.classList.add('card')

                card.style.backgroundImage =
                    //pull from python app

                this.board.insertBefore(card, this.board.firstChild)

       }

我使用的新闻 API 以如下所示的 json 格式返回数据(注意 urlToImage 部分):

{u'description': u'CNN political analyst Carl Bernstein discusses with Don Lemon about how members of the Republican party are enabling President Donald Trump\'s "authoritarian" behavior.', u'title': u"Bernstein says Republicans are enabling Trump as 'mad king'", u'url': u'https://www.cnn.com/videos/politics/2020/11/20/carl-bernstein-trump-republican-party-mad-king-sot-vpx.cnn', u'author': None, u'publishedAt': u'2020-11-20T07:44:46Z', u'content': None, u'source': {u'id': u'cnn', u'name': u'CNN'}, u'urlToImage': u'https://cdn.cnn.com/cnnnext/dam/assets/201120000727-bernstein-ctn-mad-king-sot-vpx-super-tease.jpg'}

这是我的简单烧瓶应用程序:

from flask import Flask, render_template
from news import searchQuery
app = Flask(__name__)
@app.route('/')
def hello_world():
    return render_template('index.html')

任何想法都将不胜感激。

【问题讨论】:

    标签: python html flask frontend


    【解决方案1】:

    您可以在前端 (HTML) 上使用 ajax,并在后端 (flask) 上创建一个新的端点 (路由)。

    在 HTML 上

    function push(news_id){
         $.ajax({
            // news_id will be used as the id of the image.
            url : '/getImage/' + news_id,
            type : 'GET',
            success : function(response){
              // change the div background here
            }
            error : function(){
              // Error
            }
         });
    }
    

    在烧瓶上

    @app.route('getImage/<news_id>', methods = ['GET'])
    def getImage(news_id):
       # any logic to retrieve the image path/url from database
       # example
       news = News.query.get(news_id)
       return jsonify(news.news_image_url)
    

    虽然您的应用(您提供的代码)有点简单,但这只是基本概念。 还有很多东西有待探索。

    【讨论】:

    • 感谢您的回复,我会尝试一下。我肯定希望扩展它,可能会添加机器学习推荐器和其他附加功能。
    猜你喜欢
    • 2018-09-10
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多