在Angu中共享从.py到.html的变量

2024-05-13 03:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我正在为我的公司开发一个带有angular和Spring5的Web应用程序作为基准项目应用程序。在这个webapp主页中,有一个“最新消息”组件,我想在其中显示项目官方网站的链接。你知道吗

我可以通过添加到项目文件夹中的python文件获得这些链接。我把这些链接存储在一个列表中。 现在,我不知道如何在我的html文件中得到这个列表来显示在我的网站上。你知道吗

如果你有什么建议,或者你认为有更好的方法,请告诉我。你知道吗

下面是我的Python代码:

> from flask import Flask, render_template from bs4 import BeautifulSoup
> import requests
> 
> source = requests.get('http://eurobench2020.eu/').text soup =
> BeautifulSoup(source, 'lxml') news =
> soup.find(id="recent-posts-3").select('a')
> 
> oui = [] i = 0 for link in news:
>     oui.append(link.get('href'))
>     print(i)
>     print(link.get('href'))
>     i = i+1 print(oui)
> 
> app = Flask(__name__) @app.route('/')
> 
> def index():
>     return render_template('index.html', oui = oui) app.run(debug=True)

我想在我的html中显示“oui”列表


Tags: 文件项目fromimportapp应用程序flask列表
1条回答
网友
1楼 · 发布于 2024-05-13 03:22:41

如果要将数据直接放入模板中,基本上您的想法是正确的:

您有一个app.py文件和一个带有index.html模板的templates目录。你知道吗

├── app.py
├── templates
    └── index.html

对于您的app.py

from flask import Flask, render_template
from bs4 import BeautifulSoup
import requests

source = requests.get('http://eurobench2020.eu/').text 
soup = BeautifulSoup(source, 'lxml') 
news = soup.find(id="recent-posts-3").select('a')

oui = []
for link in news:
    oui.append(link.get('href'))

app = Flask(__name__) 

@app.route('/')
def index():
    return render_template('index.html', data=dict(oui=oui))

if __name__ == '__main__':
    app.run(debug=True)

对于您的index.html

<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset="utf-8" />
    <title>Hello world!</title>
</head>
<body>
    <div>
        <p>Here's your data</p>
        <ul>
            {% for link in data.oui %}
            <li>
                <a href='{{link}}'>{{link}}</a>
            </li>
            {% endfor %}
        </ul>
    </div>
</body>
</html>

但是,正如其他人所提到的,如果您想将它与Angular或其他具有自己模板的web框架一起使用,并且不想使用Python&Jinja2进行模板化,那么您应该将数据公开为带有API的资源。在这种情况下,您需要pip安装flask restful并将app.py更改为如下内容:

from flask import Flask, jsonify, render_template
from flask_restful import Api, Resource
from bs4 import BeautifulSoup
import requests

source = requests.get('http://eurobench2020.eu/').text 
soup = BeautifulSoup(source, 'lxml') 
news = soup.find(id="recent-posts-3").select('a')

oui = []
for link in news:
    oui.append(link.get('href'))

app = Flask(__name__) 
api = Api(app)

class OuiData(Resource):
    def get(self):
        return jsonify(oui)

@app.route('/')
def index():
    return render_template('index.html', data=dict(oui=oui))

api.add_resource(OuiData, '/api/oui')

if __name__ == '__main__':
    app.run(debug=True)

然后,您可以在角度服务中获得数据,如下所示:

getOuiData(): Observable<HttpResponse<OuiData>> {
  return this.http.get<OuiData>('http://localhost:5000/api/oui');
}
getOuiData().subscribe(x => { console.log(x); } )

相关问题 更多 >