python - 如何通过 Jinja2 访问 JSON 中的特定元素
问题描述
我目前正在使用 python 通过 Microsoft Graph API 从 Azure Active Directory 检索数据:
结果
现在我需要做的是,使用这些数据以更好的方式(更具可读性)显示它,例如以简洁的方式显示每个活动目录对象的每个属性,如下所示:
您将在我的代码中看到为我提供 json 数据的函数是:
graph_data = requests.get(endpoint, headers=http_headers, stream=False).json()
代码
配置文件
RESOURCE = "https://graph.microsoft.com" # Add the resource you want the access token for
TENANT = "joanperez5hotmail.onmicrosoft.com";
AUTHORITY_HOST_URL = "https://login.microsoftonline.com"
CLIENT_ID = "HERE I WROTE MY CLIENT ID";
CLIENT_SECRET = "HERE I WROTE MY CLIENT SECRET";
# These settings are for the Microsoft Graph API Call
API_VERSION = 'v1.0'
应用程序.py
import adal
import flask #web framework
import uuid
import requests
import config
app = flask.Flask(__name__)
app.debug = True
app.secret_key = 'development'
PORT = 5000 # A flask app by default runs on PORT 5000
AUTHORITY_URL = config.AUTHORITY_HOST_URL + '/' + config.TENANT
REDIRECT_URI = 'http://localhost:{}/getAToken'.format(PORT)
TEMPLATE_AUTHZ_URL = ('https://login.microsoftonline.com/{}/oauth2/authorize?' +
'response_type=code&client_id={}&redirect_uri={}&' +
'state={}&resource={}')
@app.route("/")
def main():
login_url = 'http://localhost:{}/login'.format(PORT)
resp = flask.Response(status=307)
resp.headers['location'] = login_url
return resp
@app.route("/login")
def login():
auth_state = str(uuid.uuid4())
flask.session['state'] = auth_state
authorization_url = TEMPLATE_AUTHZ_URL.format(
config.TENANT,
config.CLIENT_ID,
REDIRECT_URI,
auth_state,
config.RESOURCE)
resp = flask.Response(status=307)
resp.headers['location'] = authorization_url
return resp
@app.route("/getAToken")
def main_logic():
code = flask.request.args['code']
state = flask.request.args['state']
if state != flask.session['state']:
raise ValueError("State does not match")
auth_context = adal.AuthenticationContext(AUTHORITY_URL)
token_response = auth_context.acquire_token_with_authorization_code(code, REDIRECT_URI, config.RESOURCE,
config.CLIENT_ID, config.CLIENT_SECRET)
# It is recommended to save this to a database when using a production app.
flask.session['access_token'] = token_response['accessToken']
return flask.redirect('/graphcall')
@app.route('/graphcall')
def graphcall():
if 'access_token' not in flask.session:
return flask.redirect(flask.url_for('login'))
endpoint = config.RESOURCE + '/' + config.API_VERSION + '/groups/' #https://graph.microsoft.com/v1.0/groups/
http_headers = {'Authorization': flask.session.get('access_token'),
'User-Agent': 'adal-python-sample',
'Accept': 'application/json',
'Content-Type': 'application/json',
'client-request-id': str(uuid.uuid4())}
graph_data = requests.get(endpoint, headers=http_headers, stream=False).json()
return flask.render_template('homePage.html', graph_data=graph_data)
if __name__ == "__main__":
app.run()
编辑
从评论中添加问题:如何访问 Jinja 中的每个特定元素?
解决方案
要回答您的评论问题,“我将如何访问每个特定元素”,您可以这样做作为示例。
my_data = [{'id': 1, 'name': 'Frank'}, {'id': 2, 'name': 'Rakesh'}]
然后这将在您render_template
的烧瓶中返回(我可以通过您的代码看到,您已经在做)
在您的 Jinja 模板中,您将执行以下操作:
<table>
{% for md in my_data %}
<tr>
<td>{{ md.id }}</td><td>{{ md.name }}</td>
</tr>
{% endfor %}
</table>
这应该让你朝着正确的方向前进。除此之外,您还必须对Jinja2及其工作原理进行一些研究。
推荐阅读
- laravel - 如何在 laravel 视图中使用 foreach 显示数据
- html - 使用 Bootstrap 4 嵌套行中的图像大小
- android - 蓝牙服务器关闭
- r - R:使用 as.data.frame() 将列表转换为数据框时遇到问题
- r - 使用命令行在 r 中执行 gmail_auth() 每次都要求进行身份验证
- python - 属性错误:“dict”对象没有属性“endswith”
- c# - 使用 C# 将文件上传到另一台服务器/计算机
- angular - 错误类型错误:表单提交后无法读取未定义的属性“文本”
- amazon-web-services - 如何使 aws 管理员无法访问非管理员用户设置的机密?
- bash - 如何在不删除文件名的扩展点的情况下重命名