【问题标题】:Google App Engine Python do ASP.NET MVC routing with webapp2Google App Engine Python 用 webapp2 做 ASP.NET MVC 路由
【发布时间】:2012-10-07 19:21:57
【问题描述】:

我希望能够以与 ASP.net MVC 类似的方式路由我的请求。

例如地址 /Home/Index/query-string/ 应该将请求映射到 HomeController 并调用 Index 方法。

我为此做了一个实现并且它有效,但我想知道一个更好的方法来做到这一点。我有 刚开始第一次使用 Google App Engine 和 Python,我没有太多开发网站和网络应用程序的经验。

这是我的实现

Yaml 文件:

- url: /.*
script: router.app

路由配置:

def StartUp():
    sys.path.append(os.path.join(os.getcwd(), 'System'))
    sys.path.append(os.path.join(os.getcwd(), 'Controllers'))
    sys.path.append(os.path.join(os.getcwd(), 'Models'))
    app.run()

app = webapp2.WSGIApplication([webapp2.Route('/', handler=Router, name='Default', defaults={'handler': 'home', 'method': 'index', 'query': ''}, build_only=False, handler_method='map'),
                            webapp2.Route('/<query>', handler=Router, name='DefaultC', defaults={'handler': 'home', 'method': 'index'}, build_only=False, handler_method='map'),
                            webapp2.Route('/<handler>/', handler=Router, name='DefaultCS', defaults={'method': 'index', 'query': ''}, build_only=False, handler_method='map'),
                            webapp2.Route('/<handler>/<query>', handler=Router, name='DefaultCA', defaults={'method': 'index'}, build_only=False, handler_method='map'),
                            webapp2.Route('/<handler>/<method>/', handler=Router, name='DefaultCAS', defaults={'query': ''}, build_only=False, handler_method='map'),
                            webapp2.Route('/<handler>/<method>/<query>', handler=Router, name='DefaultAll', build_only=False, handler_method='map'),
                            webapp2.Route('/<handler>/<method>/<query>/', handler=Router, name='DefaultAllS', build_only=False, handler_method='map')],
                            debug=True)

if __name__ == '__main__':
    StartUp()

路由器

class Router(webapp2.RequestHandler):

    def getControllerName(self, handler):
            handler = handler.lower()
            if(len(handler) == 0):
                    """ Error - redirect to error page """
                    return webapp2.redirect('/Error/')
            if len(handler) == 1:
                    handler = handler[0].capitalize()
            else:
                    handler = handler[0].capitalize() + handler[1:]

            handler = handler + 'Controller'

            return handler

    def getActionName(self, method):
            method = method.lower()
            if(len(method) == 0):
                    """ Error - redirect to error page """
                    return webapp2.redirect('/Error/')
            if len(method) == 1:
                    method = method[0].capitalize()
            else:
                    method = method[0].capitalize() + method[1:]

            requestType = self.request.method.lower()
            requestType = requestType[0].capitalize() + requestType[1:]

            return method

    def loadController(self, controllerName):
            """ Load the controller """
            try:
                    fileName, pathName, description = imp.find_module(controllerName, None)
                    module = imp.load_module(controllerName, fileName, pathName, description)

                    # Add checking if class was found
                    controllerRef = getattr(module, controllerName)
                    return controllerRef

            except ImportError, args:
                    logging.error('Error importing controller. ' + pprint.saferepr(args))
            except Exception, args:
                    logging.error('Exception. ' + pprint.saferepr(args))
            finally:
                    fileName.close()

    def loadAction(self, controller, actionName):
            try:
                    actionRef = getattr(controller, actionName)
            except Exception, args:
                    logging.error('Exception. ' + pprint.saferepr(args))
            return actionRef

    def callController(self, controllerName, actionName, query):
            try:
                    """ Load the controller """
                    controllerRef = self.loadController(controllerName)
                    controller = controllerRef(self, query)
                    actionRef = self.loadAction(controller, actionName)
                    actionRef()
            except Exception, args:
                    logging.error('Exception. ' + pprint.saferepr(args))

    def map(self, handler, method, query):
            query = query.lower()
            """ Create Names for Controller and Action"""
            controllerName = self.getControllerName(handler)
            actionName = self.getActionName(method)

            self.callController(controllerName, actionName, query)

这是我的 Home 控制器:

class HomeController(MVC.Controller):

    def Index(self):

            path = os.path.join(os.path.dirname('Views/Home/'), 'home.html')
            self.Request.response.out.write(template.render(path, None))

【问题讨论】:

    标签: asp.net-mvc google-app-engine asp.net-mvc-routing webapp2


    【解决方案1】:

    使用这种方法我找不到更好的方法。

    另一种方法是在类和方法上使用装饰器来指定路由(不确定实现这样的功能有多容易)。

      @RouteFor('/SomePath')
      class HomeController(MVC.Controller):
            @RouteFor('/SomePath/Index')
            def Index(self):
                    path = os.path.join(os.path.dirname('Views/Home/'), 'home.html')
                    self.Request.response.out.write(template.render(path, None))
    

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 2013-09-09
      • 2012-11-15
      • 2023-03-13
      • 2016-12-04
      • 1970-01-01
      相关资源
      最近更新 更多