How to run python script results on Flask - python

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.

Related

Hello World Flask Project in VS 2022 showing default Flask page only

I am trying to get Flask hello World code working using VS 2022. Code works, but landing page that opens up is Flask default page instead of printing hello world on screen.
This is my code:
from flask import Flask
app = Flask(__name__)
if __name__ == '__main__':
app.run()
#app.route('/')
def hello():
"""Renders a sample page."""
return "Hello World!"
Here is what comes up:
Default image that shows up
What I am expecting is hello World printed on browser tab.
This is the tutorial that I have followed for Setup- https://learn.microsoft.com/en-us/visualstudio/python/learn-flask-visual-studio-step-01-project-solution?view=vs-2022
This is what my solution explorer looks like:
Solution explorer
I initially had return in place of print. That did not work. Tried it again and I still get same result. Tried changing / to /home also. Still same result. If i leave just import statement, it still opens same page. It seems my app.run is not getting called at all.
Edit: another information- In Views.py, i get message that PovertyClass could not be resolved. that is the name of my project.
move app.run() to the end of your script like this:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
"""Renders a sample page."""
return "Hello World!"
if __name__ == '__main__':
app.run()
2 Suggestions to solve your Problem:
change the URL in your browser from localhost:57345 to localhost:57345/ (add /)
add a new dummy route just for testing purposes (you should be able to copy the code i provided below)
#app.route('/home')
def show_home():
# render home page
return "This is my home page"
and then call this dummy page by the URL localhost:57345/home
Edit: like QwertYou stated -> change print to return

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 to reload a Python variable in an HTML page through Flask?

so I'm trying to do something pretty basic.
I have a Python APP which selects a random item in a list. Let's say like this:
from flask import Flask, render_template
import requests
import random
app = Flask(__name__)
#app.route('/')
def homepage():
def generator():
first_list = ['list_item1', 'list_item2', 'list_item3']
variable = random.choice(first_list)
return variable
variable = generator()
return render_template('index.html', variable=variable)
if __name__ == '__main__':
app.run()
app.run(port=4995)
And so then I have my index.html page:
<body>
<h1>{{ variable }}</h1>
</body>
So this works. When I open the index.html page I get to see either list_item1, list_item2 or list_item3.
But now, what I need to do is to create a button/function to only refresh this exact variable, instead of reloading the whole page. So that only the text changes when the function from the app randomly selects a new item in the list.
And... I can't find how to do that. Thanks for your help!
Feels like you want to create a AJAX call to another isolated method that will run to get the number. So, create another function, create a AJAX call to it and update the element.

Global GET Management in Flask

Is there any way of a 'global GET management' in Flask?
For example:
I want to show an error message, via popover, on any page of my flask application. If the user clicks on the 'close' button, the application will make a reload of the page with a new get parameter 'message_read=1'.
I want to catch this GET parameter. I am quite sure there is a better way then writing a check in every single app.route (which are a lot). Could you give me a hint please.
Thank you.
Add a before request function and handle it there. http://flask.pocoo.org/docs/0.12/api/#flask.Flask.before_request
#app.before_request
def do_stuff():
arg = request.args.get('message_read')
You may use decrators . Read about python decorators here
Here is a demonstration of custom decorator with flask.The code below shows a decorator definition and usage for your use case
Code
from flask import Flask,request
from functools import wraps
def popup_message(f):
#wraps(f)
def f_(*args,**argv):
message_read = request.args.get('message_read', None)
if message_read is not None:
return message_read
else:
return f(*args,**argv)
return f_
app = Flask(__name__)
#app.route('/earth')
#popup_message
def hello_earth():
return 'Hello,earth'
#app.route('/world')
#popup_message
def hello_world():
return 'Hello, World!'
app.run()
Usage
Run the app as
python main.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
and try making request to /earth and /world with and without message_read

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.

Categories