Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sashachabin/ceb5652079d4b84ba4862e563979a433 to your computer and use it in GitHub Desktop.
Save sashachabin/ceb5652079d4b84ba4862e563979a433 to your computer and use it in GitHub Desktop.
УрФУ. Вставка JavaScript и CSS из списка в HTML документ
from wsgiref.simple_server import make_server
# Исходный список подключаемых файлов в HTML
INCLUDES = [
'app.js',
'react.js',
'leaflet.js',
'D3.js',
'moment.js',
'math.js',
'main.css',
'bootstrap.css',
'normalize.css',
]
class WSGIMiddleware(object):
'''
WSGIMiddleware, которое добавляет стили и скрипты из INCLUDES в HTML
'''
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
response = self.app(environ, start_response).decode()
if response.find('<head>' and '<body>') > -1:
# Получение содержимого тегов <head> и <body>
htmlstart, head = response.split('<head>')
head_data = head.split('</head>')[0]
body = response.split('<body>')[1]
body_data, htmlend = body.split('</body>')
# Разделение способов подключения
scripts = ""
styles = ""
for include in INCLUDES:
if ".css" in include:
styles += '<link rel="stylesheet" href="/_static/{}" />\n\r'.format(include)
if ".js" in include:
scripts += '<script src="/_static/{}"></script>\n\r'.format(include)
# Вывод контента с добавлением стилей в <head> и скриптов в конце <body>
data = '<head>' + head_data + styles + '</head>\n\r' + '<body>' + body_data + scripts + '</body>'
yield (htmlstart + data + htmlend).encode()
else:
yield (response).encode()
def app(environ, start_response):
response_code = '200 OK'
response_type = ('Content-Type', 'text/HTML')
start_response(response_code, [response_type])
return '''<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML Document</title>
</head>
<body>
<p>Текст на странице</p>
</body>
</html>'''.encode()
app = WSGIMiddleware(app)
make_server('localhost', 80, app).serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment