玩!具有异步Web请求的框架组合动作 [英] Play! Framework composing actions with async web request

查看:61
本文介绍了玩!具有异步Web请求的框架组合动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Scala还是很陌生 我正在尝试从Play访问Instagram API!和Scala.

I'm quite new to Scala I'm trying to access Instagram API from Play! and Scala.

def authenticate = Action {
request =>
  request.getQueryString("code").map {
    code =>
      WS.url("https://api.instagram.com/oauth/access_token")
        .post(
        Map("client_id" -> Seq(KEY.key), "client_secret" -> Seq(KEY.secret), "grant_type" -> Seq("authorization_code"),
          "redirect_uri" -> Seq("http://dev.my.playapp:9000/auth/instagram"), "code" -> Seq(code))
      ) onComplete {
        case Success(result) => Redirect(controllers.routes.Application.instaline).withSession("token" -> (result.json \ "access_token").as[String])
        case Failure(e) => throw e
      }
  }
 Redirect(controllers.routes.Application.index)

}

应用执行时,在成功的情况下,最后一次重定向发生在重定向之前. 请告诉我,如何避免这种情况.而且,请让我知道我代码中的不良做法.

When app executes, the last redirect happens before redirect in case of Success. Tell me please, how to avoid it. And Also, let me know about bad practices that is in my code.

推荐答案

使用Play,您会返回结果-您不会发送结果. onComplete方法附加了一个可以执行某些操作但不返回任何内容的方法(请注意,其返回值为Unit,即void).附加了该回调之后,您将在最后一行返回Redirect,这不是您想要执行的操作.相反,您想map从WS调用中获得的将来,并返回该将来.要返回Play的未来,您需要使用Action.async构建器.例如:

With Play, you return a result - you don't send a result. The onComplete method attaches a method that does something, but doesn't return anything (note its return value is Unit, ie, void). After attaching that callback, you are then returning Redirect on the last line, which is not what you want to do. Instead you want to map the future that you get back from the WS invocation, and return that future. And to return a future in Play, you need to use the Action.async builder. eg:

def authenticate = Action.async { request =>

  request.getQueryString("code").map { code =>

    WS.url("https://api.instagram.com/oauth/access_token").post(
      Map(
        "client_id" -> Seq(KEY.key),
        "client_secret" -> Seq(KEY.secret),
        "grant_type" -> Seq("authorization_code"),
        "redirect_uri" -> Seq("http://dev.my.playapp:9000/auth/instagram"),
        "code" -> Seq(code)
      )
    ).map { result =>

      Redirect(controllers.routes.Application.instaline)
        .withSession("token" -> (result.json \ "access_token").as[String])

    }
  }.getOrElse {
    Future.successful(Redirect(controllers.routes.Application.index))
  }
}

这篇关于玩!具有异步Web请求的框架组合动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