I am working on flask app and deployed to linux server when I am doing Insert Query its giving OperationalError: attempt to write a readonly database, in error log
import sqlite3 as sql
def insertUser(username,password,email,phone):
with sql.connect("/var/www/FlaskApp/database.db") as con:
cur = con.cursor()
cur.execute("INSERT INTO user (username,password,email,phone) VALUES (?,?,?,?)", (username,password,email,phone))
con.commit()
It looks like the user running the flask application does not have permission to write to /var/www/FlaskApp/database.db. Have you checked your file permissions. It's perhaps best to have the file be owned by the user running your Flask application.
Related
I have implemented an application using python, PostgreSQL, pyqt5, Sqlalchemy and made an execution file for it through pyInstaller.
I tried installing this app on some laptops which had PostgreSQL 13 installed already on them. But there is a problem.
In some Laptops it's Ok and everything runs successfully and the database is created along with its tables on PostgreSQL, we can check it through Pgadmin 4 and we can work with the application successfully, but in some other laptops the database is created but not its tables and so the console stops and nothing appears and when we check Pgadmin there only is the database name not its tables.
P.S: the systems are Windows 10 and Windows 7.
I have no idea what to check or what to do I would appreciate it if anyone can give me any ideas.
the following code is base.py:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database
from sqlalchemy import Column
engine = create_engine('postgresql://postgres:123#localhost:5432/db23')
if not database_exists(engine.url):
create_database(engine.url)
Session = sessionmaker(bind=engine)
Base = declarative_base()
and the following function is called in initializer function of the app:
def the_first_time_caller(self):
session = Session()
# 2 - generate database schema
Base.metadata.create_all(engine) # create tables in the database
session.commit()
session.close()
with Updating Python and downgrading Sqlalchemy, It runs successfully now.
I have trouble connecting to the Azure postgres database from python. I am following the guide here - https://learn.microsoft.com/cs-cz/azure/postgresql/connect-python
I have basically the same code for setting up the connection.
But the psycopg2 and SQLalchemy throw me the same error:
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
I am able to connect to the instance by other client tools like dbeaver but from python it does not work.
When I investigate in Postgres logs I can see that the server actually authorized the connection but the next line says
could not receive data from client: An existing connection was forcibly closed by the remote host.
Python is 3.7
psycopg's version is 2.8.5
Azure Postgres region is in West Europe
Does someone has any suggestion on what should I try to make it work?
Thank you!
EDIT:
The issue resolved itself. I tried the same setup a few days later and it started working. Might have been something wrong with the Azure West Europe.
I had this issue too. I think I read somewhere (I forget where) that Azure has an issue with the # you have to for the username (user#serverName).
I created variables and an f-string and then it worked OK.
import sqlalchemy
username = 'user#server_name'
password = 'PassWord!'
host = 'server_name.postgres.database.azure.com'
database = 'your_database'
conn_str = f'postgresql+psycopg2://{username}:{password}#{host}/{database}'
After that:
engine = sqlalchemy.create_engine(conn_str, pool_pre_ping=True)
conn = engine.connect()
Test it with a simple SQL statement.
sql = 'SELECT * FROM public.some_table;'
results = conn.engine.execute(sql)
This was a connection in UK South. Before that it did complain about the format of the username having to use #, although the username was correct, as tested from the command line with PSQL and another SQL client.
psql user was created as part of the following:
postgres=# create database testdb;
postgres=# create user testuser with encrypted password 'testpass';
postgres=# grant all privileges on database testdb to testuser;
postgres=# alter user testuser createdb;
The below python3 script functions if database "testdb" exists.
However the script fails:
(NameError: name 'con' is not defined)
if "testdb" does not exist.
I fail to understand the requirement, as I havent asked to connect to the db yet. any assistance you can offer to help me understand is appreciated in advance. tnx.
# import modules
import psycopg2
# connect to db server
try:
con = psycopg2.connect(
host = "127.0.0.1",
port = "5432",
user = "testuser",
password = "testpass")
except:
print("Unable to connect to db server")
# create cursor
cur = con.cursor()
# display list of db on server
cur.execute("""SELECT datname from pg_database""")
rows = cur.fetchall()
# print list of db on server
print ("\nConnection successful. Listing databases on server:\n")
for row in rows:
print (" ", row[0])
# close the cursor
print ("\nClosing server connection.\n")
cur.close()
# close the connection
con.close()
In PostgreSQL's libpq (which psycopg2 is based on), if you specify a user name but not a dbname, it automatically tries to connect to the database which takes the same spelling as the user you specified.
You specify the user 'testuser', but don't specify a database, so it tries to connect to the database spelled 'testuser'. If that doesn't exist, of course the connection will fail.
You said the database which has to exist for this to work is "testdb", but I see that at one point you had specified the user name as "testdb" but then edited your question and changed it to "testuser". So I think the example you show is not the code you actual are running, as you did some kind of piecemeal editing of it after the fact.
In your connection code, you should specify a dbname which you know already exists.
You should really look at the gevent connection I wrote over here. It automates all of this for you and you don't have to reinvent the wheel.
Python Postgres psycopg2 ThreadedConnectionPool exhausted
I am pretty much new to this concept.
Currently, I am connecting to oracle database directly using the credentials within a python script but I want to store the connection string in a text file or a separate .py file and call them as I use the same credentials for multiple scripts.
I am using cx_oracle and sqlalchemy packages to connect to two databases as I extract data from the source and push it to the target(both the source and target are oracle databases).
import cx_Oracle
from sqlalchemy import create_engine, types
dsn_tns = cx_Oracle.makedsn('shost', 'sport', service_name='sservice_name')
conn = cx_Oracle.connect(user='suser', password='spw', dsn = dsn_tns)
engine = create_engine('oracle://tuser:tpw#thost:tport/tservice_name')
I'd really want to automate this process as I reuse the same connection string in multiple scripts and I'd really appreciate if I can get some help.
I am trying to use a VM machine with R on Azure. I want to connect it to a mariaDB on Azure.
I use the RmySQL package, and I use the following connection string:
require(RMySQL)
con <- dbConnect(RMySQL::MySQL(),
dbname="energidb",
host="energidb.mariadb.database.azure.com",
port=3306,
user="USER",
password="MY_PWD")
However, No luck I have in trying this, as R says. "Error in .local(drv, ...) :
Failed to connect to database: Error: Unknown database 'energidb'"
On azure, I promise and guarentee with my life, the name of the mariaDB is "energidb"
What am I doing wrong?
If you just create a Maria DB resource on Azure portal, then you should only have a database server.
You can connect to the Maria DB without specifying a database name. And then list all the existing databases as following:
con <- dbConnect(RMySQL::MySQL(),
host="your host address, jackmariadb.mariadb.database.azure.com",
port=3306,
user="user name, jack#jackmariadb",
password="password, d*******5")
rs = dbSendQuery(con, "show databases")
fetch(rs, n=-1)
In my case, it will just show the 3 system databases:
It turns out that on Azure, I created a mariaDB server (without any database). The database reference i made was to the server, which ofcourse is meaningless.
The solution is first to create a database (which is done by pointing at the server). From there I can point on the database.