【发布时间】:2021-09-09 05:44:25
【问题描述】:
我有一个使用 API 从 Google 表格创建的日历。我想创建另一个页面(路由)来显示日历的 html 代码(不是呈现的模板)。这是我的代码:
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google.oauth2 import service_account
from flask import Flask
from flask import Flask, flash, jsonify, redirect, render_template, request, url_for,
session
import requests
app = Flask(__name__)
SERVICE_ACCOUNT_FILE = 'keys.json'
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = None
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = 'removed for security'
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range="new!A2:D9").execute()
header = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range="new!A1:D1").execute()
request = sheet.values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range="new!A10", valueInputOption="USER_ENTERED", body=
{"values":newvalues}).execute()
@app.route('/', methods=["GET", "POST"])
def index():
values = result.get('values', [])
headers = header.get('values', [])
return render_template("index.html", values=values, headers=headers)
@app.route('/text', methods=["GET", "POST"])
def text():
t = requests.get('http://127.0.0.1:5000')
return (t.content)
if __name__ == '__main__':
app.run()
“/text”路由显示的页面与“/”页面完全相同。我希望它只返回 html 代码而不是呈现的模板。
【问题讨论】:
-
我查看了您引用的文档,但我不太确定如何使用它。这是一个单独的函数还是 def text() 函数中的一行?这是否意味着删除 .html 扩展名并将文件名 index.html 作为索引读取?我糊涂了。感谢您的澄清。
-
你想显示的,和你写在html文件中的代码一样,用jinja语法或用jinja没有jinja语法的代码。
标签: python html api flask google-sheets