References and URL rules in Flask - python

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']
# ^ ^

Related

Flask-SQLAlchemy application context error

I am trying to use SQLAlchemy not in a view function (I was doing something like this with Flask-APSheduler).
I know that there were already a lot of topics related to this theme, but none of them were helpful to me.
So, first of all I will show my code:
./run.py
from app import create_app
from flask_config import DevConfig, ProdConfig
app = create_app(DevConfig)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
./app/__init__.py
from flask import Flask
from .node import node
from .models import db
def create_app(app_config=None):
app = Flask(__name__, instance_relative_config=False)
app.config.from_object(app_config)
db.init_app(app)
app.register_blueprint(node)
return app
./app/models.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Users(BaseFuncs, db.Model):
...
./app/node.py
from flask import Blueprint, request
from .bot import bot, secret
import telebot
node = Blueprint('node', __name__)
#node.route('/{}'.format(secret), methods=['POST'])
def handler():
bot.process_new_updates([telebot.types.Update.de_json(request.get_data().decode('utf-8'))])
return 'ok', 200
./app/bot.py
from flask import current_app as app
...
#bot.message_handler(commands=['test'])
def cmd_test(message):
with app.app_context():
print(Users.query.filter_by(id=0).first())
So when I am trying to call cmd_test from my application I am getting this error:
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context(). See the
documentation for more information.
I tried to use g variable and before_request methods, because every time before calling the database there is a call to the route 'handler', but this also doesn't work.
I also tried to use db.get_app(), but there was no effect.
So my question is how to call database right outside the views?

Python Flask Application Context, how to expose app to other modules

I have a python script which uses Flask-SqlAlchemy to access a Postgres database. However, whenever I try to query the database I receive a "working out of context" error. I figured the way to do this was to wrap it in app.app_context:
import psycopg2
import json
from simple_chalk import redBright
from ...models.bin import Bin
from ...models.station import Station
from ... import db
from datetime import datetime as dt
from ... import current_app as app
def findPositionBin(stationId, find_position):
try:
with app.app_context():
result = Bin.query.filter_by(station_id=stationId).filter_by(position=find_position).first()
print("result")
return result
except Exception as e:
print(redBright(e))
However, to do so I would need to import app. The problem is that my root init.py has the app contained in a function to be called by wsgi.py to run the program.
init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_socketio import SocketIO
from flask_cors import CORS
import eventlet
import threading
db = SQLAlchemy()
migrate = Migrate()
socketio = SocketIO()
def create_app():
app = Flask(__name__, instance_relative_config=False)
CORS(app)
app.config.from_object('config.Config')
eventlet.monkey_patch()
socketio.init_app(app, cors_allowed_origins='*', async_mode='eventlet')
migrate.init_app(app, db)
with app.app_context():
from . import routes
from . import wsroutes
from .models import user, bin, ip_port, station
from .blueprints import user
from .blueprints.CubeStation import station_routes
from.database.CubeStation import station_database
from .server import startServer
from .blueprints.CubeStation.station_functions import broadcastLoop
# from .database.CubeStation import station_database
db.init_app(app)
app.register_blueprint(user.user_blueprint)
app.register_blueprint(station_routes.station_blueprint)
# app.register_blueprint(station_database.database_blueprint)
x = threading.Thread(target=startServer)
x.start()
t = threading.Thread(target=broadcastLoop)
t.start()
db.create_all()
return app
Would anyone happen to know how I can expose the app so it can be imported by other modules? Or if there is a better approach to this. Thanks in advance
Based here and here, maybe something in this way would work:
from init import app
def app_context():
with app.app_context():
yield
def findPositionBin(stationId, find_position, app_context):
try:
with app.app_context():
result = Bin.query.filter_by(station_id=stationId).filter_by(position=find_position).first()
print("result")
return result
except Exception as e:
print(redBright(e))

Access Flask-SQLAlchemy database outside of view functions

I have created a small Flask application which stores its data in an sqlite database that I access via flask-sqlalchemy.
However, when I run it, I get the following error:
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
I have debugged my application and now know that this error stems from these two functions:
def user_exists(email):
if User.query.filter_by(email = email).count() == 0:
return False
else:
return True
def get_user(email):
user = User.query.filter_by(email = email).first()
return user
Now I am wondering: Is it impossible to access the database via flask-sqlalchemy outside of view functions?
For further context, I added the files in which I configure my flask app:
presentio.py
from app import create_app
app = create_app(os.getenv("FLASK_CONFIG", "default"))
app/init.py
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from config import config
mail = Mail()
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
mail.init_app(app)
db.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix = "/auth")
from .text import text as text_blueprint
app.register_blueprint(text_blueprint, url_prefix = "/text")
return app
You need to give the flask app a context after you create it.
This is done automatically in view functions, but outside those, you need to do this after you create the app:
app.app_context().push()
See the docs: https://flask-sqlalchemy.palletsprojects.com/en/2.x/contexts/

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.

Cannot access db when running code from Interactive Console

# main.py
from flask import Flask, jsonify
from flask.ext.cors import CORS
from shared.database import db
from src import controllers
import os
app = Flask(__name__)
cors = CORS(app, allow_headers='Content-Type')
app.register_blueprint(controllers.api)
if (os.getenv('SERVER_SOFTWARE') and os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+gaerdbms:///gaiapro_api_dev?instance=dev-gaiapro-api:gaiapro-sql'
else:
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://root#127.0.0.1/gaiapro_api_dev'
app.config['DEBUG'] = True
db.init_app(app)
# shared/database.py
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# src/controllers/__init__.py
from flask import Blueprint, jsonify, request
from src import models
from src import views
from shared.helpers import *
api = Blueprint('api', __name__)
#api.route('/test')
def test():
...
# shared/helpers.py
from flask import jsonify, request, abort, make_response
from shared.database import db
def some_method():
...
db.session.commit() # Can access db normally from here
# src/models/__init__.py
from shared.database import db
class Client(db.Model):
id = db.Column(db.Integer, primary_key=True)
...
I am developing for GAE (Google App Engine). Basically what I want is to test my models in the Interactive Console from inside the Admin Server of _dev_appserver.py_.
I have tried to run the following code from the Interactive Console:
from main import *
from src import models
print models.Client.query.get(1)
The result was:
RuntimeError: application not registered on db instance and no application bound to current context
If I try just to print the db variable in this context, the result is: SQLAlchemy engine=None
I don't know what I am doing wrong. My code runs normally on the browser, but I cannot get it to work from the Interactive Console.
You need to be in an app context (or a request context) to access application bound objects.
An easy way to achieve this is to use Flask-Script, which provides a shell command that sets up the application for you. Or use Flask's integration with Click if you are using the development version.
To just get it working immediately, set up the context yourself:
ctx = app.app_context()
ctx.push()
# do stuff
ctx.pop()
# quit
You can also use a context in a with block:
with app.app_context():
# do stuff
Use flask shell instead of default python interpreter
$ flask shell
$ from yourappname import db
$ db # this will print your connection string
$ db.create_all()

Categories

Resources