简体   繁体   English

如何使用Snap Framework在服务器端存储一些对象?

[英]How do I store some object on server-side with Snap Framework?

That question was already asked in 2010, but I figure there might be a better answer today. 该问题已在2010年提出,但我认为今天可能会有更好的答案。 Basically I need to store some kind of object and access it in every request, ideally I want to be able to change that object from within a request (I guess an MVar or IORef will do for that). 基本上,我需要存储某种对象并在每个请求中访问它,理想情况下,我希望能够在请求中更改该对象(我想MVar或IORef可以做到这一点)。

The snaplet tutorial seems to indicate that it's possible, but it mostly explains how to use snaplets (that's what that tutorial is for after all), and doesn't really explain how this "App" object works or even is stored. snaplet教程似乎表明有可能,但是它主要说明了如何使用snaplet(毕竟这是该教程的目的),并且并没有真正解释该“ App”对象的工作方式或存储方式。 I have no idea how to apply that to my case, where I have no need of snaplets (I'm making an API, so I don't even need Heist). 我不知道如何将其应用到我不需要Snaplet的情况下(我正在制作API,因此甚至不需要Heist)。

So given the default code : 所以给定默认代码:

site :: Snap ()
site = do
  ifTop (writeBS "hello world") <|>
    route [ ("stuff/:param", someHandler) ] <|>
    dir "static" (serveDirectory ".")

How do I change this to "register" some object somewhere that I could use in someHandler ? 如何更改此设置以“在某些地方可以在someHandler中使用”某个对象“注册”? The answer from 2010 is just to partially apply it to every handler, which would work, but the Snaplet tutorial makes me think there must be a better way. 2010年的答案是将其部分应用到每个处理程序,这将起作用,但是Snaplet教程使我认为必须有更好的方法。

In the section "Working with State" in the snaplet tutorial they explain how to work with local state. 在snaplet教程的“使用状态”一节中,他们解释了如何使用本地状态。 If you look at the second code piece in the section called "Snaplet Overview" above that, you can see how they're setting up the state when they initialise the data type for it, using Lens. 如果您在上面的“快照概述”部分中查看第二段代码,则可以看到他们使用Lens初始化其数据类型时如何设置状态。

Not sure how familiar you are with these things, but Lens lets you access (ie read/write/adjust) pieces of data within larger values. 不知道您对这些东西有多熟悉,但是Lens允许您访问(即读/写/调整)较大值内的数据。 The entire state of the server in this case is represented as one blob of data (a record type value), which is initialised when the server is. 在这种情况下,服务器的整个状态表示为一个数据块(记录类型值),该数据块在服务器处于初始化状态时被初始化。

Note this: _companyName :: IORef B.ByteString <- is a piece of state that you can mutate in the example, and in the section "Working with state" that's just what they do. 请注意以下_companyName :: IORef B.ByteString_companyName :: IORef B.ByteString <-是一种状态,您可以在示例中_companyName :: IORef B.ByteString ,而在“使用状态”部分中,它们正是这样做的。 They have an example that takes an HTTP GET or POST to that URL, and either updates it with the new "name" param (POST) and returns the new state, or if it's a GET, it just returns the current state. 他们有一个使用HTTP GET或POST到该URL的示例,并使用新的“名称”参数(POST)更新它并返回新状态,或者如果它是GET,则仅返回当前状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM