如何禁用网络爬虫的 Rails 会话? [英] How to disable Rails sessions for web crawlers?

查看:39
本文介绍了如何禁用网络爬虫的 Rails 会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去,应用程序控制器中的这样一行会完全禁用请求的会话:

It used to be that a line like this in the application controller would disable sessions entirely for a request:

session :off, :if => Proc.new {|req| req.user_agent =~ BOT_REGEX}

在 Rails 3.x 中,这要么被弃用,要么不再有效.我意识到新概念是会话是延迟加载的,但通过应用程序的执行流使用/检查会话,即使它是网络机器人.

With Rails 3.x, this is either deprecated or no longer works. I realize that the new concept is that sessions are lazy loaded, but the execution flow through the app uses/checks sessions even if it's a web bot.

那么是否有一些新机制可以用于在每个请求的基础上禁用会话?

So is there some new mechanism that could be used to disable sessions on a per-request basis?

推荐答案

在 Rails 3 中似乎没有内置的方法来做到这一点,但你可以修补 SessionHash 到得到类似的结果:

There doesn't appear to be a built-in way to do this in Rails 3, but you can monkey patch SessionHash to get a similar result:

class ActionDispatch::Session::AbstractStore::SessionHash
  private
    def load_for_write!
      load! unless loaded? || (@env['HTTP_USER_AGENT'] =~ BOT_REGEX)
    end
end

这将阻止创建会话存储对象.您仍然可以分配到 session 哈希中,甚至可以稍后在同一请求中访问相同的会话数据.

This will prevent the session store object from being created. You will still be able to assign into the session hash, and even access that same session data later in the same request.

这篇关于如何禁用网络爬虫的 Rails 会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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