URL was not found in the server - python

I am trying to deploy my ml model in flask. The error appear when i am trying access my height-weight.html page from the home.html page.
code for app.py
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
if __name__ == "__main__":
app.run()
This works perfectly fine. It render home.html. No problem here.
Output 1:-
But as soon as I click Check Project button following error occurs.
Output 2:-
Code for height-weight.py
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))
#app.route('/predict')
def weight_predict():
return render_template('height-weight.html')
#app.route('/predict',methods=['POST'])
def predict():
if request.method == 'POST':
height = float(request.form['height'])
gender = float(request.form['gender'])
prediction = model.predict([[gender, height]])
output = round(prediction[0], 2)
return render_template('height-weight.html', weights = output)
if __name__ == "__main__":
app.run()
And finally my html code for height-weight.html look like this.
Code:-
<section id='form'>
<div class="container">
<h1>Height Weight Prediction</h1>
<form action="{{ url_for('predict')}}" method="get">
<div class="card">
<div class="card-body">
<label>Gender</label>
<input type="text" class="form-control" id='gender' placeholder="Input Your Gender" required="required">
</div>
<div class="card-body">
<label>Height</label>
<input type="text" class="form-control" id='height' placeholder="Input Your Height" required="required">
<small class="form-text text-muted">Please input your height in 'Inch'.</small>
</div>
<button type="submit">Predict Weight</button>
</div>
</form>
{{ weights }}
</div>
</section>
My expected output is to show height-weight.html pages from where i can predict the weight. This is my error. Hope you guys understand my error and please help me. Thanks in advance.

You are redirecting the page to 127.0.0.1:5000/height-weight.html which is looking for the HTML file on the backend server. You need to redirect the page to /redirect by providing it in an anchor tag.
Flask renders the HTML page and returns the response it doesn't serve the HTML page directly. That's why you are getting 404 error.
Hope this helps!

Related

Flask Templating Language Not Displaying Properly

My flask template is not displaying properly. For some reason, the templating language is being displayed on the webpage.
Here is what it looks like (red circles indicate items that should not be on the web page)
I am not sure why this is happening. The templates are stored in a folder called static and in my app.py, I have the following line as well:
app = Flask(__name__, template_folder='static')
Edit: Here is the code that renders the following portion of this page:
`
{% if passphrase %}
<div>
<h4>Information</h4>
<p>Address: 123_easy_uncover_street</p>
</div>
{% else %}
<div class="col">
<h4>Enter passphrase</h4>
<form action="" method="POST" style="text-align:left">
<label for="passphrase">Passphrase</label>
<input type="text" id="passphrase" name="passphrase">
<br>
<input type="submit" value="Submit">
</form>
</div>
<div id="status" class="col" >
<p><i>Please enter your passphrase</i></p>
</div>
{% endif %}
</div>`
Flask code:
from app.bank_database import BankDatabase
from flask import Flask, request, render_template
import random
import json
app = Flask(__name__, template_folder='static')
db = BankDatabase()
#app.route('/', methods=['GET', 'POST'])
#app.route('/index.html', methods=['GET', 'POST'])
def index():
return render_template("index.html", passphrase="")
#app.route('/check_passphrase', methods=['GET', 'POST'])
def check_passphrase():
passphrase = request.args.get("passphrase")
if db.check_passphrase(passphrase):
#Show address here
#TODO - change view to show passphrase
return render_template("index.html", passphrase=passphrase)
return render_template("index.html", passphrase="")
app.run(debug=True,host="0.0.0.0")

Flask, Passing User Entered Data Between Views

