我如何访问我的Python脚本制作的网页?



我使用MobaXterm SSH到EC2实例。在EC2实例中,我编写了如下所示的脚本:

#!/usr/bin/env python3
import mysql.connector
# Connect to the MariaDB database
host = "localhost"
username = "DBUser"
password = "DBUserPassword"
dbname = "IoTSchema"
conn = mysql.connector.connect(
host=host,
user=username,
password=password,
database=dbname
)
# Check for connection errors
if conn.is_connected():
print("Connected to MariaDB database")
else:
print("Connection failed")
exit()
# Execute SQL queries to retrieve the desired data from the two tables
cursor = conn.cursor()
query1 = "SELECT * FROM iot_sensors"
cursor.execute(query1)
conn.close()
conn = mysql.connector.connect(
host=host,
user=username,
password=password,
database=dbname
)
cursor = conn.cursor()
query2 = "SELECT * FROM appliances"
cursor.execute(query2)
# Generate the HTML code for the first table
html = "<table>"
html += "<tr><th>Column 1</th><th>Column 2</th></tr>"
for row in cursor:
html += "<tr>"
html += "<td>" + row[0] + "</td>"
html += "<td>" + row[1] + "</td>"
html += "</tr>"
html += "</table>"
# Generate the HTML code for the second table
html += "<table>"
html += "<tr><th>Column 1</th><th>Column 2</th></tr>"
for row in cursor:
html += "<tr>"
html += "<td>" + row[0] + "</td>"
html += "<td>" + row[1] + "</td>"
html += "</tr>"
html += "</table>"
# Print the HTML code
print(html)
# Close the database connection
conn.close()

脚本的目的是从我的MariaDB数据库中提取表,并将其打印到2个单独的表中。当我执行脚本时,返回如下内容。运行脚本

的结果我不确定输出是否正确,但我所期望的是能够使用EC2实例的公共IP地址访问本地机器上的网页,但连接被拒绝。

我已经确保我的实例允许所有ip协议,不确定我还可以尝试解决这个问题。任何帮助都是感激的,谢谢。

脚本只是将HTML打印到控制台输出中。要把它作为一个可以通过互联网访问的网页,你还需要做一些事情:

  1. 将html页面保存到磁盘
  2. 使用web服务器(如Apache
  3. )提供页面
  4. 打开web服务器在实例的安全组上运行的端口

这应该使您能够通过实例的公共IP访问该页。但是,如果你只想查看单个html页面,有一种简单的方法可以使用python3python -m http.server提供服务,而无需设置和运行单独的web服务器。

或者,因为您已经在AWS上运行了,您可以将html文件保存到S3桶中并从那里访问它。