【问题标题】:Scala and Play framework 2.2.0, Action.async and isAuthenticatedScala 和 Play 框架 2.2.0、Action.async 和 isAuthenticated
【发布时间】:2013-11-12 18:06:54
【问题描述】:

我有一个使用 zentasks 示例中描述的 isAuthenticated 模式的应用程序。 它还使用 Future/Async 来最小化阻塞...

  def index = isAuthenticated { username => implicit request =>        
    val promise = 
      Future {
        Foo.all()    
      }
    Async {
      promise.map(f => Ok(views.html.foo.index(username, f)))
    }        
  }

这在 Play 2.2.0 中继续有效,但已弃用 Future/Async 模式。我们应该使用 Action.async;类似:

  def asyncTest = Action.async {
    val fut = Future {
      // Artificial delay to test.
      Thread.sleep(5000)
      "McFly"
    }
    fut.map (f => Ok(f))      
  }

我的问题是;我将如何将 Action.async 与上述身份验证方法或类似方法一起使用?

【问题讨论】:

    标签: scala asynchronous playframework-2.0


    【解决方案1】:

    一种选择是通过定义IsAuthenticated 来使用Action Composition,如下所示:

    def username(request: RequestHeader) = request.session.get("email")
    
    def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Application.login)
    
    def IsAuthenticated(f: => String => Request[AnyContent] => Future[SimpleResult]) = {
      Action.async { request =>
        username(request).map { login =>
          f(login)(request)        
        }.getOrElse(Future.successful(onUnauthorized(request)))
      }
    }
    

    然后你可以通过以下方式使用它:

    def index = IsAuthenticated { user => implicit request =>
      val fut = Future {
        // Artificial delay to test.
        Thread.sleep(5000)
        "McFly"
      }
      fut.map (f => Ok(f))      
    }
    

    【讨论】:

    • 完美运行,让我深入了解这些东西的实际工作原理。谢谢!
    猜你喜欢
    • 2016-07-08
    • 2012-02-20
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 2013-10-21
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多