找到你要的答案

Q:Python routes and dispatchers - how to use the route to the associate controller/ function?

Q:Python的路线和调度员-如何使用路由到副控制器/功能?

I'm quite confused with Python as a newbie coming PHP background.

I'm trying to understand how to call a controller that is set in a route from this Python routing library.

I have the routes set like this for instance,

# 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]

As you can see that the controllers that set in the routes are not used at all. I call the individual function in if-else condition when that is a match. This is tedious and lame...

This is not how I would do it in PHP (you probably won't do it in Python too I guess). Because I would expect that the route will call the controller directly when there is a match from request - without any further if-else condition.

Any idea how can I have controller = "addUser" to call addUser function without having this below?

elif mapped['action'] == 'add':
   response_body = addUser(environ, start_response, mapped)

我完全用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条件。这是乏味和跛脚…

这不是我在PHP做(你可能不会在Python做我猜)。因为我希望路由会直接调用控制器时,有一个匹配的要求-没有任何进一步的,如果其他条件。

不知道我怎么会有控制器=“adduser”调用adduser功能没有下面的?

elif mapped['action'] == 'add':
   response_body = addUser(environ, start_response, mapped)
answer1: 回答1:

It seems to work in this way,

# Setup a mapper
from routes import Mapper

def main():

   return 'Hello World!'

def addUser():

   return 'Add User'

def deleteUser():

   return 'Delete User'

# 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:
   response_body =  mapped['controller'].encode('utf-8')

   status = '200 OK'

   response_headers = [('Content-Type', 'text/html'),
               ('Content-Length', str(len(response_body)))]
   start_response(status, response_headers)

   return [response_body]

main = main()
addUser = addUser()
deleteUser = deleteUser()

map = Mapper()
map.resource("user", "users")
map.connect("add user", "/user", controller = addUser, action = "add",
   conditions=dict(method = ["GET"]))
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"]))

它似乎以这种方式工作,

# Setup a mapper
from routes import Mapper

def main():

   return 'Hello World!'

def addUser():

   return 'Add User'

def deleteUser():

   return 'Delete User'

# 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:
   response_body =  mapped['controller'].encode('utf-8')

   status = '200 OK'

   response_headers = [('Content-Type', 'text/html'),
               ('Content-Length', str(len(response_body)))]
   start_response(status, response_headers)

   return [response_body]

main = main()
addUser = addUser()
deleteUser = deleteUser()

map = Mapper()
map.resource("user", "users")
map.connect("add user", "/user", controller = addUser, action = "add",
   conditions=dict(method = ["GET"]))
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"]))
python  python-routes