首页 > 解决方案 > 如何使用 python 的 socketio 发送 css/javascirpt 文件和 HTML?

问题描述

我有一个始终离线的 python 套接字服务器,我需要为本地客户端提供一个 HTML 页面,并来回通信。但是,当离线运行它时,它无法获取我们正在使用的远程 javascript/css,这很好,我们只是下载了文件和所需的许可证,并让 html 在本地引用它们。

这种方法仅在运行 .html 文件时有效,但是当 .html 文件由套接字服务器提供时,它缺少 .html 所指的 javascript 和 html。

我们将 .html 文件发送给客户端,如下所示:

sio = socketio.AsyncServer(cors_allowed_origins='*')
app = web.Application()
sio.attach(app)

async def index(request):
    with open('./index.html') as f:
        return web.Response(text=f.read(), content_type='text/html'


app.router.add_get('/', index)

if __name == '__main__':
    web.run_app(app)

我们假设,因为服务器只发送 .html 文件,我们没有看到本地 js/css 被正确加载。我们想知道是否有办法将这些文件与 .html 文件一起发送,以便我们可以正确显示页面。

标签: pythonsocketsoffline-modepython-socketio

解决方案


我没有使用socketio,但这可能会对你有所帮助。

我为我的 Python 服务器实现了如下:

        client, address = sock.accept()
        print('[CONNECTED] Client Connected:', address)
        req = client.recv(1024).decode('utf8')
        req = req.split(' ')[:2]
        print('[CONNECTED] New request', req[-1])
        client.send(b"HTTP/1.1 200 OK\n")
        try:
            if req[-1] == '/':
                client.send(b'Content-Type: text/html\n\n')
                client.sendfile(open('./static/html/home/index.html', 'rb'))
                # client.sendfile(open('./static/js/index.js', 'rb'))
            else:
                if '.js' in req[-1]:
                    client.send(b'Content-Type: text/javascript\n\n')
                elif '.css' in req[-1]:
                    client.send(b'Content-Type: text/css\n\n')
                else:
                    client.send(b'None')
                client.sendfile(open('.' + req[-1], 'rb'))

只需将 html 中的 JS 和/或 CSS 文件称为

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="http://localhost:1573/static/css/styles.css" />
  </head>

  <body>
    Hello World!
    <script src="http://localhost:1573/static/js/index.js"></script>
  </body>
</html>

项目目录:

./
    server.py
    static/
        html/
            index.html
        css/
            styles.css
        js/
            index.js

所以基本上我让 HTML 提到脚本作为本地服务器 localhost 文件的一部分,这使得它也发送对这些文件的请求。在服务器中,我检查是否请求 JS 或 CSS 并相应地发送它。请注意,“Content-Type”在这里起着重要作用。将 JS 作为 JS 和 CSS 作为 CSS 而不是纯文本发送。


推荐阅读