flask-调用python函数,该函数在按钮onclick事件上获取输入参数

de90aj5v  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(893)

我有一个带有下载按钮的flask web应用程序。当我点击按钮时,我想执行一个python方法,而不是javascript方法。这个python方法应该从web页面获取一些最近修改的html代码作为输入。
最准确的情况是:用户被要求在一些文本中填充空格,完成后单击下载按钮。单击按钮时,将显示一个python函数 render_pdf() 通过使用将html修改文本转换为pdf的 pdfkit 图书馆。
在最简单的版本中,“我的项目”具有以下结构:
static/sample.pdf
模板/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')

我知道我可以用javascript获取变量 htmlstr 通过做 document.getElementsByClassName("test")[0].innerHTML; 我觉得我很快就要到达那里了,我检查了可能有点老但非常相似的问题,但我只是不知道如何将输入html传递给python方法。我错过了什么?

ymdaylpp

ymdaylpp1#

定义运行脚本的url(路由)。
在javascript代码中,向步骤1中定义的url发出http请求。
它很简单,我为您编写了代码,我希望它能帮助您:
我还在github上做了一个要点
main.py

from flask import Flask, render_template
from flask import request
import pdfkit

## ## ## ## ## ## ## ## ## ## ## ##

app = Flask(__name__)

## ## ## ## ## ## ## ## ## ## ## ##

# config wkhtmltopdf on my system

path_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)

# function of rendering

def render_pdf(htmlstr):
    pdfkit.from_string(htmlstr, './static/sample.pdf', configuration=config) 

## ## ## ## ## ## ## ## ## ## ## ##

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/update-file/', methods=['POST'])
def convert_string_to_pdf():
    try:
        # geting the json request
        json = request.get_json()

        # call render_pdf function with new value
        render_pdf(json['htmlstr'])

        # '0' meaning no error
        return '0'

    except Exception as error:
        return str(error)

## ## ## ## ## ## ## ## ## ## ## ##

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

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Convert HTML to PDF</title>
</head>
<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>

    <br><br>
    <button onclick="commandServerToRender()">Convert to PDF</button>

    <br><br>
    <div id="downloadBox" hidden>
        <p style="color: green;"><b>File is ready to download</b></p>
        <a href="/static/sample.pdf" download="my_file">Download PDF File</a>
    </div>

    <div id="errorBox" hidden>
        <p style="color:red"><b>There was an error:</b></p>
        <p id="errorMessage" style="color:red"></p>
    </div>

    <script>
        function commandServerToRender() {
            test = document.getElementsByClassName("test")[0].innerHTML;
            downloadBox = document.getElementById('downloadBox');
            errorBox = document.getElementById('errorBox');
            errorMessage = document.getElementById('errorMessage');

            downloadBox.hidden = true;
            errorBox.hidden = true;

            // Sending data in JSON format using POST method
            //
            var xhr = new XMLHttpRequest();
            var url = "/update-file/";

            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/json");

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // if print 0 meaning that it was successfull
                    if (xhr.responseText == '0') {
                        downloadBox.hidden = false;

                    } else {
                        errorMessage.innerHTML = xhr.responseText;
                        errorBox.hidden = false;

                    }
                }
            };

            var data = JSON.stringify({"htmlstr": test});
            xhr.send(data);
        }
    </script>
</body>
</html>

相关问题