【问题标题】:How to execute python code on client side using flask?如何使用烧瓶在客户端执行python代码?
【发布时间】:2022-08-08 01:26:08
【问题描述】:

我有我的server.py 文件,其中有:

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

@app.route(\"/\")
@app.route(\"/home\")
def home():
  return render_template(\"home.html\",posts=posts,title=\"arroz\") 

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

我的home.html 文件有:

{%extends \"layout.html\"%}
{%block content%}
  <!--here-->
{%endblock content%}

我想在 python 文件中执行一些 python 代码客户在 home.html 文件的评论 here 中。我不能只从烧瓶中调用常规的 python 代码,因为它会在服务器端运行。如何在客户端运行它?

我的项目结构如下:

|-server.py
|-pythonToExecuteOnClientSide.py
|-templates
      |-home.html

    标签: python flask client


    【解决方案1】:

    这是行不通的,因为 Python 不是浏览器支持的网络应用语言。客户端的所有内容都需要能够在客户端计算机上运行,​​对于 Python 代码,您需要在计算机上安装 Python。

    您唯一的选择是在 JavaScript 中编写您的功能,让它在客户端运行。

    为什么您希望它在客户端运行?也许您的问题有不同的解决方案。就像一个服务器-客户端程序。

    【讨论】:

    • 我们想要暴力破解密钥生成。在服务器上这样做会压力太大。
    • 在我看来,你应该问问自己是否有合适的工具来解决你的问题。在这种情况下,桌面应用程序可能更容易实现。如果你真的想去 WebApp 看看 PyScript,这似乎是一些在浏览器中运行的 Python 实现。
    【解决方案2】:

    您已经在客户端执行 python 代码。

    {% pyton code %}  <html> {% python %}.
    

    给你一个例子。

    当你渲染你的页面时,你可以将一个名为'posts'的python变量传递给你的页面,其值为“我做到了”;以及一个名为“title”的python变量,其值为“arroz”。

    return render_template("home.html", posts=posts, title=title)
    

    您可以像这样显示这些 python 变量的值:

    {%extends "layout.html"%}
    {%block content%}
      {{ posts }} {{ title }}
    {%endblock content%}
    

    您可以像任何其他 html 内容一样格式化显示的值:

    <p> {{ posts }} </p> <h1> {{ title }} </h1>
    

    你的最终代码应该是

    服务器.py

    from flask import Flask,render_template,url_for
    app=Flask(__name__)
    
    @app.route("/")
    @app.route("/home")
    def home():
      posts = None
      title = "arroz"
      return render_template("home.html",posts=posts,title=title) 
    
    if __name__=="__main__":
      app.run(debug=False)
    

    主页.html

    {%extends "layout.html"%}
    {%block content%}
      <p> {{ posts }} </p> <h1> {{ title }} </h1>
    {%endblock content%}
    

    【讨论】:

      猜你喜欢
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多