EEVblog Electronics Community Forum

Products => Computers => Programming => Topic started by: HiSmartAlarms on July 02, 2020, 03:33:47 am

Title: Run python script from POST command?! Raspberry PI
Post by: HiSmartAlarms on July 02, 2020, 03:33:47 am
So, I had an idea to convert a project of mine from arduino to raspberry pi. The arduino version had a software controlling it, I wanted to do the same, but want it to be controlled via POST web commands (so that way it's not limited to my USB cable length). Is there anyway to make a python script run from when nginx recieves a POST command? (note i may not know what im talking about lmao)
Title: Re: Run python script from POST command?! Raspberry PI
Post by: greenpossum on July 03, 2020, 10:53:20 pm
Is there a reason you want to run nginx as the web server? Search results show that running CGI scripts from nginx is more convoluted than if you run some other webserver like apache or lighttpd.
Title: Re: Run python script from POST command?! Raspberry PI
Post by: GeorgeOfTheJungle on July 05, 2020, 01:25:43 am
1) Configure in nginx the path ("location") to proxy_pass to node-red and, 2) In node-red use the http request/response nodes and (say) node-red-contrib-pythonshell.

Easy peasy, you can have it running in a sec.
Title: Re: Run python script from POST command?! Raspberry PI
Post by: Nominal Animal on July 05, 2020, 03:20:59 am
(I removed my post, because this is the wrong forum to talk about how to do IOT securely.)
Title: Re: Run python script from POST command?! Raspberry PI
Post by: Chris42 on July 08, 2020, 09:59:22 pm
I think the best option for you is to run a simple app in flask. It is a framework for creating server side software.

Here is a quick hello world for POST request:

Code: [Select]
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/enableSkynet', methods=['POST'])
def enableSkynet():
    data = request.json
    # here is your parameter
    parameter = request.json["parameterName"]
    print(parameter)

As a body of the post request you pass a JSON encoded object containing whatever parameters you need.
Here is how you write JSON: https://www.tutorialspoint.com/json/json_syntax.htm (https://www.tutorialspoint.com/json/json_syntax.htm)

To run the above code you need to install the following dependencies (available via pip):
 - flask
 - flask-jsonpify
 - flask-restful

Flask has a built in debug server that you can run by simply running your app script from a console.

Once you are ready to deploy you can run flask on NGINX. Here is a link to a tutorial that demonstrates just that: https://www.raspberrypi-spy.co.uk/2018/12/running-flask-under-nginx-raspberry-p (https://www.raspberrypi-spy.co.uk/2018/12/running-flask-under-nginx-raspberry-p)