增加高压空闲调节
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
The MIT License (MIT)
|
||||
Copyright © 2018 Jean-Christophe Bos & HC² (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,377 @@
|
||||
|
||||
<h3>
|
||||
<p align="center">
|
||||
Also check out the new ESP32 MPY-Jama free IDE and the latest MicroWebSrv2 below:
|
||||
</p>
|
||||
</h3>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/jczic/ESP32-MPY-Jama"><img src="https://github.com/jczic/ESP32-MPY-Jama/raw/master/img/ESP32%20MPY-Jama%20NEW.png" alt="New microWebSrv2" width="350" valign="middle"></a>
|
||||
<a href="https://github.com/jczic/MicroWebSrv2"><img src="microWebSrv2.png" alt="New microWebSrv2" width="350" valign="middle"></a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
<br />
|
||||
|
||||
### MicroWebSrv is a micro HTTP Web server that supports WebSockets, html/python language templating and routing handlers, for MicroPython (principally used on ESP32 and [Pycom](http://www.pycom.io) modules. Now supports all variants of [Pyboard D-series](https://store.micropython.org/category/pyboard%20D-series) from the makers of Micropython)
|
||||
|
||||

|
||||
|
||||
Very easy to integrate and very light with 3 files only :
|
||||
- `"microWebSrv.py"` - The Web server
|
||||
- `"microWebSocket.py"` - The optional support of WebSockets
|
||||
- `"microWebTemplate.py"` - The optional templating language for **.pyhtml** rendered pages
|
||||
|
||||
Mini tuto in video by rdagger68 :
|
||||
- [https://www.youtube.com/watch?v=xscBwC1SrF4](https://www.youtube.com/watch?v=xscBwC1SrF4)
|
||||
|
||||
Simple but effective :
|
||||
- Use it to embed a cool Web site in yours modules
|
||||
- Handle GET, POST, ... requests to interract with user and configure options
|
||||
- Exchange in JSON format on HTTP methods to make an embedded fullREST API
|
||||
- Serve files on the fly to export any data to the user
|
||||
- Use routes and variable route handlers
|
||||
- Play with AjAX to interact speedly with a Web application
|
||||
- Make it a captive portal simply
|
||||
- Use WebSockets for fast and powerful data exchange
|
||||
- Make html/python files for rendering more efficient web pages
|
||||
|
||||
### Using *microWebSrv* main class :
|
||||
|
||||
| Name | Function |
|
||||
| - | - |
|
||||
| Constructor | `mws = MicroWebSrv(routeHandlers=None, port=80, bindIP='0.0.0.0', webPath="/flash/www")` |
|
||||
| Start Web server | `mws.Start(threaded=True)` |
|
||||
| Stop Web server | `mws.Stop()` |
|
||||
| Check if Web server is running | `mws.IsStarted()` |
|
||||
| Set URL location for not found page | `mws.SetNotFoundPageUrl(url=None)` |
|
||||
| Get mime type from file extention | `mws.GetMimeTypeFromFilename(filename)` |
|
||||
| Get handler function from route | `(routeHandler, routeArgs) = mws.GetRouteHandler(resUrl, method)` |
|
||||
| Callback function to enable and accept WebSockets | `mws.AcceptWebSocketCallback = _acptWS` `_acptWS(webSocket, httpClient) { }` |
|
||||
| Maximum length of memory allocated to receive WebSockets data (1024 by default) | `mws.MaxWebSocketRecvLen` |
|
||||
| New thread used for each WebSocket connection (True by default) | `mws.WebSocketThreaded` |
|
||||
| Escape string to HTML usage | `MicroWebSrv.HTMLEscape(s)` |
|
||||
|
||||
### Basic example :
|
||||
```python
|
||||
from microWebSrv import MicroWebSrv
|
||||
mws = MicroWebSrv() # TCP port 80 and files in /flash/www
|
||||
mws.Start(threaded=True) # Starts server in a new thread
|
||||
```
|
||||
|
||||
### Using as captive portal :
|
||||
```python
|
||||
# To intercept all not found queries and redirect it,
|
||||
mws.SetNotFoundPageUrl("http://my-device.wifi")
|
||||
```
|
||||
- Can be used with [MicroDNSSrv](http://microdnssrv.hc2.fr) easily.
|
||||
|
||||
### Using route handlers example :
|
||||
```python
|
||||
|
||||
routeHandlers = [
|
||||
( "relative_url_route_1", "METHOD", handlerFunc_1 ),
|
||||
( "relative_url_route_2", "METHOD", handlerFunc_2 ),
|
||||
( ... )
|
||||
]
|
||||
```
|
||||
```python
|
||||
def handlerFunc_1(httpClient, httpResponse, routeArgs=None) :
|
||||
print("In HTTP handler 1")
|
||||
|
||||
def handlerFunc_2(httpClient, httpResponse, routeArgs=None) :
|
||||
print("In HTTP handler 2")
|
||||
```
|
||||
|
||||
### Using directly route handlers decorators example :
|
||||
```python
|
||||
@MicroWebSrv.route('/get-test')
|
||||
def handlerFuncGet(httpClient, httpResponse) :
|
||||
print("In GET-TEST HTTP")
|
||||
|
||||
@MicroWebSrv.route('/post-test', 'POST')
|
||||
def handlerFuncPost(httpClient, httpResponse) :
|
||||
print("In POST-TEST HTTP")
|
||||
```
|
||||
|
||||
### Using variable routes example :
|
||||
```python
|
||||
routeHandlers = [
|
||||
( "/edit/<testid>/<testpath>", "GET", handlerFuncEdit ),
|
||||
( ... )
|
||||
]
|
||||
def handlerFuncEdit(httpClient, httpResponse, routeArgs) :
|
||||
print("In EDIT HTTP variable route :")
|
||||
print(" - testid = %s" % routeArgs['testid'])
|
||||
print(" - testpath = %s" % routeArgs['testpath'])
|
||||
```
|
||||
|
||||
Or direclty with route handler decorator :
|
||||
|
||||
```python
|
||||
@MicroWebSrv.route('/edit/<testid>/<testpath>')
|
||||
def handlerFuncEdit(httpClient, httpResponse, routeArgs) :
|
||||
print("In EDIT HTTP variable route :")
|
||||
print(" - testid = %s" % routeArgs['testid'])
|
||||
print(" - testpath = %s" % routeArgs['testpath'])
|
||||
```
|
||||
|
||||
### Using *httpClient* class in a route handler function :
|
||||
|
||||
| Name | Function |
|
||||
| - | - |
|
||||
| Get MicroWebSrv class | `httpClient.GetServer()` |
|
||||
| Get client address as tuple | `httpClient.GetAddr()` |
|
||||
| Get client IP address | `httpClient.GetIPAddr()` |
|
||||
| Get client TCP port | `httpClient.GetPort()` |
|
||||
| Get client request method | `httpClient.GetRequestMethod()` |
|
||||
| Get client request total path | `httpClient.GetRequestTotalPath()` |
|
||||
| Get client request ressource path | `httpClient.GetRequestPath()` |
|
||||
| Get client request query string | `httpClient.GetRequestQueryString()` |
|
||||
| Get client request query parameters as list | `httpClient.GetRequestQueryParams()` |
|
||||
| Get client request headers as list | `httpClient.GetRequestHeaders()` |
|
||||
| Get client request content type | `httpClient.GetRequestContentType()` |
|
||||
| Get client request content length | `httpClient.GetRequestContentLength()` |
|
||||
| Get client request content | `httpClient.ReadRequestContent(size=None)` |
|
||||
| Get client request form data as list | `httpClient.ReadRequestPostedFormData()` |
|
||||
| Get client request as JSON object | `httpClient.ReadRequestContentAsJSON()` |
|
||||
|
||||
### Using *httpResponse* class in a route handler function :
|
||||
|
||||
| Name | Function |
|
||||
| - | - |
|
||||
| Write switching protocols response | `httpResponse.WriteSwitchProto(upgrade, headers=None)` |
|
||||
| Write generic response | `httpResponse.WriteResponse(code, headers, contentType, contentCharset, content)` |
|
||||
| Write PyHTML rendered response page | `httpResponse.WriteResponsePyHTMLFile(filepath, headers=None, vars=None)` |
|
||||
| Write file directly as response | `httpResponse.WriteResponseFile(filepath, contentType=None, headers=None)` |
|
||||
| Write attached file as response | `httpResponse.WriteResponseFileAttachment(filepath, attachmentName, headers=None)` |
|
||||
| Write OK response | `httpResponse.WriteResponseOk(headers=None, contentType=None, contentCharset=None, content=None)` |
|
||||
| Write JSON object as OK response | `httpResponse.WriteResponseJSONOk(obj=None, headers=None)` |
|
||||
| Write redirect response | `httpResponse.WriteResponseRedirect(location)` |
|
||||
| Write error response | `httpResponse.WriteResponseError(code)` |
|
||||
| Write JSON object as error response | `httpResponse.WriteResponseJSONError(code, obj=None)` |
|
||||
| Write bad request response | `httpResponse.WriteResponseBadRequest()` |
|
||||
| Write forbidden response | `httpResponse.WriteResponseForbidden()` |
|
||||
| Write not found response | `httpResponse.WriteResponseNotFound()` |
|
||||
| Write method not allowed response | `httpResponse.WriteResponseMethodNotAllowed()` |
|
||||
| Write internal server error response | `httpResponse.WriteResponseInternalServerError()` |
|
||||
| Write not implemented response | `httpResponse.WriteResponseNotImplemented()` |
|
||||
|
||||
### Using route handler function example :
|
||||
|
||||
```python
|
||||
def _httpHandlerTestPost(httpClient, httpResponse) :
|
||||
formData = httpClient.ReadRequestPostedFormData()
|
||||
firstname = formData["firstname"]
|
||||
lastname = formData["lastname"]
|
||||
content = """\
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>TEST POST</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>TEST POST</h1>
|
||||
Firstname = %s<br />
|
||||
Lastname = %s<br />
|
||||
</body>
|
||||
</html>
|
||||
""" % ( MicroWebSrv.HTMLEscape(firstname),
|
||||
MicroWebSrv.HTMLEscape(lastname) )
|
||||
httpResponse.WriteResponseOk( headers = None,
|
||||
contentType = "text/html",
|
||||
contentCharset = "UTF-8",
|
||||
content = content )
|
||||
```
|
||||
|
||||
### Known mime types (content types) :
|
||||
|
||||
| File extension | Mime type |
|
||||
| - | - |
|
||||
| .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 |
|
||||
|
||||
### Default index pages order (for http://hostname/) :
|
||||
|
||||
| Filename |
|
||||
| - |
|
||||
| index.pyhtml |
|
||||
| index.html |
|
||||
| index.htm |
|
||||
| default.pyhtml |
|
||||
| default.html |
|
||||
| default.htm |
|
||||
|
||||
### Using optional module *microWebSocket* to connect WebSockets :
|
||||
|
||||
- File `"microWebSocket.py"` must be present to activate WebSockets support
|
||||
|
||||
### Enable and accept WebSockets :
|
||||
```python
|
||||
from microWebSrv import MicroWebSrv
|
||||
mws = MicroWebSrv() # TCP port 80 and files in /flash/www
|
||||
mws.MaxWebSocketRecvLen = 256 # Default is set to 1024
|
||||
mws.WebSocketThreaded = False # WebSockets without new threads
|
||||
mws.AcceptWebSocketCallback = _acceptWebSocketCallback # Function to receive WebSockets
|
||||
mws.Start(threaded=True) # Starts server in a new thread
|
||||
```
|
||||
|
||||
| Name | Function |
|
||||
| - | - |
|
||||
| Callback function to receive text message | `ws.RecvTextCallback = func(webSocket, msg)` |
|
||||
| Callback function to receive binary data | `ws.RecvBinaryCallback = func(webSocket, data)` |
|
||||
| Callback function when connection was closed | `ws.ClosedCallback = func(webSocket)` |
|
||||
| Send a text message | `ws.SendText(msg)` |
|
||||
| Send a binary message | `ws.SendBinary(data)` |
|
||||
| Check connection state | `ws.IsClosed()` |
|
||||
| Close the connection | `ws.Close()` |
|
||||
|
||||
### Basic example of callback functions :
|
||||
```python
|
||||
def _acceptWebSocketCallback(webSocket, httpClient) :
|
||||
print("WS ACCEPT")
|
||||
webSocket.RecvTextCallback = _recvTextCallback
|
||||
webSocket.RecvBinaryCallback = _recvBinaryCallback
|
||||
webSocket.ClosedCallback = _closedCallback
|
||||
|
||||
def _recvTextCallback(webSocket, msg) :
|
||||
print("WS RECV TEXT : %s" % msg)
|
||||
webSocket.SendText("Reply for %s" % msg)
|
||||
|
||||
def _recvBinaryCallback(webSocket, data) :
|
||||
print("WS RECV DATA : %s" % data)
|
||||
|
||||
def _closedCallback(webSocket) :
|
||||
print("WS CLOSED")
|
||||
```
|
||||
|
||||
### Using optional module *microWebTemplate* for *.pyhtml* rendered pages :
|
||||
|
||||
- File `"microWebTemplate.py"` must be present to activate **.pyhtml** pages
|
||||
- Pages will be rendered in HTML with integrated MicroPython code
|
||||
|
||||
| Instruction | Schema |
|
||||
| - | - |
|
||||
| PY | `{{ py }}` *MicroPython code* `{{ end }}` |
|
||||
| IF | `{{ if` *MicroPython condition* `}}` *html bloc* `{{ end }}` |
|
||||
| ELIF | `{{ elif` *MicroPython condition* `}}` *html bloc* `{{ end }}` |
|
||||
| ELSE | `{{ else }}` *html bloc* `{{ end }}` |
|
||||
| FOR | `{{ for` *identifier* `in` *MicroPython iterator* `}}` *html bloc* `{{ end }}` |
|
||||
| INCLUDE | `{{ include` *pyhtml_filename* `}}` |
|
||||
| ? | `{{` *MicroPython expression* `}}` |
|
||||
|
||||
|
||||
### Using {{ py }} :
|
||||
|
||||
```python
|
||||
{{ py }}
|
||||
import machine
|
||||
from utime import sleep
|
||||
test = 123
|
||||
def testFunc(x) :
|
||||
return 2 * x
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
### Using {{ if ... }} :
|
||||
|
||||
```python
|
||||
{{ if testFunc(5) <= 3 }}
|
||||
<span>titi</span>
|
||||
{{ elif testFunc(10) >= 15 }}
|
||||
<span>tata</span>
|
||||
{{ else }}
|
||||
<span>I like the number {{ test }} !</span>
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
### Using {{ for ... }} :
|
||||
|
||||
```python
|
||||
{{ for toto in range(testFunc(3)) }}
|
||||
<div>toto x 10 equal {{ toto * 10 }}</div>
|
||||
<hr />
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
### Using {{ include ... }} :
|
||||
|
||||
```python
|
||||
{{ include myTemplate.pyhtml }}
|
||||
```
|
||||
|
||||
### Example of a .pyhtml file :
|
||||
|
||||
```html
|
||||
<html>
|
||||
<head>
|
||||
<title>TEST PYHTML</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>BEGIN</h1>
|
||||
{{ py }}
|
||||
def _testFunction(x) :
|
||||
return "IN TEST FUNCTION %s" % x
|
||||
{{ end }}
|
||||
<div style="background-color: black; color: white;">
|
||||
{{ for toto in range(3) }}
|
||||
This is an HTML test...<br />
|
||||
TOTO = {{ toto + 1 }} !<br />
|
||||
{{ for toto2 in range(3) }}
|
||||
TOTO2 = {{ _testFunction(toto2) }}
|
||||
{{ end }}
|
||||
Ok good.<br />
|
||||
{{ end }}
|
||||
</div>
|
||||
{{ _testFunction(100) }}<br />
|
||||
<br />
|
||||
{{ if 2+5 < 3 }}
|
||||
IN IF (1)
|
||||
{{ elif 10+15 != 25 }}
|
||||
IN ELIF (2)
|
||||
{{ elif 10+15 == 25 }}
|
||||
IN ELIF (3)
|
||||
{{ else }}
|
||||
IN ELSE (4)
|
||||
{{ end }}
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
<a name="author"></a>
|
||||
## :wink: Author
|
||||
|
||||
**Jean-Christophe Bos** (:fr:)
|
||||
- GitHub: *[@jczic](https://github.com/jczic)*
|
||||
- Email: *<jczic.bos@gmail.com>*
|
||||
- Profil: *[LinkedIn](https://www.linkedin.com/in/jczic)*
|
||||
- Music: *[SoundCloud](https://soundcloud.com/jczic/sets/electro-pulse)*
|
||||
*[Spotify](https://open.spotify.com/album/5fUd57GcAIcdUn9NX3fviG)*
|
||||
*[YouTube](https://www.youtube.com/playlist?list=PL9CsGuMbcLaU02VKS7jtR6LaDNpq7MZEq)*
|
||||
|
||||
|
||||
### By JC`zic for [HC²](https://www.hc2.fr) ;')
|
||||
|
||||
*Keep it simple, stupid* :+1:
|
||||
@@ -0,0 +1,2 @@
|
||||
show_downloads: true
|
||||
theme: jekyll-theme-midnight
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
@@ -0,0 +1,121 @@
|
||||
|
||||
from microWebSrv import MicroWebSrv
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@MicroWebSrv.route('/test')
|
||||
def _httpHandlerTestGet(httpClient, httpResponse) :
|
||||
content = """\
|
||||
<!DOCTYPE html>
|
||||
<html lang=en>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>TEST GET</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>TEST GET</h1>
|
||||
Client IP address = %s
|
||||
<br />
|
||||
<form action="/test" method="post" accept-charset="ISO-8859-1">
|
||||
First name: <input type="text" name="firstname"><br />
|
||||
Last name: <input type="text" name="lastname"><br />
|
||||
<input type="submit" value="Submit">
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
""" % httpClient.GetIPAddr()
|
||||
httpResponse.WriteResponseOk( headers = None,
|
||||
contentType = "text/html",
|
||||
contentCharset = "UTF-8",
|
||||
content = content )
|
||||
|
||||
|
||||
@MicroWebSrv.route('/test', 'POST')
|
||||
def _httpHandlerTestPost(httpClient, httpResponse) :
|
||||
formData = httpClient.ReadRequestPostedFormData()
|
||||
firstname = formData["firstname"]
|
||||
lastname = formData["lastname"]
|
||||
content = """\
|
||||
<!DOCTYPE html>
|
||||
<html lang=en>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>TEST POST</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>TEST POST</h1>
|
||||
Firstname = %s<br />
|
||||
Lastname = %s<br />
|
||||
</body>
|
||||
</html>
|
||||
""" % ( MicroWebSrv.HTMLEscape(firstname),
|
||||
MicroWebSrv.HTMLEscape(lastname) )
|
||||
httpResponse.WriteResponseOk( headers = None,
|
||||
contentType = "text/html",
|
||||
contentCharset = "UTF-8",
|
||||
content = content )
|
||||
|
||||
|
||||
@MicroWebSrv.route('/edit/<index>') # <IP>/edit/123 -> args['index']=123
|
||||
@MicroWebSrv.route('/edit/<index>/abc/<foo>') # <IP>/edit/123/abc/bar -> args['index']=123 args['foo']='bar'
|
||||
@MicroWebSrv.route('/edit') # <IP>/edit -> args={}
|
||||
def _httpHandlerEditWithArgs(httpClient, httpResponse, args={}) :
|
||||
content = """\
|
||||
<!DOCTYPE html>
|
||||
<html lang=en>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>TEST EDIT</title>
|
||||
</head>
|
||||
<body>
|
||||
"""
|
||||
content += "<h1>EDIT item with {} variable arguments</h1>"\
|
||||
.format(len(args))
|
||||
|
||||
if 'index' in args :
|
||||
content += "<p>index = {}</p>".format(args['index'])
|
||||
|
||||
if 'foo' in args :
|
||||
content += "<p>foo = {}</p>".format(args['foo'])
|
||||
|
||||
content += """
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
httpResponse.WriteResponseOk( headers = None,
|
||||
contentType = "text/html",
|
||||
contentCharset = "UTF-8",
|
||||
content = content )
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _acceptWebSocketCallback(webSocket, httpClient) :
|
||||
print("WS ACCEPT")
|
||||
webSocket.RecvTextCallback = _recvTextCallback
|
||||
webSocket.RecvBinaryCallback = _recvBinaryCallback
|
||||
webSocket.ClosedCallback = _closedCallback
|
||||
|
||||
def _recvTextCallback(webSocket, msg) :
|
||||
print("WS RECV TEXT : %s" % msg)
|
||||
webSocket.SendText("Reply for %s" % msg)
|
||||
|
||||
def _recvBinaryCallback(webSocket, data) :
|
||||
print("WS RECV DATA : %s" % data)
|
||||
|
||||
def _closedCallback(webSocket) :
|
||||
print("WS CLOSED")
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
#routeHandlers = [
|
||||
# ( "/test", "GET", _httpHandlerTestGet ),
|
||||
# ( "/test", "POST", _httpHandlerTestPost )
|
||||
#]
|
||||
|
||||
srv = MicroWebSrv(webPath='/web_root/web_admin/')
|
||||
srv.MaxWebSocketRecvLen = 256
|
||||
srv.WebSocketThreaded = False
|
||||
srv.AcceptWebSocketCallback = _acceptWebSocketCallback
|
||||
srv.Start()
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
@@ -0,0 +1,284 @@
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
from hashlib import sha1
|
||||
from binascii import b2a_base64
|
||||
from struct import pack
|
||||
from _thread import start_new_thread, allocate_lock
|
||||
import gc
|
||||
|
||||
class MicroWebSocket :
|
||||
|
||||
# ============================================================================
|
||||
# ===( Constants )============================================================
|
||||
# ============================================================================
|
||||
|
||||
_handshakeSign = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
|
||||
_opContFrame = 0x0
|
||||
_opTextFrame = 0x1
|
||||
_opBinFrame = 0x2
|
||||
_opCloseFrame = 0x8
|
||||
_opPingFrame = 0x9
|
||||
_opPongFrame = 0xA
|
||||
|
||||
_msgTypeText = 1
|
||||
_msgTypeBin = 2
|
||||
|
||||
# ============================================================================
|
||||
# ===( Utils )===============================================================
|
||||
# ============================================================================
|
||||
|
||||
@staticmethod
|
||||
def _tryAllocByteArray(size) :
|
||||
for x in range(10) :
|
||||
try :
|
||||
gc.collect()
|
||||
return bytearray(size)
|
||||
except :
|
||||
pass
|
||||
return None
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _tryStartThread(func, args=()) :
|
||||
for x in range(10) :
|
||||
try :
|
||||
gc.collect()
|
||||
start_new_thread(func, args)
|
||||
return True
|
||||
except :
|
||||
global _mws_thread_id
|
||||
try :
|
||||
_mws_thread_id += 1
|
||||
except :
|
||||
_mws_thread_id = 0
|
||||
try :
|
||||
start_new_thread('MWS_THREAD_%s' % _mws_thread_id, func, args)
|
||||
return True
|
||||
except :
|
||||
pass
|
||||
return False
|
||||
|
||||
# ============================================================================
|
||||
# ===( Constructor )==========================================================
|
||||
# ============================================================================
|
||||
|
||||
def __init__(self, socket, httpClient, httpResponse, maxRecvLen, threaded, acceptCallback) :
|
||||
self._socket = socket
|
||||
self._httpCli = httpClient
|
||||
self._closed = True
|
||||
self._lock = allocate_lock()
|
||||
self.RecvTextCallback = None
|
||||
self.RecvBinaryCallback = None
|
||||
self.ClosedCallback = None
|
||||
|
||||
if hasattr(socket, 'read'): # MicroPython
|
||||
self._socketfile = self._socket
|
||||
else: # CPython
|
||||
self._socketfile = self._socket.makefile('rwb')
|
||||
|
||||
if self._handshake(httpResponse) :
|
||||
self._ctrlBuf = MicroWebSocket._tryAllocByteArray(0x7D)
|
||||
self._msgBuf = MicroWebSocket._tryAllocByteArray(maxRecvLen)
|
||||
if self._ctrlBuf and self._msgBuf :
|
||||
self._msgType = None
|
||||
self._msgLen = 0
|
||||
if threaded :
|
||||
if MicroWebSocket._tryStartThread(self._wsProcess, (acceptCallback, )) :
|
||||
return
|
||||
else :
|
||||
self._wsProcess(acceptCallback)
|
||||
return
|
||||
print("MicroWebSocket : Out of memory on new WebSocket connection.")
|
||||
try :
|
||||
if self._socketfile is not self._socket:
|
||||
self._socketfile.close()
|
||||
self._socket.close()
|
||||
except :
|
||||
pass
|
||||
|
||||
# ============================================================================
|
||||
# ===( Functions )============================================================
|
||||
# ============================================================================
|
||||
|
||||
def _handshake(self, httpResponse) :
|
||||
try :
|
||||
key = self._httpCli.GetRequestHeaders().get('sec-websocket-key', None)
|
||||
if key :
|
||||
key += self._handshakeSign
|
||||
r = sha1(key.encode()).digest()
|
||||
r = b2a_base64(r).decode().strip()
|
||||
httpResponse.WriteSwitchProto("websocket", { "Sec-WebSocket-Accept" : r })
|
||||
return True
|
||||
except :
|
||||
pass
|
||||
return False
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _wsProcess(self, acceptCallback) :
|
||||
self._socket.settimeout(3600)
|
||||
self._closed = False
|
||||
try :
|
||||
acceptCallback(self, self._httpCli)
|
||||
except Exception as ex :
|
||||
print("MicroWebSocket : Error on accept callback (%s)." % str(ex))
|
||||
while not self._closed :
|
||||
if not self._receiveFrame() :
|
||||
self.Close()
|
||||
if self.ClosedCallback :
|
||||
try :
|
||||
self.ClosedCallback(self)
|
||||
except Exception as ex :
|
||||
print("MicroWebSocket : Error on closed callback (%s)." % str(ex))
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _receiveFrame(self) :
|
||||
try :
|
||||
b = self._socketfile.read(2)
|
||||
if not b or len(b) != 2 :
|
||||
return False
|
||||
|
||||
fin = b[0] & 0x80 > 0
|
||||
opcode = b[0] & 0x0F
|
||||
masked = b[1] & 0x80 > 0
|
||||
length = b[1] & 0x7F
|
||||
|
||||
if opcode == self._opContFrame and not self._msgType :
|
||||
return False
|
||||
elif opcode == self._opTextFrame :
|
||||
self._msgType = self._msgTypeText
|
||||
elif opcode == self._opBinFrame :
|
||||
self._msgType = self._msgTypeBin
|
||||
|
||||
if length == 0x7E :
|
||||
b = self._socketfile.read(2)
|
||||
if not b or len(b) != 2 :
|
||||
return False
|
||||
length = (b[0] << 8) + b[1]
|
||||
elif length == 0x7F :
|
||||
return False
|
||||
|
||||
mask = self._socketfile.read(4) if masked else None
|
||||
if masked and (not mask or len(mask) != 4) :
|
||||
return False
|
||||
|
||||
if opcode == self._opContFrame or \
|
||||
opcode == self._opTextFrame or \
|
||||
opcode == self._opBinFrame :
|
||||
|
||||
if length > 0 :
|
||||
buf = memoryview(self._msgBuf)[self._msgLen:]
|
||||
if length > len(buf) :
|
||||
return False
|
||||
x = self._socketfile.readinto(buf[0:length])
|
||||
if x != length :
|
||||
return False
|
||||
if masked :
|
||||
for i in range(length) :
|
||||
idx = self._msgLen + i
|
||||
self._msgBuf[idx] ^= mask[i%4]
|
||||
self._msgLen += length
|
||||
if fin :
|
||||
b = bytes(memoryview(self._msgBuf)[:self._msgLen])
|
||||
if self._msgType == self._msgTypeText :
|
||||
if self.RecvTextCallback :
|
||||
try :
|
||||
self.RecvTextCallback(self, b.decode())
|
||||
except Exception as ex :
|
||||
print("MicroWebSocket : Error on recv text callback (%s)." % str(ex))
|
||||
else :
|
||||
if self.RecvBinaryCallback :
|
||||
try :
|
||||
self.RecvBinaryCallback(self, b)
|
||||
except Exception as ex :
|
||||
print("MicroWebSocket : Error on recv binary callback (%s)." % str(ex))
|
||||
self._msgType = None
|
||||
self._msgLen = 0
|
||||
else :
|
||||
return False
|
||||
|
||||
elif opcode == self._opPingFrame :
|
||||
|
||||
if length > len(self._ctrlBuf) :
|
||||
return False
|
||||
if length > 0 :
|
||||
x = self._socketfile.readinto(self._ctrlBuf[0:length])
|
||||
if x != length :
|
||||
return False
|
||||
pingData = memoryview(self._ctrlBuf)[:length]
|
||||
else :
|
||||
pingData = None
|
||||
self._sendFrame(self._opPongFrame, pingData)
|
||||
|
||||
elif opcode == self._opCloseFrame :
|
||||
self.Close()
|
||||
|
||||
except :
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _sendFrame(self, opcode, data=None, fin=True) :
|
||||
if not self._closed and opcode >= 0x00 and opcode <= 0x0F :
|
||||
dataLen = 0 if not data else len(data)
|
||||
if dataLen <= 0xFFFF :
|
||||
b1 = (0x80 | opcode) if fin else opcode
|
||||
b2 = 0x7E if dataLen >= 0x7E else dataLen
|
||||
self._lock.acquire()
|
||||
try :
|
||||
if self._socketfile.write(pack('>BB', b1, b2)) == 2 :
|
||||
if dataLen > 0 :
|
||||
if dataLen >= 0x7E :
|
||||
self._socketfile.write(pack('>H', dataLen))
|
||||
ret = self._socketfile.write(data) == dataLen
|
||||
else :
|
||||
ret = True
|
||||
if self._socketfile is not self._socket :
|
||||
self._socketfile.flush() # CPython needs flush to continue protocol
|
||||
self._lock.release()
|
||||
return ret
|
||||
except :
|
||||
pass
|
||||
self._lock.release()
|
||||
return False
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def SendText(self, msg) :
|
||||
return self._sendFrame(self._opTextFrame, msg.encode())
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def SendBinary(self, data) :
|
||||
return self._sendFrame(self._opBinFrame, data)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def IsClosed(self) :
|
||||
return self._closed
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def Close(self) :
|
||||
if not self._closed :
|
||||
try :
|
||||
self._sendFrame(self._opCloseFrame)
|
||||
if self._socketfile is not self._socket:
|
||||
self._socketfile.close()
|
||||
self._socket.close()
|
||||
self._closed = True
|
||||
except :
|
||||
pass
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
|
||||
@@ -0,0 +1,881 @@
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
|
||||
from json import loads, dumps
|
||||
from os import stat
|
||||
from _thread import start_new_thread
|
||||
import socket
|
||||
import gc
|
||||
import re
|
||||
|
||||
try :
|
||||
from microWebTemplate import MicroWebTemplate
|
||||
except :
|
||||
pass
|
||||
|
||||
try :
|
||||
from microWebSocket import MicroWebSocket
|
||||
except :
|
||||
print("MicroWebSrv: MicroWebSocket module not found, WebSocket support disabled")
|
||||
pass
|
||||
|
||||
class MicroWebSrvRoute :
|
||||
def __init__(self, route, method, func, routeArgNames, routeRegex) :
|
||||
self.route = route
|
||||
self.method = method
|
||||
self.func = func
|
||||
self.routeArgNames = routeArgNames
|
||||
self.routeRegex = routeRegex
|
||||
|
||||
|
||||
class MicroWebSrv :
|
||||
|
||||
# ============================================================================
|
||||
# ===( Constants )============================================================
|
||||
# ============================================================================
|
||||
|
||||
_indexPages = [
|
||||
"index.pyhtml",
|
||||
"index.html",
|
||||
"index.htm",
|
||||
"default.pyhtml",
|
||||
"default.html",
|
||||
"default.htm"
|
||||
]
|
||||
|
||||
_mimeTypes = {
|
||||
".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 = {
|
||||
"&" : "&",
|
||||
'"' : """,
|
||||
"'" : "'",
|
||||
">" : ">",
|
||||
"<" : "<"
|
||||
}
|
||||
|
||||
_pyhtmlPagesExt = '.pyhtml'
|
||||
|
||||
# ============================================================================
|
||||
# ===( Class globals )=======================================================
|
||||
# ============================================================================
|
||||
|
||||
_docoratedRouteHandlers = []
|
||||
|
||||
# ============================================================================
|
||||
# ===( Utils )===============================================================
|
||||
# ============================================================================
|
||||
|
||||
@classmethod
|
||||
def route(cls, url, method='GET'):
|
||||
""" Adds a route handler function to the routing list """
|
||||
def route_decorator(func):
|
||||
item = (url, method, func)
|
||||
cls._docoratedRouteHandlers.append(item)
|
||||
return func
|
||||
return route_decorator
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def HTMLEscape(s) :
|
||||
return ''.join(MicroWebSrv._html_escape_chars.get(c, c) for c in s)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _startThread(func, args=()) :
|
||||
try :
|
||||
start_new_thread(func, args)
|
||||
except :
|
||||
global _mwsrv_thread_id
|
||||
try :
|
||||
_mwsrv_thread_id += 1
|
||||
except :
|
||||
_mwsrv_thread_id = 0
|
||||
try :
|
||||
start_new_thread('MWSRV_THREAD_%s' % _mwsrv_thread_id, func, args)
|
||||
except :
|
||||
return False
|
||||
return True
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@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 _unquote_plus(s) :
|
||||
return MicroWebSrv._unquote(s.replace('+', ' '))
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _fileExists(path) :
|
||||
try :
|
||||
stat(path)
|
||||
return True
|
||||
except :
|
||||
return False
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _isPyHTMLFile(filename) :
|
||||
return filename.lower().endswith(MicroWebSrv._pyhtmlPagesExt)
|
||||
|
||||
# ============================================================================
|
||||
# ===( Constructor )==========================================================
|
||||
# ============================================================================
|
||||
|
||||
def __init__( self,
|
||||
routeHandlers = [],
|
||||
port = 80,
|
||||
bindIP = '0.0.0.0',
|
||||
webPath = "/flash/www" ) :
|
||||
|
||||
self._srvAddr = (bindIP, port)
|
||||
self._webPath = webPath
|
||||
self._notFoundUrl = None
|
||||
self._started = False
|
||||
|
||||
self.MaxWebSocketRecvLen = 1024
|
||||
self.WebSocketThreaded = True
|
||||
self.AcceptWebSocketCallback = None
|
||||
self.LetCacheStaticContentLevel = 2
|
||||
|
||||
self._routeHandlers = []
|
||||
routeHandlers += self._docoratedRouteHandlers
|
||||
for route, method, func in routeHandlers :
|
||||
routeParts = route.split('/')
|
||||
# -> ['', 'users', '<uID>', 'addresses', '<addrID>', 'test', '<anotherID>']
|
||||
routeArgNames = []
|
||||
routeRegex = ''
|
||||
for s in routeParts :
|
||||
if s.startswith('<') and s.endswith('>') :
|
||||
routeArgNames.append(s[1:-1])
|
||||
routeRegex += '/(\\w*)'
|
||||
elif s :
|
||||
routeRegex += '/' + s
|
||||
routeRegex += '$'
|
||||
# -> '/users/(\w*)/addresses/(\w*)/test/(\w*)$'
|
||||
routeRegex = re.compile(routeRegex)
|
||||
|
||||
self._routeHandlers.append(MicroWebSrvRoute(route, method, func, routeArgNames, routeRegex))
|
||||
|
||||
# ============================================================================
|
||||
# ===( Server Process )=======================================================
|
||||
# ============================================================================
|
||||
|
||||
def _serverProcess(self) :
|
||||
self._started = True
|
||||
while True :
|
||||
try :
|
||||
client, cliAddr = self._server.accept()
|
||||
except Exception as ex :
|
||||
if ex.args and ex.args[0] == 113 :
|
||||
break
|
||||
continue
|
||||
self._client(self, client, cliAddr)
|
||||
self._started = False
|
||||
|
||||
# ============================================================================
|
||||
# ===( Functions )============================================================
|
||||
# ============================================================================
|
||||
|
||||
def Start(self, threaded=False) :
|
||||
if not self._started :
|
||||
self._server = socket.socket()
|
||||
self._server.setsockopt( socket.SOL_SOCKET,
|
||||
socket.SO_REUSEADDR,
|
||||
1 )
|
||||
self._server.bind(self._srvAddr)
|
||||
self._server.listen(16)
|
||||
if threaded :
|
||||
MicroWebSrv._startThread(self._serverProcess)
|
||||
else :
|
||||
self._serverProcess()
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def Stop(self) :
|
||||
if self._started :
|
||||
self._server.close()
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def IsStarted(self) :
|
||||
return self._started
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def SetNotFoundPageUrl(self, url=None) :
|
||||
self._notFoundUrl = url
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def GetMimeTypeFromFilename(self, filename) :
|
||||
filename = filename.lower()
|
||||
for ext in self._mimeTypes :
|
||||
if filename.endswith(ext) :
|
||||
return self._mimeTypes[ext]
|
||||
return None
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def GetRouteHandler(self, resUrl, method) :
|
||||
if self._routeHandlers :
|
||||
#resUrl = resUrl.upper()
|
||||
if resUrl.endswith('/') :
|
||||
resUrl = resUrl[:-1]
|
||||
method = method.upper()
|
||||
for rh in self._routeHandlers :
|
||||
if rh.method == method :
|
||||
m = rh.routeRegex.match(resUrl)
|
||||
if m : # found matching route?
|
||||
if rh.routeArgNames :
|
||||
routeArgs = {}
|
||||
for i, name in enumerate(rh.routeArgNames) :
|
||||
value = m.group(i+1)
|
||||
try :
|
||||
value = int(value)
|
||||
except :
|
||||
pass
|
||||
routeArgs[name] = value
|
||||
return (rh.func, routeArgs)
|
||||
else :
|
||||
return (rh.func, None)
|
||||
return (None, None)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _physPathFromURLPath(self, urlPath) :
|
||||
if urlPath == '/' :
|
||||
for idxPage in self._indexPages :
|
||||
physPath = self._webPath + '/' + idxPage
|
||||
if MicroWebSrv._fileExists(physPath) :
|
||||
return physPath
|
||||
else :
|
||||
physPath = self._webPath + urlPath.replace('../', '/')
|
||||
if MicroWebSrv._fileExists(physPath) :
|
||||
return physPath
|
||||
return None
|
||||
|
||||
# ============================================================================
|
||||
# ===( Class Client )========================================================
|
||||
# ============================================================================
|
||||
|
||||
class _client :
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self, microWebSrv, socket, addr) :
|
||||
socket.settimeout(2)
|
||||
self._microWebSrv = microWebSrv
|
||||
self._socket = socket
|
||||
self._addr = addr
|
||||
self._method = None
|
||||
self._path = None
|
||||
self._httpVer = None
|
||||
self._resPath = "/"
|
||||
self._queryString = ""
|
||||
self._queryParams = { }
|
||||
self._headers = { }
|
||||
self._contentType = None
|
||||
self._contentLength = 0
|
||||
|
||||
if hasattr(socket, 'readline'): # MicroPython
|
||||
self._socketfile = self._socket
|
||||
else: # CPython
|
||||
self._socketfile = self._socket.makefile('rwb')
|
||||
|
||||
self._processRequest()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processRequest(self) :
|
||||
try :
|
||||
response = MicroWebSrv._response(self)
|
||||
if self._parseFirstLine(response) :
|
||||
if self._parseHeader(response) :
|
||||
upg = self._getConnUpgrade()
|
||||
if not upg :
|
||||
routeHandler, routeArgs = self._microWebSrv.GetRouteHandler(self._resPath, self._method)
|
||||
if routeHandler :
|
||||
try :
|
||||
if routeArgs is not None:
|
||||
routeHandler(self, response, routeArgs)
|
||||
else :
|
||||
routeHandler(self, response)
|
||||
except Exception as ex :
|
||||
print('MicroWebSrv handler exception:\r\n - In route %s %s\r\n - %s' % (self._method, self._resPath, ex))
|
||||
raise ex
|
||||
elif self._method.upper() == "GET" :
|
||||
filepath = self._microWebSrv._physPathFromURLPath(self._resPath)
|
||||
if filepath :
|
||||
if MicroWebSrv._isPyHTMLFile(filepath) :
|
||||
response.WriteResponsePyHTMLFile(filepath)
|
||||
else :
|
||||
contentType = self._microWebSrv.GetMimeTypeFromFilename(filepath)
|
||||
if contentType :
|
||||
if self._microWebSrv.LetCacheStaticContentLevel > 0 :
|
||||
if self._microWebSrv.LetCacheStaticContentLevel > 1 and \
|
||||
'if-modified-since' in self._headers :
|
||||
response.WriteResponseNotModified()
|
||||
else:
|
||||
headers = { 'Last-Modified' : 'Fri, 1 Jan 2018 23:42:00 GMT', \
|
||||
'Cache-Control' : 'max-age=315360000' }
|
||||
response.WriteResponseFile(filepath, contentType, headers)
|
||||
else :
|
||||
response.WriteResponseFile(filepath, contentType)
|
||||
else :
|
||||
response.WriteResponseForbidden()
|
||||
else :
|
||||
response.WriteResponseNotFound()
|
||||
else :
|
||||
response.WriteResponseMethodNotAllowed()
|
||||
elif upg == 'websocket' and 'MicroWebSocket' in globals() \
|
||||
and self._microWebSrv.AcceptWebSocketCallback :
|
||||
MicroWebSocket( socket = self._socket,
|
||||
httpClient = self,
|
||||
httpResponse = response,
|
||||
maxRecvLen = self._microWebSrv.MaxWebSocketRecvLen,
|
||||
threaded = self._microWebSrv.WebSocketThreaded,
|
||||
acceptCallback = self._microWebSrv.AcceptWebSocketCallback )
|
||||
return
|
||||
else :
|
||||
response.WriteResponseNotImplemented()
|
||||
else :
|
||||
response.WriteResponseBadRequest()
|
||||
except :
|
||||
response.WriteResponseInternalServerError()
|
||||
try :
|
||||
if self._socketfile is not self._socket:
|
||||
self._socketfile.close()
|
||||
self._socket.close()
|
||||
except :
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _parseFirstLine(self, response) :
|
||||
try :
|
||||
elements = self._socketfile.readline().decode().strip().split()
|
||||
if len(elements) == 3 :
|
||||
self._method = elements[0].upper()
|
||||
self._path = elements[1]
|
||||
self._httpVer = elements[2].upper()
|
||||
elements = self._path.split('?', 1)
|
||||
if len(elements) > 0 :
|
||||
self._resPath = MicroWebSrv._unquote_plus(elements[0])
|
||||
if len(elements) > 1 :
|
||||
self._queryString = elements[1]
|
||||
elements = self._queryString.split('&')
|
||||
for s in elements :
|
||||
param = s.split('=', 1)
|
||||
if len(param) > 0 :
|
||||
value = MicroWebSrv._unquote(param[1]) if len(param) > 1 else ''
|
||||
self._queryParams[MicroWebSrv._unquote(param[0])] = value
|
||||
return True
|
||||
except :
|
||||
pass
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _parseHeader(self, response) :
|
||||
while True :
|
||||
elements = self._socketfile.readline().decode().strip().split(':', 1)
|
||||
if len(elements) == 2 :
|
||||
self._headers[elements[0].strip().lower()] = elements[1].strip()
|
||||
elif len(elements) == 1 and len(elements[0]) == 0 :
|
||||
if self._method == 'POST' or self._method == 'PUT' :
|
||||
self._contentType = self._headers.get("content-type", None)
|
||||
self._contentLength = int(self._headers.get("content-length", 0))
|
||||
return True
|
||||
else :
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _getConnUpgrade(self) :
|
||||
if 'upgrade' in self._headers.get('connection', '').lower() :
|
||||
return self._headers.get('upgrade', '').lower()
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetServer(self) :
|
||||
return self._microWebSrv
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetAddr(self) :
|
||||
return self._addr
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetIPAddr(self) :
|
||||
return self._addr[0]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetPort(self) :
|
||||
return self._addr[1]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestMethod(self) :
|
||||
return self._method
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestTotalPath(self) :
|
||||
return self._path
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestPath(self) :
|
||||
return self._resPath
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestQueryString(self) :
|
||||
return self._queryString
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestQueryParams(self) :
|
||||
return self._queryParams
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestHeaders(self) :
|
||||
return self._headers
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestContentType(self) :
|
||||
return self._contentType
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestContentLength(self) :
|
||||
return self._contentLength
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReadRequestContent(self, size=None) :
|
||||
if size is None :
|
||||
size = self._contentLength
|
||||
if size > 0 :
|
||||
try :
|
||||
return self._socketfile.read(size)
|
||||
except :
|
||||
pass
|
||||
return b''
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReadRequestPostedFormData(self) :
|
||||
res = { }
|
||||
data = self.ReadRequestContent()
|
||||
if data :
|
||||
elements = data.decode().split('&')
|
||||
for s in elements :
|
||||
param = s.split('=', 1)
|
||||
if len(param) > 0 :
|
||||
value = MicroWebSrv._unquote_plus(param[1]) if len(param) > 1 else ''
|
||||
res[MicroWebSrv._unquote_plus(param[0])] = value
|
||||
return res
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReadRequestContentAsJSON(self) :
|
||||
data = self.ReadRequestContent()
|
||||
if data :
|
||||
try :
|
||||
return loads(data.decode())
|
||||
except :
|
||||
pass
|
||||
return None
|
||||
|
||||
# ============================================================================
|
||||
# ===( Class Response )======================================================
|
||||
# ============================================================================
|
||||
|
||||
class _response :
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self, client) :
|
||||
self._client = client
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _write(self, data, strEncoding='ISO-8859-1') :
|
||||
if data :
|
||||
if type(data) == str :
|
||||
data = data.encode(strEncoding)
|
||||
data = memoryview(data)
|
||||
while data :
|
||||
n = self._client._socketfile.write(data)
|
||||
if n is None :
|
||||
return False
|
||||
data = data[n:]
|
||||
return True
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _writeFirstLine(self, code) :
|
||||
reason = self._responseCodes.get(code, ('Unknown reason', ))[0]
|
||||
return self._write("HTTP/1.1 %s %s\r\n" % (code, reason))
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _writeHeader(self, name, value) :
|
||||
return self._write("%s: %s\r\n" % (name, value))
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _writeContentTypeHeader(self, contentType, charset=None) :
|
||||
if contentType :
|
||||
ct = contentType \
|
||||
+ (("; charset=%s" % charset) if charset else "")
|
||||
else :
|
||||
ct = "application/octet-stream"
|
||||
self._writeHeader("Content-Type", ct)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _writeServerHeader(self) :
|
||||
self._writeHeader("Server", "MicroWebSrv by JC`zic")
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _writeEndHeader(self) :
|
||||
return self._write("\r\n")
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _writeBeforeContent(self, code, headers, contentType, contentCharset, contentLength) :
|
||||
self._writeFirstLine(code)
|
||||
if isinstance(headers, dict) :
|
||||
for header in headers :
|
||||
self._writeHeader(header, headers[header])
|
||||
if contentLength > 0 :
|
||||
self._writeContentTypeHeader(contentType, contentCharset)
|
||||
self._writeHeader("Content-Length", contentLength)
|
||||
self._writeServerHeader()
|
||||
self._writeHeader("Connection", "close")
|
||||
self._writeEndHeader()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteSwitchProto(self, upgrade, headers=None) :
|
||||
self._writeFirstLine(101)
|
||||
self._writeHeader("Connection", "Upgrade")
|
||||
self._writeHeader("Upgrade", upgrade)
|
||||
if isinstance(headers, dict) :
|
||||
for header in headers :
|
||||
self._writeHeader(header, headers[header])
|
||||
self._writeServerHeader()
|
||||
self._writeEndHeader()
|
||||
if self._client._socketfile is not self._client._socket :
|
||||
self._client._socketfile.flush() # CPython needs flush to continue protocol
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponse(self, code, headers, contentType, contentCharset, content) :
|
||||
try :
|
||||
if content :
|
||||
if type(content) == str :
|
||||
content = content.encode(contentCharset)
|
||||
contentLength = len(content)
|
||||
else :
|
||||
contentLength = 0
|
||||
self._writeBeforeContent(code, headers, contentType, contentCharset, contentLength)
|
||||
if content :
|
||||
return self._write(content)
|
||||
return True
|
||||
except :
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponsePyHTMLFile(self, filepath, headers=None, vars=None) :
|
||||
if 'MicroWebTemplate' in globals() :
|
||||
with open(filepath, 'r') as file :
|
||||
code = file.read()
|
||||
mWebTmpl = MicroWebTemplate(code, escapeStrFunc=MicroWebSrv.HTMLEscape, filepath=filepath)
|
||||
try :
|
||||
tmplResult = mWebTmpl.Execute(None, vars)
|
||||
return self.WriteResponse(200, headers, "text/html", "UTF-8", tmplResult)
|
||||
except Exception as ex :
|
||||
return self.WriteResponse( 500,
|
||||
None,
|
||||
"text/html",
|
||||
"UTF-8",
|
||||
self._execErrCtnTmpl % {
|
||||
'module' : 'PyHTML',
|
||||
'message' : str(ex)
|
||||
} )
|
||||
return self.WriteResponseNotImplemented()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseFile(self, filepath, contentType=None, headers=None) :
|
||||
try :
|
||||
size = stat(filepath)[6]
|
||||
if size > 0 :
|
||||
with open(filepath, 'rb') as file :
|
||||
self._writeBeforeContent(200, headers, contentType, None, size)
|
||||
try :
|
||||
buf = bytearray(1024)
|
||||
while size > 0 :
|
||||
x = file.readinto(buf)
|
||||
if x < len(buf) :
|
||||
buf = memoryview(buf)[:x]
|
||||
if not self._write(buf) :
|
||||
return False
|
||||
size -= x
|
||||
return True
|
||||
except :
|
||||
self.WriteResponseInternalServerError()
|
||||
return False
|
||||
except :
|
||||
pass
|
||||
self.WriteResponseNotFound()
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseFileAttachment(self, filepath, attachmentName, headers=None) :
|
||||
if not isinstance(headers, dict) :
|
||||
headers = { }
|
||||
headers["Content-Disposition"] = "attachment; filename=\"%s\"" % attachmentName
|
||||
return self.WriteResponseFile(filepath, None, headers)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseOk(self, headers=None, contentType=None, contentCharset=None, content=None) :
|
||||
return self.WriteResponse(200, headers, contentType, contentCharset, content)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseJSONOk(self, obj=None, headers=None) :
|
||||
return self.WriteResponse(200, headers, "application/json", "UTF-8", dumps(obj))
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseRedirect(self, location) :
|
||||
headers = { "Location" : location }
|
||||
return self.WriteResponse(302, headers, None, None, None)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseError(self, code) :
|
||||
responseCode = self._responseCodes.get(code, ('Unknown reason', ''))
|
||||
return self.WriteResponse( code,
|
||||
None,
|
||||
"text/html",
|
||||
"UTF-8",
|
||||
self._errCtnTmpl % {
|
||||
'code' : code,
|
||||
'reason' : responseCode[0],
|
||||
'message' : responseCode[1]
|
||||
} )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseJSONError(self, code, obj=None) :
|
||||
return self.WriteResponse( code,
|
||||
None,
|
||||
"application/json",
|
||||
"UTF-8",
|
||||
dumps(obj if obj else { }) )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseNotModified(self) :
|
||||
return self.WriteResponseError(304)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseBadRequest(self) :
|
||||
return self.WriteResponseError(400)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseForbidden(self) :
|
||||
return self.WriteResponseError(403)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseNotFound(self) :
|
||||
if self._client._microWebSrv._notFoundUrl :
|
||||
self.WriteResponseRedirect(self._client._microWebSrv._notFoundUrl)
|
||||
else :
|
||||
return self.WriteResponseError(404)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseMethodNotAllowed(self) :
|
||||
return self.WriteResponseError(405)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseInternalServerError(self) :
|
||||
return self.WriteResponseError(500)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseNotImplemented(self) :
|
||||
return self.WriteResponseError(501)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def FlashMessage(self, messageText, messageStyle='') :
|
||||
if 'MicroWebTemplate' in globals() :
|
||||
MicroWebTemplate.MESSAGE_TEXT = messageText
|
||||
MicroWebTemplate.MESSAGE_STYLE = messageStyle
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
_errCtnTmpl = """\
|
||||
<html>
|
||||
<head>
|
||||
<title>Error</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>%(code)d %(reason)s</h1>
|
||||
%(message)s
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
_execErrCtnTmpl = """\
|
||||
<html>
|
||||
<head>
|
||||
<title>Page execution error</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>%(module)s page execution error</h1>
|
||||
%(message)s
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
_responseCodes = {
|
||||
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.'),
|
||||
}
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 43 KiB |
@@ -0,0 +1,336 @@
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
class MicroWebTemplate :
|
||||
|
||||
# ============================================================================
|
||||
# ===( Constants )============================================================
|
||||
# ============================================================================
|
||||
|
||||
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'
|
||||
INSTRUCTION_INCLUDE = 'include'
|
||||
|
||||
MESSAGE_TEXT = ''
|
||||
MESSAGE_STYLE = ''
|
||||
|
||||
# ============================================================================
|
||||
# ===( Constructor )==========================================================
|
||||
# ============================================================================
|
||||
|
||||
def __init__(self, code, escapeStrFunc=None, filepath='') :
|
||||
self._code = code
|
||||
self._escapeStrFunc = escapeStrFunc
|
||||
self._filepath = filepath
|
||||
self._pos = 0
|
||||
self._endPos = len(code)-1
|
||||
self._line = 1
|
||||
self._reIdentifier = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$')
|
||||
self._pyGlobalVars = { }
|
||||
self._pyLocalVars = { }
|
||||
self._rendered = ''
|
||||
self._instructions = {
|
||||
MicroWebTemplate.INSTRUCTION_PYTHON : self._processInstructionPYTHON,
|
||||
MicroWebTemplate.INSTRUCTION_IF : self._processInstructionIF,
|
||||
MicroWebTemplate.INSTRUCTION_ELIF : self._processInstructionELIF,
|
||||
MicroWebTemplate.INSTRUCTION_ELSE : self._processInstructionELSE,
|
||||
MicroWebTemplate.INSTRUCTION_FOR : self._processInstructionFOR,
|
||||
MicroWebTemplate.INSTRUCTION_END : self._processInstructionEND,
|
||||
MicroWebTemplate.INSTRUCTION_INCLUDE: self._processInstructionINCLUDE,
|
||||
}
|
||||
|
||||
# ============================================================================
|
||||
# ===( Functions )============================================================
|
||||
# ============================================================================
|
||||
|
||||
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 Exception(str(ex))
|
||||
|
||||
# ============================================================================
|
||||
# ===( Utils )===============================================================
|
||||
# ============================================================================
|
||||
|
||||
def _parseCode(self, pyGlobalVars, pyLocalVars, execute) :
|
||||
if pyGlobalVars:
|
||||
self._pyGlobalVars.update(pyGlobalVars)
|
||||
if pyLocalVars:
|
||||
self._pyLocalVars.update(pyLocalVars)
|
||||
self._pyLocalVars['MESSAGE_TEXT'] = MicroWebTemplate.MESSAGE_TEXT
|
||||
self._pyLocalVars['MESSAGE_STYLE'] = MicroWebTemplate.MESSAGE_STYLE
|
||||
self._rendered = ''
|
||||
newTokenToProcess = self._parseBloc(execute)
|
||||
if newTokenToProcess is not None :
|
||||
raise Exception( '"%s" instruction is not valid here (line %s)'
|
||||
% (newTokenToProcess, self._line) )
|
||||
MicroWebTemplate.MESSAGE_TEXT = ''
|
||||
MicroWebTemplate.MESSAGE_STYLE = ''
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _parseBloc(self, execute) :
|
||||
while self._pos <= self._endPos :
|
||||
c = self._code[self._pos]
|
||||
if c == MicroWebTemplate.TOKEN_OPEN[0] and \
|
||||
self._code[ self._pos : self._pos + MicroWebTemplate.TOKEN_OPEN_LEN ] == MicroWebTemplate.TOKEN_OPEN :
|
||||
self._pos += MicroWebTemplate.TOKEN_OPEN_LEN
|
||||
tokenContent = ''
|
||||
x = self._pos
|
||||
while True :
|
||||
if x > self._endPos :
|
||||
raise Exception("%s is missing (line %s)" % (MicroWebTemplate.TOKEN_CLOSE, self._line))
|
||||
c = self._code[x]
|
||||
if c == MicroWebTemplate.TOKEN_CLOSE[0] and \
|
||||
self._code[ x : x + MicroWebTemplate.TOKEN_CLOSE_LEN ] == MicroWebTemplate.TOKEN_CLOSE :
|
||||
self._pos = x + MicroWebTemplate.TOKEN_CLOSE_LEN
|
||||
break
|
||||
elif c == '\n' :
|
||||
self._line += 1
|
||||
tokenContent += c
|
||||
x += 1
|
||||
newTokenToProcess = self._processToken(tokenContent, execute)
|
||||
if newTokenToProcess is not None :
|
||||
return newTokenToProcess
|
||||
continue
|
||||
elif c == '\n' :
|
||||
self._line += 1
|
||||
if execute :
|
||||
self._rendered += c
|
||||
self._pos += 1
|
||||
return None
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processToken(self, tokenContent, execute) :
|
||||
tokenContent = tokenContent.strip()
|
||||
parts = tokenContent.split(' ', 1)
|
||||
instructName = parts[0].strip()
|
||||
instructBody = parts[1].strip() if len(parts) > 1 else None
|
||||
if len(instructName) == 0 :
|
||||
raise Exception( '"%s %s" : instruction is missing (line %s)'
|
||||
% (MicroWebTemplate.TOKEN_OPEN, MicroWebTemplate.TOKEN_CLOSE, self._line) )
|
||||
newTokenToProcess = None
|
||||
if instructName in self._instructions :
|
||||
newTokenToProcess = self._instructions[instructName](instructBody, execute)
|
||||
elif execute :
|
||||
try :
|
||||
s = str( eval( tokenContent,
|
||||
self._pyGlobalVars,
|
||||
self._pyLocalVars ) )
|
||||
if (self._escapeStrFunc is not None) :
|
||||
self._rendered += self._escapeStrFunc(s)
|
||||
else :
|
||||
self._rendered += s
|
||||
except Exception as ex :
|
||||
raise Exception('%s (line %s)' % (str(ex), self._line))
|
||||
return newTokenToProcess
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionPYTHON(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
raise Exception( 'Instruction "%s" is invalid (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_PYTHON, self._line) )
|
||||
pyCode = ''
|
||||
while True :
|
||||
if self._pos > self._endPos :
|
||||
raise Exception( '"%s" instruction is missing (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
c = self._code[self._pos]
|
||||
if c == MicroWebTemplate.TOKEN_OPEN[0] and \
|
||||
self._code[ self._pos : self._pos + MicroWebTemplate.TOKEN_OPEN_LEN ] == MicroWebTemplate.TOKEN_OPEN :
|
||||
self._pos += MicroWebTemplate.TOKEN_OPEN_LEN
|
||||
tokenContent = ''
|
||||
x = self._pos
|
||||
while True :
|
||||
if x > self._endPos :
|
||||
raise Exception("%s is missing (line %s)" % (MicroWebTemplate.TOKEN_CLOSE, self._line))
|
||||
c = self._code[x]
|
||||
if c == MicroWebTemplate.TOKEN_CLOSE[0] and \
|
||||
self._code[ x : x + MicroWebTemplate.TOKEN_CLOSE_LEN ] == MicroWebTemplate.TOKEN_CLOSE :
|
||||
self._pos = x + MicroWebTemplate.TOKEN_CLOSE_LEN
|
||||
break
|
||||
elif c == '\n' :
|
||||
self._line += 1
|
||||
tokenContent += c
|
||||
x += 1
|
||||
tokenContent = tokenContent.strip()
|
||||
if tokenContent == MicroWebTemplate.INSTRUCTION_END :
|
||||
break
|
||||
raise Exception( '"%s" is a bad instruction in a python bloc (line %s)'
|
||||
% (tokenContent, self._line) )
|
||||
elif c == '\n' :
|
||||
self._line += 1
|
||||
if execute :
|
||||
pyCode += c
|
||||
self._pos += 1
|
||||
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
|
||||
pyCode = ''
|
||||
for line in lines :
|
||||
if line.find(indent) == 0 :
|
||||
line = line[len(indent):]
|
||||
pyCode += line + '\n'
|
||||
try :
|
||||
exec(pyCode, self._pyGlobalVars, self._pyLocalVars)
|
||||
except Exception as ex :
|
||||
raise Exception('%s (line %s)' % (str(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 Exception('%s (line %s)' % (str(ex), self._line))
|
||||
else :
|
||||
result = False
|
||||
newTokenToProcess = self._parseBloc(execute and result)
|
||||
if newTokenToProcess is not None :
|
||||
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
|
||||
return None
|
||||
elif newTokenToProcess == MicroWebTemplate.INSTRUCTION_ELSE :
|
||||
newTokenToProcess = self._parseBloc(execute and not result)
|
||||
if newTokenToProcess is not None :
|
||||
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
|
||||
return None
|
||||
raise Exception( '"%s" instruction waited (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
raise Exception( '"%s" instruction is missing (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
elif newTokenToProcess == MicroWebTemplate.INSTRUCTION_ELIF :
|
||||
self._processInstructionIF(self._elifInstructionBody, execute and not result)
|
||||
return None
|
||||
raise Exception( '"%s" instruction waited (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
raise Exception( '"%s" instruction is missing (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_IF, self._line) )
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionELIF(self, instructionBody, execute) :
|
||||
if instructionBody is None :
|
||||
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_ELIF, self._line) )
|
||||
self._elifInstructionBody = instructionBody
|
||||
return MicroWebTemplate.INSTRUCTION_ELIF
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionELSE(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
raise Exception( 'Instruction "%s" is invalid (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_ELSE, self._line) )
|
||||
return MicroWebTemplate.INSTRUCTION_ELSE
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionFOR(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
parts = instructionBody.split(' ', 1)
|
||||
identifier = parts[0].strip()
|
||||
if self._reIdentifier.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 Exception('%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 != MicroWebTemplate.INSTRUCTION_END :
|
||||
break
|
||||
else :
|
||||
newTokenToProcess = self._parseBloc(False)
|
||||
if newTokenToProcess is not None :
|
||||
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
|
||||
return None
|
||||
raise Exception( '"%s" instruction waited (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
raise Exception( '"%s" instruction is missing (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
raise Exception( '"%s %s" is an invalid syntax'
|
||||
% (MicroWebTemplate.INSTRUCTION_FOR, instructionBody) )
|
||||
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_FOR, self._line) )
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionEND(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
raise Exception( 'Instruction "%s" is invalid (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
return MicroWebTemplate.INSTRUCTION_END
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionINCLUDE(self, instructionBody, execute) :
|
||||
if not instructionBody :
|
||||
raise Exception( '"%s" alone is an incomplete syntax (line %s)' % (MicroWebTemplate.INSTRUCTION_INCLUDE, self._line) )
|
||||
filename = instructionBody.replace('"','').replace("'",'').strip()
|
||||
idx = self._filepath.rindex('/')
|
||||
if idx >= 0 :
|
||||
filename = self._filepath[:idx+1] + filename
|
||||
with open(filename, 'r') as file :
|
||||
includeCode = file.read()
|
||||
|
||||
self._code = self._code[:self._pos] + includeCode + self._code[self._pos:]
|
||||
self._endPos += len(includeCode)
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 7.7 KiB |
@@ -0,0 +1,28 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang=fr>
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Page de test MicroWebSrv</title>
|
||||
<link rel="stylesheet" href="style.css" />
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Page de test MicroWebSrv</h1>
|
||||
<h2>Hello !</h2>
|
||||
<p>
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget ligula quis libero mollis dapibus. Suspendisse potenti. Nullam facilisis neque et sem. Proin placerat adipiscing urna. Aenean sollicitudin. Mauris lorem erat, fringilla quis, sagittis a, varius sed, nunc. Pellentesque ligula. Nullam egestas eleifend turpis. Vivamus ac sapien. Sed venenatis, ligula ut scelerisque vehicula, erat tellus euismod ipsum, eget faucibus tortor arcu et lectus. Vivamus vel purus. Fusce dignissim tortor quis diam elementum fermentum. Mauris eleifend lorem vel arcu. Vivamus tempus faucibus lectus. Curabitur volutpat ornare mi. Curabitur ac libero. Sed eu elit ac metus egestas iaculis.
|
||||
</p>
|
||||
<br />
|
||||
<hr />
|
||||
<br />
|
||||
<div style="text-align: center">
|
||||
<img src="pdf.png" />
|
||||
<p>
|
||||
Afficher « <a href="test.pdf">un fichier PDF</a> »
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.4 KiB |
@@ -0,0 +1,36 @@
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
body {
|
||||
background-color: white;
|
||||
font-family: Verdana, sans-serif;
|
||||
font-size: 100%;
|
||||
}
|
||||
h1 {
|
||||
font-size: 200%;
|
||||
color: navy;
|
||||
text-align: center;
|
||||
}
|
||||
h2 {
|
||||
font-size: 150%;
|
||||
color: red;
|
||||
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;
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,34 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>TEST</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>BEGIN</h1>
|
||||
{{ py }}
|
||||
def _testFunction(x) :
|
||||
return "IN TEST FUNCTION %s" % x
|
||||
{{ end }}
|
||||
<div style="background-color: black; color: white;">
|
||||
{{ for toto in range(3) }}
|
||||
This is an HTML test...<br />
|
||||
TOTO = {{ toto + 1 }} !<br />
|
||||
{{ for toto2 in range(3) }}
|
||||
TOTO2 = {{ _testFunction(toto2) }}
|
||||
{{ end }}
|
||||
Ok good.<br />
|
||||
{{ end }}
|
||||
</div>
|
||||
{{ _testFunction(100) }}<br />
|
||||
<br />
|
||||
{{ if 2+5 < 3 }}
|
||||
IN IF (1)
|
||||
{{ elif 10+15 != 25 }}
|
||||
IN ELIF (2)
|
||||
{{ elif 10+15 == 25 }}
|
||||
IN ELIF (3)
|
||||
{{ else }}
|
||||
IN ELSE (4)
|
||||
{{ end }}
|
||||
<h1>JC :')</h1>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,78 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>MicroWebSocket Test</title>
|
||||
</head>
|
||||
|
||||
<script language="javascript">
|
||||
|
||||
var output;
|
||||
|
||||
function init()
|
||||
{
|
||||
output = document.getElementById("output");
|
||||
testWebSocket();
|
||||
}
|
||||
|
||||
function testWebSocket()
|
||||
{
|
||||
var wsUri = "ws://" + window.location.hostname;
|
||||
writeToScreen("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) };
|
||||
}
|
||||
|
||||
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() }, 500 )
|
||||
}
|
||||
|
||||
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>
|
||||
<h2>MicroWebSocket Test :</h2>
|
||||
<div id="output"></div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
Reference in New Issue
Block a user