Calling a python function over the web using AJAX? - python

I want to send a string to a python function I have written and want to display the return value of that function on a web page. After some initial research, WSGI sounds like the way to go. Preferably, I don't want to use any fancy frameworks. I'm pretty sure some one has done this before. Need some reassurance. Thanks!

You can try Flask, it's a framework, but tiny and 100% WSGI 1.0 compliant.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
Note: Flask sits on top of Werkzeug and may need other libraries like sqlalchemy for DB work or jinja2 for templating.

You can use cgi...
#!/usr/bin/env python
import cgi
def myMethod(some_parameter):
// do stuff
return something
form = cgi.FieldStorage()
my_passed_in_param = form.getvalue("var_passed_in")
my_output = myMethod(my_passed_in_param)
print "Content-Type: text/html\n"
print my_output
This is just a very simple example. Also, your content-type may be json or plain text... just wanted to show an example.

In addition to Flask, bottle is also simple and WSGI compliant:
from bottle import route, run
#route('/hello/:name')
def hello(name):
return 'Hello, %s' % name
run(host='localhost', port=8080)
# --> http://localhost:8080/hello/world

Related

How do I go about running a Python program from within Flask web server?

I have a Python program that's designed to allow the user to select points on an image. The points that are clicked are saved to a YML file.
I currently have it set up in a way where, when the Python program is called from the server, it executes the Python GUI in a separate window (as it would if you executed it through the command line) and the user input is taken through the command line I used to run the server. I'd like this to all be internal. As in, everything runs through the server if that makes sense.
How would I go about doing this? Is there a library available that makes something like this possible? The code belows shows how the Python program is currently run within the server. If you go the the /test url, it executes in this case.
Hopefully this image will give you an idea of what I'm trying to do. Essentially, I need to image to be open AND interact-able in the server. I don't need the exact code to do this, just an explanation of how I should go about doing it.
- project
- data (folder that holds output information from pythonGUI.py)
- app
- templates
- index.html
- routes.py
- models.py
- __init__.py
- pythonGUI.py
- config.py
- server.py
routes.py
from app import app
from flask import Flask, request, render_template, session
import pythonGUI
app.secret_key = app.config['SECRET_KEY']
#app.route('/')
#app.route('/index')
def index():
return render_template('index.html')
#app.route('/test')
def test():
return pythonGUI.main()
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8000', debug=True)
pythonGUI.py
from app import app
import cv2
def main():
#Some code here
if __name__ == '__main__':
main()
If you need more code, please let me know. I'm not sure what would be relevant to show in this case. Thank you
At the moment, I'm not sure you need an image library; you might be fine with just Javascript and Flask.
Here's how I would go about it:
There's questions about getting coordinates from a picture using Javascript. After about 10 seconds of Googling, I found this: get image pixel coordinates relative left top corner
Take that output and send it to another route in flask. Something like this:
from flask import request
def image_coordinate_processing(x,y):
#Do stuff
return result
#app.route('/_img_coordinates')
def _img_coordinates():
x = int(request.args.get('x'))
y = int(request.args.get('y'))
result = image_coordinate_processing(x,y)
return 'completed'
In your template, you would send the data like this:
{{url_for('_img_coordinates', x=x, y=y)}}
Obviously this isn't all the code, but should get you in a decent direction.

How does flask know which function to call for a specific web adress?

In the populair web framework flask a basic web page looks like this:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
I am pretty new to python and i was wondering how this exactly works. I get that # is a decorator that decorates the hello function but how does flask that is has to call the underlying hello funtion or even knows it exists, because the code does not run the hello function like this:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
hello()
When i am coding i like to know how something works before i just randomly accept anything. I searched my but off looking for an answer but could not find a pleasent answer. Also i looked in the source code but i was not able to find out how it works
So now the real question: How can i recreate something similair in plain python? So running a function without really calling it in the main code first.
Ps. Sorry for my bad english, it is not my main language.
app.route() remembers the URL ("/") and the function associated with it (hello). Later, app.run() can query that association and invoke hello.
How can i recreate something similair in plain python?
This program might give you an understanding of how hello() is invoked:
class Flask:
def __init__(self):
self.routes = {}
def route(self, path):
def wrapper(fn):
self.routes[path] = fn
return fn
return wrapper
def run(self):
# Networking code goes here.
# Suppose "/" comes in as a request, then this happens:
self.routes["/"]()
app = Flask()
#app.route("/")
def hello():
print("Inside hello")
return "Hello World!"
app.run()
Alternatively, you can examine the flask source: https://github.com/pallets/flask Specifically, app.route() is defined here: https://github.com/pallets/flask/blob/0.12.2/flask/app.py#L1054 and the call to hello() is here: https://github.com/pallets/flask/blob/0.12.2/flask/app.py#L1052

