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.
Related
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
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.
I was just wondering how to set one part of a python Flask web address to a python variable.
Python code
from flask import Flask
app = Flask(__name__)
#app.route('/<variable>')
def test(variable):
test = variable
return("Hello World!!")
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
Im not 100% sure what you mean but heres some code using dynamic urls with flask
#app.route('/study_type/')
#app.route('/study_type/<study>')
def study_type(study=None):
if study == '1':
return render_template('1.html')
elif study == '2':
return render_template('2.html')
else:
return render_template('study_type.html')
In this this example is a user goes to /study_type/1 they get redirected to 1.html. If they just hit /study_type they get redirected to study_type.html. You can pass in the dynamic url value in the route/view function
You can print out the variable using (in your example):
return("Hello World!! " + variable)
or
print(variable)
Or you can return it to the template:
if study == '1':
return render_template('1.html', study_no=study)
and then it will be available in your jinja template as study_no
I'm not sure if i follow your question completely but if you are just trying to pass a variable through from the route to the function. There are some examples here http://exploreflask.com/en/latest/views.html#url-converters
Depending on the type of variable you can enter that in the route. e.g
#app.route('/user/id/<int:user_id>')
def profile(user_id):
pass
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.
In my app, each page is each Python class. From page A, I want to take some data in this page and redirect to page B.
Does Google App Engine has some ways to do it ? (I don't want to use something like: global variable or cookie for this small work)
Thanks :)
You can compute the value you need in the first handler (AHandler), then redirect to the second handler (BHandler) passing that value as a GET parameter. Finally BHandler, reads that parameter and does something with it. Here is some code:
import urllib
class AHandler(webapp2.RequestHandler):
def get(self):
name = 'Some name'
redirect('b?%s' % urllib.urlencode({'name': name}))
class BHandler(webapp2.RequestHandler):
def get(self):
name = self.request.get('name')
# do something with name