python - 如何在 localhost 中单独使用 Python 显示 HTML
问题描述
我正在尝试仅使用 python 显示我的 html 文件。就像我一样python code.py
,我将能够访问我的 htmllocalhost:8080
html 文件是相互访问的静态文件。例如,index.html
定向到contact.html
所有访问css
文件夹。
如何打开我的 html 文件以使其显示在网页上?
以下是我到目前为止所拥有的。
html_file = []
with open("index.html", "r") as f:
for line in f.readlines():
html_file.append(line)
有没有办法做python code.py
,当我访问时localhost:8000
会显示代码?我可以访问每个页面。
这是一个示例 html 文件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<img class="resize" src="./pictures/logo.png" alt="logo">
<nav>
<ul class="nav-links">
<li class="active"><a href="./index.html">Home</a></li>
<li><a href="./contact.html">Contact</a></li>
</ul>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')
})
</script>
</nav>
</header>
</body>
</html>
解决方案
有一种方法可以使用 Python Web 框架(如Flask
或Django
. 在典型的烧瓶场景中,您的代码将如下所示:-
1)安装烧瓶: -
pip install flask
2)code.py
这样写:-
from flask import Flask, url_for
from flask import render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('hello.html')
3)接下来创建一个模板folder
,其中放置您的html文件,我将其命名为hello.html
templates > hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<img class="resize" src="./pictures/logo.png" alt="logo">
<nav>
<ul class="nav-links">
<li class="active"><a href="./index.html">Home</a></li>
<li><a href="./contact.html">Contact</a></li>
</ul>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')
})
</script>
</nav>
</header>
</body>
</html>
4)您的目录结构如下所示:-
/code.py
/templates
/hello.html
5)运行python code.py
,你可以看到你的页面localhost:5000
。
推荐阅读
- javascript - Javascript 从 JSON 文件数据中查找平均值
- node.js - Amazon MQ 未收到任何队列消息
- javascript - 点击方法没有响应 Jamboard
- android - 我怎样才能避免 java.io.StreamCorruptedException:无效的流标头:00000000
- python - Kivy - 无法重新聚焦输入字段?
- java - th:文本无法正确显示
- jupyter-notebook - 为什么必须在 Jupyter notebook 中重新运行之前的代码框?
- airflow - 气流传感器中的“重新安排”模式如何工作?
- javascript - 使用带有画布的全屏 API
- coldfusion - 在 API 中为我们保护 ColdFusion CFAdmin 密码