【问题标题】:How to create html using user input and display it in a new tab?如何使用用户输入创建 html 并将其显示在新选项卡中?
【发布时间】:2018-04-03 08:45:27
【问题描述】:

我想运行一个烧瓶应用程序,用户可以在其中提供一些用户输入,这些输入用于创建一个 HTML 页面,然后应该在新选项卡中显示该页面。 HTML 是使用外部工具创建的(这里由函数 get_html 模仿,它实际上将用户输入作为参数),所以我不能只使用我呈现的模板(我认为)。

我已经可以接受用户输入并创建我希望显示的 HTML,但是,我还没有设法为它打开一个新选项卡。如何实现?

这是我的代码:

from __future__ import print_function, division

from flask import Flask, render_template, request, jsonify
import json

# Initialize the Flask application
app = Flask(__name__)


@app.route('/html_in_tab')
def get_html():

    # provided by an external tool 
    # takes the user input as argument (below mimicked by a simple string concatenation)

    return '<!DOCTYPE html><title>External html</title><div>Externally created</div>'


@app.route('/_process_data')
def data_collection_and_processing():

    # here we collect some data and then create the html that should be displayed in the new tab
    some_data = json.loads(request.args.get('some_data'))

    # just to see whether data is retrieved
    print(some_data)

    # oversimplified version of what actually happens; get_html comes from an external tool
    my_new_html = get_html() + '<br>' + some_data
    print(my_new_html)

    # this html should now be displyed in a new tab
    return my_new_html


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


if __name__ == '__main__':

    app.run(debug=True)

index.html 如下所示:

<!DOCTYPE html>
<html lang="en">
  <head>
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <div class="container">
      <div class="header">
        <h3 class="text-muted">Get new tab!</h3>
      </div>
      <button type="button" id="process_input">Process!</button>

      <a href="/html_in_tab" class="button" target='_blank'>Go to results</a>

    </div>
    <script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
    <script type="text/javascript">
      $(document).ready(function() {

        // clicking the button works fine: data is processed correctly
        $('#process_input').bind('click', function() {
            $.getJSON('/_process_data', {
                some_data: JSON.stringify('some data')

            });
          // can this be changed to show the processed html?
          window.open("/html_in_tab", "_blank");
          return false;

        });
      });
    </script>
  </body>
</html>

所以,现在window.open 部分打开了一个新选项卡,但它应该显示my_new_html,即data_collection_and_processing 新创建的HTML。我怎样才能做到这一点?

【问题讨论】:

    标签: python flask


    【解决方案1】:

    目前,您只是在端点 "/html_in_tab" 打开一个新窗口,它将访问 get_html() 的 Flask 路由,并在没有用户输入的情况下显示标准 HTML。

    您可以尝试的一种方法是打开一个新窗口并使用更新的内容设置文档正文 innerHTML:

    <script type="text/javascript">                                             
      $(document).ready(function() {                                            
    
        $('#process_input').bind('click', function() {                          
    
            $.get('/_process_data', {                                           
    
                some_data: JSON.stringify('some data'),                         
    
            }).success(function(data) {                                         
    
                    var win = window.open("", "_blank");                        
                    win.document.body.innerHTML = data;                         
    
            })                                                                  
    
            return false;                                                       
    
        });                                                                     
      });                                                                       
    </script> 
    

    【讨论】:

    • 感谢您的即时回复!这似乎有效(赞成)。您是否看到了一个更优雅的解决方案,或者这会是要走的路吗?
    • 很难说不知道你的 get_html 函数的真实世界限制。如果 HTML 格式是标准的,您可能希望简单地将用户输入传递给 Flask 路由并将该输入传递给 Flask 的 render_template 函数。如果您需要调用外部服务来获取 HTML,那么我在上面发布的答案可能是一个足够好的解决方案。
    • 好的,再次感谢。现在,我需要这个外部工具来创建然后显示的整个页面。将检查我是否可以访问源代码,然后可能能够提取相关部分以创建 html;然后我可以创建一个模板并直接使用render_template
    【解决方案2】:

    如下图修改你的html:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h3 class="text-muted">Get new tab!</h3>
          </div>
          <button type="button" id="process_input">Process!</button>
    
          <a href="/html_in_tab" class="button" target='_blank'>Go to results</a>
    
        </div>
        <script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
        <script type="text/javascript">
          $(document).ready(function() {
    
            // clicking the button works fine: data is processed correctly
            $('#process_input').bind('click', function() {
                $.getJSON('/_process_data', {
                    some_data: JSON.stringify('some data')
    
                }); 
              // can this be changed to show the processed html?
              window.open("/process_data", "_blank");
              return false;
    
            });
          });
        </script>
      </body>
    </html>
    

    和Python脚本如下图:

    from __future__ import print_function, division
    
    from flask import Flask, render_template, request, jsonify
    import json
    # Initialize the Flask application
    app = Flask(__name__)
    
    @app.route('/html_in_tab')
    def get_html():
    
        # provided by an external tool
        return '<!DOCTYPE html><title>External html</title><div>Externally created</div>'
    
    
    @app.route('/_process_data')
    def data_collection_and_processing():
        # here we collect some data and then create the html that should be displayed in the new tab
        some_data = json.loads(request.args.get('some_data'))
        # just to see whether data is retrieved
        print(some_data)
    
        # oversimplified version of what actually happens; get_html comes from an external tool
        my_new_html = get_html() + '<br>' + some_data
        with open('templates/changed_html.html','w') as f: #write the html string to file
            f.writelines(my_new_html)
        # this html should now be displyed in a new tab
        return ''
    
    @app.route('/process_data')
    def process_data():
        return render_template('changed_html.html')
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    
    if __name__ == '__main__':
    
        app.run(debug=True)
    

    【讨论】:

    • 谢谢!这也很好(赞成),但似乎比其他解决方案慢,然后还需要创建我想避免的临时文件......
    猜你喜欢
    • 2013-10-05
    • 1970-01-01
    • 2018-07-29
    • 2021-02-13
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多