Running a Python code on HTML page using Flask - python

I am new to Flask. I want to run my Python project, when the start button is pressed from the HTML page and display the string which is returned from the Python code, on the HTML page. I am using Python flask.
This is the HTML file with the button.(The name of the HTML file is json.html)
<!DOCTYPE html>
<html>
<body>
<h1>Smart Job Interviewer</h1>
<button type="button">Start the Interview</button>
</body>
</html>
Following is the Python flask file. newexecutiontest is my python file and run() is the function that I need to run. This function returns a string and I want to display it on the HTML page.
from flask import Flask
from TextToSpeech import newexecutiontest
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('json.html')
def dynamic_page():
return newexecutiontest.run()
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8000', debug=True)
When I run the code and load the web page it says that "This site can't be reached"
Can someone please help me to achieve the above task.
Thank you in advance.

Try changing the IP to localhost or 127.0.0.1
You should keep the html template under the folder /templates

You could make the button part of a form, so that it is routed back to your python module on click (just printing a string on button click could more easily be done with javascript, but I assume run() performs some logic as well). Also add some input field to the form so you can know it was submitted:
<form method="GET">
<input type="hidden" name="start">
<button type="submit">Start the Interview</button>
</form>
Now in the flask file, you can perform a basic check to see if "start", or whatever name you gave your input, exists in the get request arguments - which would mean the form was submitted. It is possible to pass arguments to an html file, so we will pass None if the form wasn't submitted or the desired string if it was:
from flask import request
#app.route('/')
def index():
return render_template('json.html', test_str=dynamic_page() if request.args.get("start") is not None else None)
And finally, you can check the value of test_str in the html file and print it accordingly, using the jinja templating engine. Logic is declared between {% and %}, while evaluations are declared between {{ and }}. Adding this to the html file where you want the string to be printed should work:
{% if test_str is not none %}
<p>{{ test_str }}</p>
{% endif %}

Related

cannot get html front end to pass input to python script using flask

So, I am building a webapp which takes a link from a shopping website then runs it through a python script which interprets the data, stores it in a database and that populates a table for reference.
I am running into a couple issues:
if I put the link into the front end input (html) then submit it just takes me to "page isn't working HTTP error 405". I'm not sure what to do about that one.
the more pressing issue is that even though I believe I routed the input properly through flask I get this issue when I run the python script alongside the frontend
"RuntimeError: Working outside of request context."
I tried some of the advice mentioned in these existing posts to no avail:
Sending data from HTML form to a Python script in Flask
Connecting python script with html button and flask
I also tried changing the script itself to use getvalue() instead of getvalue when associating it as an input variable for the python script to work with.
this is my route code from app.py
#app.route("/", methods=['POST'])
def getvalue():
HTML_Info = request.form['data_bridge']
return HTML_Info
code for the HTML input
<form name="passdata" action="{{ url_for('getvalue') }}" method="POST">
<input type='text' name="data_bridge" placeholder="paste shoe link here">
<input type="submit">
</form>
and the python code just imports the app file and the getvalue function and then assigns it to a variable.
if you guys could help me sort this out I would greatly appreciate it.
I assume you want to take an input (e.g. shoe link) from the user and then do some operations based on the input.
To access the HTML form from / path you need to enable both GET and POST requests in that route. Otherwise, when you try to access the root path / from your browser, you will get the HTTP Method not allowed error.
app.py:
from flask import Flask, render_template, request
app = Flask(__name__)
def get_value_related_info(value):
return f"You have entered {value}"
#app.route('/', methods=['POST', 'GET'])
def getvalue():
if request.method == "POST":
HTML_Info = request.form['data_bridge']
return get_value_related_info(HTML_Info)
return render_template('form.html', text="")
if __name__ == "__main__":
app.run(debug=True)
Output:
Before form submission:
After form submission:
templates/form.html:
<html>
<head>
<title>Form example</title>
</head>
<body>
<form name="passdata" action="{{ url_for('getvalue') }}" method="POST">
<input type='text' name="data_bridge" placeholder="paste shoe link here">
<input type="submit">
</form>
</body>
</html>
Explanation:
I have mocked the functionality on the user input in get_value_related_info method.
References:
Flask documentation for request object

How to run an HTML input as a python variable? [duplicate]

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
HTML Code
<!DOCTYPE html>
<html>
<head>
<h1>App</h1>
</head>
<body>
<form action="Test.py" method="GET">
<label for="search">Enter keyword here</label>
<input type="text" name="userInput" required></input>
<input type="submit" value="submit"></input>
</form>
</body>
</html>
Flask Code
from flask import Flask, url_for, request
app = Flask(__name__)
#app.route("extPage.html", methods=['POST', 'GET'])
userinput = request.form("userInput")
print(userinput)
Whenever I run the HTML and submit something, it just returns the python flask code on the webpage. Want I am trying to do is use the userInput tag to create a variable to use in a python program not related. I need the input returned as a string which is why I am testing it with "print(userinput). My goal is to print the submission.
Place the print statement within a function below the route decorator.
something like:
#Don't call html pages. Call routes that return html pages
#app.route("/extPage/", methods=['POST', 'GET'])
def index():
userinput = request.form("userInput")
print(userinput)
return render_template('return_page.html', ui=userinput)
You can find the official documentation's tutorial here. It's what helped me the most when I have gotten stuck.

