首页 > 解决方案 > 如何在 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>

标签: pythonhtmlpython-3.x

解决方案


有一种方法可以使用 Python Web 框架(如FlaskDjango. 在典型的烧瓶场景中,您的代码将如下所示:-

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


推荐阅读