【发布时间】: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