【问题标题】:Call Rails 4 param in Python script在 Python 脚本中调用 Rails 4 参数
【发布时间】:2015-05-02 00:54:53
【问题描述】:

我正在尝试在 Python 脚本中使用来自 rails 控制器的表单输入。我的 rails(4.2.1 版)应用程序上有一个表单,它接收一个 url,然后我想在 Python 脚本中使用该 url。我是 Rails 新手,不知道该怎么做。我的应用程序已经能够接受表单输入并将它们呈现在页面上,并且能够调用 Python 脚本并运行它,但我需要将它们链接在一起。

这是目前为止的控制器代码:

class ContestsController < ApplicationController
  def index
    value = %x(python /Users/my/Desktop/rails_test.py 2>&1)
    render :text => value
    @contests = Contest.all
  end

  def new
    @contest = Contest.new
  end

  def create
    @contest = Contest.new(contest_params)

    if @contest.save
      redirect_to contests_url
    else
      render 'new'
    end
  end

  private

  def contest_params
    params.require(:contest).permit(:site, :contest_url)
  end
end

我的 Python rails_test.py 脚本是:

#!/bin/bash

print "Python script works!"
#url = last :contest_url param from rails app
#print url

尝试 #1:

我将rails代码修改为:

value = %x(python /Users/jdesilvio/Desktop/rails_test.py #{Shellwords.escape(params[:contest_url])} 2>&1)

我将 Python 脚本修改为:

#!/Users/me/anaconda/bin/python2.7 python

import sys

print "Python script works!"
print "Url: ", sys.argv[1]

输出是:

Python script works! Url:

我的表格是:

<%= form_for @contest do |f| %>
  <div>
    <%= f.label :site %>
    <%= f.text_field :site %>
  </div>
  <div>
    <%= f.label :contest_url %>
    <%= f.text_field :contest_url %>
  </div>
  <%= f.submit %>
<% end %>

【问题讨论】:

标签: python ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

您可以将它们作为命令行参数传递给您的脚本。 %x 进行字符串插值,但您需要小心并验证输入,因为有人可能会将 params[:contest_url] = " &amp;&amp; rm -rf / " 或类似的东西传递到您的脚本中并导致您出现问题(永远不要相信用户输入)所以 Shellwords (http://ruby-doc.org/stdlib-2.0/libdoc/shellwords/rdoc/Shellwords.html) 类可以帮助。也许是这样的。

value = %x(/Users/my/Desktop/rails_test.py #{Shellwords.escape(params[:site])} #{Shellwords.escape(params[:contest_url])} 2>&1)

然后让你的 python 脚本通过 STDIN 读取值

#!/usr/bin/env python
import sys

print "Site: ", sys.argv[1]
print "Url: ", sys.argv[2]

我让你的 python 脚本 shebang 调用 /usr/bin/env python,但如果 python 不在你的 rails 应用程序正在运行的用户路径中,你可能需要完整路径。此外,如果您将其作为 python 可执行文件的参数调用,则不需要在 python 脚本的顶部使用 /bin/bash

【讨论】:

  • 我做了您建议的更改(见上文),但没有打印出argv。这就是你让我进入 Python 路径的意思吗?在我的测试编辑器中,#{Shellwords...} 周围的大括号不会关闭,不确定我的编辑器中是否有问题或代码中是否存在问题..
  • 好像没有传递参数。当我这样做时:#{Shellwords.escape("test") 输出打印 'test'。但是当我做#{Shellwords.escape(params[:contest_url])} 时,输出是''
  • 试试contest_params[:site]
  • 我也是这么想的,但是当我使用contest_params[:site] 时出现错误:param is missing or the value is empty: contest
  • 您的表单是什么样的?还要查看你的日志,看看 params 散列是作为什么传入的。你需要匹配它。你用表格了吗?还是表单标签?
猜你喜欢
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 2022-01-18
  • 2018-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
相关资源
最近更新 更多