NameError: global name 'flask' is not defined - python

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

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 Flatpages not able to load table of contents

I made the following small website as an introduction to Flask, and already it doesn't work! It's not able to load the table-of-contents page.
My app.py, which is the server is as follows:
import os
from flask import Flask, request, render_template
from flask_flatpages import FlatPages
from Engine.nerve_net import Nerve_Tree
# Some configuration, ensures:
# 1. Pages are loaded on request.
# 2. File name extension for pages is html.
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.html'
#Instantiate the Flask app
app = Flask(__name__)
app.config.from_object(__name__)
pages = FlatPages(app)
#app.route("/")
#app.route("/index")
def index():
return render_template('index.html') #This returns the main welcome page
#app.route("/contents")
def contents():
return render_template('contents.html', pages=pages) #This returns the table of contents page
# URL Routing - Flat Pages: Retrieves the page path
#app.route("/<path:path>/")
def page(path):
page = pages.get_or_404(path)
return render_template("page.html", page=page)
if __name__ == "__main__":
app.run(debug=True)
My table of contents, the page which displays all files within the pages directory is as follows:
{% extends "tab.html" %}
{% block content %}
</br>
<h2>TABLE OF CONTENTS</h2>
<ul>
{% for page in pages %}
<li>
<a href="{{ url_for("page", page=page.path) }}">{{ page.title }}
</li>
{% else %}
<li>No pages so far</li>
{% endfor %}
</ul>
{% endblock content %}
In this example there is only one page in the pages directory named ncs1.html, which is as follows:
title: Hello
published: 2010-12-22
Hello, *World*!
Lorem ipsum dolor sit amet
Pointing the browser to my main welcome page on http://127.0.0.1:5000/ renders the page successfully. However pointing my browser to the table-of-contents-page on http://127.0.0.1:5000/contents gives the following error:
Could not build url for endpoint 'page' with values ['page']. Did you forget to specify values ['path']?
Where am I going wrong?
As the author above mentioned, changing the table-of-contents code worked:
<a href="{{ url_for('page', path=page.path) }}"

URL was not found in the server

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!

using flask variables in html templates

When I try to use a varible from a url argument the text disappears, here's the app.py code:
from flask import Flask, render_template
import os
TEMPLATE_DIR = os.path.abspath('templates')
STATIC_DIR = os.path.abspath('static')
app = Flask(__name__, template_folder=TEMPLATE_DIR, static_folder=STATIC_DIR)
#app.route('/<string:name>')
def home(name):
return render_template('index.html', variable=name)
Here's what I am doing in the index.html file in templates folder:
<body>
<h1 class="header">Hello {{ name }}</h1>
<h3>Attention! This is a testing website with learning purpouses.</h3>
</body>
But when I run the app.py no error is displayed but it doesnt display the Hello {{ name }} line
Try this since you have assigned your name value to variable in your code :
<body>
<h1 class="header">Hello {{ variable }}</h1>
<h3>Attention! This is a testing website with learning purpouses.</h3>
</body>

405 method not allowed when trying to upload a file to process on AWS S3 using Flask

I have created a Flask API which gets an Excel file from the user, runs a few operations on the data, and let's the user download the updated file. It is running fine on the local server. However, when I tried to run it on the AWS S3 bucket, it throws an error "405 Method Not Allowed" for "POST" operation.
My index.html looks like this:
<html>
<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>
<br>
<button type="submit" class="btn btn-default"> Download Results </button>
</br>
</form>
</div>
</body>
</html>
And the flask file:
from flask import Flask, request, render_template, send_file
from io import BytesIO
import jsonify
import traceback
import pandas as pd
from pandas import datetime
import xlrd
import xlsxwriter
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/upload', methods=['GET','POST'])
def upload():
if request.method == 'POST':
file = request.files['inputFile']
file.save(file.filename)
return process(file.filename)
def process(filename):
#
### DO DATA(PANDAS) OPERATIONS ###
#
return send_file(output, attachment_filename=name+'.xlsx', as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)
How do I make it run on S3? I tried updating the bucket policy to accept POST requests but that does not seem to help.
You're putting your Python code in the wrong AWS service, what you need is to deploy it on Elastic beanstalk. S3 is meant for storing static files like .html, .css or .js.
In this nice tutorial from the official AWS Docs, you can find what you need. Also, remember to have all the permissions you may need granted to not get a 403 error.

Categories