【发布时间】:2021-09-20 16:05:26
【问题描述】:
我有一个带有下载按钮的 Flask 网络应用程序。当我单击按钮时,我想执行 python 方法,而不是 javascript 方法。这个 python 方法应该从网页中获取一些最近修改的 html 代码作为输入。
最准确的情况如下:要求用户填写一些文本中的空白,完成后点击下载按钮。当按钮被点击时,一个python函数render_pdf()被执行,它使用pdfkit库将html修改后的文本转换为pdf。
在最简单的版本中,我的项目具有以下结构:
- static/sample.pdf
- templates/index.html
- main.py
这是我到目前为止的代码:
main.py
from flask import Flask, render_template
import pdfkit
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
index.html
<body>
<p class="test">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, beatae!
<span contenteditable="true" class="badge alert-info name" data-placeholder="Enter your name" data-focused-advice="Start typing"></span><i class="fa fa-lg fa-plus-circle"></i>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Perspiciatis, laboriosam?
</p>
<button onclick="render_pdf()"><a href="../static/sample.pdf" download="my_file">Download</a></button>
</body>
我要执行的python方法应该是这个,传入htmlstr作为输入:
import pdfkit
def render_pdf(htmlstr):
pdfkit.from_string(htmlstr, './static/sample.pdf')
我知道我可以通过执行document.getElementsByClassName("test")[0].innerHTML; 来使用 javascript 获得变量 htmlstr
我觉得我离那里很近,我已经检查了maybe a bit old but very similar questions,但我只是不知道如何将输入的 html 传递给 python 方法。我错过了什么?
【问题讨论】:
标签: javascript python html ajax flask