LocalProxy wrong in flask - python

I'm a beginner of flask,when i tried to run app.py on the server,it seemed to be wrong.And it can works on localhost.
I think it's wrong with the database and have tried to change the ip of database,but it not worked.
Traceback (most recent call last):
File "app.py", line 27, in <module>
import auth
File "/tmp/pycharm_project_flaskr/auth.py", line 5, in <module>
from db import get_db, User
File "/tmp/pycharm_project_flaskr/db.py", line 22, in <module>
db.init_app(app)
File "/usr/local/lib/python3.7/site-packages/flask_sqlalchemy/extension.py", line 305, in init_app
engines = self._app_engines.setdefault(app, {})
File "/usr/local/lib/python3.7/weakref.py", line 489, in setdefault
return self.data.setdefault(ref(key, self._remove),default)
TypeError: cannot create weak reference to 'LocalProxy' object
That's the way about databases.
app = current_app
DB_URI = 'mysql+pymysql://{}:{}#{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy()
db.init_app(app)

I had the same issue yesterday (on Flask 2.2.2) only connecting to my production database, not local. I fixed it without downgrading Flask by re-ordering some of the steps initializing my app.
My final version was:
from flask import Flask
import os
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
with app.app_context():
database_uri = (
f'postgresql+psycopg2://{os.getenv("POSTGRES_USER")}:'
+ f'{os.getenv("POSTGRES_PW")}#'
+ f'{os.getenv("POSTGRES_URL")}/'
+ f'{os.getenv("POSTGRES_DB")}'
)
app.config["SQLALCHEMY_DATABASE_URI"] = database_uri
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
migrate = Migrate(app, db)
db.create_all()
db.session.commit()
import api
api.add_all_apis(app=app)
if __name__ == "__main__":
app.run(host="0.0.0.0")

I change the version of flask from 2.2.2 to 2.0.3 and the problem was solved.

Related

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_restless with sqlalchemy doesn't generate api endpoints and gives "has no attribute extensions" error using blueprints

for my webapp I want to automatically generate a REST API. I read the of flask_restless docs, tried several tutorials and did everything as described:
my routes are to be located in module app.main.api.pv_tool.py
from . import api
from app.__init__ import db, app
from app.models import University
import flask_restless
manager = flask_restless.APIManager(app, session=db.scoped_session)
manager.create_api(University, methods=['GET'])
#api.route('/')
def index():
return 'asdf'
where University is defined in models.py
from sqlalchemy import String, Integer
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
...
class University(Base):
__tablename__ = 'unis'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(64), nullable=False, unique=True)
def __repr__(self):
return '<Uni %r>' % self.name
...
and the connection to the existing and filled database is established in database.py:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from app.models import Base
class Database:
path = 'sqlite:///pv_tool.sqlite'
engine = None
session = None
scoped_session = None
def __init__(self, path=path):
self.engine = create_engine(path, convert_unicode=True)
Base.metadata.bind = self.engine
db_session = sessionmaker(bind=self.engine, autocommit=False)
db_session.bind = self.engine
self.session = db_session()
self.scoped_session = scoped_session(self.session)
Base.metadata.create_all()
Now in my browser or using requests library module I get 'asdf' response on http://localhost:5000.
However, I cannot reach my University data trying everything like: localhost:5000/unis, localhost:5000/api/unis and so on. I always get a 404 response.
Without any errors this issue is hard to pursue. Does anybody have an idea how I could debug this in general and what my error in the code might be?
In PyCharm Debugger the manager object seems to have some API to create:
But I have no idea what I could look for here next.
Also, I get an error on runtime when I try using create_api_blueprints in pv_tool.py:
...
manager = flask_restless.APIManager(app, session=db.scoped_session)
api_bp = manager.create_api_blueprint('unis', University, methods=['GET'])
app.register_blueprint(api_bp)
...
Traceback (most recent call last): File "run.py", line 5, in <module>
from app import app File "/Users/rich/code/src/github.com/pv-tool-backend/app/__init__.py", line 4, in <module>
from app.main.api import api File "/Users/rich/code/src/github.com/pv-tool-backend/app/main/api/__init__.py", line 5, in <module>
from . import pv_tool File "/Users/rich/code/src/github.com/pv-tool-backend/app/main/api/pv_tool.py", line 11, in <module>
api_bp = manager.create_api_blueprint('unis', University, methods=['GET']) File "/Users/rich/code/src/github.com/pv-tool-backend/pv_tool_backend_venv/lib/python3.6/site-packages/flask_restless/manager.py", line 549, in create_api_blueprint
restlessinfo = app.extensions['restless'] AttributeError: type object 'University' has no attribute 'extensions'
This is how I run the app:
run.py
from app import app
app.run(debug=True, host='0.0.0.0', port=5000)
app module's init.py
from flask import Flask
from flask_cors import CORS
from app.main.api import api
from app.database import Database
db = Database()
app = Flask(__name__)
app.register_blueprint(api)
CORS(app)
Starting in terminal:
rich#local:~ $ python run.py
Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
Restarting with stat
Debugger is active!
Debugger PIN: 122-170-707
I managed to get it to work by shifting to use flask_sqlalchemy instead of the pure sqlalchemy.

Flask circular dependency