CS50 Final Project - File Upload from html.site to flask does not work due to false form method

I've been working myself through CS50 lately but now I'm struggling with my final project. One of the key elements is to allow users to upload images from an html website while the image will be further processed via an application.py. Overall I'll use flask.
Unfortunately this is where I'm already struggling. I tried all ways I could find to upload pictures and the result is always similar, when pressing the submit-button I receive an Internal Server Error message. I even copied code from youtube or forums which worked fine in the video but not in my IDE. Is it possible that the CS50 IDE blocks file uploads in general?
If not I isolate the problem to the code below and would highly appreciate if you could have a quick look. Probably it's a tiny problem I just don't get.
Code in my application.py
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/upload", methods=["POST"])
def upload():
file = request.files["inputFile"]
return file.filename
if __name__ == "__main__":
app.run(debug=True)
Code in the index.html
<!DOCTYPE html>
<html lang="en">
<head>
FILE UPLOAD EXAMPLE
</head>
<body>
<div class="container">
<h1>File Input</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<div class="form-group">
<label for="inputFile">File input</label>
<input type="file" name="inputFile">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</body>
I tried to isolate the problem and one thing I found is that the form always returns "GET" when the submit button is pressed while it is specifically defined in the form method that return should be "POST.
Anyhow, thank you so much for any comments in advance!
Best,
Martin
It works when you have templates directory in your project structure.
myproject/
__init__.py
app.py
templates/
index.html
This is because Flask's default template path is templates.
if you want to change it to something else for ex 'my_templates' then you should override it while creating app.
app = Flask(__name__, template_folder='my_templates')
Btw there is no real DB/file store code return so it will just return you the filename as response.

How to use json.dumps() to render python object in Flask app?

Hi all: I'm using Flask to develop a simple web app. I have a python function that return a collection of objects that I then want to render inside a template (i.e {{ object1.value }}) in a html page. I was thinking about creating a dictionary containing the object values that would then be passed on to the page as a jsonify string through a GET request.
The Flask app looks like this:
#app.route('/')
def hello():
python_func(object1,object2,object3...)
data = json.dumps({object1.key: object1.value, object2.key: object2.value ...})
if request.is_xhr:
return jsonify(data=data)
if request.method == "GET":
return render_template('main.html',data=data)
if __name__ == '__main__':
app.run()
The html page looks like this:
<div class ="dice">
<div class ="dice-1">
<div class="card" id ="card1" >
<p>{{ data }}</p>
</div>
</div>
And script with an event button. When button is clicked the object values are updated:
<script>
$(function() {
$('#roll-button').click(function() {
$.get('/', function(data){
document.getElementById("card1").innerHTML = data.data;
})
});
});
</script>
This seems to work to pass the object values to the template. I can see a string object with all the object keys and values when I update the page.
My problem is that I don't know how to use the string inside the template. I am confused about the documentation (https://docs.python.org/3.4/library/json.html) on the subject about decoding json.
Hence this question: how can parse the string containing all the object values to render inside the template to ideally look like this: {{ object1.value }}, {{ object2.value }}, {{ object3.other_attribute }} etc...
Can I create a python dictionary from the json string for me to use in the template?
Thank you for your help!
Cam
Don't pass JSON to your template, pass a dictionary. If you want non-dynamic rendering of data in HTML go with Jinja and flask's built in stuff.
from flask import render_template
#api.route('/foo', methods=['GET'])
def foo():
my_dictionary = {'a':'b', 'foo':'baz'}
return render_template('foo.html', my_data=my_dictionary)
Then in your html template
<!DOCTYPE html>
<html lang="en-ca">
<body>
{% for key in my_data %}
<h1>{{key}}</h1>
<h1>{{my_data.key}}</h1>
{% endfor %}
</body>
</html>
If you want to make the data available as a javascript object on the client side for live updating you will have to make an ajax call and do some templating on the front-end. If you don't mind page reloads just stick with flask's templating engine.

How to display a variable in HTML

I am making a web app using Python and have a variable that I want to display on an HTML page. How can I go about doing so? Would using {% VariableName %} in the HTML page be the right approach to this?
This is very clearly explained in the Flask documentation so I recommend that you read it for a full understanding, but here is a very simple example of rendering template variables.
HTML template file stored in templates/index.html:
<html>
<body>
<p>Here is my variable: {{ variable }}</p>
</body>
</html>
And the simple Flask app:
from flask import Flask, render_template
app = Flask('testapp')
#app.route('/')
def index():
return render_template('index.html', variable='12345')
if __name__ == '__main__':
app.run()
Run this script and visit http://127.0.0.1:5000/ in your browser. You should see the value of variable rendered as 12345

Categories