sea*_*and 8 asynchronous scala playframework-2.0
我有一个使用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)))
}
}
Run Code Online (Sandbox Code Playgroud)
这在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))
}
Run Code Online (Sandbox Code Playgroud)
我的问题是; 我如何使用Action.async与上面的身份验证方法,或类似的东西?
一种选择是通过定义如下来使用Action CompositionIsAuthenticated
:
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)))
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以通过以下方式使用它:
def index = IsAuthenticated { user => implicit request =>
val fut = Future {
// Artificial delay to test.
Thread.sleep(5000)
"McFly"
}
fut.map (f => Ok(f))
}
Run Code Online (Sandbox Code Playgroud)