增加高压空闲调节

This commit is contained in:
2026-06-10 11:23:24 +08:00
parent ee45729b5b
commit d44140d999
123 changed files with 22413 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*.egg-info
/dist
/.venv*
+8
View File
@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (https://www.hc2.fr)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,18 @@
"""
The MIT License (MIT)
Copyright © 2024 Jean-Christophe Bos (jczic.bos@gmail.com)
"""
print()
print(' -------------------------')
print(' - Python MicroWebSrv2 -')
print(' - version 2.1.0 -')
print(' - by JC`zic -')
print(' -------------------------')
print()
from .libs.XAsyncSockets import *
from .libs.urlUtils import *
from .webRoute import *
from .microWebSrv2 import *
@@ -0,0 +1,416 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from . import *
from .httpResponse import HttpResponse
from binascii import a2b_base64
import json
# ============================================================================
# ===( HttpRequest )==========================================================
# ============================================================================
class HttpRequest :
MAX_RECV_HEADER_LINES = 100
# ------------------------------------------------------------------------
def __init__(self, microWebSrv2, xasCli) :
self._mws2 = microWebSrv2
self._xasCli = xasCli
self._waitForRecvRequest()
# ------------------------------------------------------------------------
def _recvLine(self, onRecv) :
self._xasCli.AsyncRecvLine(onLineRecv=onRecv, timeoutSec=self._mws2._timeoutSec)
# ------------------------------------------------------------------------
def _waitForRecvRequest(self) :
self._httpVer = ''
self._method = ''
self._path = ''
self._headers = { }
self._content = None
self._response = HttpResponse(self._mws2, self)
self._recvLine(self._onFirstLineRecv)
# ------------------------------------------------------------------------
def _onFirstLineRecv(self, xasCli, line, arg) :
try :
elements = line.strip().split()
if len(elements) == 3 :
self._httpVer = elements[2].upper()
self._method = elements[0].upper()
elements = elements[1].split('?', 1)
self._path = UrlUtils.UnquotePlus(elements[0])
self._queryString = (elements[1] if len(elements) > 1 else '')
self._queryParams = { }
if self._queryString :
elements = self._queryString.split('&')
for s in elements :
p = s.split('=', 1)
if len(p) > 0 :
v = (UrlUtils.Unquote(p[1]) if len(p) > 1 else '')
self._queryParams[UrlUtils.Unquote(p[0])] = v
self._recvLine(self._onHeaderLineRecv)
else :
self._response.ReturnBadRequest()
except :
self._response.ReturnBadRequest()
# ------------------------------------------------------------------------
def _onHeaderLineRecv(self, xasCli, line, arg) :
try :
elements = line.strip().split(':', 1)
if len(elements) == 2 :
if len(self._headers) < HttpRequest.MAX_RECV_HEADER_LINES :
self._headers[elements[0].strip().lower()] = elements[1].strip()
self._recvLine(self._onHeaderLineRecv)
else :
self._response.ReturnEntityTooLarge()
elif len(elements) == 1 and len(elements[0]) == 0 :
self._processRequest()
else :
self._response.ReturnBadRequest()
except :
self._response.ReturnBadRequest()
# ------------------------------------------------------------------------
def _processRequest(self) :
if not self._processRequestModules() :
if not self.IsUpgrade :
if not self._processRequestRoutes() :
if self._method in ('GET', 'HEAD') :
filename = self._mws2.ResolvePhysicalPath(self._path)
if filename :
ct = self._mws2.GetMimeTypeFromFilename(filename)
if ct :
self._response.AllowCaching = True
self._response.ContentType = ct
self._response.ReturnFile(filename)
else :
self._response.ReturnForbidden()
else :
self._response.ReturnNotFound()
elif self._method == 'OPTIONS' :
if self._mws2.CORSAllowAll :
self._response.SetHeader( 'Access-Control-Allow-Methods', '*' )
self._response.SetHeader( 'Access-Control-Allow-Headers', '*' )
self._response.SetHeader( 'Access-Control-Allow-Credentials', 'true' )
self._response.SetHeader( 'Access-Control-Max-Age', '86400' )
self._response.ReturnOk()
else :
self._response.ReturnMethodNotAllowed()
else :
self._response.ReturnNotImplemented()
# ------------------------------------------------------------------------
def _processRequestModules(self) :
for modName, modInstance in self._mws2._modules.items() :
try :
modInstance.OnRequest(self._mws2, self)
if self._response.HeadersSent :
return True
except Exception as ex :
self._mws2.Log( 'Exception in request handler of module "%s" (%s).'
% (modName, ex),
self._mws2.ERROR )
return False
# ------------------------------------------------------------------------
def _processRequestRoutes(self) :
self._routeResult = ResolveRoute(self._method, self._path)
if self._routeResult :
cntLen = self.ContentLength
if not cntLen :
self._routeRequest()
elif self._method != 'GET' and self._method != 'HEAD' :
if cntLen <= self._mws2._maxContentLen :
def onContentRecv(xasCli, content, arg) :
self._content = content
self._routeRequest()
self._content = None
try :
self._xasCli.AsyncRecvData( size = cntLen,
onDataRecv = onContentRecv,
timeoutSec = self._mws2._timeoutSec )
except :
self._mws2.Log( 'Not enough memory to read a content of %s bytes.' % cntLen,
self._mws2.ERROR )
self._response.ReturnServiceUnavailable()
else :
self._response.ReturnEntityTooLarge()
else :
self._response.ReturnBadRequest()
return True
return False
# ------------------------------------------------------------------------
def _routeRequest(self) :
try :
currentResp = self._response
if self._routeResult.Args :
self._routeResult.Handler(self._mws2, self, self._routeResult.Args)
else :
self._routeResult.Handler(self._mws2, self)
if not currentResp.HeadersSent :
self._mws2.Log( 'No response was sent from route %s.'
% self._routeResult,
self._mws2.WARNING )
currentResp.ReturnNotImplemented()
except Exception as ex :
self._mws2.Log( 'Exception raised from route %s: %s'
% (self._routeResult, ex),
self._mws2.ERROR )
currentResp.ReturnInternalServerError()
# ------------------------------------------------------------------------
def GetPostedURLEncodedForm(self) :
res = { }
if self.ContentType.lower() == 'application/x-www-form-urlencoded' :
try :
elements = bytes(self._content).decode('UTF-8').split('&')
for s in elements :
p = s.split('=', 1)
if len(p) > 0 :
v = (UrlUtils.UnquotePlus(p[1]) if len(p) > 1 else '')
res[UrlUtils.UnquotePlus(p[0])] = v
except :
pass
return res
# ------------------------------------------------------------------------
def GetPostedJSONObject(self) :
if self.ContentType.lower() == 'application/json' :
try :
s = bytes(self._content).decode('UTF-8')
return json.loads(s)
except :
pass
return None
# ------------------------------------------------------------------------
def GetHeader(self, name) :
if not isinstance(name, str) or len(name) == 0 :
raise ValueError('"name" must be a not empty string.')
return self._headers.get(name.lower(), '')
# ------------------------------------------------------------------------
def CheckBasicAuth(self, username, password) :
if not isinstance(username, str) :
raise ValueError('"username" must be a string.')
if not isinstance(password, str) :
raise ValueError('"password" must be a string.')
auth = self.Authorization
if auth :
try :
auth = auth.split()
if len(auth) == 2 and auth[0].lower() == 'basic' :
auth = a2b_base64(auth[1].encode()).decode()
auth = auth.split(':')
return ( auth[0].lower() == username.lower() and \
auth[1] == password )
except :
pass
return False
# ------------------------------------------------------------------------
def CheckBearerAuth(self, token) :
if not isinstance(token, str) :
raise ValueError('"token" must be a string.')
auth = self.Authorization
if auth :
try :
auth = auth.split()
return ( len(auth) == 2 and \
auth[0].lower() == 'bearer' and \
auth[1] == token )
except :
pass
return False
# ------------------------------------------------------------------------
@property
def UserAddress(self) :
return self._xasCli.CliAddr
# ------------------------------------------------------------------------
@property
def IsSSL(self) :
return self._xasCli.IsSSL
# ------------------------------------------------------------------------
@property
def HttpVer(self) :
return self._httpVer
# ------------------------------------------------------------------------
@property
def Method(self) :
return self._method
# ------------------------------------------------------------------------
@property
def Path(self) :
return self._path
# ------------------------------------------------------------------------
@property
def QueryString(self) :
return self._queryString
# ------------------------------------------------------------------------
@property
def QueryParams(self) :
return self._queryParams
# ------------------------------------------------------------------------
@property
def Host(self) :
return self._headers.get('host', '')
# ------------------------------------------------------------------------
@property
def Accept(self) :
s = self._headers.get('accept', None)
if s :
return [x.strip() for x in s.split(',')]
return [ ]
# ------------------------------------------------------------------------
@property
def AcceptEncodings(self) :
s = self._headers.get('accept-encoding', None)
if s :
return [x.strip() for x in s.split(',')]
return [ ]
# ------------------------------------------------------------------------
@property
def AcceptLanguages(self) :
s = self._headers.get('accept-language', None)
if s :
return [x.strip() for x in s.split(',')]
return [ ]
# ------------------------------------------------------------------------
@property
def Cookies(self) :
s = self._headers.get('cookie', None)
if s :
return [x.strip() for x in s.split(';')]
return [ ]
# ------------------------------------------------------------------------
@property
def CacheControl(self) :
return self._headers.get('cache-control', '')
# ------------------------------------------------------------------------
@property
def Referer(self) :
return self._headers.get('referer', '')
# ------------------------------------------------------------------------
@property
def ContentType(self) :
return self._headers.get('content-type', '').split(';', 1)[0].strip()
# ------------------------------------------------------------------------
@property
def ContentLength(self) :
try :
return int(self._headers.get('content-length', 0))
except :
return 0
# ------------------------------------------------------------------------
@property
def UserAgent(self) :
return self._headers.get('user-agent', '')
# ------------------------------------------------------------------------
@property
def Authorization(self) :
return self._headers.get('authorization', '')
# ------------------------------------------------------------------------
@property
def Origin(self) :
return self._headers.get('origin', '')
# ------------------------------------------------------------------------
@property
def IsKeepAlive(self) :
return ('keep-alive' in self._headers.get('connection', '').lower())
# ------------------------------------------------------------------------
@property
def IsUpgrade(self) :
return ('upgrade' in self._headers.get('connection', '').lower())
# ------------------------------------------------------------------------
@property
def Upgrade(self) :
return self._headers.get('upgrade', '')
# ------------------------------------------------------------------------
@property
def Content(self) :
return self._content
# ------------------------------------------------------------------------
@property
def Response(self) :
return self._response
# ------------------------------------------------------------------------
@property
def XAsyncTCPClient(self) :
return self._xasCli
# ============================================================================
# ============================================================================
# ============================================================================
@@ -0,0 +1,550 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from os import stat
import json
# ============================================================================
# ===( HttpResponse )=========================================================
# ============================================================================
class HttpResponse :
_RESPONSE_CODES = {
100: ( 'Continue',
'Request received, please continue.' ),
101: ( 'Switching Protocols',
'Switching to new protocol; obey Upgrade header.' ),
200: ( 'OK',
'Request fulfilled, document follows.' ),
201: ( 'Created',
'Document created, URL follows' ),
202: ( 'Accepted',
'Request accepted, processing continues off-line.' ),
203: ( 'Non-Authoritative Information',
'Request fulfilled from cache' ),
204: ( 'No Content',
'Request fulfilled, nothing follows.' ),
205: ( 'Reset Content',
'Clear input form for further input.' ),
206: ( 'Partial Content',
'Partial content follows.' ),
300: ( 'Multiple Choices',
'Object has several resources -- see URI list.' ),
301: ( 'Moved Permanently',
'Object moved permanently -- see URI list.' ),
302: ( 'Found',
'Object moved temporarily -- see URI list.' ),
303: ( 'See Other',
'Object moved -- see Method and URL list.' ),
304: ( 'Not Modified',
'Document has not changed since given time.' ),
305: ( 'Use Proxy',
'You must use proxy specified in Location to access this resource.' ),
307: ( 'Temporary Redirect',
'Object moved temporarily -- see URI list.' ),
400: ( 'Bad Request',
'Bad request syntax or unsupported method.' ),
401: ( 'Unauthorized',
'No permission -- see authorization schemes.' ),
402: ( 'Payment Required',
'No payment -- see charging schemes.' ),
403: ( 'Forbidden',
'Request forbidden -- authorization will not help.' ),
404: ( 'Not Found',
'Nothing matches the given URI.' ),
405: ( 'Method Not Allowed',
'Specified method is invalid for this resource.' ),
406: ( 'Not Acceptable',
'URI not available in preferred format.' ),
407: ( 'Proxy Authentication Required',
'You must authenticate with this proxy before proceeding.' ),
408: ( 'Request Timeout',
'Request timed out; try again later.' ),
409: ( 'Conflict',
'Request conflict.' ),
410: ( 'Gone',
'URI no longer exists and has been permanently removed.' ),
411: ( 'Length Required',
'Client must specify Content-Length.' ),
412: ( 'Precondition Failed',
'Precondition in headers is false.' ),
413: ( 'Request Entity Too Large',
'Entity is too large.' ),
414: ( 'Request-URI Too Long',
'URI is too long.' ),
415: ( 'Unsupported Media Type',
'Entity body in unsupported format.' ),
416: ( 'Requested Range Not Satisfiable',
'Cannot satisfy request range.' ),
417: ( 'Expectation Failed',
'Expect condition could not be satisfied.' ),
500: ( 'Internal Server Error',
'Server got itself in trouble.' ),
501: ( 'Not Implemented',
'Server does not support this operation.' ),
502: ( 'Bad Gateway',
'Invalid responses from another server/proxy.' ),
503: ( 'Service Unavailable',
'The server cannot process the request due to a high load.' ),
504: ( 'Gateway Timeout',
'The gateway server did not receive a timely response.' ),
505: ( 'HTTP Version Not Supported',
'Cannot fulfill request.' )
}
_CODE_CONTENT_TMPL = """\
<html>
<head>
<title>MicroWebSrv2</title>
</head>
<body style="font-family: Verdana; background-color: Black; color: White;">
<h2>MicroWebSrv2 - [%(code)d] %(reason)s</h2>
%(message)s
</body>
</html>
"""
# ------------------------------------------------------------------------
def __init__(self, microWebSrv2, request) :
self._mws2 = microWebSrv2
self._request = request
self._xasCli = request.XAsyncTCPClient
self._headers = { }
self._allowCaching = False
self._acAllowOrigin = None
self._contentType = None
self._contentCharset = None
self._contentLength = 0
self._stream = None
self._sendingBuf = None
self._hdrSent = False
self._onSent = None
# ------------------------------------------------------------------------
def SetHeader(self, name, value) :
if not isinstance(name, str) or len(name) == 0 :
raise ValueError('"name" must be a not empty string.')
if value is None :
raise ValueError('"value" cannot be None.')
self._headers[name] = str(value)
# ------------------------------------------------------------------------
def _onDataSent(self, xasCli, arg) :
if self._stream :
try :
n = self._stream.readinto(self._sendingBuf)
if n < len(self._sendingBuf) :
self._stream.close()
self._stream = None
self._sendingBuf = self._sendingBuf[:n]
except :
self._xasCli.Close()
self._mws2.Log( 'Stream cannot be read for request "%s".'
% self._request._path,
self._mws2.ERROR )
return
if self._sendingBuf :
if self._contentLength :
self._xasCli.AsyncSendSendingBuffer( size = len(self._sendingBuf),
onDataSent = self._onDataSent )
if not self._stream :
self._sendingBuf = None
else :
def onChunkHdrSent(xasCli, arg) :
def onChunkDataSent(xasCli, arg) :
def onLastChunkSent(xasCli, arg) :
self._xasCli.AsyncSendData(b'0\r\n\r\n', onDataSent=self._onDataSent)
if self._stream :
onDataSent = self._onDataSent
else :
self._sendingBuf = None
onDataSent = onLastChunkSent
self._xasCli.AsyncSendData(b'\r\n', onDataSent=onDataSent)
self._xasCli.AsyncSendSendingBuffer( size = len(self._sendingBuf),
onDataSent = onChunkDataSent )
data = ('%x\r\n' % len(self._sendingBuf)).encode()
self._xasCli.AsyncSendData(data, onDataSent=onChunkHdrSent)
else :
self._xasCli.OnClosed = None
if self._keepAlive :
self._request._waitForRecvRequest()
else :
self._xasCli.Close()
if self._onSent :
try :
self._onSent(self._mws2, self)
except Exception as ex :
self._mws2.Log( 'Exception raised from "Response.OnSent" handler: %s' % ex,
self._mws2.ERROR )
# ------------------------------------------------------------------------
def _onClosed(self, xasCli, closedReason) :
if self._stream :
try :
self._stream.close()
except :
pass
self._stream = None
self._sendingBuf = None
# ------------------------------------------------------------------------
def _makeBaseResponseHdr(self, code) :
reason = self._RESPONSE_CODES.get(code, ('Unknown reason', ))[0]
self._mws2.Log( 'From %s:%s %s%s %s >> [%s] %s'
% ( self._xasCli.CliAddr[0],
self._xasCli.CliAddr[1],
('SSL-' if self.IsSSL else ''),
self._request._method,
self._request._path,
code,
reason ),
self._mws2.DEBUG )
if self._mws2.AllowAllOrigins :
self._acAllowOrigin = self._request.Origin
if self._acAllowOrigin :
self.SetHeader('Access-Control-Allow-Origin', self._acAllowOrigin)
self.SetHeader('Server', 'MicroWebSrv2 by JC`zic')
hdr = ''
for n in self._headers :
hdr += '%s: %s\r\n' % (n, self._headers[n])
resp = 'HTTP/1.1 %s %s\r\n%s\r\n' % (code, reason, hdr)
return resp.encode('ISO-8859-1')
# ------------------------------------------------------------------------
def _makeResponseHdr(self, code) :
if code >= 200 and code < 300 :
self._keepAlive = self._request.IsKeepAlive
else :
self._keepAlive = False
if self._keepAlive :
self.SetHeader('Connection', 'Keep-Alive')
self.SetHeader('Keep-Alive', 'timeout=%s' % self._mws2._timeoutSec)
else :
self.SetHeader('Connection', 'Close')
if self._allowCaching :
self.SetHeader('Cache-Control', 'public, max-age=31536000')
else :
self.SetHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
if self._contentType :
ct = self._contentType
if self._contentCharset :
ct += '; charset=%s' % self._contentCharset
self.SetHeader('Content-Type', ct)
if self._contentLength :
self.SetHeader('Content-Length', self._contentLength)
return self._makeBaseResponseHdr(code)
# ------------------------------------------------------------------------
def SwitchingProtocols(self, upgrade) :
if not isinstance(upgrade, str) or len(upgrade) == 0 :
raise ValueError('"upgrade" must be a not empty string.')
if self._hdrSent :
self._mws2.Log( 'Response headers already sent for request "%s".'
% self._request._path,
self._mws2.WARNING )
return
self.SetHeader('Connection', 'Upgrade')
self.SetHeader('Upgrade', upgrade)
data = self._makeBaseResponseHdr(101)
self._xasCli.AsyncSendData(data)
self._hdrSent = True
# ------------------------------------------------------------------------
def ReturnStream(self, code, stream) :
if not isinstance(code, int) or code <= 0 :
raise ValueError('"code" must be a positive integer.')
if not hasattr(stream, 'readinto') or not hasattr(stream, 'close') :
raise ValueError('"stream" must be a readable buffer protocol object.')
if self._hdrSent :
self._mws2.Log( 'Response headers already sent for request "%s".'
% self._request._path,
self._mws2.WARNING )
try :
stream.close()
except :
pass
return
if self._request._method != 'HEAD' :
self._stream = stream
self._sendingBuf = memoryview(self._xasCli.SendingBuffer)
self._xasCli.OnClosed = self._onClosed
else :
try :
stream.close()
except :
pass
if not self._contentType :
self._contentType = 'application/octet-stream'
if not self._contentLength :
self.SetHeader('Transfer-Encoding', 'chunked')
data = self._makeResponseHdr(code)
self._xasCli.AsyncSendData(data, onDataSent=self._onDataSent)
self._hdrSent = True
# ------------------------------------------------------------------------
def Return(self, code, content=None) :
if not isinstance(code, int) or code <= 0 :
raise ValueError('"code" must be a positive integer.')
if self._hdrSent :
self._mws2.Log( 'Response headers already sent for request "%s".'
% self._request._path,
self._mws2.WARNING )
return
if not content :
respCode = self._RESPONSE_CODES.get(code, ('Unknown reason', ''))
self._contentType = 'text/html'
content = self._CODE_CONTENT_TMPL % { 'code' : code,
'reason' : respCode[0],
'message' : respCode[1] }
if isinstance(content, str) :
content = content.encode('UTF-8')
if not self._contentType :
self._contentType = 'text/html'
self._contentCharset = 'UTF-8'
elif not self._contentType :
self._contentType = 'application/octet-stream'
self._contentLength = len(content)
data = self._makeResponseHdr(code)
if self._request._method != 'HEAD' :
data += bytes(content)
self._xasCli.AsyncSendData(data, onDataSent=self._onDataSent)
self._hdrSent = True
# ------------------------------------------------------------------------
def ReturnJSON(self, code, obj) :
if not isinstance(code, int) or code <= 0 :
raise ValueError('"code" must be a positive integer.')
self._contentType = 'application/json'
try :
content = json.dumps(obj)
except :
raise ValueError('"obj" cannot be converted into JSON format.')
self.Return(code, content)
# ------------------------------------------------------------------------
def ReturnOk(self, content=None) :
self.Return(200, content)
# ------------------------------------------------------------------------
def ReturnOkJSON(self, obj) :
self.ReturnJSON(200, obj)
# ------------------------------------------------------------------------
def ReturnFile(self, filename, attachmentName=None) :
if not isinstance(filename, str) or len(filename) == 0 :
raise ValueError('"filename" must be a not empty string.')
if attachmentName is not None and not isinstance(attachmentName, str) :
raise ValueError('"attachmentName" must be a string or None.')
try :
size = stat(filename)[6]
except :
self.ReturnNotFound()
return
try :
file = open(filename, 'rb')
except :
self.ReturnForbidden()
return
if attachmentName :
cd = 'attachment; filename="%s"' % attachmentName.replace('"', "'")
self.SetHeader('Content-Disposition', cd)
if not self._contentType :
self._contentType = self._mws2.GetMimeTypeFromFilename(filename)
self._contentLength = size
self.ReturnStream(200, file)
# ------------------------------------------------------------------------
def ReturnNotModified(self) :
self.Return(304)
# ------------------------------------------------------------------------
def ReturnRedirect(self, location) :
if not isinstance(location, str) or len(location) == 0 :
raise ValueError('"location" must be a not empty string.')
self.SetHeader('Location', location)
self.Return(307)
# ------------------------------------------------------------------------
def ReturnBadRequest(self) :
self.Return(400)
# ------------------------------------------------------------------------
def ReturnUnauthorized(self, typeName, realm=None) :
if not isinstance(typeName, str) or len(typeName) == 0 :
raise ValueError('"typeName" must be a not empty string.')
if realm is not None and not isinstance(realm, str) :
raise ValueError('"realm" must be a string or None.')
wwwAuth = typeName
if realm :
wwwAuth += (' realm="%s"' % realm.replace('"', "'")) if realm else ''
self.SetHeader('WWW-Authenticate', wwwAuth)
self.Return(401)
# ------------------------------------------------------------------------
def ReturnForbidden(self) :
self.Return(403)
# ------------------------------------------------------------------------
def ReturnNotFound(self) :
if self._mws2._notFoundURL :
self.ReturnRedirect(self._mws2._notFoundURL)
else :
self.Return(404)
# ------------------------------------------------------------------------
def ReturnMethodNotAllowed(self) :
self.Return(405)
# ------------------------------------------------------------------------
def ReturnEntityTooLarge(self) :
self.Return(413)
# ------------------------------------------------------------------------
def ReturnInternalServerError(self) :
self.Return(500)
# ------------------------------------------------------------------------
def ReturnNotImplemented(self) :
self.Return(501)
# ------------------------------------------------------------------------
def ReturnServiceUnavailable(self) :
self.Return(503)
# ------------------------------------------------------------------------
def ReturnBasicAuthRequired(self) :
self.ReturnUnauthorized('Basic')
# ------------------------------------------------------------------------
def ReturnBearerAuthRequired(self) :
self.ReturnUnauthorized('Bearer')
# ------------------------------------------------------------------------
@property
def Request(self) :
return self._request
# ------------------------------------------------------------------------
@property
def UserAddress(self) :
return self._xasCli.CliAddr
# ------------------------------------------------------------------------
@property
def IsSSL(self) :
return self._xasCli.IsSSL
# ------------------------------------------------------------------------
@property
def AllowCaching(self) :
return self._allowCaching
@AllowCaching.setter
def AllowCaching(self, value) :
if not isinstance(value, bool) :
raise ValueError('"AllowCaching" must be a boolean.')
self._allowCaching = value
# ------------------------------------------------------------------------
@property
def AccessControlAllowOrigin(self) :
return self._acAllowOrigin
@AccessControlAllowOrigin.setter
def AccessControlAllowOrigin(self, value) :
if value is not None and not isinstance(value, str) :
raise ValueError('"AccessControlAllowOrigin" must be a string or None.')
self._acAllowOrigin = value
# ------------------------------------------------------------------------
@property
def ContentType(self) :
return self._contentType
@ContentType.setter
def ContentType(self, value) :
if value is not None and not isinstance(value, str) :
raise ValueError('"ContentType" must be a string or None.')
self._contentType = value
# ------------------------------------------------------------------------
@property
def ContentCharset(self) :
return self._contentCharset
@ContentCharset.setter
def ContentCharset(self, value) :
if value is not None and not isinstance(value, str) :
raise ValueError('"ContentCharset" must be a string or None.')
self._contentCharset = value
# ------------------------------------------------------------------------
@property
def ContentLength(self) :
return self._contentLength
@ContentLength.setter
def ContentLength(self, value) :
if not isinstance(value, int) or value < 0 :
raise ValueError('"ContentLength" must be a positive integer or zero.')
self._contentLength = value
# ------------------------------------------------------------------------
@property
def HeadersSent(self) :
return self._hdrSent
# ------------------------------------------------------------------------
@property
def OnSent(self) :
return self._onSent
@OnSent.setter
def OnSent(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnSent" must be a function.')
self._onSent = value
# ============================================================================
# ============================================================================
# ============================================================================
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,218 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
class UrlUtils :
# ----------------------------------------------------------------------------
@staticmethod
def Quote(s, safe='/') :
r = ''
for c in str(s) :
if (c >= 'a' and c <= 'z') or \
(c >= '0' and c <= '9') or \
(c >= 'A' and c <= 'Z') or \
(c in '.-_') or (c in safe) :
r += c
else :
for b in c.encode('UTF-8') :
r += '%%%02X' % b
return r
# ----------------------------------------------------------------------------
@staticmethod
def UrlEncode(s) :
return UrlUtils.Quote(s, ';/?:@&=+$,')
# ----------------------------------------------------------------------------
@staticmethod
def Unquote(s) :
r = str(s).split('%')
try :
b = r[0].encode()
for i in range(1, len(r)) :
try :
b += bytes([int(r[i][:2], 16)]) + r[i][2:].encode()
except :
b += b'%' + r[i].encode()
return b.decode('UTF-8')
except :
return str(s)
# ----------------------------------------------------------------------------
@staticmethod
def UnquotePlus(s) :
return UrlUtils.Unquote(str(s).replace('+', ' '))
# ============================================================================
# ===( Class Url )============================================================
# ============================================================================
class Url :
def __init__(self, url='') :
self.URL = url
# ------------------------------------------------------------------------
def __repr__(self) :
return self.URL if self.URL is not None else ''
# ------------------------------------------------------------------------
def IsHttps(self) :
return (self._proto == 'https')
# ------------------------------------------------------------------------
@property
def URL(self) :
host = self.Host
if host != '' :
proto = self.Proto
port = self.Port
if ( proto == 'http' and port == 80 ) or \
( proto == 'https' and port == 443 ) :
port = ''
else :
port = ':' + str(port)
url = proto + '://' + host + port + self.Path
url = UrlUtils.UrlEncode(url)
qs = self.QueryString
if qs != '' :
return url + '?' + qs
return url
return None
@URL.setter
def URL(self, value) :
try :
s = str(value)
if '://' in s :
proto, s = s.split('://', 1)
else :
proto = 'http'
except :
raise ValueError('URL error (%s)' % value)
self.Proto = proto
if '/' in s :
host, path = s.split('/', 1)
elif '?' in s :
host, path = s.split('?', 1)
path = '?' + path
else :
host = s
path = ''
if ':' in host :
try :
host, port = host.split(':')
self.Port = port
except :
raise ValueError('URL host:port error (%s)' % host)
self.Host = host
self._queryParams = { }
self.Path = path
# ------------------------------------------------------------------------
@property
def Proto(self) :
return self._proto
@Proto.setter
def Proto(self, value) :
value = str(value).lower()
if value == 'http' :
self._port = 80
elif value == 'https' :
self._port = 443
else :
raise ValueError('Unsupported URL protocol (%s)' % value)
self._proto = value
# ------------------------------------------------------------------------
@property
def Host(self) :
return self._host
@Host.setter
def Host(self, value) :
self._host = UrlUtils.UnquotePlus(value)
# ------------------------------------------------------------------------
@property
def Port(self) :
return self._port
@Port.setter
def Port(self, value) :
try :
p = int(value)
except :
raise ValueError('Port must be an integer value')
if p <= 0 or p >= 65536 :
raise ValueError('Port must be greater than 0 and less than 65536')
self._port = p
# ------------------------------------------------------------------------
@property
def Path(self) :
return self._path
@Path.setter
def Path(self, value) :
x = value.split('?', 1)
if len(x[0]) > 0 :
if x[0][0] != '/' :
x[0] = '/' + x[0]
self._path = UrlUtils.UnquotePlus(x[0])
else :
self._path = '/'
if len(x) == 2 :
self.QueryString = x[1]
# ------------------------------------------------------------------------
@property
def QueryString(self) :
r = ''
for param in self._queryParams :
if param != '' :
if r != '' :
r += '&'
r += UrlUtils.Quote(param) + '=' + UrlUtils.Quote(self._queryParams[param])
return r
@QueryString.setter
def QueryString(self, value) :
self._queryParams = { }
for x in value.split('&') :
param = x.split('=', 1)
if param[0] != '' :
value = UrlUtils.Unquote(param[1]) if len(param) > 1 else ''
self._queryParams[UrlUtils.Unquote(param[0])] = value
# ------------------------------------------------------------------------
@property
def QueryParams(self) :
return self._queryParams
@QueryParams.setter
def QueryParams(self, value) :
if not isinstance(value, dict) :
raise ValueError('QueryParams must be a dict')
self._queryParams = value
# ============================================================================
# ============================================================================
# ============================================================================
@@ -0,0 +1,544 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from . import *
from .httpRequest import HttpRequest
from os import stat
from sys import implementation
from _thread import stack_size
# ============================================================================
# ===( MicroWebSrv2 )=========================================================
# ============================================================================
class MicroWebSrv2Exception(Exception) :
pass
# ----------------------------------------------------------------------------
class MicroWebSrv2 :
_DEFAULT_PAGES = [
"index.html",
"index.htm",
"default.html",
"default.htm"
]
_MIME_TYPES = {
".txt" : "text/plain",
".htm" : "text/html",
".html" : "text/html",
".css" : "text/css",
".csv" : "text/csv",
".js" : "application/javascript",
".xml" : "application/xml",
".xhtml" : "application/xhtml+xml",
".json" : "application/json",
".zip" : "application/zip",
".pdf" : "application/pdf",
".ts" : "application/typescript",
".woff" : "font/woff",
".woff2" : "font/woff2",
".ttf" : "font/ttf",
".otf" : "font/otf",
".jpg" : "image/jpeg",
".jpeg" : "image/jpeg",
".png" : "image/png",
".gif" : "image/gif",
".svg" : "image/svg+xml",
".ico" : "image/x-icon"
}
_HTML_ESCAPE_CHARS = {
"&" : "&amp;",
'"' : "&quot;",
"'" : "&apos;",
">" : "&gt;",
"<" : "&lt;"
}
_STAT_MODE_DIR = 1 << 14
DEBUG = 0x00
INFO = 0x01
WARNING = 0x02
ERROR = 0x03
MSG_TYPE_STR = {
DEBUG : 'DEBUG',
INFO : 'INFO',
WARNING : 'WARNING',
ERROR : 'ERROR'
}
# ------------------------------------------------------------------------
_modules = { }
# ------------------------------------------------------------------------
def __init__(self) :
self._backlog = None
self._slotsCount = None
self._slotsSize = None
self._keepAlloc = None
self._maxContentLen = None
self._bindAddr = ('0.0.0.0', 80)
self._sslContext = None
self._rootPath = 'www'
self._timeoutSec = 2
self._notFoundURL = None
self._allowAllOrigins = False
self._corsAllowAll = False
self._onLogging = None
self._xasSrv = None
self._xasPool = None
self.SetNormalConfig()
# ------------------------------------------------------------------------
@staticmethod
def _physPathExists(physPath) :
try :
stat(physPath)
return True
except :
return False
# ------------------------------------------------------------------------
@staticmethod
def _physPathIsDir(physPath) :
return (stat(physPath)[0] & MicroWebSrv2._STAT_MODE_DIR != 0)
# ------------------------------------------------------------------------
@staticmethod
def LoadModule(modName) :
if not isinstance(modName, str) or len(modName) == 0 :
raise ValueError('"modName" must be a not empty string.')
if modName in MicroWebSrv2._modules :
raise MicroWebSrv2Exception('Module "%s" is already loaded.' % modName)
try :
modPath = MicroWebSrv2.__module__.split('microWebSrv2')[0] \
+ ('mods.%s' % modName)
print('loadmod',modPath)
module = getattr(__import__(modPath).mods, modName)
modClass = getattr(module, modName)
if type(modClass) is not type :
raise Exception
modInstance = modClass()
MicroWebSrv2._modules[modName] = modInstance
return modInstance
except :
raise MicroWebSrv2Exception('Cannot load module "%s".' % modName)
# ------------------------------------------------------------------------
@staticmethod
def HTMLEscape(s) :
if not isinstance(s, str) :
raise ValueError('"s" must be a string.')
return ''.join(MicroWebSrv2._HTML_ESCAPE_CHARS.get(c, c) for c in s)
# ------------------------------------------------------------------------
@staticmethod
def AddDefaultPage(filename) :
if not isinstance(filename, str) or len(filename) == 0 :
raise ValueError('"filename" must be a not empty string.')
MicroWebSrv2._DEFAULT_PAGES.append(filename)
# ------------------------------------------------------------------------
@staticmethod
def AddMimeType(ext, mimeType) :
if not isinstance(ext, str) or len(ext) == 0 :
raise ValueError('"ext" must be a not empty string.')
if not isinstance(mimeType, str) or len(mimeType) == 0 :
raise ValueError('"mimeType" must be a not empty string.')
MicroWebSrv2._MIME_TYPES[ext.lower()] = mimeType.lower()
# ------------------------------------------------------------------------
@staticmethod
def GetMimeTypeFromFilename(filename) :
filename = filename.lower()
for ext in MicroWebSrv2._MIME_TYPES :
if filename.endswith(ext) :
return MicroWebSrv2._MIME_TYPES[ext]
return None
# ------------------------------------------------------------------------
def StartInPool(self, asyncSocketsPool) :
if not isinstance(asyncSocketsPool, XAsyncSocketsPool) :
raise ValueError('"asyncSocketsPool" must be a XAsyncSocketsPool class.')
if self._xasSrv :
raise MicroWebSrv2Exception('Server is already running.')
try :
xBufSlots = XBufferSlots( slotsCount = self._slotsCount,
slotsSize = self._slotsSize,
keepAlloc = self._keepAlloc )
except :
raise MicroWebSrv2Exception('Not enough memory to allocate slots.')
try :
self._xasSrv = XAsyncTCPServer.Create( asyncSocketsPool = asyncSocketsPool,
srvAddr = self._bindAddr,
srvBacklog = self._backlog,
bufSlots = xBufSlots )
except :
raise MicroWebSrv2Exception('Cannot bind server on %s:%s.' % self._bindAddr)
self._xasSrv.OnClientAccepted = self._onSrvClientAccepted
self._xasSrv.OnClosed = self._onSrvClosed
self.Log('Server listening on %s:%s.' % self._bindAddr, MicroWebSrv2.INFO)
# ------------------------------------------------------------------------
def StartManaged(self, parllProcCount=1, procStackSize=0) :
if not isinstance(parllProcCount, int) or parllProcCount < 0 :
raise ValueError('"parllProcCount" must be a positive integer or zero.')
if not isinstance(procStackSize, int) or procStackSize < 0 :
raise ValueError('"procStackSize" must be a positive integer or zero.')
if self._xasSrv :
raise MicroWebSrv2Exception('Server is already running.')
if procStackSize == 0 and implementation.name == 'micropython' :
procStackSize = 8*1024
try :
saveStackSize = stack_size(procStackSize)
except Exception as ex :
raise ValueError('"procStackSize" of %s is not correct (%s).' % (procStackSize, ex))
self._xasPool = XAsyncSocketsPool()
try :
self.StartInPool(self._xasPool)
try :
self.Log('Starts the managed pool to wait for I/O events.', MicroWebSrv2.INFO)
self._xasPool.AsyncWaitEvents(threadsCount=parllProcCount)
except :
raise MicroWebSrv2Exception('Not enough memory to start %s parallel processes.' % parllProcCount)
except Exception as ex :
self.Stop()
raise ex
finally :
try :
stack_size(saveStackSize)
except :
pass
# ------------------------------------------------------------------------
def Stop(self) :
if self._xasSrv :
self._xasSrv.Close()
self._xasSrv = None
if self._xasPool :
self.Log('Stops the managed pool.', MicroWebSrv2.INFO)
self._xasPool.StopWaitEvents()
self._xasPool = None
# ------------------------------------------------------------------------
def Log(self, msg, msgType) :
if self._onLogging :
try :
self._onLogging(self, str(msg), msgType)
return
except Exception as ex :
msgType = MicroWebSrv2.ERROR
msg = 'Exception raised from "OnLoggin" handler: %s' % ex
t = MicroWebSrv2.MSG_TYPE_STR.get(msgType, None)
if t :
print('MWS2-%s> %s' % (t, msg))
# ------------------------------------------------------------------------
def ResolvePhysicalPath(self, urlPath) :
if not isinstance(urlPath, str) or len(urlPath) == 0 :
raise ValueError('"urlPath" must be a not empty string.')
try :
physPath = self._rootPath + urlPath.replace('..', '/')
if physPath.endswith('/') :
physPath = physPath[:-1]
if MicroWebSrv2._physPathIsDir(physPath) :
for filename in MicroWebSrv2._DEFAULT_PAGES :
p = physPath + '/' + filename
if MicroWebSrv2._physPathExists(p) :
return p
return physPath
except :
return None
# ------------------------------------------------------------------------
def _onSrvClientAccepted(self, xAsyncTCPServer, xAsyncTCPClient) :
if self._sslContext :
try :
xAsyncTCPClient.StartSSLContext( sslContext = self._sslContext,
serverSide = True )
except :
self.Log( 'SSL connection failed from %s:%s.'
% xAsyncTCPClient.CliAddr,
MicroWebSrv2.DEBUG )
xAsyncTCPClient.Close()
return
HttpRequest(self, xAsyncTCPClient)
# ------------------------------------------------------------------------
def _onSrvClosed(self, xAsyncTCPServer, closedReason) :
self.Log('Server %s:%s closed.' % self._bindAddr, MicroWebSrv2.INFO)
# ------------------------------------------------------------------------
def _validateChangeConf(self, name='Configuration') :
if self._xasSrv :
raise MicroWebSrv2Exception('%s cannot be changed while the server is running.' % name)
# ------------------------------------------------------------------------
def EnableSSL(self, certFile, keyFile, caFile=None) :
import ssl
if not hasattr(ssl, 'SSLContext') :
raise MicroWebSrv2Exception('Unable to use SSL (implementation not supported).')
if not isinstance(certFile, str) or len(certFile) == 0 :
raise ValueError('"certFile" must be a not empty string.')
if not isinstance(keyFile, str) or len(keyFile) == 0 :
raise ValueError('"keyFile" must be a not empty string.')
if caFile is not None and not isinstance(caFile, str) :
raise ValueError('"caFile" must be a string or None.')
self._validateChangeConf()
try :
ctx = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH,
cafile = caFile )
except :
raise ValueError('"caFile" must indicate a valid PEM file.')
try :
ctx.load_cert_chain(certfile=certFile, keyfile=keyFile)
except :
raise ValueError('"certFile" and "keyFile" must indicate the valid certificate and key files.')
self._sslContext = ctx
if self._bindAddr[1] == 80 :
self._bindAddr = (self._bindAddr[0], 443)
# ------------------------------------------------------------------------
def DisableSSL(self) :
self._validateChangeConf()
self._sslContext = None
if self._bindAddr[1] == 443 :
self._bindAddr = (self._bindAddr[0], 80)
# ------------------------------------------------------------------------
def SetEmbeddedConfig(self) :
self._validateChangeConf()
self._backlog = 8
self._slotsCount = 16
self._slotsSize = 1024
self._keepAlloc = True
self._maxContentLen = 16*1024
# ------------------------------------------------------------------------
def SetLightConfig(self) :
self._validateChangeConf()
self._backlog = 64
self._slotsCount = 128
self._slotsSize = 1024
self._keepAlloc = True
self._maxContentLen = 512*1024
# ------------------------------------------------------------------------
def SetNormalConfig(self) :
self._validateChangeConf()
self._backlog = 256
self._slotsCount = 512
self._slotsSize = 4*1024
self._keepAlloc = True
self._maxContentLen = 2*1024*1024
# ------------------------------------------------------------------------
def SetLargeConfig(self) :
self._validateChangeConf()
self._backlog = 512
self._slotsCount = 2048
self._slotsSize = 16*1024
self._keepAlloc = True
self._maxContentLen = 8*1024*1024
# ------------------------------------------------------------------------
@property
def IsRunning(self) :
return ( self._xasPool is not None and \
self._xasPool.WaitEventsProcessing and \
self._xasSrv is not None )
# ------------------------------------------------------------------------
@property
def ConnQueueCapacity(self) :
return self._backlog
@ConnQueueCapacity.setter
def ConnQueueCapacity(self, value) :
if not isinstance(value, int) or value <= 0 :
raise ValueError('"ConnQueueCapacity" must be a positive integer.')
self._validateChangeConf('"ConnQueueCapacity"')
self._backlog = value
# ------------------------------------------------------------------------
@property
def BufferSlotsCount(self) :
return self._slotsCount
@BufferSlotsCount.setter
def BufferSlotsCount(self, value) :
if not isinstance(value, int) or value <= 0 :
raise ValueError('"BufferSlotsCount" must be a positive integer.')
self._validateChangeConf('"BufferSlotsCount"')
self._slotsCount = value
# ------------------------------------------------------------------------
@property
def BufferSlotSize(self) :
return self._slotsSize
@BufferSlotSize.setter
def BufferSlotSize(self, value) :
if not isinstance(value, int) or value <= 0 :
raise ValueError('"BufferSlotSize" must be a positive integer.')
self._validateChangeConf('"BufferSlotSize"')
self._slotsSize = value
# ------------------------------------------------------------------------
@property
def KeepAllocBufferSlots(self) :
return self._keepAlloc
@KeepAllocBufferSlots.setter
def KeepAllocBufferSlots(self, value) :
if not isinstance(value, bool) :
raise ValueError('"KeepAllocBufferSlots" must be a boolean.')
self._validateChangeConf('"KeepAllocBufferSlots"')
self._keepAlloc = value
# ------------------------------------------------------------------------
@property
def MaxRequestContentLength(self) :
return self._maxContentLen
@MaxRequestContentLength.setter
def MaxRequestContentLength(self, value) :
if not isinstance(value, int) or value <= 0 :
raise ValueError('"MaxRequestContentLength" must be a positive integer.')
self._maxContentLen = value
# ------------------------------------------------------------------------
@property
def BindAddress(self) :
return self._bindAddr
@BindAddress.setter
def BindAddress(self, value) :
if not value or len(value) != 2 or \
not isinstance(value[0], str) or \
not isinstance(value[1], int) :
raise ValueError('"BindAddress" must be a tuple of (ipAddr, tcpPort).')
if value[1] < 1 or value[1] > 65535 :
raise ValueError('"BindAddress" has an incorrect port number.')
self._validateChangeConf('"BindAddress"')
self._bindAddr = value
# ------------------------------------------------------------------------
@property
def IsSSLEnabled(self) :
return (self._sslContext is not None)
# ------------------------------------------------------------------------
@property
def RootPath(self) :
return self._rootPath
@RootPath.setter
def RootPath(self, value) :
if not isinstance(value, str) or len(value) == 0 :
raise ValueError('"RootPath" must be a not empty string.')
self._validateChangeConf('"RootPath"')
self._rootPath = (value[:-1] if value.endswith('/') else value)
# ------------------------------------------------------------------------
@property
def RequestsTimeoutSec(self) :
return self._timeoutSec
@RequestsTimeoutSec.setter
def RequestsTimeoutSec(self, value) :
if not isinstance(value, int) or value <= 0 :
raise ValueError('"RequestsTimeoutSec" must be a positive integer.')
self._timeoutSec = value
# ------------------------------------------------------------------------
@property
def NotFoundURL(self) :
return self._notFoundURL
@NotFoundURL.setter
def NotFoundURL(self, value) :
if value is not None and not isinstance(value, str) :
raise ValueError('"NotFoundURL" must be a string or None.')
self._notFoundURL = value
# ------------------------------------------------------------------------
@property
def AllowAllOrigins(self) :
return self._allowAllOrigins
@AllowAllOrigins.setter
def AllowAllOrigins(self, value) :
if not isinstance(value, bool) :
raise ValueError('"AllowAllOrigins" must be a boolean.')
self._allowAllOrigins = value
# ------------------------------------------------------------------------
@property
def CORSAllowAll(self) :
return self._corsAllowAll
@CORSAllowAll.setter
def CORSAllowAll(self, value) :
if not isinstance(value, bool) :
raise ValueError('"CORSAllowAll" must be a boolean.')
self._corsAllowAll = value
# ------------------------------------------------------------------------
@property
def OnLogging(self) :
return self._onLogging
@OnLogging.setter
def OnLogging(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnLogging" must be a function.')
self._onLogging = value
# ============================================================================
# ============================================================================
# ============================================================================
@@ -0,0 +1,394 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from os import stat
import re
# ============================================================================
# ===( MicroWebSrv2 : PyhtmlTemplate Module )=================================
# ============================================================================
class PyhtmlTemplate :
_CODE_CONTENT_DEBUG = """\
<html>
<head>
<title>MicroWebSrv2</title>
</head>
<body style="font-family: Verdana; background-color: Black; color: White;">
<h2>MicroWebSrv2 - [500] Internal Server Error</h2>
<div style="margin: 20px;">
<h3>PyhtmlTemplate Module Debug</h3>
<div style="padding: 15px; background-color: Crimson;">
Exception in %(path)s<br />
%(message)s
</div>
</div>
</body>
</html>
"""
# ------------------------------------------------------------------------
def __init__(self) :
self._showDebug = False
self._pyGlobalVars = { }
# ------------------------------------------------------------------------
def OnRequest(self, microWebSrv2, request) :
if (request.Method == 'GET' or request.Method == 'HEAD') and \
request.Path.lower().endswith('.pyhtml') :
filepath = microWebSrv2.ResolvePhysicalPath(request.Path)
self.ReturnTemplate(microWebSrv2, request, filepath)
# ------------------------------------------------------------------------
def ReturnTemplate(self, microWebSrv2, request, filepath):
if not filepath:
request.Response.ReturnNotFound()
return
try :
with open(filepath, 'r') as file :
code = file.read()
except :
request.Response.ReturnForbidden()
return
try :
self._pyGlobalVars['Request'] = request
codeTemplate = CodeTemplate(code, microWebSrv2.HTMLEscape)
content = codeTemplate.Execute(self._pyGlobalVars, None)
request.Response.ReturnOk(content)
except Exception as ex :
microWebSrv2.Log( 'Exception raised from pyhtml template file "%s": %s' % (filepath, ex),
microWebSrv2.ERROR )
if self._showDebug :
request.Response.Return( 500,
PyhtmlTemplate._CODE_CONTENT_DEBUG
% { 'path' : filepath,
'message' : ex } )
else :
request.Response.ReturnInternalServerError()
# ------------------------------------------------------------------------
def SetGlobalVar(self, globalVarName, globalVar) :
if not isinstance(globalVarName, str) or len(globalVarName) == 0 :
raise ValueError('"globalVarName" must be a not empty string.')
self._pyGlobalVars[globalVarName] = globalVar
# ------------------------------------------------------------------------
def GetGlobalVar(self, globalVarName) :
if not isinstance(globalVarName, str) or len(globalVarName) == 0 :
raise ValueError('"globalVarName" must be a not empty string.')
try :
return self._pyGlobalVars[globalVarName]
except :
return None
# ------------------------------------------------------------------------
@property
def ShowDebug(self) :
return self._showDebug
@ShowDebug.setter
def ShowDebug(self, value) :
if not isinstance(value, bool) :
raise ValueError('"ShowDebug" must be a boolean.')
self._showDebug = value
# ============================================================================
# ===( CodeTemplate )=========================================================
# ============================================================================
class CodeTemplateException(Exception) :
pass
class CodeTemplate :
# ------------------------------------------------------------------------
TOKEN_OPEN = '{{'
TOKEN_CLOSE = '}}'
TOKEN_OPEN_LEN = len(TOKEN_OPEN)
TOKEN_CLOSE_LEN = len(TOKEN_CLOSE)
INSTRUCTION_PYTHON = 'py'
INSTRUCTION_IF = 'if'
INSTRUCTION_ELIF = 'elif'
INSTRUCTION_ELSE = 'else'
INSTRUCTION_FOR = 'for'
INSTRUCTION_END = 'end'
RE_IDENTIFIER = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$')
# ------------------------------------------------------------------------
def __init__(self, code, escapeStrFunc=None) :
self._code = code
self._escapeStrFunc = escapeStrFunc
self._pos = 0
self._endPos = len(code)-1
self._line = 1
self._pyGlobalVars = { }
self._pyLocalVars = { }
self._rendered = ''
self._instructions = {
CodeTemplate.INSTRUCTION_PYTHON : self._processInstructionPYTHON,
CodeTemplate.INSTRUCTION_IF : self._processInstructionIF,
CodeTemplate.INSTRUCTION_ELIF : self._processInstructionELIF,
CodeTemplate.INSTRUCTION_ELSE : self._processInstructionELSE,
CodeTemplate.INSTRUCTION_FOR : self._processInstructionFOR,
CodeTemplate.INSTRUCTION_END : self._processInstructionEND
}
# ------------------------------------------------------------------------
def Validate(self, pyGlobalVars=None, pyLocalVars=None) :
try :
self._parseCode(pyGlobalVars, pyLocalVars, execute=False)
return None
except Exception as ex :
return str(ex)
# ----------------------------------------------------------------------------
def Execute(self, pyGlobalVars=None, pyLocalVars=None) :
try :
self._parseCode(pyGlobalVars, pyLocalVars, execute=True)
return self._rendered
except Exception as ex :
raise CodeTemplateException(str(ex))
# ------------------------------------------------------------------------
def _parseCode(self, pyGlobalVars, pyLocalVars, execute) :
self._pos = 0
self._line = 1
self._pyGlobalVars = (pyGlobalVars if isinstance(pyGlobalVars, dict) else { })
self._pyLocalVars = (pyLocalVars if isinstance(pyLocalVars, dict) else { })
self._rendered = ''
self._pyGlobalVars['print'] = self._renderingPrint
newTokenToProcess = self._parseBloc(execute)
if newTokenToProcess is not None :
raise CodeTemplateException( '"%s" instruction is not valid here (line %s)'
% (newTokenToProcess, self._line) )
# ------------------------------------------------------------------------
def _parseBloc(self, execute) :
while True :
idx = self._code.find(CodeTemplate.TOKEN_OPEN, self._pos)
end = (idx < 0)
if end :
idx = self._endPos+1
code = self._code[self._pos:idx]
self._line += code.count('\n')
if execute :
self._rendered += code
if end :
self._pos = idx
return None
self._pos = idx + CodeTemplate.TOKEN_OPEN_LEN
idx = self._code.find(CodeTemplate.TOKEN_CLOSE, self._pos)
if idx < 0 :
raise CodeTemplateException('"%s" is required but the end of code has been found' % CodeTemplate.TOKEN_CLOSE)
tokenContent = self._code[self._pos:idx].strip()
self._line += tokenContent.count('\n')
self._pos = idx + CodeTemplate.TOKEN_CLOSE_LEN
newTokenToProcess = self._processToken(tokenContent, execute)
if newTokenToProcess is not None :
return newTokenToProcess
# ------------------------------------------------------------------------
def _renderingPrint(self, s) :
self._rendered += str(s)
# ------------------------------------------------------------------------
def _processToken(self, tokenContent, execute) :
parts = tokenContent.split(' ', 1)
instructName = parts[0].strip()
instructBody = parts[1].strip() if len(parts) > 1 else None
if len(instructName) == 0 :
raise CodeTemplateException( '"%s %s" : instruction is missing (line %s)'
% (CodeTemplate.TOKEN_OPEN, CodeTemplate.TOKEN_CLOSE, self._line) )
newTokenToProcess = None
if instructName in self._instructions :
newTokenToProcess = self._instructions[instructName](instructBody, execute)
elif execute :
try :
ret = eval( tokenContent,
self._pyGlobalVars,
self._pyLocalVars )
if ret is not None :
if (self._escapeStrFunc is not None) :
self._rendered += self._escapeStrFunc(str(ret))
else :
self._rendered += str(ret)
except Exception as ex :
raise CodeTemplateException('%s (line %s)' % (ex, self._line))
return newTokenToProcess
# ------------------------------------------------------------------------
def _processInstructionPYTHON(self, instructionBody, execute) :
if instructionBody is not None :
raise CodeTemplateException( 'Instruction "%s" is invalid (line %s)'
% (CodeTemplate.INSTRUCTION_PYTHON, self._line) )
idx = self._code.find(CodeTemplate.TOKEN_OPEN, self._pos)
if idx < 0 :
raise CodeTemplateException('"%s" is required but the end of code has been found' % CodeTemplate.TOKEN_OPEN)
pyCode = self._code[self._pos:idx]
self._line += pyCode.count('\n')
self._pos = idx + CodeTemplate.TOKEN_OPEN_LEN
idx = self._code.find(CodeTemplate.TOKEN_CLOSE, self._pos)
if idx < 0 :
raise CodeTemplateException('"%s" is required but the end of code has been found' % CodeTemplate.TOKEN_CLOSE)
tokenContent = self._code[self._pos:idx].strip()
self._line += tokenContent.count('\n')
self._pos = idx + CodeTemplate.TOKEN_CLOSE_LEN
if tokenContent != CodeTemplate.INSTRUCTION_END :
raise CodeTemplateException( '"%s" is a bad instruction in a python bloc (line %s)'
% (tokenContent, self._line) )
if execute :
lines = pyCode.split('\n')
indent = ''
for line in lines :
if len(line.strip()) > 0 :
for c in line :
if c == ' ' or c == '\t' :
indent += c
else :
break
break
indentLen = len(indent)
for i in range(len(lines)) :
if lines[i].startswith(indent) :
lines[i] = lines[i][indentLen:] + '\n'
else :
lines[i] += '\n'
pyCode = ''.join(lines)
try :
exec(pyCode, self._pyGlobalVars, self._pyLocalVars)
except Exception as ex :
raise CodeTemplateException('%s (line %s)' % (ex, self._line))
return None
# ------------------------------------------------------------------------
def _processInstructionIF(self, instructionBody, execute) :
if instructionBody is not None :
if execute :
try :
if (' ' not in instructionBody) and \
('=' not in instructionBody) and \
('<' not in instructionBody) and \
('>' not in instructionBody) and \
(instructionBody not in self._pyGlobalVars) and \
(instructionBody not in self._pyLocalVars):
result = False
else:
result = bool(eval(instructionBody, self._pyGlobalVars, self._pyLocalVars))
except Exception as ex :
raise CodeTemplateException('%s (line %s)' % (ex, self._line))
else :
result = False
newTokenToProcess = self._parseBloc(execute and result)
if newTokenToProcess is not None :
if newTokenToProcess == CodeTemplate.INSTRUCTION_END :
return None
elif newTokenToProcess == CodeTemplate.INSTRUCTION_ELSE :
newTokenToProcess = self._parseBloc(execute and not result)
if newTokenToProcess is not None :
if newTokenToProcess == CodeTemplate.INSTRUCTION_END :
return None
raise CodeTemplateException( '"%s" instruction waited (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
raise CodeTemplateException( '"%s" instruction is missing (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
elif newTokenToProcess == CodeTemplate.INSTRUCTION_ELIF :
self._processInstructionIF(self._elifInstructionBody, execute and not result)
return None
raise CodeTemplateException( '"%s" instruction waited (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
raise CodeTemplateException( '"%s" instruction is missing (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
raise CodeTemplateException( '"%s" alone is an incomplete syntax (line %s)'
% (CodeTemplate.INSTRUCTION_IF, self._line) )
# ------------------------------------------------------------------------
def _processInstructionELIF(self, instructionBody, execute) :
if instructionBody is None :
raise CodeTemplateException( '"%s" alone is an incomplete syntax (line %s)'
% (CodeTemplate.INSTRUCTION_ELIF, self._line) )
self._elifInstructionBody = instructionBody
return CodeTemplate.INSTRUCTION_ELIF
# ------------------------------------------------------------------------
def _processInstructionELSE(self, instructionBody, execute) :
if instructionBody is not None :
raise CodeTemplateException( 'Instruction "%s" is invalid (line %s)'
% (CodeTemplate.INSTRUCTION_ELSE, self._line) )
return CodeTemplate.INSTRUCTION_ELSE
# ------------------------------------------------------------------------
def _processInstructionFOR(self, instructionBody, execute) :
if instructionBody is not None :
parts = instructionBody.split(' ', 1)
identifier = parts[0].strip()
if CodeTemplate.RE_IDENTIFIER.match(identifier) is not None and len(parts) > 1 :
parts = parts[1].strip().split(' ', 1)
if parts[0] == 'in' and len(parts) > 1 :
expression = parts[1].strip()
newTokenToProcess = None
beforePos = self._pos
if execute :
try :
result = eval(expression, self._pyGlobalVars, self._pyLocalVars)
except :
raise CodeTemplateException('%s (line %s)' % (str(expression), self._line))
if execute and len(result) > 0 :
for x in result :
self._pyLocalVars[identifier] = x
self._pos = beforePos
newTokenToProcess = self._parseBloc(True)
if newTokenToProcess != CodeTemplate.INSTRUCTION_END :
break
else :
newTokenToProcess = self._parseBloc(False)
if newTokenToProcess is not None :
if newTokenToProcess == CodeTemplate.INSTRUCTION_END :
return None
raise CodeTemplateException( '"%s" instruction waited (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
raise CodeTemplateException( '"%s" instruction is missing (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
raise CodeTemplateException( '"%s %s" is an invalid syntax'
% (CodeTemplate.INSTRUCTION_FOR, instructionBody) )
raise CodeTemplateException( '"%s" alone is an incomplete syntax (line %s)'
% (CodeTemplate.INSTRUCTION_FOR, self._line) )
# ------------------------------------------------------------------------
def _processInstructionEND(self, instructionBody, execute) :
if instructionBody is not None :
raise CodeTemplateException( 'Instruction "%s" is invalid (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
return CodeTemplate.INSTRUCTION_END
# ============================================================================
# ============================================================================
# ============================================================================
@@ -0,0 +1,477 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from hashlib import sha1
from binascii import b2a_base64
from struct import pack
# ============================================================================
# ===( MicroWebSrv2 : WebSockets Module )=====================================
# ============================================================================
class WebSockets :
_PROTOCOL_VERSION = 13
_HANDSHAKE_SIGN = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
# ------------------------------------------------------------------------
def __init__(self) :
self._onWebSocketProtocol = None
self._onWebSocketAccepted = None
# ------------------------------------------------------------------------
def OnRequest(self, microWebSrv2, request) :
if request.IsUpgrade and request.Upgrade.lower() == 'websocket' :
ver = request.GetHeader('Sec-Websocket-Version')
if ver == str(WebSockets._PROTOCOL_VERSION) :
response = request.Response
key = request.GetHeader('Sec-Websocket-Key')
if key :
try :
key += WebSockets._HANDSHAKE_SIGN
sec = sha1(key.encode()).digest()
sec = b2a_base64(sec).decode().strip()
protocols = request.GetHeader('Sec-WebSocket-Protocol')
response.SetHeader('Sec-WebSocket-Accept', sec)
if protocols and self._onWebSocketProtocol :
protocols = [x.strip() for x in protocols.split(',')]
try :
proto = self._onWebSocketProtocol(microWebSrv2, protocols)
except Exception as ex :
microWebSrv2.Log( 'Exception raised from "WebSockets.OnWebSocketProtocol" handler: %s' % ex,
microWebSrv2.ERROR )
raise ex
if proto in protocols :
response.SetHeader('Sec-WebSocket-Protocol', proto)
response.SwitchingProtocols('websocket')
WebSocket(self, microWebSrv2, request)
except :
response.ReturnInternalServerError()
else :
response.ReturnBadRequest()
# ------------------------------------------------------------------------
@property
def OnWebSocketProtocol(self) :
return self._onWebSocketProtocol
@OnWebSocketProtocol.setter
def OnWebSocketProtocol(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnWebSocketProtocol" must be a function.')
self._onWebSocketProtocol = value
# ------------------------------------------------------------------------
@property
def OnWebSocketAccepted(self) :
return self._onWebSocketAccepted
@OnWebSocketAccepted.setter
def OnWebSocketAccepted(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnWebSocketAccepted" must be a function.')
self._onWebSocketAccepted = value
# ============================================================================
# ===( WebSocket )============================================================
# ============================================================================
class WebSocket :
_OP_FRAME_CONT = 0x00
_OP_FRAME_TEXT = 0x01
_OP_FRAME_BIN = 0x02
_OP_FRAME_CLOSE = 0x08
_OP_FRAME_PING = 0x09
_OP_FRAME_PONG = 0x0A
_MSG_TYPE_TEXT = 0x01
_MSG_TYPE_BIN = 0x02
# ------------------------------------------------------------------------
def __init__(self, wsMod, mws2, request) :
self._mws2 = mws2
self._request = request
self._xasCli = request.XAsyncTCPClient
self._currentMsgType = None
self._currentMsgData = None
self._isClosed = False
self._waitFrameTimeoutSec = 300
self._maxRecvMsgLen = mws2.MaxRequestContentLength
self._onTextMsg = None
self._onBinMsg = None
self._onClosed = None
onWSAccepted = wsMod.OnWebSocketAccepted
self._mws2.Log( '%sWebSocket %s from %s:%s.'
% ( ('SSL-' if request.IsSSL else ''),
'accepted' if onWSAccepted else 'denied',
self._xasCli.CliAddr[0],
self._xasCli.CliAddr[1] ),
self._mws2.INFO )
if not onWSAccepted :
self._close(1001, 'Going away...')
return
self._xasCli.OnClosed = self._onXAsCliClosed
try :
onWSAccepted(self._mws2, self)
except Exception as ex :
self._mws2.Log( 'Exception raised from "WebSockets.OnWebSocketAccepted" handler: %s' % ex,
self._mws2.ERROR )
self._close(1011, 'Unexpected error')
return
self._waitFrame()
# ------------------------------------------------------------------------
def _recvData(self, onRecv, size=None) :
self._xasCli.AsyncRecvData( size = size,
onDataRecv = onRecv,
timeoutSec = self._mws2.RequestsTimeoutSec )
# ------------------------------------------------------------------------
def _onXAsCliClosed(self, xasCli, closedReason) :
self._isClosed = True
if self._onClosed :
try :
self._onClosed(self)
except Exception as ex :
self._mws2.Log( 'Exception raised from "WebSocket.OnClosed" handler: %s' % ex,
self._mws2.ERROR )
# ------------------------------------------------------------------------
def _waitFrame(self) :
def onHdrStartingRecv(xasCli, data, arg) :
fin = data[0] & 0x80 > 0
opcode = data[0] & 0x0F
masked = data[1] & 0x80 > 0
length = data[1] & 0x7F
# Control frame ?
isCtrlFrame = ( opcode != WebSocket._OP_FRAME_TEXT and \
opcode != WebSocket._OP_FRAME_BIN and \
opcode != WebSocket._OP_FRAME_CONT )
if ( isCtrlFrame and not fin ) \
or \
( opcode == WebSocket._OP_FRAME_CONT and \
not self._currentMsgType ) \
or \
( self._currentMsgType and \
( opcode == WebSocket._OP_FRAME_TEXT or \
opcode == WebSocket._OP_FRAME_BIN ) ) :
# Bad frame in the context,
self._close(1002, 'Protocol error (bad frame in the context)')
return
def endOfHeader(dataLen, maskingKey) :
def onPayloadDataRecv(xasCli, data, arg) :
if maskingKey :
for i in range(dataLen) :
data[i] ^= maskingKey[i%4]
if self._currentMsgData :
try :
self._currentMsgData += data
except :
# Frame is too large for memory allocation,
self._close(1009, 'Frame is too large to be processed')
return
else :
self._currentMsgData = data
if fin :
# Frame is fully received,
if self._currentMsgType == WebSocket._MSG_TYPE_TEXT :
# Text frame,
if self._onTextMsg :
try :
msg = bytes(self._currentMsgData).decode('UTF-8')
try :
self._onTextMsg(self, msg)
except Exception as ex :
self._mws2.Log( 'Exception raised from "WebSocket.OnTextMessage" handler: %s' % ex,
self._mws2.ERROR )
self._close(1011, 'Unexpected error while processing text message')
return
except :
self._mws2.Log( 'Error during UTF-8 decoding of websocket text message.',
self._mws2.WARNING )
self._close(1007, 'Error to decode UTF-8 text message')
return
else :
self._close(1003, 'Text messages are not implemented')
return
elif self._currentMsgType == WebSocket._MSG_TYPE_BIN :
# Binary frame,
if self._onBinMsg :
try :
self._onBinMsg(self, bytes(self._currentMsgData))
except Exception as ex :
self._mws2.Log( 'Exception raised from "WebSocket.OnBinaryMessage" handler: %s' % ex,
self._mws2.ERROR )
self._close(1011, 'Unexpected error while processing binary message')
return
else :
self._close(1003, 'Binary messages are not implemented')
return
self._currentMsgType = None
self._currentMsgData = None
self._waitFrame()
# - End of onPayloadDataRecv -
if not isCtrlFrame :
# Message frame or continuation frame,
if self._maxRecvMsgLen :
l = dataLen
if self._currentMsgData :
l += len(self._currentMsgData)
if l > self._maxRecvMsgLen :
# Message length exceeds the defined limit,
self._close(1009, 'Frame is too large to be processed')
return
if opcode == WebSocket._OP_FRAME_TEXT :
self._currentMsgType = WebSocket._MSG_TYPE_TEXT
elif opcode == WebSocket._OP_FRAME_BIN :
self._currentMsgType = WebSocket._MSG_TYPE_BIN
try :
self._recvData(onPayloadDataRecv, dataLen)
except :
# Frame is too large for memory allocation,
self._close(1009, 'Frame is too large to be processed')
elif opcode == WebSocket._OP_FRAME_PING :
# Ping control frame,
if dataLen > 0 :
def onPingDataRecv(xasCli, data, arg) :
data = bytearray(data)
self._sendFrame(WebSocket._OP_FRAME_PONG, data)
self._waitFrame()
self._recvData(onPingDataRecv, dataLen)
else :
self._sendFrame(WebSocket._OP_FRAME_PONG)
self._waitFrame()
elif opcode == WebSocket._OP_FRAME_PONG :
# Pong control frame,
if dataLen > 0 :
def onPongDataRecv(xasCli, data, arg) :
self._waitFrame()
self._recvData(onPongDataRecv, dataLen)
else :
self._waitFrame()
elif opcode == WebSocket._OP_FRAME_CLOSE :
# Close control frame,')
if dataLen > 0 :
def onCloseDataRecv(xasCli, data, arg) :
self._close()
self._recvData(onCloseDataRecv, dataLen)
else :
self._close()
else :
# Unknown frame type,
self._close(1002, 'Protocol error (bad opcode)')
# - End of endOfHeader -
def getMaskingKey(dataLen) :
if masked :
# Frame is masked by the next 4 bytes key,
def onMaskingKeyRecv(xasCli, data, arg) :
endOfHeader(dataLen=dataLen, maskingKey=bytes(data))
self._recvData(onMaskingKeyRecv, 4)
else :
# Frame is not masked,
endOfHeader(dataLen=dataLen, maskingKey=None)
# - End of getMaskingKey -
if length == 0 and not isCtrlFrame :
# Bad frame for a no control frame without payload data,
self._close(1002, 'Protocol error (payload data required)')
elif length <= 0x7D :
# Frame length <= 0x7D,
getMaskingKey(dataLen=length)
elif isCtrlFrame :
# Bad frame for length of control frame > 0x7D,
self._close(1002, 'Protocol error (bad control frame length)')
elif length == 0x7E :
# Frame length is encoded on next 16 bits,
def onLenExt1Recv(xasCli, data, arg) :
length = (data[0] << 8) + data[1]
if length < 0x7E :
# Bad frame for 16 bits length < 0x7E,
self._close(1002, 'Protocol error (bad length encoding)')
else :
getMaskingKey(dataLen=length)
self._recvData(onLenExt1Recv, 2)
else :
# Frame length is encoded on next 64 bits.
# It's too large and not implemented,
self._close(1009, 'Frame is too large to be processed')
# - End of onHdrStartingRecv -
self._xasCli.AsyncRecvData( size = 2,
onDataRecv = onHdrStartingRecv,
timeoutSec = self._waitFrameTimeoutSec )
# ------------------------------------------------------------------------
def _sendFrame(self, opcode, data=None, fin=True) :
try :
if opcode >= 0x00 and opcode <= 0x0F :
length = len(data) if data else 0
if length <= 0xFFFF :
data = bytes([ (opcode | 0x80) if fin else opcode ] ) \
+ bytes([ length if length <= 0x7D else 0x7E ] ) \
+ (pack('>H', length) if length >= 0x7E else b'') \
+ (bytes(data) if data else b'')
return self._xasCli.AsyncSendData(data)
except :
pass
return False
# ------------------------------------------------------------------------
def _close(self, statusCode=None, reason=None, waitCloseFrame=False) :
if not self._isClosed :
if statusCode :
data = pack('>H', statusCode)
if reason :
data += reason.encode('UTF-8')
else :
data = None
self._sendFrame(WebSocket._OP_FRAME_CLOSE, data)
self._isClosed = True
if waitCloseFrame :
return
self._xasCli.Close()
# ------------------------------------------------------------------------
def SendTextMessage(self, msg) :
if not isinstance(msg, str) or len(msg) == 0 :
raise ValueError('"msg" must be a not empty string.')
if not self._isClosed :
try :
msg = msg.encode('UTF-8')
except :
return False
return self._sendFrame(WebSocket._OP_FRAME_TEXT, msg)
return False
# ------------------------------------------------------------------------
def SendBinaryMessage(self, msg) :
try :
bytes([msg[0]])
except :
raise ValueError('"msg" must be a not empty bytes object.')
if not self._isClosed :
return self._sendFrame(WebSocket._OP_FRAME_BIN, msg)
return False
# ------------------------------------------------------------------------
def Close(self) :
if not self._isClosed :
self._close(1000, 'Normal closure', waitCloseFrame=True)
# ------------------------------------------------------------------------
@property
def Request(self) :
return self._request
# ------------------------------------------------------------------------
@property
def IsClosed(self) :
return self._isClosed
# ------------------------------------------------------------------------
@property
def WaitFrameTimeoutSec(self) :
return self._waitFrameTimeoutSec
@WaitFrameTimeoutSec.setter
def WaitFrameTimeoutSec(self, value) :
if not isinstance(value, int) or value <= 0 :
raise ValueError('"WaitFrameTimeoutSec" must be a positive integer.')
self._waitFrameTimeoutSec = value
# ------------------------------------------------------------------------
@property
def MaxRecvMessageLength(self) :
return self._maxRecvMsgLen
@MaxRecvMessageLength.setter
def MaxRecvMessageLength(self, value) :
if value is not None and (not isinstance(value, int) or value < 125) :
raise ValueError('"MaxRecvMessageLength" must be an integer >= 125 or None.')
self._maxRecvMsgLen = value
# ------------------------------------------------------------------------
@property
def OnTextMessage(self) :
return self._onTextMsg
@OnTextMessage.setter
def OnTextMessage(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnTextMessage" must be a function.')
self._onTextMsg = value
# ------------------------------------------------------------------------
@property
def OnBinaryMessage(self) :
return self._onBinMsg
@OnBinaryMessage.setter
def OnBinaryMessage(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnBinaryMessage" must be a function.')
self._onBinMsg = value
# ------------------------------------------------------------------------
@property
def OnClosed(self) :
return self._onClosed
@OnClosed.setter
def OnClosed(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnClosed" must be a function.')
self._onClosed = value
# ============================================================================
# ============================================================================
# ============================================================================
@@ -0,0 +1,184 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
import re
# ============================================================================
# ===( @WebRoute decorator )==================================================
# ============================================================================
def WebRoute(method=None, routePath=None, name=None) :
if type(method) is type(lambda x:x) and not routePath :
raise ValueError('[@WebRoute] arguments are required for this decorator.')
def decorated(handler) :
RegisterRoute(handler, method, routePath, name)
s = (' (%s)' % name) if name else ''
print(' + [@WebRoute] %s %s' % (method, routePath) + s)
return handler
return decorated
# ============================================================================
# ===( RegisterResult )=======================================================
# ============================================================================
def RegisterRoute(handler, method, routePath, name=None) :
if type(handler) is not type(lambda x:x) :
raise ValueError('"handler" must be a function.')
if not isinstance(method, str) or len(method) == 0 :
raise ValueError('"method" requires a not empty string.')
if not isinstance(routePath, str) or len(routePath) == 0 :
raise ValueError('"routePath" requires a not empty string.')
if routePath[0] != '/' :
raise ValueError('"routePath" must start with a "/".')
if name is not None and not isinstance(name, str) :
raise ValueError('"name" must be a string or None.')
method = method.upper()
if len(routePath) > 1 and routePath.endswith('/') :
routePath = routePath[:-1]
# Route -> '/users/<uID>/addresses/<addrID>/test/<anotherID>'
# Regex -> '/users/(\w*)/addresses/(\w*)/test/(\w*)$'
# Args -> ['uID', 'addrID', 'anotherID']
argNames = [ ]
regex = ''
try :
for i, part in enumerate(routePath.lower().split('/')) :
if i > 0 :
if part.startswith('<') and part.endswith('>') :
argName = part[1:-1]
if not argName :
raise Exception
argNames.append(argName)
regex += '/([\\w.]*)'
else :
regex += '/' + part
regex = re.compile(regex + '$')
except :
raise ValueError('Bad route path: "%s".' % routePath)
for regRoute in _registeredRoutes :
if regRoute.Method == method and regRoute.Regex == regex :
raise ValueError('Duplicated route: "%s".' % routePath)
regRoute = _registeredRoute(handler, method, routePath, name, regex, argNames)
_registeredRoutes.append(regRoute)
# ============================================================================
# ===( ResolveRoute )=========================================================
# ============================================================================
def ResolveRoute(method, path) :
try :
path = path.lower()
if len(path) > 1 and path.endswith('/') :
path = path[:-1]
for regRoute in _registeredRoutes :
if regRoute.Method == method :
reMatch = regRoute.Regex.match(path)
if reMatch :
if not regRoute.ArgNames :
return RouteResult(regRoute)
args = { }
for i, argName in enumerate(regRoute.ArgNames) :
argValue = reMatch.group(i+1)
try :
argValue = int(argValue)
except :
pass
args[argName] = argValue
return RouteResult(regRoute, args)
except :
pass
return None
# ============================================================================
# ===( PathFromRoute )========================================================
# ============================================================================
def PathFromRoute(routeName, routeArgs={ }) :
if not isinstance(routeName, str) or len(routeName) == 0 :
raise ValueError('"routeName" requires a not empty string.')
if not isinstance(routeArgs, dict) :
raise ValueError('"routeArgs" must be a dict.')
for regRoute in _registeredRoutes :
if regRoute.Name == routeName :
path = regRoute.RoutePath
for argName in regRoute.ArgNames :
arg = routeArgs.get(argName, None)
if arg is None :
raise ValueError('"routeArgs" does not contains "%s" for route %s.' % (argName, routeName))
path = path.replace('<%s>' % argName, str(arg))
return path
raise ValueError('"routeName" is not a registered route (%s).' % routeName)
# ============================================================================
# ===( RouteResult )==========================================================
# ============================================================================
class RouteResult :
def __init__(self, regRoute, args=None) :
self._regRoute = regRoute
self._args = args
def __repr__(self) :
if self._regRoute.Name :
return self._regRoute.Name
return '%s %s' % (self._regRoute.Method, self._regRoute.RoutePath)
@property
def Handler(self) :
return self._regRoute.Handler
@property
def Method(self) :
return self._regRoute.Method
@property
def RoutePath(self) :
return self._regRoute.RoutePath
@property
def Name(self) :
return self._regRoute.Name
@property
def Args(self) :
return self._args
# ============================================================================
# ===( Methods )==============================================================
# ============================================================================
GET = 'GET'
HEAD = 'HEAD'
POST = 'POST'
PUT = 'PUT'
DELETE = 'DELETE'
OPTIONS = 'OPTIONS'
PATCH = 'PATCH'
# ============================================================================
# ===( Private registered routes )===========================================
# ============================================================================
_registeredRoutes = [ ]
# ------------------------------------------------------------------------
class _registeredRoute :
def __init__(self, handler, method, routePath, name, regex, argNames) :
self.Handler = handler
self.Method = method
self.RoutePath = routePath
self.Name = name
self.Regex = regex
self.ArgNames = argNames
# ============================================================================
# ============================================================================
# ============================================================================
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDODCCAiACCQCr018O4/g/kzANBgkqhkiG9w0BAQUFADBdMQswCQYDVQQGEwJG
UjEOMAwGA1UEBwwFUEFSSVMxDDAKBgNVBAoMA0hDMjERMA8GA1UEAwwIKi5oYzIu
ZnIxHTAbBgkqhkiG9w0BCQEWDmNvbnRhY3RAaGMyLmZyMCAXDTE4MTIxNjEyMTI0
NFoYDzIyOTIwOTI5MTIxMjQ0WjBdMQswCQYDVQQGEwJGUjEOMAwGA1UEBwwFUEFS
SVMxDDAKBgNVBAoMA0hDMjERMA8GA1UEAwwIKi5oYzIuZnIxHTAbBgkqhkiG9w0B
CQEWDmNvbnRhY3RAaGMyLmZyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
AQEAvj1L4FLuOLypHqERQKkYcGJyIwt0vm/lbl6+hDF0nt3GVmYijorLuUn1tTE2
93cXrixbZ9Bd65c8hsmEvVZbvjG2UmhXxGxk7NserbF4fAyZ+w7k+L0YOO1s5A53
TcqWOLUd7E8J36j+SVx90T3VMnrl655K+ZqWM0IQnmLweddp+y1rZ0gAUhR/wmUB
gWlfCCyhRl9ktAD0q0e6sVq7x/fwYTpG5ENCGPD3ZVlsgMWZMcj8liFbY7YNsVxD
O1+eH6A20X7FwOSpX9AxVoYnDfB0Dlh0/7FaYIZ0ZhDDyvied43WW2DTEkKsdC48
8Yr7GBb1Fw/Go3oYkaMChQN/FQIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQBW/KlS
gTScaWf1RcpjHvvdBYfBwSlYZg5sxVbV2cPmC+M52EPbzIT5qM6TnTwnJgywj+zx
NzxVvDwDIfLNO8NmKvsVjvzaMgjPoeknoZ33jULfLF8cgwrFzE+XmXUDii9dugQm
GipA0JcWHGnR93pYJoZuXH7ACneNR3MNYIkHJ2M+PkkVppdx8ilOwgTI4pCLGAhm
fwc/Bmkz6HEwju6vRzwdae9Z0xL7wKmZxO2IujbZpgQvwhf0ZvJzpXlmK2dxcBL/
YrwgvneacuXWM3SXPTIlCNgYHzi0Mi+ElUqnfAjI1MtMOpW+jKpZxHRkJqfwFalp
fLavWdBgXaJKb3Tx
-----END CERTIFICATE-----
@@ -0,0 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAvj1L4FLuOLypHqERQKkYcGJyIwt0vm/lbl6+hDF0nt3GVmYi
jorLuUn1tTE293cXrixbZ9Bd65c8hsmEvVZbvjG2UmhXxGxk7NserbF4fAyZ+w7k
+L0YOO1s5A53TcqWOLUd7E8J36j+SVx90T3VMnrl655K+ZqWM0IQnmLweddp+y1r
Z0gAUhR/wmUBgWlfCCyhRl9ktAD0q0e6sVq7x/fwYTpG5ENCGPD3ZVlsgMWZMcj8
liFbY7YNsVxDO1+eH6A20X7FwOSpX9AxVoYnDfB0Dlh0/7FaYIZ0ZhDDyvied43W
W2DTEkKsdC488Yr7GBb1Fw/Go3oYkaMChQN/FQIDAQABAoIBAFZYmAHfYkTaTKCc
VqpUlcUcydViM8DkJOytkCeMEvSwkH9SqEiucr1M9nshNWOo6FSjyXEbQCXYZR6A
hQEzGzz+b1SEC6IZ2M0wv4Hy1U7ooVM0dXT4zu+3w/7XGgty8jAW9Nf3H/ImUBSY
KHs6Z3QcGBOTq1ATfC0TxVs+aQvDk/ceLuEbjDZAyhkqJTcUJaUrai91dwe1ChQj
uBZCRa87Z7gdFBItY+g8RBtdOoT9KZNDZ4OqHXpzzg0la1GMbLKNA82dqUx3mexr
HHlxV+cDt7gFT80Usj9Knk0tQnoiLkxFBblcHId9b93bSKdzFiVAUxkCkbI8xcUX
JVf9a1kCgYEA4NsV5sFye2O+7Idwm1eUu4e/lXBrnwpNmDVy3rYlweQGNSyMrU+A
wcBS7bAghq4QdFbZMEqNVxyFJFa7W1Xvy3HqCpsEUnDO6n9wCN8aCUGMU2YFP9Y/
OoIrTye2ZO36C5pwZiOmT8KZ3Z45f1CxKrgVRDVnfwcCd7xLpPL4BKcCgYEA2JbJ
i8eismhpx4oGvoV1LCgiazgm5+w1b+ZvzaknAAocqwNXLMVNqbGNY/136dCB1DYj
A/Nvyr/WxBBTwYEXOoefgD0BpV2JjBmHckBTtwC8v3Ybi1dLm+JOtFT9uB1hXn/u
08VahTU9GSo8OCyeJF5eDLcg3Rx0ZGtFRYPWieMCgYAN0CemR1f7EIOYEDHwuQ6f
/pTcX02dNYrSwOXPnKzxHkrrVVNHCk1EmcX+aAV3gJXuL6+j8dCA+3WKZ/GWiM70
VokkIaXAUsHDUhTV1q7IxsgSD4BfDZBQzdJPSIdB6ASmVdR10dbTq4a8QI4TridU
En7r88Pp38pdBKo49dwanQKBgHnF9ZVIbfoe6HJO8VHHGUT1X7ymuoEk9jpu9idM
VmgYR1wDKc07NVoWQKeaSARGvegBdBhxk0YMLATaJS0jllrLC+t+4WEHQSFq7RNY
hXjbykNfdUcXkqQXTibnrisJIciO50lbqXRBpZNzgp4Wv+c0w24kvC51JB+djDn0
UPf/AoGBAKZoSsbLjSIrxXDkASEGohLgId7AqJBndzCVzWV2+YQrgJCMMorBFVqC
7myB69IDooBFhR7D0Is3uIUzyk62zeRSQPTgQYjUq1LYtvB+sLA3Dqs8cWdFWpAc
a8lnxGKUNRpO18WIuNbFSibK6jyPqA1iRn/9KhZwRmygNzMh/f9P
-----END RSA PRIVATE KEY-----
+1
View File
@@ -0,0 +1 @@
microwebsrv2.hc2.fr
@@ -0,0 +1 @@
theme: jekyll-theme-hacker
Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

+189
View File
@@ -0,0 +1,189 @@
import sys
sys.path.append('/web_root/microWebServer2/')
from MicroWebSrv2.microWebSrv2 import *
from time import sleep
from _thread import allocate_lock
# ============================================================================
# ============================================================================
# ============================================================================
@WebRoute(GET, '/test-redir')
def RequestTestRedirect(microWebSrv2, request) :
request.Response.ReturnRedirect('/test.pdf')
# ============================================================================
# ============================================================================
# ============================================================================
@WebRoute(GET, '/test-post', name='TestPost1/2')
def RequestTestPost(microWebSrv2, request) :
content = """\
<!DOCTYPE html>
<html>
<head>
<title>POST 1/2</title>
</head>
<body>
<h2>MicroWebSrv2 - POST 1/2</h2>
User address: %s<br />
<form action="/test-post" method="post">
First name: <input type="text" name="firstname"><br />
Last name: <input type="text" name="lastname"><br />
<input type="submit" value="OK">
</form>
</body>
</html>
""" % request.UserAddress[0]
request.Response.ReturnOk(content)
# ------------------------------------------------------------------------
@WebRoute(POST, '/test-post', name='TestPost2/2')
def RequestTestPost(microWebSrv2, request) :
data = request.GetPostedURLEncodedForm()
try :
firstname = data['firstname']
lastname = data['lastname']
except :
request.Response.ReturnBadRequest()
return
content = """\
<!DOCTYPE html>
<html>
<head>
<title>POST 2/2</title>
</head>
<body>
<h2>MicroWebSrv2 - POST 2/2</h2>
Hello %s %s :)<br />
</body>
</html>
""" % ( MicroWebSrv2.HTMLEscape(firstname),
MicroWebSrv2.HTMLEscape(lastname) )
request.Response.ReturnOk(content)
# ============================================================================
# ============================================================================
# ============================================================================
def OnWebSocketAccepted(microWebSrv2, webSocket) :
print('Example WebSocket accepted:')
print(' - User : %s:%s' % webSocket.Request.UserAddress)
print(' - Path : %s' % webSocket.Request.Path)
print(' - Origin : %s' % webSocket.Request.Origin)
if webSocket.Request.Path.lower() == '/wschat' :
WSJoinChat(webSocket)
else :
webSocket.OnTextMessage = OnWebSocketTextMsg
webSocket.OnBinaryMessage = OnWebSocketBinaryMsg
webSocket.OnClosed = OnWebSocketClosed
# ============================================================================
# ============================================================================
# ============================================================================
def OnWebSocketTextMsg(webSocket, msg) :
print('WebSocket text message: %s' % msg)
webSocket.SendTextMessage('Received "%s"' % msg)
# ------------------------------------------------------------------------
def OnWebSocketBinaryMsg(webSocket, msg) :
print('WebSocket binary message: %s' % msg)
# ------------------------------------------------------------------------
def OnWebSocketClosed(webSocket) :
print('WebSocket %s:%s closed' % webSocket.Request.UserAddress)
# ============================================================================
# ============================================================================
# ============================================================================
global _chatWebSockets
_chatWebSockets = [ ]
global _chatLock
_chatLock = allocate_lock()
# ------------------------------------------------------------------------
def WSJoinChat(webSocket) :
webSocket.OnTextMessage = OnWSChatTextMsg
webSocket.OnClosed = OnWSChatClosed
addr = webSocket.Request.UserAddress
with _chatLock :
for ws in _chatWebSockets :
ws.SendTextMessage('<%s:%s HAS JOINED THE CHAT>' % addr)
_chatWebSockets.append(webSocket)
webSocket.SendTextMessage('<WELCOME %s:%s>' % addr)
# ------------------------------------------------------------------------
def OnWSChatTextMsg(webSocket, msg) :
addr = webSocket.Request.UserAddress
with _chatLock :
for ws in _chatWebSockets :
ws.SendTextMessage('<%s:%s> %s' % (addr[0], addr[1], msg))
# ------------------------------------------------------------------------
def OnWSChatClosed(webSocket) :
addr = webSocket.Request.UserAddress
with _chatLock :
if webSocket in _chatWebSockets :
_chatWebSockets.remove(webSocket)
for ws in _chatWebSockets :
ws.SendTextMessage('<%s:%s HAS LEFT THE CHAT>' % addr)
# ============================================================================
# ============================================================================
# ============================================================================
print()
# Loads the PyhtmlTemplate module globally and configure it,
pyhtmlMod = MicroWebSrv2.LoadModule('PyhtmlTemplate')
pyhtmlMod.ShowDebug = True
pyhtmlMod.SetGlobalVar('TestVar', 12345)
# Loads the WebSockets module globally and configure it,
wsMod = MicroWebSrv2.LoadModule('WebSockets')
wsMod.OnWebSocketAccepted = OnWebSocketAccepted
# Instanciates the MicroWebSrv2 class,
mws2 = MicroWebSrv2()
mws2.BindAddress = ('0.0.0.0', 8080) # Binds to all interfaces on port 8080.
# SSL is not correctly supported on MicroPython.
# But you can uncomment the following for standard Python.
# mws2.EnableSSL( certFile = 'SSL-Cert/openhc2.crt',
# keyFile = 'SSL-Cert/openhc2.key' )
# For embedded MicroPython, use a very light configuration,
mws2.SetEmbeddedConfig()
# All pages not found will be redirected to the home '/',
mws2.NotFoundURL = '/'
# Starts the server as easily as possible in managed mode,
mws2.StartManaged()
# Main program loop until keyboard interrupt,
try :
while mws2.IsRunning :
sleep(1)
except KeyboardInterrupt :
pass
# End,
print()
mws2.Stop()
print('Bye')
print()
# ============================================================================
# ============================================================================
# ============================================================================
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md'), encoding='utf-8').read()
setup(
name='MicroWebSrv2',
version='2.0.6',
description='Embedded webserver for MicroPython and CPython',
long_description=README,
author='Jean-Christophe Bos',
author_email='jczic.bos@gmail.com',
url='https://github.com/jczic/MicroWebSrv2',
download_url='https://github.com/jczic/MicroWebSrv2/archive/master.zip',
packages=find_packages(),
classifiers=[
'Environment :: Web Environment',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Embedded Systems',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: MicroPython',
'License :: OSI Approved :: MIT License',
'Development Status :: 5 - Production/Stable',
],
)
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

+43
View File
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang=fr>
<head>
<meta charset="UTF-8" />
<title>MicroWebSrv2</title>
<link rel="stylesheet" href="style.css" />
</head>
<body style="padding: 0 70px;">
<h1>&lt; MicroWebSrv2 /&gt;</h1>
<h2>About</h2>
<p>
This project follows the embedded <a href="https://github.com/jczic/MicroWebSrv">MicroWebSrv</a>,
which is mainly used on microcontrollers such as Pycom, ESP32 and STM32 on Pyboards.<br />
<br />
In a need for scalability and to meet the IoT universe, <b>microWebSrv2</b> was developed as a new project
and has been completely redesigned to be much more robust and efficient that its predecessor.<br />
<br />
Internal mechanisms works <b>directly at I/O level</b>, are fully asynchronous from end to end, and manages the memory in a highly optimized way.
Also, architecture makes its integration very easy and the source code, <b>MIT licensed</b>, remains really small.<br />
<br />
</p>
<ul>
<li><a href="test-redir">Test a redirection</a></li>
<li><a href="test-post">Test a POST form</a></li>
<li><a href="wstest.html">Test the WebSockets page</a></li>
<li><a href="wschat.html">Test the multi-users chat page</a></li>
<li><a href="test.pyhtml">Test a pyhtml template page</a></li>
</ul>
<br />
<hr />
<br />
<div style="text-align: center">
<img src="pdf.png" />
<p>
View a « <a href="test.pdf">PDF file</a> »
</p>
</div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

+44
View File
@@ -0,0 +1,44 @@
html, body {
margin: 0;
padding: 0;
}
body {
margin: 30px;
background-color: white;
font-family: "Trebuchet MS", Verdana, sans-serif;
letter-spacing: 2px;
}
h1 {
color: #D35F8D;
text-align: center;
}
h2 {
color: #5FA3D3;
padding-left: 15px;
}
p, ul, li, td {
color: black;
}
a:link {
color: green;
text-decoration: underline;
}
a:visited {
color: gray;
}
a:hover {
color: red;
text-decoration: none;
}
a:active, a:focus {
color: red;
}
.sep {
margin: 15px 0;
height: 3px;
background-color: #5FA3D3;
}
.label {
color: #D35F8D;
font-weight: bold;
}
Binary file not shown.
+133
View File
@@ -0,0 +1,133 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>MicroWebSrv2 - PyhtmlTemplate Module</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
{{ py }}
import sys
global Toto
try :
Toto += 1
except :
Toto = 1
{{ end }}
<h1>MicroWebSrv2 - PyhtmlTemplate Module</h1>
<div class="sep"></div>
Platform: {{ sys.platform }} <br />
Version: {{ sys.version }} <br />
<div class="sep"></div>
Global var "TestVar" : <span class="label">{{ TestVar }}</span><br />
* Set from the main program.
<div class="sep"></div>
Global var "Toto" : <span class="label">{{ Toto }}</span><br />
* Refresh this page to see this variable changing.
<div class="sep"></div>
{{ py }}
print('Unescaped HTML: <strong><u>Okay</u></strong>')
{{ end }}
<div class="sep"></div>
Your address:<br />
<ul>
<li> IP = {{ Request.UserAddress[0] }} </li>
<li> Port = {{ Request.UserAddress[1] }} </li>
</ul>
<div class="sep"></div>
{{ if 'CHROME' in Request.UserAgent.upper() }}
You are on <span class="label">Chrome</span> browser.
{{ elif 'FIREFOX' in Request.UserAgent.upper() }}
You are on <span class="label">Firefox</span> browser.
{{ else }}
You are not on Chrome or Firefox browser.
{{ end }}
<div class="sep"></div>
You are in SSL: {{ Request.IsSSL }}<br />
<div class="sep"></div>
Your host: {{ Request.Host }}<br />
<div class="sep"></div>
Requested path: {{ Request.Path }}<br />
<div class="sep"></div>
Your query params:
{{ if not Request.QueryParams }}
<a href="?question=How are you?&answer=I'm fine!">
Test query string on this page.
</a>
{{ else }}
<ul>
{{ for param in Request.QueryParams }}
<li>Param "{{ param }}" = "{{ Request.QueryParams[param] }}"</li>
{{ end }}
</ul>
{{ end }}
<div class="sep"></div>
Accepted content types:
<ul>
{{ for accept in Request.Accept }}
<li>{{ accept }}</li>
{{ end }}
</ul>
<div class="sep"></div>
Accepted encodings:
<ul>
{{ for encoding in Request.AcceptEncodings }}
<li>{{ encoding }}</li>
{{ end }}
</ul>
<div class="sep"></div>
Accepted languages:
<ul>
{{ for language in Request.AcceptLanguages }}
<li>{{ language }}</li>
{{ end }}
</ul>
<div class="sep"></div>
Your request is keep-alive: {{ Request.IsKeepAlive }}<br />
<div class="sep"></div>
Your user agent:<br />
{{ Request.UserAgent }}
<div class="sep"></div>
</body>
</html>
+124
View File
@@ -0,0 +1,124 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>MicroWebSrv2 - WS Chat</title>
<link rel="stylesheet" href="style.css" />
</head>
<style>
.chat-zone {
height : 350px;
padding: 10px;
background-color: #304050;
font: 15px monospace;
color: white;
overflow: scroll;
}
#input-chat {
height: 40px;
border: 0px;
padding: 0px 10px;
outline: none;
border-top: 1px solid white;
background-color: #304050;
font: 15px monospace;
letter-spacing: 2px;
color: white;
}
input {
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
width: 100%;
margin-top: 3px;
border: 2px solid #5FA3D3;
}
</style>
<script language="javascript">
function init()
{
var scheme
if (window.location.protocol == 'https:')
scheme = 'wss:';
else
scheme = 'ws:';
var wsUri = scheme + '//' + window.location.hostname + '/wschat';
writeLineToChat("Connection to " + wsUri + "...")
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen (evt) };
websocket.onclose = function(evt) { onClose (evt) };
websocket.onmessage = function(evt) { onMessage (evt) };
websocket.onerror = function(evt) { onError (evt) };
getElmById("input-chat").addEventListener("keyup", onChatLine);
getElmById("input-chat").focus()
}
function getElmById(id) {
return document.getElementById(id);
}
function writeLineToChat(line)
{
var elm = getElmById('chat');
if (elm)
{
var lineElm = document.createElement('div');
if (line) {
var time = new Date().toLocaleTimeString();
lineElm.innerText = "[" + time + "] " + line;
}
else
lineElm.innerHTML = '&nbsp;';
elm.appendChild(lineElm);
elm.scrollTop = elm.scrollHeight;
}
}
function onOpen(evt)
{
writeLineToChat("[CONNECTED]")
}
function onClose(evt)
{
writeLineToChat("[CONNECTION CLOSED]")
}
function onMessage(evt)
{
writeLineToChat(evt.data)
}
function onError(evt)
{
writeLineToChat("[CONNECTION ERROR]")
}
function onChatLine(e) {
key = (e.key || e.keyCode);
if (key === 13 || key.toUpperCase() === "ENTER") {
input = getElmById("input-chat");
line = input.value.trim();
input.value = "";
if (line.length > 0)
websocket.send(line);
}
}
window.addEventListener("load", init, false);
</script>
<body>
<h1>MicroWebSrv2 - WS Chat</h1>
<div id="chat" class="chat-zone">
</div>
<input id="input-chat" type="text" />
</body>
</html>
+92
View File
@@ -0,0 +1,92 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>MicroWebSrv2 - WebSockets Module</title>
<link rel="stylesheet" href="style.css" />
</head>
<script language="javascript">
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
var scheme, defaultPort
if (window.location.protocol == 'https:')
{
scheme = 'wss:';
defaultPort = 443;
}
else
{
scheme = 'ws:';
defaultPort = 80;
}
var wsUri = scheme + '//' + window.location.hostname;
if (window.location.port !== defaultPort)
wsUri += ':' + window.location.port;
writeToScreen("Connecting to " + wsUri + "...")
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen (evt) };
websocket.onclose = function(evt) { onClose (evt) };
websocket.onmessage = function(evt) { onMessage (evt) };
websocket.onerror = function(evt) { onError (evt) };
}
function onOpen(evt)
{
writeToScreen("<strong>-- CONNECTED --</strong>");
SendMsg("Hello world :)");
SendMsg("This is a WebSocket test");
SendMsg("(with a text frame encoded in UTF-8)");
setTimeout( function() { websocket.close() }, 3000 )
}
function onClose(evt)
{
writeToScreen("<strong>-- DISCONNECTED --</strong>");
}
function onMessage(evt)
{
writeToScreen('MSG FROM SERVER : <span style="color: blue;">' + evt.data + '</span>');
}
function onError(evt)
{
writeToScreen('ERROR : <span style="color: red;">' + evt.data + '</span>');
}
function SendMsg(msg)
{
writeToScreen('MSG TO SERVER : <span style="color: green;">' + msg + '</span>');
websocket.send(msg);
}
function writeToScreen(s)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = s;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<body>
<h1>MicroWebSrv2 - WebSockets Module</h1>
<div id="output"></div>
</body>
</html>