使用HTML调用python函数 [英] Call python function using HTML

查看:283
本文介绍了使用HTML调用python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  def search():
带有一个名称列表打开('business_ten.json')为f:
data = f.read()
jsondata = json.loads(data)


用于jsondata ['rows']:
#print row ['text']
a = str(row ['name'])

打印
返回a


search()

我试图在使用Flask的HTML文件

  {%extendslayout.html%} 
{%block content%}
< div class =jumbo>
< h2>欢迎使用评分应用< h2>
< h3>这是Rating app< h3>的主页。
< / div>
< body>
< p> {{search.a}}< / p>
< / body>
{%endblock%}

我的路线文件如下:

  from flask import Flask,render_template 
app = Flask(__ name__)

@ app.route('/ ')
def hello_world():
return'Hello gugugWorld!'
@ app.route('/ crawl')
def crawl():
return render_template ('crawl.html')


解决方案

要做到这一点:$ b​​
$ 1您可以注册一个新的Jinja2过滤器

2您可以传递您的函数作为Jinja2参数(这个更容易)

对于方法2:

 <$ c 
def crawl():
return render_template('crawl.html',myfunction = search)

在模板调用时,参数有一个函数

$ p $ {%extendslayout.html%}
{%block content%}
< div class =jumbo>
< h2>欢迎使用评分应用< h2>
< h3>这是Rating app< h3>的主页。
< / div>
< body>
< p> {{myfunction()}}< / p>
< / body>
{%endblock%}


I have a function in python that displays a list of names.

def search():
    with open('business_ten.json') as f:
    data=f.read()
    jsondata=json.loads(data)


for row in jsondata['rows']:
    #print row['text']
    a=str(row['name'])

    print a 
    return a


    search()

I am trying to call this function in an HTML file using Flask

{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Rating app<h2>
<h3>This is the home page for the Rating app<h3>
</div>
<body>
    <p>{{ search.a }}</p>
</body>
{% endblock %}

My routes file is as follows:

from flask import Flask,render_template
app = Flask(__name__)

@app.route('/')
def hello_world():
return 'Hello gugugWorld!'
@app.route('/crawl')
def crawl():
return render_template('crawl.html')

解决方案

There are many ways to do this:

1 - You can register a new Jinja2 filter

2 - You can pass your function as a Jinja2 parameter (This one is easier)

For method 2:

@app.route('/crawl')
def crawl():
    return render_template('crawl.html', myfunction=search)

On the template call the parameter has a function

{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Rating app<h2>
<h3>This is the home page for the Rating app<h3>
</div>
<body>
 <p>{{ myfunction() }}</p>
</body> 
{% endblock %}

这篇关于使用HTML调用python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