关于使用缓存或基于 cookie 的会话的服务器端会话的疑问

发布于 2024-12-28 04:39:01 字数 636 浏览 2 评论 0原文

我对网络开发还很陌生。我正在使用 Flask、Sqlalchemy 和 Postgresql。

据我了解,每个新请求就像程序的一个新线程。创建新的 sqlalchemy 会话,我们使用它来管理数据库操作并返回响应。之后新线程也被关闭,连接返回到池中。

我登录一个用户并获取用户 orm 对象中的所有用户数据。我将它存储在使用 cookie 的 Flask 会话变量中。现在我还想在整个用户会话而不是请求的范围内保存一些其他用户相关的数据。我怀疑将所有数据存储在 cookie 中,原因有两个:

1. Unnecessary data travel back and forth.
2. data can be read easily.

我的怀疑是否有效?

所以我的其他问题是:

  1. 在某种程度上,我是否正确地避免在每个请求中获取一些会话范围的数据而不陷入过早优化的陷阱? 或者 当需要出现时,我是否应该担心这个问题,而现在只专注于创建一个工作应用程序?

  2. 基于 cookie 的会话的替代方案是服务器端会话,可以通过使用 redis 或 memcache 来完成。 Beaker 库从何而来?它是一个独立的东西还是与redis或memcache结合使用?

I am pretty new to web development. I am working with Flask, Sqlalchemy and Postgresql.

As far as I have understood, every new request is like a new thread of the program. New sqlalchemy session is created using which we manage our db operations and return a response. After that new thread is also closed and connections returned to the pool.

I login a user and get all user data in an user orm object. I stored it in flask session variable which uses cookie. Now I also want to save some other user related data for the span of whole user session not a request. I have doubts storing all that data in a cookie for 2 reasons:

1. Unnecessary data travel back and forth.
2. data can be read easily.

Are my doubts valid?

So my other questions are :

  1. Am I right on some level to avoid getting some session wide data in each request without getting into the trap of premature optimization?
    or
    Should I worry about this later when need arises and right now concentrate only on creating a working app?

  2. Alternative to cookie based session is server side session which can be done by using redis or memcache. Where does Beaker library comes into this? Is it a standalone thing or to be used in conjunction with redis or memcache?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里泪两行 2025-01-04 04:39:01

大多数浏览器支持最大 4096 字节的 cookie。 (来源

如果您想要保存的内容超过此值,则应使用服务器端会话后端,例如 Redis 或 Memcache。用 Redis 或 Memcache 接口替换 Flask 的默认 cookie 会话接口非常容易。 Armin 有一个 redis 的精彩片段。如果您更喜欢 memcache,则可以使用相同的 memcache 方法替换代码片段中的 redis 内容。 ;)

Most browsers support cookies of up to 4096 bytes. (Source)

If you want to save more than this than you should use a server-side session backend like Redis or Memcache. It's very easy to replace the default cookie session interface of Flask with a Redis or Memcache interface. There is a great snippet for redis by Armin. If you prefere memcache than you can replace the redis stuff of the snippet with the same memcache methods. ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文