Unknown database error after creating it (sqlalchemy) - python

I'm getting the next error while trying to run my Flask app:
sqlalchemy.exc.OperationalError
OperationalError: (_mysql_exceptions.OperationalError) (1049, "Unknown database '/home/gerardo/Documentos/python_web_dev/flask-intro/app2.db'")
so it seems like there is no database.. but I ran the next scripts using sqlalchemy_utils and everything was ok:
engine = create_engine("mysql://root:#localhost/home/gerardo/Documentos/python_web_dev/flask-intro/app2.db")
create_database(engine.url)
but still I get the error..

You have confused MySQL, a database server, with SQLite, a database in a file. You created a SQLite file, but are trying to tell MySQL to connect to it, which makes no sense.
Use the sqlite dialect in the connection string.
You can avoid typing the whole path (and tying the app to that path) by pointing to the file relative to the app's location.
import os
db_path = os.path.realpath(os.path.join(os.path.dirname(__file__), 'app2.db'))
engine = create_engine('sqlite://{}'.format(db_path))
Consider using Flask-SQLAlchemy rather than trying to manage the database yourself.

Related

Heroku App can Interact with Heroku-postgres locally, but not When Deployed to Heroku

I am making a Flask app for a very simple game that I am hosting on Heroku, and it interacts with a Heroku-Postgres "hobby-dev" level database. When hosted locally, the app can interact with the database perfectly (. However, when I deploy it on Heroku, it will usually crash not long after it tries to interact with the database. Pages that don't require this interaction work fine. Specifically, I receive the following two errors in Heroku's logs:
2021-05-19T19:23:20.943811+00:00 app[web.1]:cur = db.cursor()
2021-05-19T19:23:20.943812+00:00 app[web.1]: psycopg2.InterfaceError: connection already closed
and...
2021-05-19T19:20:35.682211+00:00 app[web.1]: cur.execute("select * from mock_table;")
2021-05-19T19:20:35.682211+00:00 app[web.1]: psycopg2.OperationalError: SSL error: decryption failed or bad record mac
I have a few theories for the cause based on research, but I am not sure:
The database connection is only created once at the very beginning of the Flask app.
I store the Python code for interacting with the database in a separate module. I make the original connection once using psycopg2.connect(...) in the Flask app module, but I pass it to another module and its methods to actually interact with the database.
Something else causes the database connection to end
Are any of these close, and does anyone understand what I am missing? I can provide more info if it is required, but I didn't want to put too much.
According to this article, one possible reason for the errors I am receiving is a timed-out database connection. Thus, all I had to do was place my database calling methods in a try-except block and re-establish the connection if an error occurred. As an example,
cur.execute("select * from mock_table;")
could be replaced with...
try:
cur.execute("select * from mock_table;")
except:
#remake connection here
db.connect(host=host, database=database, user=user, password=password)
cur.execute("select * from mock_table;")
It isn't the most elegant solution, and it might have some flaws, but it has fixed the issue successfully so far, so I figured that I would share it.

How to connect to PostgreSQL using SQLAlchemy?

I am trying to connect to my PostgreSQL database using SLQAlchemy. I have installed psycopg2 and tried to connect to database with a raw python code and it worked but this time I am trying using SQLAlchemy. I read the documentation from SQLAlchemy docs. This might look very simple and I could not find a solution in the internet either for this specific one.
This is my code, so simple:
import psycopg2
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine('postgresql+psycopg2://nysa:mypassword#127.0.0.1:46015/nysa')
db = scoped_session(sessionmaker(bind=engine))
connection = engine.connect()
result = connection.execute('select*from table')
print(result)
When running the *.py file nothing happens and there are no errors and I tried to find the issue with pycharm's debugger and I noticed that in the line connection = engine.connect() gets stuck like in a infinite loop. I am pretty sure that my database credentials are correct. How do I connect to database?
Got it. When I opening pgAdmin it shows a different port and I thought that I had to put that port in the code, that is why It did not work. Worked with 127.0.0.1:5432.

sqlacodegen doesn't make any Tables

I'm running a PostgreSQL database on a server and I'm trying to connect to it using SQLAlchemy. I found that sqlacodegen was a good tool to generate the MetaData object automatically along with its Tables. But when I try and run sqlacodgen postgresql+psycopg2://username:password#host:5432/dbname, I only get this:
# coding: utf-8
from sqlalchemy import MetaData
metadata = MetaData()
The connection string is definitely correct, and the database is up - I ran a small Python script using that connection string to connect to the database and used execute to run a query on it, and it returns exactly what I expected.
I'm not sure where even to start with debugging this. What could I do to see what's wrong? Is there some sort of requirement that sqlacodegen has that I'm missing?
As it turns out this problem was unrelated to sqlacodegen. All the tables in my database are prefixed with dbname. Passing in --schema dbname works.

No SQLlite database in directory after calling create_engine in SQLAlchemy

After navigating to a directory and typing the commands in the Python shell:
from sqlalchemy import *
db = create_engine('sqlite:///tutorial.db')
I do not see a database file called tutorial.db file in the directory. Do I have to use a different command to create the actual database file and save it?
SQLAlchemy's Engine object lazily constructs the actual underlying database connection, waiting until the first database operation before trying to connect to the database.
Try running a query or creating a table and see if the database appears.

Connect to a Sybase database in Python without a DSN?

I'm trying to connect to a Sybase database in Python (using the python-sybase DBAPI and sqlalchemy module), and I'm currently receiving the following error:
ct_connect(): directory service layer: internal directory control layer error: There was an error encountered while binding to the directory service
Here's the code:
import sqlalchemy
connect_url = sqlalchemy.engine.url.URL(drivername='pysybase', username='read_only', password='*****', host='hostname', port=9000, database='tablename', query=None)
db = sqlalchemy.create_engine(connect_url)
connection = db.connect()
I've also tried to connect without sqlalchemy - ie, just importing the Python Sybase module directly and attempting to connect, but I still get the same error.
I've done quite a bit of googling and searching here on SO and at the doc sites for each of the packages I'm using. One common suggestion was to verify the DSN settings, as that's what's causing ct_connect() to trip up, but I am able to connect to and view the database in my locally-installed copy of DBArtisan just fine, and I believe that uses the same DSN.
Perhaps I should attempt to connect in a way without a DSN? Or is there something else I'm missing here?
Any ideas or feedback are much appreciated, thank you!
I figured out the issue for anyone else who might be having a similar problem.
Apparently, even though I had valid entries for the hostname in my sql.ini file and DSN table, Sybase was not reading it correctly - I had to open DSEdit (one of the tools that comes with Sybase) and re-enter the server/hostname info.

Categories

Resources