小编Rah*_*hul的帖子

如何从python中的文件中读取多个字典?

我对python比较陌生.我正在尝试读取包含多个词典的ascii文件.该文件具有以下格式.

{Key1: value1
 key2: value2
 ...
}
{Key1: value1
 key2: value2
 ...
}
{
...
Run Code Online (Sandbox Code Playgroud)

文件中的每个字典都是嵌套字典.我试图将其作为词典列表阅读.有没有简单的方法来做到这一点?我尝试了以下代码,但它似乎不起作用

data = json.load(open('doc.txt'))
Run Code Online (Sandbox Code Playgroud)

python file-io json dictionary python-2.7

5
推荐指数
1
解决办法
2586
查看次数

before_action 中的 render/head 不会停止执行其余操作

我有一个私有方法authenticate_user!在我的应用程序控制器中,它验证标头中的令牌并返回用户记录(如果找到)。这是它的样子。

def authenticate_user!
  # authenticate
  @current_login = Login.where(oauth2_token: bearer_token).first
  head 401 if @current_login.nil? # and return
  @current_user = @current_login.user
  head 401 if @current_user.nil? 
end
Run Code Online (Sandbox Code Playgroud)

我使用此方法对控制器中的用户进行身份验证,如下所示。

class AddressesController < ApplicationController
   before_action :authenticate_user!

   def some_action
      data = @current_user.some_associated_records
      render json: {data: data}
   end
end
Run Code Online (Sandbox Code Playgroud)

理想情况下,当找不到登录名或找不到相应的用户时,我应该从authenticate_user 获得 401 响应!方法。

相反,我总是收到 500 内部服务器错误。不知何故,它head 401 if current_login.nil?不会停止执行链。即使渲染状态:401 也不起作用。

根据我的理解,如果 Rails在 before_action 过滤器中找到 arender或 a命令,则它会返回。head我缺少什么?

编辑:

以下解决方案有效:

      private

      def authenticate_user!(*)
        @current_login = Login.where(oauth2_token: bearer_token).first!
        @current_user = @current_login.user
        rescue ActiveRecord::RecordNotFound
          head …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails before-filter ruby-on-rails-4

5
推荐指数
1
解决办法
3379
查看次数