Run Python Script into Flask - python

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.

Related

Python Return multiple variables after pause in function

I have found a piece of flask: https://github.com/pratik55/Python-Flask-dynamic-update- code that dynamically updates the HTML, but it requires a function like time.time() - it outputs, pauses, and outputs again. I would like a custom function to do just this but not with a time value.
I tried something similar to this https://www.geeksforgeeks.org/g-fact-41-multiple-return-values-in-python/ but I could not put a pause in between each output.
The flask code looks like this:
from flask import Flask, jsonify, render_template, request
import webbrowser
import time
app = Flask(__name__)
#app.route('/_stuff', methods = ['GET'])
def stuff():
return jsonify(result=time.time())
#app.route('/')
def index():
return render_template('dy1.html')
if __name__ == '__main__':
app.run()
The result is just a question mark when I replace result=time.time() with something else unless its very explicit like result="hello"
Thanks

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 can I make command line arguments visible to Flask routes?

I am using Flask to build a tool to view data locally in a browser. I want to pass the directory containing the data as a command line argument, and then pass it to the appropriate routing function to do the rendering.
This does what I want, but with global variables:
dataDir = None
def initializeData(pathname):
global dataDir
dataDir = pathname
#app.route('/')
def home():
# Use dataDir as desired
if __name__ == '__main__':
initializeData(sys.argv[1])
app = Flask(__name__)
app.run()
Is there a better way to communicate between the command line and my routes?
Your flask app has a config property. Also, this code will fail with a NameError. You want something like this:
import sys
from flask import Flask
app = Flask(__name__)
#app.route('/')
def home():
return 'You wanted {!r} directory'.format(app.config.get('some_setting'))
if __name__ == '__main__':
app.config['some_setting'] = sys.argv[1]
app.run()
Consider using app.config.from_json('config.json') so that you can configure your env parameters in a json file.

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.

Calling a python function over the web using AJAX?

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

Categories