简体   繁体   中英

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

So I want to use a Python script in a Rails app and I have this route defined:

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

Then in my view I have this link:

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

Then in my decks#controller I have this public method:

  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

So I am making a hash with all of the information and calling to_json on it, I also have require 'json' at the top of the controller file. Then in the python file make_deck.py I have something like this:

def main():
    args = sys.argv

    data = args[1]

    print(data)

    json_data = json.loads(data)

    print(json_data)

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

However the line json_data = json.loads(data) throws an error: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

What I don't understand is that I'm passing a string that is the result of calling #to_json on a hash, however then in Python json.loads() can't parse it correctly, it seems like it should. Any idea where I'm going wrong here?

Instead of escaped double quote with extra quote ( \"" ) use single quote ( ' ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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