将Flask-Python与HTML和JavaScript集成

时间:2018-02-16 12:49:31

标签: javascript python html flask

在我的代码中,我希望在app.py中的特定条件为true时运行index.html页面中定义的Javascript,否则脚本不应运行。我怎样才能做到这一点?

{{1}}

请帮助..

1 个答案:

答案 0 :(得分:0)

python脚本应该像这样

 app = Flask(__name__)
 @app.route('/',methods=["GET","POST"])
 def index():
    script = False

    if request.method == 'POST':
        search_token = request.args.get("validationtoken")
        print "search", search_token
        if search_token != None:
           # text = search_token
           resp = Response(search_token, status=200, mimetype='plain/text')
           print "resp",resp
           return resp
        else:
           print " Notification 
           script = True
           render_template('index.html', Script=script)



    elif request.method=="GET":
        code=request.args.get('code')
        state=request.args.get('state')
     ----

index.html应该是这样的

{% if Script %}
    <script type="text/javascript">
     "Your code lies here"
    </script>

您可以使用这种方式将python脚本(您的应用)中的变量传递给index.html模板,因为Flask使用了Jinja模板。