so I have tried to fix this internal server error for a few days now for a personal project and when I debug just says "NameError: name 'pred' is not defined". I have looked at other posts and such, but I haven't had any luck so far. Here is the code I have written:
!pip install flask-ngrok
from flask import Flask, render_template, request
from flask_ngrok import run_with_ngrok
import pickle
app = Flask(__name__, template_folder="templates")
run_with_ngrok(app)
def cloud_prediction(time):
model = pickle.load(open('model.pkl', 'rb'))
return float(model.forecast(time)[0][time-1])
#app.route("/", methods= ["GET", "POST"])
def final():
if request.method =="POST":
time = int(request.form["time"])
global pred
pred = cloud_prediction(time)
mypred= pred
print(mypred)
return render_template("index.html", name= mypred)
if __name__=="__main__":
app.run()
My index.html file is saved in a folder named templates, and it looks like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WeatherNexus Inc.</title>
<meta name="description" content="A fortune teller for cloud activity.">
<meta name="author" content="Jesus_Lopez">
<meta property="og:title" content="WeatherNexus Inc.">
<meta property="og:type" content="website">
<meta property="og:description" content="A fortune teller for cloud activity.">
</head>
<body>
<body bgcolor='black' text='white'>
<h1>WeatherNexus Inc.<h1>
<p>
<font size=15 class="text-center">
Please input the time when you want to predict the cloud coverage. Timesteps are in 5 min increments. Ex: 6 = 30min
</p>
<form action="/" method="POST">
<input type="number" name="time" placeholder="Input Time here">
<input type="submit">
<p>Here is your residual output: </p>{{name}}
</form>
</body>
</html>
The thing is, if I take "name = mypred" out of the render_template command, then the variable gets defined and prints in the notebook, but I'd like to print the result in the webpage not just in my notebook.
Thanks for any help or suggestions.
#app.route("/", methods= ['GET'])
def home():
return render_template('index.html')
This was needed before my final definition.
Related
I wanted to integrate my frontend code with my python backend functionality
This is my frontend code with html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Subtitle AI</title>
...
</head>
<body>
<div class="upload">
<h3>Step 1: upload a .wav file</h3>
<input id="wavFile" type="file" name="myFile" accept=".wav" />
<button id="submit-button">Submit</button>
</div>
<h3>Step 2: Wait for model to generate closed captioning</h3>
<p id="result"></p>
<script>
$("#submit-button").click(function(event) {
let parameter1 = {
return1: $("#wavFile").val(),
};
$.post(
"http://127.0.0.1:5000/predict",
JSON.stringify(parameter1),
function(transcription) {
$("#result").text(transcription.result);
console.log(transcription);
}
);
});
</script>
</body>
</html>
And this is my pytohn backend code functionality + attempted integration. I tried to integrate it with Flask, not sure what went wrong, but when I clicked the button, the return value from my python backend function is not displaying.
...
from flask import Flask
from flask import jsonify
app = Flask(__name__)
#app.route('/predict', methods=['POST'])
...
# define the prediction function which takes in the file path to a wav file and outputs the predicted words
def predict (model, device, path):
...
# decode the IDs to text
transcription = processor.decode(predicted_ids[0])
return jsonify(transcription)
I would like to use flask to check when a button is pressed in an HTML coded website, the website will be up and running and the py app needs to be running too and wait for the button click, then on the button click, it will get the input content and print it. How do I do this?
this is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
</head>
<body>
<input type="hallo">
<button>Hallo</button>
</body>
</html>
I have searched for a while but nothing I tried worked, please help.
some code snippets would be great, thanks.
Use a simple form that is submitted with a post request.
The value from the input field is queried using the name attribute.
The button of type submit submits the form.
from flask import (
Flask,
render_template,
request
)
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
print(request.form.get('hallo'))
return render_template('index.html')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
</head>
<body>
<form method="post">
<input type="text" name="hallo" />
<button type="submit">Hallo</button>
</form>
</body>
</html>
I'm building a website in flask and python and I want to store the user's input in a variable, then output it onto the website screen.
This is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
<div><h1>Home Page</h1>
<p>Hello, {{ name }}</p>
</div>
<form>
<label for="fname">Enter Sq. ft.</label><br>
<input type="text" id="estimate" name="estimate" value="Ex. 1000"><br>
<input type="submit" value="Calculate Estimate">
</form>
Click me
</body>
</html>
and this is my python/flask code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/my-link/')
def my_link():
temp = 0
for i in range(10):
temp = i
return str(temp)
if __name__ == '__main__':
app.run(debug=True, port=8000)
When I run this, this is what I see:
When I type in 54 and hit "Calculate Estimate", I don't understand why I get http://127.0.0.1:8000/?estimate=54 in my search bar, I don't understand why it's going there. How would I be able to get that 54 and just print it on the website screen?
While I would recommend using POST if you're submitting sensitive data, GET suffices in your case.
To solve your issue, we have to first specify an action endpoint (by default, it's /, which loads too much responsibility onto one endpoint).
<form action="/calculate-estimate">
<label for="fname">Enter Sq. ft.</label><br>
<input type="text" id="estimate" name="estimate" value="Ex. 1000"><br>
<input type="submit" value="Calculate Estimate">
</form>
Second, we need to create a FLASK endpoint to handle the form data.
#app.route("/calculate-estimate", methods=["GET"])
def calculate_estimate():
estimate = request.args.get("estimate")
## Use your data however you desire.
This should be enough to solve your issue.
I am trying to create a search engine where the search will happen through a reference number provided to customers and from that reference number their all details will be displayed on a webpage. I have created an HTML page name as Track.html and the main python code is below. please help I am new to programming.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Track</title>
</head>
<body>
<body bgcolor="lightblue">
<center>
<h1><font size="7" color="purple" face="Russo one">TRACK YOUR COMPLAINT:</font></h1>
</center>
<FORM action="{{url_for('track')}}"method="post">
<p>
<br>
<b>Reference number:</b>
<input type="text" name="Reference_number" value="{{request.form.track}}"><br/>
</p>
<p><br>
<input type="Submit" name="request" value="Submit"><br/>
</p>
<b><H2>{{records}}</H2></b>
Click here to submit your complaint.
</FORM>
</body>
</html>
#app.route('/Track.html', methods=['GET', 'POST'])
def track():
if request.method == "POST":
conn = db_connect()
cur = conn.cursor()
cur.executemany('''select * from complaint_application where Reference_number = %s''', request.form['track'])
return render_template("Track.html", records=cur.fetchall())
return render_template('Track.html')
if __name__ == '__main__':
app.run(host='0.0.0.0',port='5000')
from flask import Flask,render_template,url_for
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/okay")
def okay():
return render_template("okay.html")
if __name__ == '__main__':
app.run(debug=True)
this is index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>index</h1>
<h2 onclick="{{ url_for('okay') }}">click me</h2>
<h2>click me</h2>
</body>
</html>
click me
this is not working
also
form action url_for is not working
change route and send message using socketio but socketio is working
how to solve this issue?
When used on a HTML element, onclick normally results to a call to a script function like this onclick=myFunction().
<body>
<h1>index</h1>
<h2 id="foo" onclick="myFunction();">click me</h2>
<h2>click me</h2>
</body>
You'll need to add some Javascript code for onclick=myFunction(); to work.
function myFunction() {
$.ajax({
url: '/okay',
data: JSON.stringify(data),
method: 'POST',
contentType: 'application/json',
success: function(data) {
$('#foo').replaceWith(data);
}
});
};