How to integrate a standalone Python script into a Rails application?

后端 未结 5 2192
你的背包
你的背包 2020-12-24 06:05

I\'ve got a program that has a small file structure going on and is then ran using

python do_work.py foo bar

I want my Rails users to press

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 06:52

    It partly depends on the format of the data. If it's not too long and can be rendered directly in the browser, you can just do something like this in a rails controller:

    result = `python do_work.py foo bar`
    render :text => result
    

    And assuming that result is plain ASCII text, the result will go straight to their browser. If the params to do_work.py come from the user you MUST validate them first though, so you don't wind up creating a nasty vulnerability for yourself. Using the system() call would probably be safer in that case.

    If you want to send the results back as a file, look at ruby's Tempfile class for creating the file (in a way that won't stick around forever), and rails' send_file and send_data commands for some different options to send back the results that way.

提交回复
热议问题