介紹
web.ctx 是一個建基於 threadeddict class 的 code 來, 它是 thread-safe 的.
web.ctx holds variables for each request that contain specific information
成員
- env
A dictionary containing the standard WSGI environment variables (HTTP_ Variables)
Header
X-Forwarded-For
會變成
HTTP_X_FORWARDED_FOR
- home http://example.org/admin
- method GET / POST
- homedomain protocol + host
- protocol http / https
- host example.org:8080
-
ip xxx.xxx.xxx.xxx
----------------------------------------------------------- - path the path requested by the user, relative to the current application
- query (?fourlegs=good&twolegs=bad)
- fullpath path + query
Example
Example1:
client_ip = web.ctx.ip
Example2:
referer = web.ctx.env.get('HTTP_REFERER', 'http://google.com')
This code uses web.ctx.env to access the HTTP_REFERER environment variable. If there isn't one, it defaults to google.com.
寫東西進 web.ctx
web.ctx can be set by a loadhoo()
function loadhook(h)
Converts a load hook into an application processor.
>>> app = auto_application() >>> def f(): "something done before handling request" ... >>> app.add_processor(loadhook(f))
應用例子: 寫 session 進去
In its default behavior, session information can only be shared from within the main application(app.py),
even if you 'import' the session from other modules.
app.py
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer = {'test': 'woot', 'foo':''}) def session_hook(): web.ctx.session = session app.add_processor(web.loadhook(session_hook))
sub-app.py
print web.ctx.session.test web.ctx.session.foo = 'bar'