I am developing a Flask application. It is still relatively small. I had only one app.py file, but because I needed to do database migrations, I divided it into 3 using this guide:
https://realpython.com/blog/python/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/
However, I now can't run my application as there is a circular dependency between app and models.
app.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import render_template, request, redirect, url_for
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DB_URL']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.debug = True
db = SQLAlchemy(app)
from models import User
... routes ...
if __name__ == "__main__":
app.run()
models.py:
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return self.username
manage.py:
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == "__main__":
manager.run()
They are all in the same directory. When I try to run python app.py to start the server, I receive an error which definitely shows a circular dependency (which is pretty obvious). Did I make any mistakes when following the guide or is the guide wrong? How can I refactor this to be correct?
Thanks a lot.
EDIT: Traceback
Traceback (most recent call last):
File "app.py", line 14, in <module>
from models import User
File "/../models.py", line 1, in <module>
from app import db
File "/../app.py", line 14, in <module>
from models import User
ImportError: cannot import name User
I propose the following structure:
# app/extensions.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
...
# app/app.py
from app.extensions import db
def create_app(config_object=ProdConfig):
app = Flask(__name__.split('.')[0])
app.config.from_object(config_object)
register_extensions(app)
...
def register_extensions(app):
db.init_app(app)
...
# manage.py
from yourapp.app import create_app
app = create_app()
app.debug = True
...
In this case, database, app, and your models are all in separate modules and there are no conflicting or circular imports.
I chased this for a few hours, landing here a few times, and it turned out I was importing my page modules (the ones holding the #app.route commands) before the line where the app was created. This is easy to do since import commands tend to be placed at the very beginning, but it doesn't work in this case.
So this:
# app/__init__.py
print("starting __init__.py")
from flask import Flask
from flask import render_template
import matplotlib.pyplot as plt
import numpy as np
import mpld3
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config')
from . import index
from . import simple
app.run(threaded=False)
print("finished __init__.py")
Instead of having all imports on top.
Placing this here because this has to be a common error for casual flask users to encounter and they are likely to land here. I have hit it as least twice in the last couple of years.

Sqlalchemy db.create_all() not creating tables

I am currently following this pattern to avoid circular imports. This pattern seems to be pretty niche so it's been difficult trying to find a solution googling.
models.py
from sqlalchemy.orm import relationship
db = SQLAlchemy()
class Choice(db.Model):
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.String(32))
votes = relationship("Vote")
def __init__(self, text):
self.text = text
application.py
app = Flask(__name__)
app.debug = True
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite3')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app) # Reinitialiez db.Model to avoid cyclical imports in models.py
db_create.py
#!flask/bin/python
from application import app, db
from models import Choice
db.init_app(app)
db.create_all()
db.session.add(Choice("Red"))
db.session.add(Choice("Blue"))
db.session.add(Choice("Green"))
db.session.commit()
When I run db_create.py separately, I get:
$ python db_create.py
Traceback (most recent call last):
File "db_create.py", line 6, in <module>
db.create_all()
File "/home/ubuntu/.virtualenvs/paw-py/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 972, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "/home/ubuntu/.virtualenvs/paw-py/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 949, in _execute_for_all_tables
app = self.get_app(app)
File "/home/ubuntu/.virtualenvs/paw-py/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 922, in get_app
raise RuntimeError('application not registered on db '
RuntimeError: application not registered on db instance and no application bound to current context
What should I do? What is the best pattern to deal with this? I've even tried adding db.create_all() in my application.py after if __name__ == '__main__' but I am still getting the same error
Tell Flask-SQLAlchemy which is "current" app with app_context
with app.app_context():
# your code here
db.create_all()

flask sqlalchemy example around existing database

Problem: there needs to be full working example of auto-mapping sqlalchemy to an existing database in an app with multiple binds.
I want to bind to two databases and have one auto-map the tables. I need to do this because i don't have control over one DB, thus would have to constantly re-write my models and might delete new tables every time i migrate.
I love the answers given here, but i can't seem to make it work in Flask (I am able to use the sqlalchemy only to query as per the example).
The model.py I set up from the example above results in
EDIT I pulled the line
db.Model.metadata.reflect[db.engine]
from another post, and it should be db.Model.metadata.reflect(db.engine)
very simple solution
here is my model.py
from app import db
from sqlalchemy.orm import relationship
db.Model.metadata.reflect[db.engine]#change to (db.engine)
class Buildings(db.Model):
__table__ = db.Model.metadata.tables['test']
__bind_key__ = 'chet'
def __repr__(self):
return self.test1
.... other models from sqlalchemy uri here...
i get this
>>> from app import db, models
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "app/__init__.py", line 69, in <module>
from app import views, models
File "app/views.py", line 1, in <module>
from app import app,models, db
File "app/models.py", line 163, in <module>
db.Model.metadata.reflect[db.engine]
TypeError: 'instancemethod' object has no attribute '__getitem__'
Here's my config.py
SQLALCHEMY_DATABASE_URI = 'postgresql://chet#localhost/ubuntuweb'
SQLALCHEMY_BINDS = {
'chet': 'postgresql://chet#localhost/warehouse',
}
here's my init.py file
from flask import Flask
from flask_bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.admin import Admin, BaseView, expose
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.login import LoginManager, UserMixin, login_required
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'app/static'
app.config.from_object('config')
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
Bootstrap(app)
from app import views, models
admin = Admin(app)
Your code has
db.Model.metadata.reflect[db.engine]
When it should be
db.Model.metadata.reflect(db.engine) # parens not brackets
This should have been pretty obvious from the stack trace....

Categories

Resources