How to run python script results on Flask

I have created an app.py and index.html file. My problem is that I want to execute a python script with the input I gathered from POST when submit is clicked, and then display the script output on the same or different html page. I used CGI and Flask. I do not fully know how to proceed. I research online, but couldn't find anything very helpful. Any help would be appreciated.
Here is my code.
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
#app.route("/")
def main():
return render_template('index.html')
#app.route("/src_code/main.py", methods = ['POST'])
def run_app():
id = request.form['id']
name = request.form['name']
url = request.form['url']
if not id or not name or not url:
return render_template('index.html')
else:
#execute the python script.
if __name__ == "__main__":
app.run()
EDIT:
I have used the following code to import my function. At the end, though I have received an error when I clicked the submit button on index.html
script_analyze = Analyzer()
result = script_analyze.main()
return render_template(results.html', data=result)
AttributeError: 'WSGIRequestHandler' object has no attribute 'environ'
I am unsure why this attribute error is raised.
Since you want to execute another Python script... If you are able to import the other script then you can just use something like the following to call it and store the results - assuming the other script is a value-returning function.
from othermodule import function_to_run
...
# where you want to call it
result = function_to_run()
Then you can use render_template as others have said, passing this result as the data to the template (or simply return the result if it's already in the format you want to output with Flask).
Does that work, or is the script you want to run something that this wouldn't work for? Let us know more about the script if it's an issue.

Run Python Script into Flask

I've a desktop application to detect faces written in python script, using opencv and numpy.
i want to put these python files into flask and run it, would it run without problems? like
import cv2
import numpy as np
from flask import Flask
app = Flask(__name__)
## define my functions here
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
#call the functions here
app.run()
would that work? if not how do i get it included? thanks!
Yes it would work, one thing you should know is if you do like below, the HTTP request won't return until after the processing is done e.g.
#app.route('/webcam')
def webcam_capture():
"""
Returns a picture snapshot from the webcam
"""
image = cv2... # call a function to get an image
response = make_response(image) # make an HTTP response with the image
response.headers['Content-Type'] = 'image/jpeg'
response.headers['Content-Disposition'] = 'attachment; filename=img.jpg'
return response
Otherwise, if you put in the main function like below
if __name__ == '__main__':
# <-- No need to put things here, unless you want them to run before
# the app is ran (e.g. you need to initialize something)
app.run()
Then your flask app won't start until the init/processing is done.

App Engine regex issues directing URL to script and handlers

I am trying to break my app into separate scripts. Part of this effort meant breaking the api calls into it's own file. However the calls to the api (like http://example.com/api/game/new no longer work).
My app.yaml contains this:
- url: /api.*
script: api.py
which seems to be redirecting properly because this configuration works:
def main():
application = webapp.WSGIApplication([('/.*', TestPage)], debug=True)
util.run_wsgi_app(application)
however this one doesn't:
def main():
application = webapp.WSGIApplication([('/game/new$', CreateGame),
('/game/(d+)$', GameHandler)],
debug=True)
util.run_wsgi_app(application)
The URL patterns you use in the WSGI application have to be the full path - eg, /api/game/.... The App Engine infrastructure uses the regular expressions in app.yaml to route requests, but it does not modify the request path based on them.
My guess is you are trying to pass some arguments to your handler.
Try this. It will give you a hint.
#!/usr/bin/env python
import wsgiref.handlers
from google.appengine.ext import webapp
class MyHandler(webapp.RequestHandler):
def get(self, string=None):
if string:
self.response.out.write("Hello World!! %s" % string)
else:
self.response.out.write("Hello World!! (and no word)")
def main():
app = webapp.WSGIApplication([
(r'/word/(\w+)/?$', MyHandler),
(r'.*', MyHandler),
], debug=True)
wsgiref.handlers.CGIHandler().run(app)
if __name__ == "__main__":
main()
Hope it helps. Cheers.

Categories