简体   繁体   中英

How to execute python code on client side using flask?

I have my server.py file, where i have:

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)

My home.html file has:

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

I want to execute some python code in a python file on the client side in the comment here on the home.html file. I can't just call regular python code from flask, because that would run on the server side. How can I run it on the client side?

My project's structure is the following:

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

This won't work since Python is not a web-app language supported by browsers. Everything that is client-side needs to be able to run on the client computer and for Python code you need to have Python installed on your computer.

The only option you have is to code your feature in JavaScript to let it run on the client side.

Why exactly do you want it to run on the client side? Maybe there is a different solution for your problem. Like a server-client program.

You are already executing python code on the client side.

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

to give you an example.

when you render your page you can pass a python variable named 'posts' to your page with the value "i did it"; along with a python variable named 'title' with the value "arroz".

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

you can display the value of those python variables like this:

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

you can format the value displayed just like any other html content:

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

your final code should be

server.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)

home.html

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM