Flask: NameError: 'app' is not defined? - python

My Flask application has been running fine for the last 24 hours, however I just took it offline to work on it and i'm trying to start it up again and i'm getting this error:
Traceback (most recent call last):
File "runserver.py", line 1, in <module>
from app import app
File "/home/MY NAME/APP FOLDER NAME/app.py", line 15, in <module>
from Views import *
File "/home/MY NAME/APP FOLDER NAME/Views.py", line 1, in <module>
#app.route('/contact', methods=('GET', 'POST'))
NameError: name 'app' is not defined
I am running the application currently by calling python runserver.py
runserver.py:
from app import app
app.run(threaded = True, debug=True, host='0.0.0.0')
Views.py: contains all of my routes, I won't post them all, as the error is coming from the first time app is mentioned in this file.
#app.route('/contact', methods=('GET', 'POST'))
def contact():
form = ContactForm()
if request.method == 'POST':
msg = Message("CENSORED,
sender='CENSORED',
recipients=['CENSORED'])
msg.body = """
From: %s <%s>,
%s
""" % (form.name.data, form.email.data, form.message.data)
mail.send(msg)
return "><p><br>Successfully sent message!</p></body>"
elif request.method == 'GET':
return render_template('contact.html', form=form)
app.py: Here is the top of my app.py file, where I define app = Flask(__name__) as well as import my statements.
from flask import Flask, request, render_template, redirect, url_for, send_file
from geopy.geocoders import Bing
from geopy.exc import GeocoderTimedOut
import re
import urllib
from bs4 import BeautifulSoup
from openpyxl import load_workbook
from openpyxl.styles import Style, Font
import os
import pandas as pd
import numpy as np
import datetime
from Helper_File import *
from Lists import *
from Views import *
from flask_mail import Mail, Message
from forms import ContactForm
global today
geolocator = Bing('Censored')
app = Flask(__name__)
EDIT: I have made the changes suggested in the answer below, but am getting this when I access the page:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Here is my file structure:
DHLSoftware.com
|-static
|-style.css
|-templates
|- seperate html file for each page template
|-app.py
|-forms.py
|-helper_file.py
|-Lists.py
|-runserver.py
|-Views.py

In app.py you should remove the from Views import *. Instead in your Views.py you need to have from app import app
That will bring app into the views namespace and I believe that should work for you.

Related

TypeError: Blueprint.__init__() got an unexpected keyword argument 'template_folder'

This is what my directory looks like
p/
student/
template/
student/
index.html/
views.py/
__init__.py/
app.py/
this is what my app.py file looks like
from flask import Flask, render_template
from p import app
#app.route("/")
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run()
__init__.py file
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] =
"postgresql://postgres:1234#localhost/studentRegDB"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
Migrate(app, db)
from p.student.views import student_blueprints
app.register_blueprint(student_blueprints, url_prefix='/student')
views.py file
from flask import Flask, request
import psycopg2
from p import db
from p.student.forms import studentform
from p.student.models import Student
from flask import Flask, render_template, url_for,redirect
from flask_blueprint import Blueprint
student_blueprints = Blueprint('student', __name__, template_folder='student')
#student_blueprints.route("/add", methods=["GET", "POST"])
def addstudent():
form = studentform()
if form.validate_on_submit():
name = request.form['name']
course = request.form['course']
new_student = Student(name,course)
db.session.add(new_student)
db.session.commit()
return redirect(url_for("success.html"))
return render_template("student.html", form=form)
when run the code i get the following error
student_blueprints = Blueprint('student', name, template_folder='student')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Blueprint.init() got an unexpected keyword argument 'template_folder'
thank you for your help
You have to be very careful with names. The package flask_blueprint is unrelated to the flask blueprints you get from from flask import Blueprint, and has completely different parameters.
I suggest you pip uninstall flask-blueprint, and change your code to
from flask import Blueprint

AssertionError: View function mapping is overwriting an existing endpoint function:

I am creating an app with python and flask. I am getting the following error:
Traceback (most recent call last):
File "C:\Users\Albert\PycharmProjects\Carro\views_trips.py", line 10, in <module>
def index():
File "C:\Users\Albert\PycharmProjects\Carro\venv\lib\site-packages\flask\scaffold.py", line 439, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "C:\Users\Albert\PycharmProjects\Carro\venv\lib\site-packages\flask\scaffold.py", line 57, in wrapper_func
return f(self, *args, **kwargs)
File "C:\Users\Albert\PycharmProjects\Carro\venv\lib\site-packages\flask\app.py", line 1090, in add_url_rule
raise AssertionError(
AssertionError: View function mapping is overwriting an existing endpoint function: index
I have only one route.
from flask import render_template, request, redirect, session, flash, url_for, send_from_directory
from app import app
from models import Trips, Users, Cars, db
import time
from helpers import *
from flask_bcrypt import check_password_hash
#app.route('/')
def index():
nickname = 'Bertimaz'
trip = Trips.query.filter_by(user_nickname=nickname).order_by(Trips.initialTime.desc()).first()
user = Users.query.filter_by(nickname='Bertimaz') # não ta achando usuario
print(user.name)
car = Cars.query.filter_by(plate=trip.car_plate)
return render_template('home.html', titulo='Viagens', trip=trip, user=user, car=car)
It was able to run it before I started implementing my SQL alchemy models and I tried changing the index function name
Instead of running the file with the routes instead of the correct script below:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from flask_bcrypt import Bcrypt
app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
from views_trips import *
from views_user import *
if __name__ == '__main__':
app.run(debug=True)
In your init.py, import the Falsk app and assign the value to that app.
from flask import **app**, Flask
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from app.config import Config
**app = Flask(__name__)
app.config.from_object(Config)**
# DB
db = SQLAlchemy(app)
migrate = Migrate(app, db)
After you have these above entries, you can import the app as
from app import app
NOTE: Do not import the app in multiple py files.

Python flask api routes 404 Not found error

As the title of the question says, all the routes which are not in the main file i.e. app.py are throwing Not Found 404 error. Below are the details of my small project:
Directory structure:
server
-> user
-> __init__.py
-> models.py
-> routes.py
-> app.py
-> __init__.py
app.py:
from flask import Flask
app = Flask(__name__)
from user import routes
#app.route('/') # THIS ROUTE WORKS
def index():
return '<h1>HOME</h1>'
if __name__ == '__main__':
app.run(debug = True)
routes.py:
from app import app
#app.route('/register', methods=['GET']) # THIS DOESN'T WORK - 404 NOT FOUND ERROR
def register_user():
return '<h1>Register a user!</h1>'
I cannot find out what is wrong here, I also tried the Blueprint method but I keep getting circular import error.
EDIT:
Flask Blueprint approach:
app.py:
from flask import Flask
from pymongo import MongoClient
app = Flask(__name__)
mongo_client = MongoClient(mongoUri)
db = mongo_client[DB_NAME]
from user.routes import bp
app.register_blueprint(bp)
#app.route('/')
def index():
return '<h1>HOME</h1>'
if __name__ == '__main__':
app.run(debug = True)
user/routes.py:
from flask import Blueprint, render_template_string
from user.models import User # if I comment this, it starts working...
bp = Blueprint('user', __name__)
#bp.route('/register', methods=['POST'])
def register_user():
user = User()
user.register()
return user
#bp.route('/register', methods=['GET'])
def check_user():
return render_template_string('<h1>User Registered</h1>')
user/models.py:
import uuid
from urllib import request
from flask import jsonify
from app import db # fishy...
class User(object):
def register(self):
user = {
'_id': uuid.uuid4().hex,
'email': request.form.get('email'),
'password': request.form.get('password'),
}
db.users.insert_one(user):
return jsonify(user), 200
I'm now getting this error as I mentioned earlier:
Traceback (most recent call last):
File "D:\project\server\app.py", line 10, in <module>
from user.routes import bp
File "D:\project\server\user\routes.py", line 2, in <module>
from user.models import User
File "D:\project\server\user\models.py", line 5, in <module>
from app import db
File "D:\project\server\app.py", line 10, in <module>
from user.routes import bp
ImportError: cannot import name 'bp' from partially initialized module 'user.routes' (most likely due to a circular import) (D:\project\server\user\routes.py)
You need to first define a Blueprint, and then use that for your routes/APIs. In route.py write this:
from flask import Blueprint, render_template_string
from user.models import User
bp = Blueprint('user', __name__)
#bp.route('/register', methods=['POST'])
def register_user():
user = User()
user.register()
return user
#bp.route('/register', methods=['GET'])
def check_user():
return render_template_string('<h1>User Registered</h1>')
Then you need to import and register your blueprint. In app.py have this:
from flask import Flask
app = Flask(__name__)
from user.routes import bp
app.register_blueprint(bp)
#app.route('/')
def index():
return '<h1>HOME</h1>'
if __name__ == '__main__':
app.run(debug = True)
Have another file in the same directory as app.py, you can call it extensions.py:
from pymongo import MongoClient
mongo_client = MongoClient(mongoUri)
db = mongo_client[DB_NAME]```
And finally models.py will look like this:
...
from extensions import db
...

Upload image to folder with Flask

I have a flask app to let a user upload a picture. I want to be able to save that picture into a folder. However, the console returns an error. The path is correct, so I am not sure what am I missing:
Error:
/c/UOMDataAnalytics/MINSTP201902DATA4/Homework/VisualizePictures/OldPortsApp/static/Images/uploads/WIN_20140917_095804.JPG
Flask code:
import os
import pandas as pd
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from flask import Flask, jsonify, render_template,make_response,url_for
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
from flask import request, redirect
app = Flask(__name__, static_url_path='/static')
UploadDir="/Images/uploads/"
# image upload route
#app.route("/upload-image", methods=["GET", "POST"])
def upload_image():
app.config["IMAGE_UPLOADS"] = UploadDir
# print (app.config["IMAGE_UPLOADS"])
if request.method == "POST":
if request.files:
image = request.files["image"]
image.save(os.path.join(app.config["IMAGE_UPLOADS"], image.filename))
print(image.filename)
return redirect(request.url)
return render_template("public/upload_image.html")
if __name__ == "__main__":
app.run()
I would expect to see the uploaded picture on the upload directory. I want to deploy this to heroku.
I think it's an issue with path. just try to replace this line
image.save(os.path.join(os.path.abspath(__file__),'..', UploadDir, image.filename)).
I think It'll work.
This one worked fine for me!
picture_path = os.path.join(app.root_path, '/Images/uploads/', image.filename)
image.save(picture_path)

References and URL rules in Flask

I've got a problem with my simple app in Flask. I want to write a registration page, that connect with datebase by SQLAlchemy. I've got app.py file that look like this:
import flask
import settings
import os
from flask_sqlalchemy import SQLAlchemy
# Views
from main import Main
from login import Login
from remote import Remote
from register import Register
#from models import User
#from models import Task
app = flask.Flask(__name__)
app.config['SESSION_TYPE'] = 'filesystem'
app.secret_key = os.urandom(24)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////database.db'
db = SQLAlchemy(app)
# Routes
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=Main.as_view('page'),
methods=["GET"])
app.add_url_rule('/login/',
view_func=Login.as_view('login'),
methods=["GET", "POST"])
app.add_url_rule('/remote/',
view_func=Remote.as_view('remote'),
methods=['GET', 'POST'])
app.add_url_rule('/register/',
view_func=Register.as_view('register'),
methods=['GET', 'POST'])
#app.errorhandler(404)
def page_not_found(error):
return flask.render_template('404.html'), 404
app.debug = True
app.run()
So, as you can see I have URL rules in this file and now I want to use db variable in Register view, so I need import it there, my code for this file looks like this:
import flask, flask.views
from app import db
class Register(flask.views.MethodView):
def get(self):
return flask.render_template('register.html')
def post(self):
new_user = User(username = request.form['username'],
password = request.form['passwd']
db.session.add(new_user)
db.session.commit()
return flask.redirect(flask.url_for('index'))
In that case I get error, cause I have "tied" references, in app file is:
from register import Register
but in Register file is
from app import db
So it, obviously can't work, my solutions is to add URL rule in Register file. But I don't know how. Could you anyone help me?
Sorry for my confusing title, but I just getting started with Flask and I dnon't know how to name it.
You need to move your db assignment to before the imports that expect db to exist:
import flask
import settings
import os
from flask_sqlalchemy import SQLAlchemy
app = flask.Flask(__name__)
app.config['SESSION_TYPE'] = 'filesystem'
app.secret_key = os.urandom(24)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////database.db'
db = SQLAlchemy(app)
# Views
# These can now use
# from app import db
# because that line has executed above
from main import Main
from login import Login
from remote import Remote
from register import Register
#from models import User
#from models import Task
Now when you import the register module and the from app import db line runs, the db variable actually exists in the app module.
Note that you cannot now use app.py as the main script; if you use python app.py then it'll be imported as the __main__ module instead of app module, and using from app import db will create a new module, separate from the main script.
Either use a separate serving script, like serve.py and move your app.run() call into that file:
from app import app
app.debug = True
app.run()
or use from __main__ import db.
You also are missing a closing ) in your register module:
new_user = User(username = request.form['username'],
password = request.form['passwd']
# ^ ^

Categories

Resources