# ESP32网站开发手册

PCY-ESP32-N1
默认集成了
MicroWebSrv2
模块,
也就是说,它也是一个微型的Web服务器。接下来我们来介绍如何在PCY-ESP32-N1
开发板上进行微型网站的开发。
# MicroWebSrv2介绍
MicroWebSrv2是适用于MicroPython
和CPython
的功能强大的新型嵌入式Web服务器,支持路由处理(route handlers),
支持WebSockets、PyhtmlTemplate等模块,支持巨量并发请求。
它是完全异步的,连接和内存管理得到了很好的优化,提高了响应速度。
主要应用在
Pyboard
Pycom WiPy
ESP32
STM32
等资源紧张的开发板上。
# 默认页面
当请求的路径指向目录时,将使用如下文件作为默认页面。
页面文件名 |
---|
index.html |
index.htm |
default.html |
default.htm |
提示
可以通过调用MicroWebSrv2.AddDefaultPage静态方法来全局添加新的默认页面。
# 静态资源访问
只需要将静态资源文件,放到www
目录下,就可以被访问到。
MIME类型允许特定文件作为可读资源,并与相应的内容类型一起传输。
文件扩展名 | MIME类型 |
---|---|
.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 |
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 |
提示
可以通过调用MicroWebSrv2.AddMimeType静态方法来全局添加新的MIME类型。
# 处理网页路由
microWebSrv2具有简单有效的网络路由系统。 一个带有装饰器的简单处理程序函数,使您可以处理请求。
处理请求的示例:
from MicroWebSrv2 import *
@WebRoute(GET, '/test')
def RequestTest(microWebSrv2, request) :
request.Response.ReturnOkJSON({
'ClientAddr' : request.UserAddress,
'Accept' : request.Accept,
'UserAgent' : request.UserAgent
})
提示
更多详细文档,请转Web路由。
# MicroWebSrv2类
MicroWebSrv2是主类,并且已经被程序框架创建了实例对象。 想要访问该对象,需要如下方法引用:
from PineconeNode import mws2
print(dir(mws2))
# MicroWebSrv2静态方法
- MicroWebSrv2.LoadModule(...)
@staticmethod
def LoadModule(modName)
# 为MicroWebSrv2的所有实例加载一个全局专用模块。
# -返回模块的实例化类。
# 此实例可用于配置全局参数和回调。
# -<modName>是模块的名称,必须是非空字符串。
# 如果发生错误,将引发异常。
- MicroWebSrv2.HTMLEscape(...)
@staticmethod
def HTMLEscape(s)
# Escapes HTML special characters of a text to use it in HTML code.
# - Returns the escaped string of <s>.
# - <s> is a text that must be escaped and must be a string.
# An exception can be raised if <s> is not correct.
- MicroWebSrv2.AddDefaultPage(...)
@staticmethod
def AddDefaultPage(filename)
# Adds a new default page that it can be returned when a directory resource is requested.
# Default pages are searched by order in list and file must be found in the directory.
# Ex: AddDefaultPage('home.html')
# - No return value.
# - <filename> is the name of page file that will be searched and must be a not empty string.
# An exception can be raised if <filename> is not correct.
- MicroWebSrv2.AddMimeType(...)
@staticmethod
def AddMimeType(ext, mimeType)
# Adds a new MIME type to support specified file type and response content type.
# Ex: AddMimeType('.tar', 'application/x-tar')
# - No return value.
# - <ext> is the file extention including the dot and must be a not empty string.
# - <mimeType> is the name of MIME type and must be a not empty string.
# An exception can be raised if arguments are not correct.
- MicroWebSrv2.GetMimeTypeFromFilename(...)
@staticmethod
def GetMimeTypeFromFilename(filename)
# Obtains the name of MIME type corresponding to a filename.
# - Returns the name of MIME type found in string, returns None otherwise.
# - <filename> is a path to a file and must be a not empty string.
# MicroWebSrv2实例方法
- mws2.ResolvePhysicalPath(...)
def ResolvePhysicalPath(self, urlPath)
# Resolves the specified relative URL path to the physical path.
# - Returns the physical path found or None.
# - <urlPath> is the relative URL path to resolve and must be a not empty string.
# An exception can be raised if <urlPath> is not correct.
- mws2.EnableSSL(...)
def EnableSSL(self, certFile, keyFile, caFile=None)
# Configures the web server to apply the SSL/TLS security layer (https).
# Warning, the ssl library must be implements SSLContext on Python version to support secured web server.
# - No return value.
# - <certFile> is the path of the certificate file and must be a not empty string.
# - <keyFile> is the path of the private key file and must be a not empty string.
# - <caFile> is the path of a PEM file and must be a not empty string or None.
# If the web server port in BindAddress is 80 (default http), it automatically switches to port 443 (default https).
# An exception will be raised if an error occurs.
- mws2.DisableSSL(...)
def DisableSSL(self)
# Configures the web server as SSL/TLS web server (https).
# - No return value.
# If the web server port in BindAddress is 443 (default https), it automatically switches to port 80 (default http).
# An exception can be raised if an error occurs.
# MicroWebSrv2属性
名称 | 类型 | Get | Set | 说明 |
---|---|---|---|---|
IsRunning | bool | ☑️ | - | Indicates that the server is running. |
ConnQueueCapacity | int | ☑️ | ☑️ | Queue capacity of the TCP server (backlog). |
BufferSlotsCount | int | ☑️ | ☑️ | Number of pre-allocated memory buffer slots. |
BufferSlotSize | int | ☑️ | ☑️ | Size of each pre-allocated memory buffer slots. |
KeepAllocBufferSlots | bool | ☑️ | ☑️ | Maintains the allocation of memory buffer slots. |
MaxRequestContentLength | int | ☑️ | ☑️ | Maximum content length who can be processed by a request. |
BindAddress | tuple | ☑️ | ☑️ | Local bind address of the TCP server such as a tuple of (str_ip_addr, int_port). |
IsSSLEnabled | bool | ☑️ | - | Indicates that SSL/TLS security layer with certificate is currently enabled. |
RootPath | str | ☑️ | ☑️ | Path of the root folder that contains the web files. |
RequestsTimeoutSec | int | ☑️ | ☑️ | Timeout in seconds to waiting the next data reception of requests. |
NotFoundURL | str or None | ☑️ | ☑️ | URL used to redirects requests not found. |
AllowAllOrigins | bool | ☑️ | ☑️ | Indicates that all resource origins of requests are allowed. |
CORSAllowAll | bool | ☑️ | ☑️ | Allows all CORS values for the pre-flight requests (OPTIONS). |
OnLogging | callback or None | ☑️ | ☑️ | Callback function when the server logs information. |
提示
上面的回调函数的定义如下:
def OnLogging(microWebSrv2, msg, msgType)
# <microWebSrv2> is of type MicroWebSrv2
# <msg> is of type str
# <msgType> can take following values:
# - MicroWebSrv2.DEBUG
# - MicroWebSrv2.INFO
# - MicroWebSrv2.WARNING
# - MicroWebSrv2.ERROR
# Web路由
Web路由使您可以定义对特定资源的条件访问路径,并对相应的http请求作出反应。 它们还提供了使用自由条件的可能性,这些条件可以作为输入元素来检索。
在microWebSrv2中,Web路由是由
processing handler
处理函数,
requested method
请求方法,
requested path
请求路径,
以及optional name
可选名称组成。
请求的路径也可以包含可变部分,这些可变部分可以作为参数检索。
最后,在http请求期间,如果方法和路径与路由匹配,则使用期望的参数调用处理函数。
# 路由处理
路由处理是用路由设置装饰的函数。
此设置使用WebRoute
来装饰,其定义如下:
@WebRoute(method,routePath,name = None)
# <method>是http请求的方法,并且必须为非空字符串。
# <routePath>是http请求的路径,并且必须为非空字符串。
# <name>是可选的路由名称,必须为字符串或None。
处理函数的定义如下:
@WebRoute(...)
def RequestHandler(microWebSrv2,request)
# <microWebSrv2>类型为MicroWebSrv2
# <request>类型为HttpRequest
该方法参数可以是一个字符串,如下:
GET
,
HEAD
,
POST
,
PUT
,
DELETE
,
OPTIONS
,
PATCH
该routePath参数必须以/
开头,并指定路径的相对URL。
注意
路由处理函数是全局的,并且可以用MicroWebSrv2类的任何实例调用。
处理函数示例:
@WebRoute(GET, '/my-resource')
def RequestHandler1(microWebSrv2, request) :
pass
@WebRoute(POST, '/test/virtual-page.html', 'myTestRoute')
def RequestHandler2(microWebSrv2, request) :
pass
@WebRoute(OPTIONS, '/')
def RequestHandler3(microWebSrv2, request) :
pass
# 路由参数
可以包含可以作为输入元素检索的路由参数。 通过使用和命名和构建
这些参数可以直接定义到请求路径中,如下所示,用<
和>
包裹:
@WebRoute(GET, '/users/<id>/profile/<property>')
在这个网页路由中,定义了两个参数:
id
和property
。
因此,路由是可变的,并且对应于可以使用任何参数的请求路径。
'/users/123/profile/firstname'
因此,处理函数定义如下:
@WebRoute(...)
def RequestHandler(microWebSrv2, request, args)
# <microWebSrv2> is of type MicroWebSrv2
# <request> is of type HttpRequest
# <args> is a dictionary of route arguments
现在,args
可以像args['id']
或args['property']
这样使用。
请注意,值可以是字符串,也可以直接是整数。
# 路由方法
- RegisterRoute(...)
def RegisterRoute(handler, method, routePath, name=None)
# Registers a global web route directly, without decorator usage.
# - No return value.
# - <handler> is the route processing handler and must be a function (see above).
# - <method> is the http requested method and must be a not empty string.
# - <routePath> is the http requested path and must be a not empty string.
# - <name> is an optional route name and must be a string or None.
# An exception can be raised if arguments are not correct.
- ResolveRoute(...)
def ResolveRoute(method, path)
# Resolves a web route using a method and a path.
# - Returns a RouteResult class if no error occurred and route was found, returns None otherwise.
# - <method> is an http method and must be of string type.
# - <path> is an http relative path and must be of string type.
RouteResult类开放以下属性:
名称 | 类型 |
---|---|
Handler | processing handler |
Method | string |
RoutePath | string |
Name | string or None |
Args | dictionary |
- PathFromRoute(...)
def PathFromRoute(routeName, routeArgs={ })
# Constructs the relative path from the route name and route arguments.
# - Returns a string that is the relative path.
# - <routeName> is the name of the web route and must be a not empty string.
# - <routeArgs> is a dictionary of needed argument names and values.
# An exception can be raised if arguments are not correct or route was not found.
# HttpRequest类
HttpRequest类表示web服务器接收到的http请求。
它可以在web路由处理程序或模块中获得。
它还允许您处理响应。
# HttpRequest实例方法
- httpRequest.GetPostedURLEncodedForm(...)
def GetPostedURLEncodedForm(self)
# Obtains name/value pairs from an URL encoded form.
# The http request must have an URL encoded form content.
# - Returns a dictionary of name/value pairs (string for both).
- httpRequest.GetPostedJSONObject(...)
def GetPostedJSONObject(self)
# Obtains the object posted in JSON format.
# The http request must have a JSON content.
# - Returns any type of object or None.
- httpRequest.GetHeader(...)
def GetHeader(self, name)
# Obtains the value of an http request header.
# - Returns always a string value.
# - <name> must be a not empty string.
# An exception can be raised if <name> is not correct.
- httpRequest.CheckBasicAuth(...)
def CheckBasicAuth(self, username, password)
# Checks if the http request is authenticated with the "Basic" method.
# - Returns True if the authentication is correct, returns False otherwise.
# - <username> must be a string.
# - <password> must be a string.
# An exception can be raised if arguments are not correct.
- httpRequest.CheckBearerAuth(...)
def CheckBearerAuth(self, token)
# Checks if the http request is authenticated with the "Bearer" method.
# - Returns True if authentication is correct, returns False otherwise.
# - <token> is the session token and must be a string.
# An exception can be raised if <token> is not correct.
# HttpRequest属性
名称 | 类型 | Get | Set | 说明 |
---|---|---|---|---|
UserAddress | tuple | ☑️ | - | User remote address of the http connection such as a tuple of (str_ip_addr, int_port). |
IsSSL | bool | ☑️ | - | Indicates that the http connection is secured by SSL/TLS security layer with certificate. |
HttpVer | str | ☑️ | - | Version of the client protocol of the http connection. |
Method | str | ☑️ | - | Name of the method transmitted with this request. |
Path | str | ☑️ | - | Path of the resource transmitted with this request. |
QueryString | str | ☑️ | - | Full query string transmitted with this request. |
QueryParams | dict | ☑️ | - | Parameters of the query string transmitted with this request. |
Host | str | ☑️ | - | Hostname transmitted with this request. |
Accept | list | ☑️ | - | List of possible content types expected in response to this request. |
AcceptEncodings | list | ☑️ | - | List of possible encodings expected in response to this request. |
AcceptLanguages | list | ☑️ | - | *List of possible languages expected in response to this request. |
Cookies | list | ☑️ | - | List of cookies transmitted with this request. |
CacheControl | str | ☑️ | - | Control of cache transmitted with this request. |
Referer | str | ☑️ | - | Referer address transmitted with this request. |
ContentType | str | ☑️ | - | Type of the content included in this request. |
ContentLength | int | ☑️ | - | Length of the content included in this request. |
UserAgent | str | ☑️ | - | Name of the client agent transmitted with this request. |
Authorization | str | ☑️ | - | Authorization string transmitted with this request. |
Origin | str | ☑️ | - | Address of the origin transmitted with this request. |
IsKeepAlive | bool | ☑️ | - | Indicates that the http connection can be keep alive. |
IsUpgrade | bool | ☑️ | - | Indicates that the http connection must be upgraded. |
Upgrade | str | ☑️ | - | Upgrade string transmitted with this request. |
Content | memoryview or None | ☑️ | - | Raw data of the content included in this request. |
Response | HttpResponse | ☑️ | - | Http response related to this connection. |
XAsyncTCPClient | XAsyncTCPClient | ☑️ | - | Asynchronous TCP connection from the XAsyncSockets library. |
# HttpResponse类
HttpResponse类用于管理http请求的响应。
它可以通过实例化的HttpRequest的Response
属性获得。
# HttpResponse实例方法
- httpResponse.SetHeader(...)
def SetHeader(self, name, value)
# Set a header to the http response.
# - No return value.
# - <name> must be a not empty string.
# - <value> may be anything but cannot be None.
# An exception can be raised if arguments are not correct.
- httpResponse.SwitchingProtocols(...)
def SwitchingProtocols(self, upgrade)
# Sends a special http response to upgrade the connection.
# - No return value.
# - <upgrade> must be a not empty string.
# An exception can be raised if <upgrade> is not correct.
- httpResponse.ReturnStream(...)
def ReturnStream(self, code, stream)
# Sends a stream content to the http response.
# - No return value.
# - <code> is the http status code and must be a positive integer.
# - <stream> must be a readable buffer protocol object.
# An exception can be raised if arguments are not correct.
- httpResponse.Return(...)
def Return(self, code, content=None)
# Sends an http response with or without content.
# - No return value.
# - <code> is the http status code and must be a positive integer.
# - <content> must be a string or in bytes or convertible into bytes or None.
# An exception can be raised if arguments are not correct.
- httpResponse.ReturnJSON(...)
def ReturnJSON(self, code, obj)
# Sends an http response with a JSON content.
# - No return value.
# - <code> is the http status code and must be a positive integer.
# - <obj> can be anything and will be serialized (stringify process).
# An exception can be raised if arguments are not correct.
- httpResponse.ReturnOk(...)
def ReturnOk(self, content=None)
# Sends a success http response with or without content.
# - No return value.
# - <content> must be a string or in bytes or convertible into bytes or None.
# An exception can be raised if <content> is not correct.
- httpResponse.ReturnOkJSON(...)
def ReturnOkJSON(self, obj)
# Sends a success http response with a JSON content.
# - No return value.
# - <obj> can be anything and will be serialized (stringify process).
# An exception can be raised if <obj> is not correct.
- httpResponse.ReturnFile(...)
def ReturnFile(self, filename, attachmentName=None)
# Sends a file to the http response.
# - No return value.
# - <filename> is the physical path of the file and must be a not empty string.
# - <attachmentName> can be the name of the file to save, in string, or None.
# If None, the user will see it "on the fly" in his browser, he will can save it otherwise.
# An exception can be raised if arguments are not correct.
- httpResponse.ReturnNotModified(...)
def ReturnNotModified(self)
# Sends a not modified http response.
# Used in resources caching context.
# - No return value.
- httpResponse.ReturnRedirect(...)
def ReturnRedirect(self, location)
# Sends a temporary redirect http response.
# Used to move the user to a new url.
# - No return value.
# - <location> is the relative or absolute URL and must be a not empty string.
# An exception can be raised if <location> is not correct.
- httpResponse.ReturnBadRequest(...)
def ReturnBadRequest(self)
# Sends a bad request http response.
# Used for user request error.
# - No return value.
- httpResponse.ReturnUnauthorized(...)
def ReturnUnauthorized(self, typeName, realm=None)
# Sends an unauthorized http response.
# Used if the user needs to authenticate.
# - No return value.
# - <typeName> is the name of required authentication and must be a not empty string.
# - <realm> is a name for the protected resource and can be a string or None.
# An exception can be raised if arguments are not correct.
- httpResponse.ReturnForbidden(...)
def ReturnForbidden(self)
# Sends a forbidden http response.
# Used to indicate a denied access.
# - No return value.
- httpResponse.ReturnNotFound(...)
def ReturnNotFound(self)
# Sends a not found http response.
# Used to indicate that the resource does not exist.
# - No return value.
- httpResponse.ReturnMethodNotAllowed(...)
def ReturnMethodNotAllowed(self)
# Sends a method not allowed http response.
# Used if the method is not supported for resource.
# - No return value.
- httpResponse.ReturnEntityTooLarge(...)
def ReturnEntityTooLarge(self)
# Sends an entity too large http response.
# Used for an excessive content size.
# - No return value.
- httpResponse.ReturnInternalServerError(...)
def ReturnInternalServerError(self)
# Sends an internal server error http response.
# Used if an error has occurred.
# - No return value.
- httpResponse.ReturnNotImplemented(...)
def ReturnNotImplemented(self)
# Sends a not implemented http response.
# Used in case of a non-existent process of the resource.
# - No return value.
- httpResponse.ReturnServiceUnavailable(...)
def ReturnServiceUnavailable(self)
# Sends a service unavailable http response.
# Used if it is currently impossible to process the request.
# - No return value.
- httpResponse.ReturnBasicAuthRequired(...)
def ReturnBasicAuthRequired(self)
# Sends an http response to indicate that "Basic" authentication is required.
# - No return value.
- httpResponse.ReturnBearerAuthRequired(...)
def ReturnBearerAuthRequired(self)
# Sends an http response to indicate that "Bearer" authentication is required.
# - No return value.
# HttpResponse属性
名称 | 类型 | Get | Set | 说明 |
---|---|---|---|---|
Request | HttpRequest | ☑️ | - | Http request related to this response. |
UserAddress | tuple | ☑️ | - | User remote address of the http connection such as a tuple of (str_ip_addr, int_port). |
IsSSL | bool | ☑️ | - | Indicates that the http connection is secured by SSL/TLS security layer with certificate. |
AllowCaching | bool | ☑️ | ☑️ | Indicates to the user the possible caching of this response. |
AccessControlAllowOrigin | str or None | ☑️ | ☑️ | Indicates to the user the allowed resource origin. |
ContentType | str or None | ☑️ | ☑️ | Type of the content of this response. |
ContentCharset | str or None | ☑️ | ☑️ | Encoding charset used for the content of this response. |
ContentLength | int | ☑️ | ☑️ | Length of the content of this response. |
HeadersSent | bool | ☑️ | - | Indicates that response http headers was already sent. |
OnSent | callback or None | ☑️ | ☑️ | Callback function when response is fully sent. |
提示
上面的回调函数的定义如下:
def OnSent(microWebSrv2, response)
# <microWebSrv2> is of type MicroWebSrv2
# <response> is of type HttpResponse
# 添加模块
# WebSocket模块
from MicroWebSrv2 import *
WS_CHAT_SUB_PROTOCOL = 'myGreatChat-v1'
def OnWebSocketProtocol(microWebSrv2, protocols) :
if WS_CHAT_SUB_PROTOCOL in protocols :
return WS_CHAT_SUB_PROTOCOL
def OnWebSocketAccepted(microWebSrv2, webSocket) :
print('New WebSocket (myGreatChat proto) accepted from %s:%s.' % webSocket.Request.UserAddress)
wsMod = MicroWebSrv2.LoadModule('WebSockets')
wsMod.OnWebSocketProtocol = OnWebSocketProtocol
wsMod.OnWebSocketAccepted = OnWebSocketAccepted
# WebSockets模块属性
名称 | 类型 | Get | Set | 说明 |
---|---|---|---|---|
OnWebSocketProtocol | callback or None | ☑️ | ☑️ | Callback function when a new WebSocket connection negociates a sub-protocol. |
OnWebSocketAccepted | callback or None | ☑️ | ☑️ | Callback function when a new WebSocket connection is accepted. |
提示
上面的回调函数的定义如下:
def OnWebSocketProtocol(microWebSrv2, protocols)
# <microWebSrv2> is of type MicroWebSrv2
# <protocols> is a string list of proposed protocols
# RETURN: If you select a protocol, you must return it (the same as in the list)
def OnWebSocketAccepted(microWebSrv2, webSocket)
# <microWebSrv2> is of type MicroWebSrv2
# <webSocket> is of type WebSocket
# WebSocket类
WebSocket类是被WebSockets模块自动实例化的。
在回调OnWebSocketAccepted中接受新连接时,可以获得WebSocket。
为了接收各种事件,分配WebSocket回调也很重要。
# WebSocket实例方法
- webSocket.SendTextMessage(...)
def SendTextMessage(self, msg)
# Sends a text message through the WebSocket.
# - Returns True or False.
# - <msg> must be a not empty string.
# An exception can be raised if <msg> is not correct.
- webSocket.SendBinaryMessage(...)
def SendBinaryMessage(self, msg)
# Sends a binary message through the WebSocket.
# - Returns True or False.
# - <msg> must be in bytes or convertible into bytes and not empty.
# An exception can be raised if <msg> is not correct.
- webSocket.Close(...)
def Close(self)
# Closes the WebSocket.
# - No return value.
# WebSocket属性
名称 | 类型 | Get | Set | 说明 |
---|---|---|---|---|
Request | HttpRequest | ☑️ | - | Http request related to this connection. |
IsClosed | bool | ☑️ | - | Indicates that connection is closed. |
WaitFrameTimeoutSec | int | ☑️ | ☑️ | Timeout in seconds to waiting next frame. |
MaxRecvMessageLength | int or None | ☑️ | ☑️ | Maximum length of messages to receive. |
OnTextMessage | callback or None | ☑️ | ☑️ | Callback function to receive text messages. |
OnBinaryMessage | callback or None | ☑️ | ☑️ | Callback function to receive binary messages. |
OnClosed | callback or None | ☑️ | ☑️ | Callback function when connection is closed. |
提示
上面的回调函数的定义如下:
def OnTextMessage(webSocket, msg)
# <webSocket> is of type WebSocket
# <msg> is of type str
def OnBinaryMessage(webSocket, msg)
# <webSocket> is of type WebSocket
# <msg> is of type memoryview
def OnClosed(webSocket)
# <webSocket> is of type WebSocket
# PyhtmlTemplate模块
from MicroWebSrv2 import *
pyhtmlTemplateMod = MicroWebSrv2.LoadModule('PyhtmlTemplate')
pyhtmlTemplateMod.ShowDebug = True
在**.pyhtml**页面中,您必须使用以下说明:
说明 | 代码构架 |
---|---|
PY | {{ py }} Python code {{ end }} |
IF | {{ if Python condition }} html bloc {{ end }} |
ELIF | {{ elif Python condition }} html bloc {{ end }} |
ELSE | {{ else }} html bloc {{ end }} |
FOR | {{ for identifier in Python iterator }} html bloc {{ end }} |
Expression | {{ Python expression }} |
请看test.pyhtml页面示例:
Global var "Toto": <span class="label">{{ Toto }}</span><br />
* Refresh this page to see this variable changing.
<div class="sep"></div>
Your address:<br />
<ul>
<li> IP = {{ Pequest.UserAddress[0] }}</li>
<li> Port = {{ Pequest.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 />
显示页面效果如下:
# PyhtmlTemplate模块实例方法
- pyhtmlTemplateMod.SetGlobalVar(...)
def SetGlobalVar(self, globalVarName, globalVar)
# Defines a global variable accessible by all pyhtml pages.
# - No return value.
# - <globalVarName> must be a not empty string.
# - <globalVar> must be an object or None.
# An exception can be raised if <globalVarName> is not correct.
- pyhtmlTemplateMod.GetGlobalVar(...)
def GetGlobalVar(self, globalVarName)
# Retrieves a global variable accessible by all pyhtml pages.
# - Returns an object or None.
# - <globalVarName> must be a not empty string.
# An exception can be raised if <globalVarName> is not correct.
# PyhtmlTemplate模块属性
名称 | 类型 | Get | Set | 说明 |
---|---|---|---|---|
ShowDebug | bool | ☑️ | ☑️ | Enables debugging on web pages. |