python - 如何使用 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 文件一起发送,以便我们可以正确显示页面。
解决方案
我没有使用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 而不是纯文本发送。
推荐阅读
- database - 将 docker 内部创建的迁移脚本复制到外部数据库
- angular - 在数据库中存储 Angular 反应式表单验证规则
- vba - 如何在字段中插入全局变量?
- twitter-bootstrap - Change target background color of transition of buttons in bootstrap 4
- javascript - D3.js 中的链式转换(强制布局)
- javascript - JQuery 无法在移动设备(iPhone)上打开 Bootstrap 模式
- typescript - 具有未确定属性的类
- angular - 如何拼接数组中的单选按钮值
- python - Sending two Pandas dataframes side-by-side using HTML in email
- javascript - Select2 - 呈现搜索输入而不是可点击的选择