我对 Python 作为 PHP 背景的新手感到很困惑。
我试图了解如何从这个Python 路由库调用在路由中设置的控制器。
例如,我有这样设置的路线,
# Setup a mapper
from routes import Mapper
map = Mapper()
map.connect("add user", "/user", controller = "addUser", action = "add",
conditions=dict(method=["GET"]))
map.connect("post user", "/user", controller = "postUser", action = "post",
conditions=dict(method=["POST"]))
map.connect("update user", "/user/{id}", controller = "updateUser", action = "update",
conditions=dict(method=["GET"]))
map.connect("put user", "/user/{id}", controller = "putUser", action = "put",
conditions=dict(method=["PUT"]))
map.connect("delete user", "/user/{id}", controller = "deleteUser", action = "delete",
conditions=dict(method=["DELETE"]))
map.connect("home", "/", controller = "main", action = "index", conditions=dict(method=["GET"]))
# This is our application object. It could have any name,
# except when using mod_wsgi where it must be "application"
def application(environ, start_response):
# Get the request path info.
uri = environ.get('PATH_INFO', '')
path_info = uri if uri else '/'
# Get the HTTP request method: PUT, GET, DELETE, POST.
request_method = environ.get('REQUEST_METHOD', '')
map.environ = {'REQUEST_METHOD': request_method}
# Match a URL, returns a dict or None if no match
mapped = map.match(path_info)
# Everything done, return the response:
if mapped['action'] == 'index' :
response_body = index(environ, start_response, mapped)
elif mapped['action'] == 'add':
response_body = addUser(environ, start_response, mapped)
elif mapped['action'] == 'put':
response_body = putUser(environ, start_response, mapped)
elif mapped['action'] == 'delete':
response_body = deleteUser(environ, start_response, mapped)
else:
response_body = "Not found."
status = '200 OK'
response_headers = [('Content-Type', 'text/html'),
('Content-Length', str(len(response_body)))]
start_response(status, response_headers)
return [response_body]
如您所见,在路由中设置的控制器根本没有使用。当匹配时,我在 if-else 条件下调用单个函数。这是乏味和蹩脚的...
这不是我在 PHP 中的做法(我猜你可能也不会在 Python 中这样做)。因为我希望路由会在请求匹配时直接调用控制器 -没有任何进一步的 if-else 条件。
知道如何在没有controller = "addUser"
下面的情况下调用addUser
函数吗?
elif mapped['action'] == 'add':
response_body = addUser(environ, start_response, mapped)