SQLite objects created in a thread can only be used in that same thread.
app = Flask(__name__)
#app.route("/test/")
def test():
conn = sqlite3.connect("god_attributes.db")
c = conn.cursor()
c.execute("SELECT * FROM god_icon_table")
all = c.fetchall()
return render_template("test.html", all = all)
I'm making a flask app and I have a lot of methods that need to pull data from a db using SQL db calls. I am wondering if I can store methods somewhere else and call them by importing to organize things. Basically I want the entire app route for test to be like this:
app = Flask(__name__)
#app.route("/test/")
def test():
all = get_all()
return render_template("test.html", all = all)
where get_all() does everything from conn to fetchall in the first code sample
So I figured out a structural solution. Wasnt able to place a get_all() method that does the SQL commands directly. I made a new json file from the database and used that json to get the information
Related
In FastAPI I had the following function that I used to open and close a DB session:
def get_db():
try:
db = SessionLocal()
yield db
finally:
db.close()
And within the routes of my API I would do something like that:
#router.get("/")
async def read_all_events(user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
logger.info("API read_all_events")
if user is None:
raise http_user_credentials_not_valid_exception()
return db.query(models.Events).all()
You can see that I am injectin the session in the api call.
So now i want to do something similar within a python function:
def do_something():
#get person data from database
#play with person data
#save new person data in database
#get cars data from database
So i am wondering if I should use the same approach than in FastAPI (i do not know how) or if i just should be openning and clossing the connection manually like that:
def do_something():
try:
db = SessionLocal()
yield db
#get person data from database
#play with person data
#save new person data in database
#get cars data from database
finally:
db.close()
Thanks
The usage of yield in this case is so that Depends(get_db) returns the db session instance, so that it can be used in the fastapi route, and as soon as the fastapi route returns response to user, the finally clause (db.close()) will be executed. This is good because every request will be using a separate db session, and db connections will be closed after every route response.
If you want to use the db session normally in a function, just get the db instance using db = SessionLocal(), and proceed to use the db instance in the function.
Example:
def do_something():
db = SessionLocal()
event = db.query(models.Events).first()
db.delete(event)
db.commit()
db.close()
I have an issue with in my Flask app concerning SQLAlchemy and MySQL.
In one of my file: connection.py I have a function that creates a DB connection and set it as a global variable:
db = None
def db_connect(force=False):
global db
db = pymysql.connect(.....)
def makecursor():
cursor = db.cursor(pymysql.cursors.DictCursor)
return db, cursor
And then I have a User Model created with SQL ALchemy models.ppy
class User(Model):
id = column........
It inherits from Model which is a class that I create in another file orm.py
import connection
Engine = create_engine(url, creator=lambda x: connection.makecursor()[0], pool_pre_ping=True)
session_factory = sessionmaker(bind=Engine, autoflush=autoflush)
Session = scoped_session(session_factory)
class _Model:
query = Session.query_property()
Model = declarative_base(cls=_Model, constructor=model_constructor)
In my application I can have long script running so the DB timeout. So I have a function that "reconnect" my DB (it actually only create a new connexion and replace the global DB variable)
My goal is to be able to catch the close of my DB and reconnect it instantly. I tried with SQLAlchemy events but it never worked. (here)
Here is some line that reproduces the error:
res = User.query.filter_by(username="myuser#gmail.com").first()
connection.db.close()
# connection.reconnect() # --> SOLUTION
res = User.query.filter_by(username="myuser#gmail.com").first()
If you guys have any ideas of how to achieve that, let me know 🙏🏻
Oh and I forgot, this application is still running with python2.7.
I am trying to connect my flask application to a DB2 database,but somehow I am unable to do. here is what I am trying to do,
I am using flask extension flask_db2 for this purpose and below is how I am trying to connect
from flask import Flask
from flask_db2 import DB2
app = Flask(__name__)
#app.route('/')
def index()
cur = db.connection.cursor("DATABASE=name;HOSTNAME=host;PORT=60000;PROTOCOL=TCPIP;UID=username;PWD=password)
from flask import Flask
from flask_db2 import DB2
app = Flask(__name__)
app.config['DB2_DATABASE'] = 'sample'
app.config['DB2_HOSTNAME'] = 'localhost'
app.config['DB2_PORT'] = 50000
app.config['DB2_PROTOCOL'] = 'TCPIP'
app.config['DB2_USER'] = 'db2inst1'
app.config['DB2_PASSWORD'] = 'db2inst1'
db = DB2(app) #You forgot that
#app.route('/')
def index():
cur = db.connection.cursor()
cur.execute(...)
First: You forgot to have an object to use the flask db2 module.
The DB2(app) is a constructor for your Flask extension and will bind your application to this module.
where as
db = DB2(app)
Initialises your db object with help of your extension's constructor which you can further use for your Database operations.
Secondly: use app configs to play with DB2 credentials. (This step should be done before you bind the app)
Third: You can execute your query like this
cur.execute("SELECT id FROM users") #something like that
I hope I have clarified :D just drop message. Ill try helping more.
I have a simple Flask web app that uses peewee to manage the MySQL connection. Unfortunately it seems I missed something important from my code, therefore I'm getting an pymysql.err.OperationalError: (2006, "MySQL server has gone away.. error after 10-20 minutes of using the site. If I restart the app it works fine again, so I assume I handle the connection/connections wrong.
I have some basic queries that I'm using to display lists on my UI. Since I'm new to Python it's possible that my whole logic is wrong, so I would be really happy if somebody could me explain what is the right way to manage (connect-close connection) queries with peewee in my case (simple website without any user functions).
You can see on the below code how I'm doing it now. It's fine until I connect, but after I connected to the db I'm just calling the queries without dealing the connection. I assume I should close the connection based on the query that has been called, but couldn't find a proper way. Calling the myDB.close() isn't enough or I'm using it in wrong.
# this is how I connect to the MySQL
import peewee as pw
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
myDB = pw.MySQLDatabase("", host="", user="", passwd="")
class MySQLModel(pw.Model):
"""A base model that will use our MySQL database"""
class Meta:
database = myDB
class city(MySQLModel):
...
class building(MySQLModel):
...
myDB.connect()
# this is how I manage the homepage
cityList = []
cityList = city.select().order_by(city.objectId).limit(15)
buildings = []
buildings = building.select().order_by(building.buildingName).limit(180)
def getSearchResult (content_from_url):
searchResultList = []
searchResultList = city.select().where(city.objTitle.contains(content_from_url))
return searchResultList
#app.route('/', methods=['GET', 'POST'])
def main_page():
search = request.args.get('search')
if search:
return render_template("results.html", search = getSearchResult(search), str = search)
else:
return render_template("home.html", name=cityList, buildList=buildings)
# and this is how the subpage
relatedCityList = []
slugObj = []
buildings2 = []
buildings2 = building.select().order_by(building.buildingName).limit(180)
def getLink (title_for_link):
slugObj = city.get(city.urlSlug == title_for_link)
return slugObj
def displayRelatedCity (city_to_filter):
resultCity = city.get(city.urlSlug == city_to_filter)
relatedCityList = city.select().where(city.objTitle == resultCity.objTitle).limit(20)
return relatedCityList
#app.route('/city-list/<content>', methods=['GET', 'POST'])
def city_page(content):
linkText = getLink(content)
return render_template("details.html", relatedCity = displayRelatedCity(content), buildingName = linkText.buildingName, buildz = buildings2)
myDB.close()
You need to be reconnecting on request/response. http://docs.peewee-orm.com/en/latest/peewee/database.html#adding-request-hooks
There's even a section on Flask.
I have read the Flask documentation and Python documentation to try to understand what these codes do. I know that it is initialise the Database but would like to know in very detail and with normal language, easy language for beginner.
Can anyone please explain me about this?
import sqlite3
from contextlib import closing
DATABASE = 'flaskr.db'
def connect_db():
return sqlite3.connect(app.config[’DATABASE’])
def init_db():
with closing(connect_db()) as db:
with app.open_resource(’schema.sql’, mode=’r’) as f:
db.cursor().executescript(f.read())
db.commit()
import sqlite3
Imports Data base connectors
from contextlib import closing
No idea why its used.
Documentetion here
DATABASE = 'flaskr.db'
Defines database,in this case it is a db file.
def connect_db():
return sqlite3.connect(app.config[’DATABASE’])
Connect DB method which returns a sqlite3 connection, using sqlite3 import and invoking connect() on it.
Hint: try >>> dir(sqlite3) after importing in your python console
def init_db():
with closing(connect_db()) as db:
with app.open_resource(’schema.sql’, mode=’r’) as f:
db.cursor().executescript(f.read())
db.commit()
Initialize database method, it takes a schema.sql and executes it on DB by f.read method.
After executing you need to commit changes to db, hence db.commit()
You can find it explained clearly here