Need help connecting Flask-SQLAlchemy to MS SQL Server 2008R2 - python

Having difficulty with getting the right connection to the database:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
engine = SQLAlchemy.create_engine()
app.config['SQLALCHEMY_DATABASE_URI'] = 'mssql-pyodbc://EVERETT-
PC\\SQLEXPRESS/iNcentDev?trusted_connection=yes'
db = SQLAlchemy(app)
SQLALCHEMY_TRACK_MODIFICATIONS = False
class Payroll(db.Model):
__tablename__ = 'pay.PayRoll'
pk = db.Column('id', db.Integer, primary_key=True)
CreateDate = db.Column('CreateDate', db.DateTime)

This worked for me:
import urllib
params = urllib.parse.quote_plus("DRIVER={SQL Server};SERVER=SERVER_NAME;DATABASE=DB;UID=user;PWD=password")
engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)

Related

sqlalchemy unknown database flask with multiple databases

I created two databases using flask and sqlalchemy. My code is as follows:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from flask_login import UserMixin
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///C:\\Users\\dmac\\testmac.db'
app.config['SQLALCHEMY_BINDS'] = {
'User': 'sqlite:///C:\\Users\\dmac\\User.db',
'Stock': 'sqlite:///C:\\Users\\dmac\\Stock.db'
}
db = SQLAlchemy(app)
migrate = Migrate(app, db, render_as_batch = True)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
class Users(UserMixin, db.Model):
__table_name__ = 'users'
__bind_key__ = 'User'
__table_args__ = {'schema': 'User'}
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(100))
class Stock(db.Model):
__table_name__ = 'stock'
__bind_key__ = 'Stock'
__table_args__ = 'Stock'
id = db.Column(db.Integer, primary_key = True)
prices = db.Column(db.Float)
I tried to perform the flask-sqlalchemy upgrade after doing the migrate and init --multidb to fill my databases with table. However, I got the following error:
sqlalchemy.exc.OperationalError:(sqlite3.OperationalError) Unknown database "USER"[SQL:'\Create Table "User.users (id INTEGER not NULL, name VARCHAR(100))](Background on this error at: http://sqlalche.me/e/e3q8)
Any help would be appreciative. Thanks

How to create db table with SQLite / SQLAlchemy?

I'm trying to create a table in an existing db with SQLAlchemy/SQLite where I have to store a user and password, but it returns an error saying the column pwd doesn't exist!
Am I missing something? Am I messing it up?
I still didn't quite understand, I followed all steps in some online tutorial but nothing still.
Here is the class object that I developed, then from another register form I try to store the pw from the application, but the error should be here in this code:
import os
basedir = os.path.abspath(os.path.dirname(__file__))
# flask imports
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from sqlalchemy import *
# create flask app
app = Flask(__name__)
# set sqllite db connection
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
engine= create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
# bcrypt extension init to app
bcrypt = Bcrypt(app)
# sqlite init to app
db = SQLAlchemy(app)
# define meta data for table
meta=MetaData()
userstable = Table('users', meta, Column('id', Integer, primary_key = True, autoincrement=True), Column('username', String, unique=True), Column('pwd', String))
# create table to sqlite
meta.create_all(engine)
class User(db.Model):
# user columns
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
username = db.Column(db.String(64), unique=True)
pwd = db.Column(db.String(128))
def __init__(self,username,pwd):
#self.id=id
self.username=username
self.pwd=bcrypt.generate_password_hash(pwd)
# create user object
user = User('anish','23434')
# insert user object to sqlite
db.session.add(user)
# commit transaction
db.session.commit()
This is the error:
sqlalchemy.exc.OperationalError OperationalError: (sqlite3.OperationalError) table user has no column named pwd [SQL: INSERT INTO user (username, pwd) VALUES (?, ?)] [parameters: ('ita_itf', '$2b$12$VmpTsd0o4uTLj0wGypGu7ujhzYHLlV8k9ekaIP1.yh5lUMMgOM4MC')]
import os
basedir = os.path.abspath(os.path.dirname(__file__))
# flask imports
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from sqlalchemy import *
# create flask app
app = Flask(__name__)
# set sqllite db connection
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
engine= create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
# bcrypt extension init to app
bcrypt = Bcrypt(app)
# sqlite init to app
db = SQLAlchemy(app)
# define meta data for table
meta=MetaData()
userstable = Table('users', meta, Column('id', Integer, primary_key = True, autoincrement=True), Column('username', String, unique=True), Column('pwd', String))
# create table to sqlite
meta.create_all(engine)
class User(db.Model):
# table name for User model
__tablename__ = "users"
# user columns
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
username = db.Column(db.String(64), unique=True)
pwd = db.Column(db.String(128))
def __init__(self,username,pwd):
#self.id=id
self.username=username
self.pwd=bcrypt.generate_password_hash(pwd)
# create user object
user = User('anish','23434')
# insert user object to sqlite
db.session.add(user)
# commit transaction
db.session.commit()

Create all tables with Flask-SQLAlchemy

I have some difficulties with the library lask-sqlalchemy, I tried to create my database with the code bellow, i have no error but no table created.
_init.py
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
app.config.from_json("C:/Users/lquastana/PycharmProjects/flask_demo/conf/api-config.json")
app.app_context().push()
db.py
from flask_sqlalchemy import SQLAlchemy
from api_lab import app
db = SQLAlchemy(app)
member.py
from api_lab.models.db import db
class Member(db.Model):
__table_args__ = {"schema": "public"}
id = db.Column(db.BigInteger,
primary_key=True,
autoincrement=True)
id_company = db.Column(db.BigInteger,
db.ForeignKey("compagny.id"),
index=True,
nullable=False)
nom = db.Column(db.String(80), unique=True, nullable=False)
age = db.Column(db.Integer, unique=True, nullable=False)
def __repr__(self):
return '<Member %r>' % self.nom
run_api.py
from api_lab import app
from api_lab.models.db import db
def main():
host = app.config["ENV"]["HOST"]
port = app.config["ENV"]["PORT"]
debug = app.config["ENV"]["DEBUG"]
app.run(host=host, port=port, debug= debug)
if __name__ == '__main__':
db.create_all()
#main()
You should put all initialization related logic into init.py
Use SQLAlchemy to setup a db connection with your app.config
init.py
from api_lab import app
from api_lab.models.db import db
from flask_sqlalchemy import SQLAlchemy
app.config.from_json("C:/Users/lquastana/PycharmProjects/flask_demo/conf/api-config.json")
app.app_context().push()
db = SQLAlchemy(app)
# initialize the DB
db.create_all()

How can I use flask-sqlalchemy with Google Cloud Functions?

How can I integrate flask-sqlalchemy with Google Cloud Functions and something like Cloud SQL?
Looking at the minimal application example, it wraps the app variable:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
But my Google Cloud Function doesn't have access to anything called app:
def my_function(request):
return "Hello world!"
Creating my own app with app = Flask(__name__) doesn't work as this app isn't used by Cloud Functions to return the response.
You can use flask.current_app instead. You'll also have to configure flask-sqlalchemy to use the Unix Domain Socket provided by CloudSQL:
from flask import current_app as app
from flask_sqlalchemy import SQLAlchemy
# Set these in the environment variables for the function
db_user = os.environ.get('CLOUD_SQL_USERNAME')
db_password = os.environ.get('CLOUD_SQL_PASSWORD')
db_name = os.environ.get('CLOUD_SQL_DATABASE_NAME')
db_connection_name = os.environ.get('CLOUD_SQL_CONNECTION_NAME')
# This is for Postgres, it's similar for MySQL
app.config['SQLALCHEMY_DATABASE_URI'] = f'postgresql://{db_user}:{db_password}#/{db_name}?host=/cloudsql/{db_connection_name}'
# This must be set, determine which is best for you
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
...
Then you can query the User model in your function:
def my_function(request):
user = User.query.first()
return f"Hello {user.username)!"

My database is not being created (flask-sqlalchemy)

Basically I'm trying to make a Flask app using flask-sqlalchemy. I want to first load up a bunch of data into my database (database.py). However, I can't get this to work or even create the myapp.db file.
I'm getting no errors, however myapp.db file is not being created.
>>> db.engine
Engine(sqlite://)
The above should be myapp something, I'm pretty sure.
I have simplified my code to make it more concise to the problem.
Here I have my app:
from flask import Flask
import os
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db_path = os.path.join(os.path.dirname(__file__), 'myapp.db')
db_uri = 'sqlite:///{}'.format(db_path)
SQLALCHEMY_DATABASE_URI = db_uri
db = SQLAlchemy(app)
from views import *
if __name__ == '__main__':
app.secret_key = os.urandom(12)
app.run(debug=True)
And I want to run my database.py to load all my data - which in my mind should be creating a myapp.db file??:
from flask_sqlalchemy import SQLAlchemy
import os
import re
from myapp import app
from models import *
## Creates our database
db.create_all()
username = test
password = test
user = User(username=username, password=password)
db.session.add(user)
db.session.commit()
Here is my models.py
from flask_sqlalchemy import SQLAlchemy
from myapp import app
# create a new SQLAlchemy object
db = SQLAlchemy(app)
class User(db.Model):
""""""
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, nullable=False)
password = db.Column(db.String, nullable=False)
Changing
SQLALCHEMY_DATABASE_URI = db_uri
to
app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
fixed it.

Categories

Resources