在不使用阻塞scala.concurrent.Await的情况下获取cookie头

时间:2018-02-22 09:22:33

标签: scala spray

我正在使用Spray Framework从Cookie Header获取JSESSIONID。

我可以使用import { BrowserModule } from '@angular/platform-browser'; import { RouterModule, Route } from '@angular/router'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { ProductComponent } from './product/product.component'; import { HomeComponent } from './home/home.component'; const routeConfig: Route[] = [ { path: '', component: HomeComponent }, { path: 'product', component: ProductComponent } ]; @NgModule({ declarations: [ AppComponent, ProductComponent, HomeComponent ], imports: [ BrowserModule, FormsModule, RouterModule.forRoot(routeConfig) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } 获取JSESSIONID,如下所示:

scala.concurrent.Await

但是,由于以下原因,上述代码看起来不太好:

使用Await阻止是一个禁忌,并且选择调用选项也是不明智的。

所以我尝试了以下内容:

val pipeline: HttpRequest => Future[HttpResponse] = sendReceive  

val responseFuture: Future[HttpResponse] = pipeline(Post(Uri(url)))
val hs : HttpResponse  = scala.concurrent.Await.result(responseFuture, 5.seconds)        

val sessionId: Option[String] = hs.headers.collectFirst {
      case h: `Set-Cookie` if h.cookie.name == "JSESSIONID" => 
      h.cookie.content
    }

println("sessionId: "+sessionId.get)

但是我不能在responseFuture.onComplete(response => { val cookies = response.get.headers.collect { case c: `Set-Cookie` => c.cookie.content } println("cookies: "+cookies(0)) }) 方法块之外使用cookies(0),因为它的范围仅限于该块。

请指教?

1 个答案:

答案 0 :(得分:0)

在这里你可以通过Spray的onComplete指令做这样的事情:

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib.animation import FuncAnimation
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

num_frames = 50
theta = np.linspace(0,2*np.pi, 10, endpoint=False)
r = np.arange(1,2.1)
z = np.arange(-2,2.1,1)


def compute_segs(i):
    offset = 2*i*np.pi/num_frames
    theta2,r2, z2 = np.meshgrid(theta+offset,r,z)

    x = r2*np.cos(theta2)
    y = r2*np.sin(theta2)

    u = x+0.2*np.cos(4*theta2)
    v = y
    w = z2+0.2*np.sign(z2)*np.sin(4*theta2)

    return x,y,z2,u,v,w


segs = compute_segs(0)
cols = ['b' for x in segs[0].ravel()]
cols[0] = 'r'
quivers = ax.quiver(*segs, length=0.1, colors = cols, normalize=True)


ax.set_xlim([-3,3])
ax.set_ylim([-3,3])
ax.set_zlim([-3,3])
def animate(i):

    segs = np.array(compute_segs(i)).reshape(6,-1)

    new_segs = [[[x,y,z],[u,v,w]] for x,y,z,u,v,w in zip(*segs.tolist())]
    quivers.set_segments(new_segs)
    return quivers


ani = FuncAnimation(fig, animate, frames = num_frames, interval = 30, blit=False)
ani.save('update_3d_quiver.gif', writer='imagemagick')

plt.show()

您可以在此处找到相同的文档:Spray onComplete

您可以在onComplete块中生成响应。

希望这适合你。