Problem transferring variables across views I tried using sessions and could not get the connection to work. Say I have two pages, a home and page2. I have a flask app that will take user input from the home and print out input on page2.
For example, if you start my app, you will see this as the home page:
This part works fine, I am able to enter a value.
What I want to happen next, is after you click submit, page2 is generated showing what was just entered:
Whatever string value was entered on home should show up in the highlighted portion.
I have the following app.py file:
from flask import Flask, render_template, request, session
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def home():
stringval = ''
if request.method == 'POST' and 'stringval' in request.form:
stringval = request.form.get('stringval')
session["stringvalue_topass"] = stringval
return render_template('page2.html', stringval = stringval)
return render_template("home.html")
#app.route('/page2', methods=['GET', 'POST'])
def page2():
stringvalue_get = session.get('stringvalue_topass')
return render_template('page2.html', stringvalue_get = stringvalue_get)
if __name__ == '__main__':
app.run(debug=True)
The following home.html:
<!doctype html>
<h1>Enter Value </h1>
<div class="main">
<form class="pure-form" method="POST" action="/page2">
stringval:<br>
<input type="text" name="stringval"><br>
<button type="submit" class="pure-button pure-button-primary" value="Submit">Submit!</button>
</form>
</div>
</body>
And the following page2.html
<!doctype html>
<h1>You have selected </h1>
<div class="main">
{% if stringvalue_get %}
<pre>
{% print(stringvalue_get) %}
</pre>
{% endif %}
</div>
</body>
Okay, there are a few issues here. Firstly, the action attribute of your form in home.html is set to "/page2". This means that when the form is submitted, the POST request is going to the /page2 endpoint rather than to the /home endpoint, where you have written the code for handling the form submission. We can fix this by just deleting the action attribute, as this means the form will post to then endpoint that loaded it - in this case /home.
Secondly, Flask sessions cannot be used without setting a secret key to encrypt the session. This can be done by assigning a value to app.secret_key, like so:
app = Flask(__name__)
app.secret_key = b"my_secret_key"
Finally, instead of passing the string to the template like so: render_template('page2.html', stringval = stringval), (note also that this should be stringval_get = stringval), you can access the session object directly from templates already. So, in all, we can change your application code to:
app.py:
from flask import Flask, render_template, request, session
app = Flask(__name__)
app.secret_key = b"my_secret_key"
#app.route('/', methods=['GET', 'POST'])
def home():
if request.method == 'POST' and 'stringval' in request.form:
session["stringvalue_topass"] = request.form.get('stringval')
return render_template('page2.html')
return render_template("home.html")
#app.route('/page2', methods=['GET', 'POST'])
def page2():
return render_template('page2.html')
And your templates to:
home.html:
<!doctype html>
<h1>Enter Value </h1>
<div class="main">
<form class="pure-form" method="POST">
stringval:<br>
<input type="text" name="stringval"><br>
<button type="submit" class="pure-button pure-button-primary" value="Submit">Submit!</button>
</form>
</div>
</body>
page2.html:
<!doctype html>
<h1>You have selected </h1>
<div class="main">
{% if 'stringvalue_topass' in session %}
<pre>
{% print(session["stringvalue_topass"]) %}
</pre>
{% endif %}
</div>
</body>

POST method not working on Flask application

I'm trying to run a simple Flask application based on multiple simple tutorials. My goal is to finish a full tutorial and manipulate the code to build a search web app that connects to a SQL server database.
However, when I try running the code and provide an integer input, the POST method is not working, so it will not return a {{value}} as specified.
I've tried adding and removing several components: adding in the action='/' on the HTML, and trying to run the code as well without it. That didn't make a difference.
I have methods=['GET', 'POST'] already.
I even tried {{ url_for('/') }} and that just gave me an Internal Server Error.
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
#app.route('/hello')
def hello():
return "My flask app"
#app.route('/', methods=["GET", "POST"])
def home():
if request.method == "POST":
value = int(request.form["number"])
add_one = value + 1
return render_template('index.html', string="WORLD!", value=add_one)
return render_template('index.html', string="WORLD!")
if __name__ == "__main__":
app.run()
HTML:
<body>
<div class="container">
<h1>Hello, {{string}}</h1>
<br>
<form action='/' role="form" method="post" onsubmit="return false;">
<div class="form-group">
<input type="number" class="form-control" name="number" placeholder="Enter a number" required>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<p>The calculated number is {{value}}</p>
<br>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</body>
While running the code my app renders successfully, but when submitting a number the server does not register the input.
I don't even receive an error. All I see in the terminal is "GET / HTTP/1.1" 200.
By removing onsubmit="return false;" attribute of the form in the HTML.
And by restarting your app and reload the HTML.
It should be working.

