【问题标题】:Updating records with Python 3 through API on Rails 4 application通过 API on Rails 4 应用程序使用 Python 3 更新记录
【发布时间】:2016-06-21 16:48:43
【问题描述】:

我正在开发一个 Rails 4 / mongoid 应用程序,它需要为其他应用程序和脚本公开 API。我需要能够通过带有 Python 3 脚本的 API 更新其中一个模型中的文档。我对 Python 有点陌生,因此在这里寻求帮助。

我已经了解了如何使用 Python 3 和 urllib 查询 Rails API,但在更新方面遇到了困难。我试图为 urllib2 使用 Python 3.5 docs,但很难将其应用到我的脚本中。

data 的内容以及如何将身份验证令牌添加到 headers,在 curl 中看起来像这样

-H 'Authorization:Token token="xxxxxxxxxxxxxxxx"'
-X POST -d "name=A60E001&status=changed"

如果有人解释如何根据name 更新status,我将不胜感激(名称还不是唯一的,但会是唯一的)。我最大的挑战是 Python 方面。一旦我在 Rails 端的 params 中获得数据,我想我可以处理它。我想。

我在下面的控制器中包含了我的模型和更新操作。

app/models/experiment.rb

class Experiment
  include Mongoid::Document
  include Mongoid::Timestamps

  field :name, type: String
  field :status, type:String
end  

app/controllers/api/v1/experiments_controller.rb

module Api
  module V1
    class ExperimentsController < ActionController::Base
      before_filter :restrict_access

      ...

      def update
        respond_to do |format|
          if @expt_proc.update(expt_proc_params)
            format.json { render :show, status: :ok, location: @expt_proc }
         else
            format.json { render json: @expt_proc.errors, status: :unprocessable_entity }
          end
        end
      end

      ...

    private
      def restrict_access
        authenticate_or_request_with_http_token do |token, options|
          ApiKey.where(access_token: token).exists?
        end
      end
    ...

【问题讨论】:

    标签: python ruby-on-rails api python-3.x ruby-on-rails-4


    【解决方案1】:

    我想出了用 Python 3 向谁发送 PATCH 请求,并将记录的 status 更新为 name

    感谢this 发布有关requests 模块的信息。我使用requests.patch 更新记录,效果很好。

    python code

    import requests
    import json
    
    url = 'http://0.0.0.0:3000/api/v1/update_expt_queue.json'
    payload = {'expt_name' : 'myExperiment1', 'status' : 'finished' }
    
    r = requests.patch(url, payload)
    

    还有两个问题:

    1. 如何向此请求添加标头,这将允许我通过基于令牌的身份验证。目前它被禁用。 request.patch 只带 2 个参数,不带 headers 参数。

    2. 如何访问由 Rails API 响应发送的 JSON。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      相关资源
      最近更新 更多