Use value from javascript on html page to execute python script - python

I have a problem. I have a project that involves sending a value from a web page to a web server and using that value to generate a voltage by commanding a digital to analog converter. For the server side I am using a Python script that works very well and I have created a simple web page in which I can enter the value wanted. But the link between them is missing. I am trying to understand CGI scripts to use them for parsing the value from the web page to the Python script but with no luck. Does anyone have any other ideas or can anyone explain CGI for beginners? Thank you.

Here is a simple Python script that pipes the output of a locally executed command (dir on a Windows computer in this case) via a web request (using the excellent web.py library):
import web
from subprocess import check_output
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
return '<pre>'+check_output('dir', shell=True)+'</pre>'
if __name__ == "__main__":
app.run()

Related

Any way to run an internal python script from a webpage?

I finally made a project that I wanted to make since a long time :
I'm using an Arduino Uno to replace my PC power button (with a simple relay) and that Arduino Board is connected to a Raspi 3 for network connection purposes
My wish is to do a webpage (or a API-Like request) that at a touch of a button (preferably in a password-protected page) It'll power the PC on
I know how to code in Python, and my script to control the Arduino is already done but I can't find a way to run, only server-side, a Python Script from a button in a webpage
I found that CherryPy framework but I don't think it'll suit my needs
Can someone give me any ideas about that please?
As already mentioned by #ForceBru, you need a python webserver.
If this can be useful to you, this is a possible unsecure implementation using flask:
from flask import Flask
from flask import request
app = Flask(__name__)
#app.route('/turnOn')
def hello_world():
k = request.args.get('key')
if k == "superSecretKey":
# Do something ..
return 'Ok'
else:
return 'Nope'
If you put this in an app.py name file and, after having installed flask (pip install flask), you run flask run you should be able to see Ok if visiting the url http://localhost:5000/turnOn?key=superSecretKey .
You could write a brief html gui with a button and a key field in a form but I leaves that to you (you need to have fun too!).
To avoid potential security issues you could use a POST method and https.
Look at the flask documentation for more infos.

Ruby on Rails hangs during HTTP request from Python script

I'm writing a web application in Ruby on Rails where users can write python code in a web editor and execute it in an docker environment on the server. I've written a simple python code that creates a docker container:
import docker
import sys
if __name__ == "__main__":
if(len(sys.argv) == 2):
token = sys.argv[1]
client = docker.from_env()
res = client.containers.run('openql','python3 /home/pythonwrapper.py '+token)
else:
print("Requires one parameter")
As you can see it creates a docker container using the image openql and execute a simple python script inside. If a user press the execute button in the web editor Ruby on Rails executes this script by using the this command: system("python","script.py","<TOKEN>") So far so good, this works all fine.
However, there is a problem executing the pythonwrapper.py inside the docker container. I'm using python's requests library for requesting the files written by the user to execute them inside the docker container. The code looks like this:
# Request all the available assets, it does not download the content of the files.
# Downloading the content of the files is done in a later request
url = rails_url+"allAssets/"+token
res = requests.get(url)
#Convert bytes into string
content = str(res.content, 'utf8')
Looks pretty simple, but the whole ruby on rails webserver hangs during this request. And the strange thing is that it all works fine if I first executes this script manually from the console after restarting the server.
The only thing I get from the Rails console if this:
Started GET "/allAssets/123" for 10.0.2.15 at 2017-08-02 10:24:59 +0200
When I quit the webserver for a restart, Ruby on Rails shows the following logs:
Screenshot console
And then nothing. Does anyone know what could be the problem?
You should be running the container in background i guess.
res = client.containers.run('openql','python3 /home/pythonwrapper.py '+token, detach=True)
This will make sure that your server is not stuck till it waits for the container to complete and finish the command it is executing

Python: Read POST Parameters

