繁体   English   中英

将 json 参数从 Ruby/Rails controller 传递给 Python 子进程

[英]Passing a json argument to a Python subprocess from Ruby/Rails controller

所以我想在 Rails 应用程序中使用 Python 脚本,我定义了这条路线:

get '/decks/:id/download', to: 'decks#download_deck', as: :download

然后在我看来,我有这个链接:

<%= link_to "Download", download_path , class: "p-2 ml-4 rounded-md bg-blue-600 text-white shadow-md align-middle" %>

然后在我的 decks#controller 我有这个公共方法:

  def download_deck
    @deck = Deck.find_by(params[:deck_id])
    my_hash = {}
    @deck.cards.each_with_index do |card, index|
      my_hash[index] = { "front" => card.front, "back" => card.back }
    end

    data_json = my_hash.to_json

    deck_filename = `python3 lib/assets/python/make_deck.py \""#{data_json}"\"`
    
    send_data deck_filename, filename: 'hello.txt'
  end

所以我正在制作一个包含所有信息的 hash 并在其上调用 to_json,我在 controller 文件的顶部也require 'json' 然后在 python 文件 make_deck.py 我有这样的东西:

def main():
    args = sys.argv

    data = args[1]

    print(data)

    json_data = json.loads(data)

    print(json_data)

    print('hello')
    print('world')

但是json_data = json.loads(data)行会引发错误: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

我不明白的是,我正在传递一个字符串,该字符串是在 hash 上调用 #to_json 的结果,但是在 Python json 中,它似乎应该正确加载。 知道我在哪里出错了吗?

使用单引号 ( ' ) 代替带有额外引号 ( \"" ) 的转义双引号:

deck_filename = `python3 lib/assets/python/make_deck.py '#{data_json}'`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM