我创建了一个获取输入搜索词的网络应用程序,它搜索一个 csv 广告创建一个新的。它将新的显示为表格,第一列是一个按钮,应该打开一个图像(每一行都是唯一的)。随着每张图片的按下,它应该将图片的名称传递给 flask,然后我将它存储在那里,并对 google drive 进行 api 调用并检索图片。名称存储正确并且 api 调用效果很好,但它既不返回模板也不返回任何文本。模板存储在模板文件夹中。
这里是搜索结果的python代码:
@app.route('/search', methods=\['GET'\])
def search():
search_query = request.args.get('search_query')
def search_word(word):
i = 0
l_rows = []
for row in df.text:
# Rows referring to blank pages are null
if not isinstance(row, float) and word in row:
if word in row:
d_rows = {"id": '<form action="/search" method="post" target="_blank"><input type="button" value="' + df.loc[i, "id"] + ' "id="seePage"></form>',
"period": df.loc[i, "period"], "committee": df.loc[i, "comitee"]}
l_rows.append(d_rows)
i += 1
new_df = pd.DataFrame.from_dict(l_rows)
html_table = new_df.to_html(classes='my-table', border=1, escape=False)
return html_table
search_word(search_query)
return render_template("search_results.html", table=search_word(search_query))
这里是搜索结果的htm代码:
<!DOCTYPE html>
<html>
<title>Search Results</title>
<head>
</head>
<body>
<div>
{{table|safe}}
</div>
<script>
var myButton = document.getElementById("seePage");
myButton.addEventListener("click", function() {
var url = "/image";
var buttonText = this.value;
var data = new URLSearchParams();
data.append("buttonText", buttonText);
fetch(url, {
method: "POST",
body: data
})
.then(function(response) {
return response.text();
})
.then(function(text) {
console.log(text);
});
});
</script>
</body>
</html>
这里是图片页面的python代码:
@app.route('/image', methods=['GET', 'POST'])
def image_display():
cell_value = request.form.get('buttonText')
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
# Set the path to the client secret JSON file
CLIENT_SECRET_FILE = 'cred_2.json'
# Create the flow object and start the authorization flow
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES, redirect_uri='http://127.0.0.1:5000')
credentials = flow.run_local_server(port=0)
# Google Drive API setup
if cell_value:
def get_image(image):
folder_id = 'the foder id'
access_token = credentials.token
print(f'access token f{access_token}')
headers = {'Authorization': 'Bearer ' + access_token}
url = 'https://www.googleapis.com/drive/v3/files?q=name="' + cell_value.strip() + '.jpg"+and+parents="' + folder_id + '"'
print("URL: " + url)
# Send request to Google Drive API
response = requests.get(url, headers=headers)
data = json.loads(response.content)
print(f"data: {data}")
# Get the download link of the first image with the matching name
try:
file_id = data['files'][0]['id']
print(f'file id: {file_id}')
image_url = 'https://drive.google.com/uc?id=' + file_id
print(f'image_url: {image_url}')
return image_url
except IndexError:
print('except')
return 'except'
image_url = get_image(cell_value)
if image_url != 'except':
return render_template('image.html', cell_value=cell_value, image_url=image_url)
else:
return render_template('image.html', cell_value=cell_value, error_message='No matching image found')
else:
return 'ok'
每个文件和文件夹都在正确的位置。在这个片段中,我创建了
get_image()
函数,但我也尝试将它放在代码中而不将这些行作为函数调用。
最后是 image.html 的 html 代码:
\<!DOCTYPE html\>
\<html\>
\<head\>
\<title\>Page Image\</title\>
\<meta charset="UTF-8"\>
\<meta name="viewport" content="width=device-width, initial-scale=1.0"\>
\</head\>
\<body\>
\<h1\>ImageId: {{ cell_value }}\</h1\>
{% if image_url %}
\<img src="{{ image_url }}" alt="{{ cell_value }}"\>
{% endif %}
{% if error_message %}
\<p class="error"\>{{ error_message }}\</p\>
{% endif %}
\</body\>
\</html\>
image_display()
的回归算什么。尽管如此,它会打印所有内容并成功检索到图像的正确 url。
我做错了什么?