I've never used python before but need to write a fairly simple script for a project I'm working on. All I need is a script that listens on port 80 for incoming HTTP POSTs and prints the posted variables/parameters and values to the command line.
What's the easiest way for a beginner to get this done?
Thanks.
Consider using Flask Framework. With just 7-8 lines your job is done.
It will print all parameter sent using post and get request to your console.
Also I would recommend to learn it.
from flask import Flask
app = Flask(__name__)
#app.route("/",methods=['POST','GET'])
def index():
print request.form
return "Please Check your command line"
if __name__ == "__main__":
app.run(host='0.0.0.0',port=80,debug=True)

REST web service with Python using WSME

I'm trying to create a simple REST Web Service using technology WSME reported here:
https://pypi.python.org/pypi/WSME
It's not clear, however, how to proceed. I have successfully installed the package WSME.0.6.4 but I don't understand how to proceed.
On the above link we can see some python code. If I wanted to test the code what should I do? I have to create a .py file? Where this file should be saved? Are there services to be started?
The documentation is not clear: it says "With this published at the / ws path of your application". What application? Do I need to install a Web Server?
Thanks.
You could use a full blown web server to run your application . For example Apache with mod_wsgi or uWSGI , but it is not always necessary .
Also you should choose a web framework to work with .
According WSME doc's it has support for Flask microframework out of the box , which is simple enough to start with .
To get started create a file with the following source code :
from wsgiref.simple_server import make_server
from wsme import WSRoot, expose
class MyService(WSRoot):
#expose(unicode, unicode)
def hello(self, who=u'World'):
return u"Hello {0} !".format(who)
ws = MyService(protocols=['restjson', 'restxml'])
application = ws.wsgiapp()
httpd = make_server('localhost', 8000, application)
httpd.serve_forever()
Run this file and point your web browser to http://127.0.0.1:8000/hello.xml?who=John
you should get <result>Hello John !</result> in response.
In this example we have used python's built in webserver which is a good choice when you need to test something out quickly .
For addition i suggest reading How python web frameworks and WSGI fit together

Output from a Python page call by a JQuery getJSON function

I'm working on a website that uses Python web.py. There is a form where the user enters input and when the submit button is hit, a python page is called (matches) using the .getJSON JQuery function show below.
function buildMatches(input){
$.getJSON("/matches", {e:input}, function(json){
//Returned JSON object is worked on
}
}
The "matches" python page grabs a value from a DB, runs some string reg ex and returns a JSON object. Everything works fine, my question is how would I be able to output something from the python page "matches" to see what is exactly happening during the reg ex operations? I've tried print "" (python 2.5), but I understand that would print to the console. I've done some research but couldn't find anything for my situation. I don't necessarily need to print it out to the HTML page, just any where where I can see what's going on. Thanks in advance for any help.
I have access to the webserver (SSH, SFTP, etc.), I tried to log by importing the logging module, below is the code I used. I could get it to log if I ran the page from the command line, but not when it is called by the JS page.
import logging
logging.basicConfig(filename='./SomeClass.log', filemode='w', level=logging.DEBUG)
class SomeClass:
logging.info('Started')
logging.info('Another log')
def __init__(self, obj):
logging.info('In the init')
def another_functio(self):
logging.info('Logging inside the function')
I've tried setting the full path of the log and I still have the same problem where the log file will only be written or updated when I run this class from the console. This doesn't work when the class is called by the webserver.
logging.basicConfig(filename='/home/.../.../.../example.log', filemode='w', level=logging.DEBUG)
Depending on how much access you have to the web server you can run your code manually so web.py uses its built-in web server. Then print statements will end up on the console.
Otherwise, have you thought about simply writing to your own log file somewhere accessible with a browser?
Thanks again for all the help. After digging more into the setup of the Apache server and Python implementation I was able to find a solution to help me see what's going and debug my web app. I saw that Apache config is setup to log errors and WSGI also blocks (pukes on) std.out. What I was able to do is redirect the print command to the Apache error log files.
print >> sys.stderr, "Debugging print with variable" + variable
Then I check the Apache error log to start debugging the web app. I thought I would share this in case anyone else ran into this problem as it was a pain for me.
Thanks again.

Categories