- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这个。
@login_manager.user_loader
def load_user(id=None):
return User.query.get(id)
在我引入 Flask-Principal 之前它一直运行良好。
@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
# Set the identity user object
identity.user = current_user
# return
if hasattr(current_user, 'id'):
identity.provides.add(UserNeed(current_user.id))
# Assuming the User model has a list of roles, update the
# identity with the roles that the user provides
if hasattr(current_user, 'roles'):
for role in current_user.roles:
identity.provides.add(RoleNeed(role.name))
添加这个会导致严重的性能问题。 SQLALCHEMY_ECHO 显示每次加载静态文件时都会查询 User 表。
#Warning: Dummy Cache
users = {}
@login_manager.user_loader
def load_user(uid=None):
if uid not in users:
users[uid] = User.query.get(uid)
return users[uid]
在这个解决了重复查询问题的实验之后,我开始意识到我需要在我的 Flask 应用程序中引入缓存。这是问题。
User.query.get(id)
?最佳答案
老问题,但在 SO 上或通过谷歌似乎没有其他答案,我花了一些时间来解决这个问题,所以也许这个答案会对某人有所帮助。
首先,你需要一些缓存后端,我使用flask-caching与 redis使用来自 pypi sudo pip install redis
的 python redis
库。
接下来,执行 from flask_caching import Cache
,然后执行 cache = Cache()
,这是我在另一个名为 extensions.py
的文件中执行的操作。如果您使用应用工厂模式,这一点很重要,因为稍后您需要导入 cache
,这有助于避免较大的 Flask 应用出现循环引用问题。
在此之后,您需要在 flask 应用程序上注册 flask-caching 扩展,我做了一个单独的 app.py
文件,如下所示:
from flask import Flask
from extensions import cache
def create_app(config_obj=None):
"""An application factory"""
app = Flask(__name__)
app.config.from_object(config_obj)
cache.init_app(app, config={'CACHE_TYPE': 'redis',
'CACHE_REDIS_HOST': '127.0.0.1',
'CACHE_REDIS_PORT': '6379',
'CACHE_REDIS_URL': 'redis://127.0.0.1:6379'})
return app
现在 cache
已在 Flask 中注册,它可以从 extensions.py
导入并在整个应用程序中使用,而不会出现循环引用问题。移动到您正在使用 user_loader
的任何文件:
import pickle
from flask import current_user
from extensions import cache
from models.user_models import User
@login_manager.user_loader
def load_user(user_id):
"""Load user by ID from cache, if not in cache, then cache it."""
# make a unique cache key for each user
user = 'user_{}'.format(user_id)
# check if the user_object is cached
user_obj = pickle.loads(cache.get(user)) if cache.get(user) else None
if user_obj is None:
query = User.query.get(int(user_id))
user_obj = pickle.dumps(query)
cache.set(user, user_obj, timeout=3600)
return query
return user_obj
最后,当您注销用户时,您可以将它们从缓存中删除:
@blueprint.route('/logout/')
@login_required
def logout():
"""Logout."""
# remove the user information from redis cache
user = 'user_{}'.format(current_user.id)
cache.delete(user)
# remove the user information from the session
logout_user()
# Remove session keys set by Flask-Principal
for key in ('identity.name', 'identity.auth_type'):
session.pop(key, None)
flash('You are logged out.', 'info')
return redirect(url_for('public.home')
这似乎工作得很好,它减少了每个用户每页三个查询对 SQLAlchemy 的查询命中,并将我的应用程序的几个部分的页面加载速度提高了 200 毫秒,同时消除了达到 SQLAlchemy 连接池限制的讨厌问题。
此解决方案的最后一个重点。如果您出于任何原因更改用户对象,例如,如果为用户分配新角色或能力,则必须从缓存中清除用户对象。例如如下:
# set the user_id from current_user.id CACHE object
user_id = current_user.id
# remove the old USER object from cache since you will change it
# first set the cache key to user_{id}
cache_user = 'user_{}'.format(user_id)
# now delete the cache key
cache.delete(cache_user)
背景:
我需要考虑缓存 flask-login user_loader 是因为我通过扩展 flask-login 类 UserMixin
和 AnonymousUserMixin
实现了访问控制列表管理一些类方法,如 get_roles
和 get_abilities
。我也在使用 flask-sqlalchemy 和 postgresql 后端,并且有一个角色表和一个与用户对象有关系的能力表。这些用户角色和能力主要在模板中进行检查,以根据用户角色和能力呈现各种 View 。
在某些时候,我注意到当打开多个浏览器选项卡或只是浏览器在我的应用程序中重新加载页面时,我开始收到错误消息 TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30
。 Flask-sqlalchemy 有 SQLALCHEMY_POOL_SIZE
和 SQLALCHEMY_MAX_OVERFLOW
的设置,但增加这些值只是掩盖了我的问题,错误仍然发生只是通过加载更多选项卡或重新加载更多页面。
深入挖掘以找出根本原因,我使用 SELECT * FROM pg_stat_activity;
查询了我的 postgresql 数据库,发现在每个请求中我都在累积多个连接,状态为 idle in transaction
其中 SQL 查询明确链接到用户、角色、能力访问检查。这些 idle in transaction
连接导致我的数据库连接池达到容量。
进一步测试发现,缓存 flask-login user_loader User
对象消除了 idle in transaction
连接,然后即使我离开了 SQLALCHEMY_POOL_SIZE
和SQLALCHEMY_MAX_OVERFLOW
为默认值,我没有再遇到 TimeoutError: QueuePool limit
。问题解决了!
关于python - 缓存 Flask-登录 user_loader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27078347/
我阅读了有关 JSR 107 缓存 (JCache) 的内容。 我很困惑:据我所知,每个 CPU 都管理其缓存内存(无需操作系统的任何帮助)。 那么,为什么我们需要 Java 缓存处理程序? (如果C
好吧,我是 jQuery 的新手。我一直在这里和那里搞乱一点点并习惯它。我终于明白了(它并不像某些人想象的那么难)。因此,鉴于此链接:http://jqueryui.com/sortable/#dis
我正在使用 Struts 2 和 Hibernate。我有一个简单的表,其中包含一个日期字段,用于存储有关何时发生特定操作的信息。这个日期值显示在我的 jsp 中。 我遇到的问题是hibernate更
我有点不确定这里发生了什么,但是我试图解释正在发生的事情,也许一旦我弄清楚我到底在问什么,就可能写一个更好的问题。 我刚刚安装了Varnish,对于我的请求时间来说似乎很棒。这是一个Magneto 2
解决 Project Euler 的问题后,我在论坛中发现了以下 Haskell 代码: fillRow115 minLength = cache where cache = ((map fill
我正试图找到一种方法来为我网络上的每台计算机缓存或存储某些 python 包。我看过以下解决方案: pypicache但它不再被积极开发,作者推荐 devpi,请参见此处:https://bitbuc
我想到的一个问题是可以从一开始就缓存网络套接字吗?在我的拓扑中,我在通过双 ISP 连接连接到互联网的 HAProxy 服务器后面有 2 个 Apache 服务器(带有 Google PageSpee
我很难说出不同缓存区域 (OS) 之间的区别。我想简要解释一下磁盘\缓冲区\交换\页面缓存。他们住在哪里?它们之间的主要区别是什么? 据我了解,页面缓存是主内存的一部分,用于存储从 I/O 设备获取的
1.题目 请你为最不经常使用(LFU)缓存算法设计并实现数据结构。 实现 LFUCache 类: LFUCache(int capacity) - 用数据结构的容量 capacity 初始化对象 in
1.题目 请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。 实现 LRUCache 类: ① LRUCache(int capacity) 以正整数作为容量 capacity
我想在访问该 View 时关闭某些页面的缓存。它适用于简单查询模型对象的页面。 好像什么时候 'django.middleware.cache.FetchFromCacheMiddleware', 启
documents为 ExePackage element state Cache属性的目的是 Whether to cache the package. The default is "yes".
我知道 docker 用图层存储每个图像。如果我在一台开发服务器上有多个用户,并且每个人都在运行相同的 Dockerfile,但将镜像存储为 user1_myapp . user2 将其存储为 use
在 Codeigniter 中没有出现缓存问题几年后,我发现了一个问题。我在其他地方看到过该问题,但没有适合我的解决方案。 例如,如果我在 View 中更改一些纯 html 文本并上传新文件并按 F5
我在 Janusgraph 文档中阅读了有关 Janusgraph Cache 的内容。关于事务缓存,我几乎没有怀疑。我在我的应用程序中使用嵌入式 janusgrah 服务器。 如果我只对例如进行读取
我想知道是否有来自终端的任何命令可以用来匹配 Android Studio 中执行文件>使缓存无效/重新启动的使用。 谢谢! 最佳答案 According to a JetBrains employe
我想制作一个 python 装饰器来内存函数。例如,如果 @memoization_decorator def add(a, b, negative=False): print "Com
我经常在 jQuery 事件处理程序中使用 $(this) 并且从不缓存它。如果我愿意的话 var $this = $(this); 并且将使用变量而不是构造函数,我的代码会获得任何显着的额外性能吗?
是的,我要说实话,我不知道varnish vcl,我可以解决一些基本问题,但是我不太清楚,这就是为什么我遇到问题了。 我正在尝试通过http请求设置缓存禁止,但是该请求不能通过DNS而是通过 Varn
在 WP 站点上加载约 4000 个并发用户时遇到此问题。 这是我的配置: F5 负载均衡器 ---> Varnish 4,8 核,32 Gb RAM ---> 9 个后端,4 个核,每个 16 RA
我是一名优秀的程序员,十分优秀!