NameError: global name 'flask' is not defined

I am fairly new to Python web programming. Request your assistance in handling the error I am getting while running a test application please. Trying to run the command - python run.py - from Powershell. It gives the error given in the title. Trying the instructions provided in this link
run.py
from tweet_harvester import app
app.run(port=8080)
Config.py
import os
DEBUG = True
TWITTER_CONSUMER_KEY = os.environ['TWITTER_CONSUMER_KEY']
TWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']
TWITTER_ACCESS_TOKEN = os.environ['TWITTER_ACCESS_TOKEN']
TWITTER_ACCESS_TOKEN_SECRET = os.environ['TWITTER_ACCESS_TOKEN_SECRET']
init.py
from flask import Flask, json, request, render_template
import tweepy
app = Flask(__name__)
app.config.from_object('config')
auth = tweepy.OAuthHandler(app.config['TWITTER_CONSUMER_KEY'],app.config['TWITTER_CONSUMER_SECRET'])
auth.set_access_token(app.config['TWITTER_ACCESS_TOKEN'],app.config['TWITTER_ACCESS_TOKEN_SECRET'])
tweepy_api = tweepy.API(auth)
def get_tweets(username):
tweets = tweepy_api.user_timeline(screen_name=username)
return [{'tweet': t.text,'created_at': t.created_at,'username': username, 'headshot_url': t.user.profile_image_url}
for t in tweets]
#app.route('/tweet-harvester/<string:username>')
def tweets(username):
return flask.render_template('tweets.html', tweets=get_tweets(username))
tweets.html - pasting only the relevant portion of header and body section
<title>Tweet Harvester</title>
<body>
<div class="container">
<h1 class="p-3">Tweet Harvester</h1>
{% for tweet in tweets %}
<div class="list-group">
<a href="#" class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<img src="{{tweet.headshot_url}}" class="w-12 p-1 float-left image-thumbnail">
<h5 class="ml-10 w-75 mb-1">{{ tweet.tweet }}</h5>
<small>{{ tweet.created_at }}</small>
</div>
</a>
</div>
{% endfor %}
You have not imported render_template from flask. You need to import it before using.
from flask import render_template
Because you are using the render_template incorrectly I guess.
It should be flask.render_template()
OR (better) for using it in your way you just need to import it from flask as
from flask import render_template

Python Flask : url_for to pass the variable to function from form template

I tried this approach to pass the form input variable to function via url_for method. But its not working. can anyone check and let me know whats wrong in this code.
Function:
#app.route('/report_data/<year>/<week>', methods = ['POST'])
def report_data(year,week):
print year
print woy
HTML Code :
<html>
<body>
<form action="{{ url_for('report_data', year=n_year, week=n_woy) }}" method="post">
<h3> Enter the details </h3>
Year :
<input type="text" name="n_year"> <br>
<br>
Week :
<input type="text" name="n_woy"> <br>
<br>
<input type="submit" value="Submit"> <br>
</form>
</body>
</html>
Issue:
Getting "None" for both variable.
Firstly, How do you provide year, week values before submitting them in your HTML code ?
Did you render the HTML template in your function? If not, how does your flask function knows that you were seeking from that specific form?
If this is your Flask app code -
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/report_data', methods = ['POST', 'GET'])
def report_data():
if request.method == 'POST':
result = request.form
query_year = result['n_year'].encode('ascii', 'ignore')
query_week = result['n_woy'].encode('ascii', 'ignore')
print(query_year, query_week)
return render_template('so_test.html')
if __name__ == '__main__':
app.run(debug=True)
And opened the URL -
http://127.0.0.1:5000/report_data
And I get this picture.
Once I post the data, I can see this data in my Flask app console.
('2018','08')

Categories