从html激活/执行python脚本(通过url而不是提交按钮)

idfiyjo8  于 2023-02-02  发布在  Python
关注(0)|答案(2)|浏览(129)

现在我有python脚本可以提取mysql数据并传递到html

  • .py脚本
import mysql.connector
import webbrowser
import time
import pymysql
from flask import Flask,render_template

app = Flask(__name__)

mydb = mysql.connector.connect(
  host="196.168.101.141",
  user="root",
  password="password123", 
  database="cool_db",  
  auth_plugin='mysql_native_password'
)
      # assume customer looking for product ID 001 item        
mycursor = mydb.cursor()
mycursor.execute("SELECT P_TITLE,P_PRICE  FROM webpage WHERE P_ID = '001'")                       
                                         
myresult = mycursor.fetchall()

print(myresult)    # does get the result I want 

# send result to index.html
@app.route('/')
def index():
    return render_template("Myshop.html", myresult = myresult)

if __name__ == "__main__":
    app.run(debug=True)
  • Myshop.html
<!DOCTYPE html>
<html>
    <body>
      <p> this is {{myresult}}</p>

    </body>
</html>
  • pic中的任务订单

我将把.py和Myshop.html都放到WinSCP中(对公众开放)

问题:如何通过输入http://192.168.0.206:8080/english/MyShop.html?ProductID=001之类的url触发.py脚本

该网页可以使用我脚本显示不同的内容
因为我看到大部分的教程是使用 flask 提交按钮
但我想使用url传递值并激活我的.py来刷新Myshop.html
嗯,我问题是**问题:如何通过输入http://192.168.0.206:8080/english/MyShop.html?ProductID=001**这样的url来触发.py脚本,任何人都可以输入url http://......ProductID=001http://.......ProductID=007来加载新页面;现在看来,我们仍然需要执行pyscript,这是“任务订单在图片”的中间步骤,我希望流程是从第一步到最后一步

9w11ddsr

9w11ddsr1#

import mysql.connector
import webbrowser
import time
import pymysql
from flask import Flask,render_template, request

app = Flask(__name__)

mydb = mysql.connector.connect(
  host="196.168.101.141",
  user="root",
  password="password123", 
  database="cool_db",  
  auth_plugin='mysql_native_password'
)    
mycursor = mydb.cursor()

# send result to index.html
@app.route('/')
def index():
    mycursor.execute("SELECT P_TITLE,P_PRICE  FROM webpage WHERE P_ID = '%s'",(request.args.get("ProductID"),))
    myresult = mycursor.fetchall()
    return render_template("Myshop.html", myresult = myresult)

if __name__ == "__main__":
    app.run(debug=True)
bvjveswy

bvjveswy2#

如果你使用的是flask,就不要在url中输入Myshop.html。你转到/路由,它会呈现myshop.html。
如果您想从get请求传递数据(如示例中所示

http://192.168.0.206:8080/?ProductID=001

您可以通过请求访问该数据

@app.route('/')
def index():
    # if key doesn't exist, returns None
    myresult = request.args.get('ProductID')

    return render_template("Myshop.html", myresult = myresult)

本教程对此进行了更详细的说明:https://www.digitalocean.com/community/tutorials/processing-incoming-request-data-in-flask

相关问题