Hello, how to i solve this sqlalchemy passing URI error? - python

hello how can i solve this error.I have tried different answers provided for this error and it's still not working.
I am getting this error:
ArgumentError(
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'api.db'
Here is my code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restless import APIManager
from sqlalchemy import MetaData
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///api.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
items = db.relationship('Item', backref='user', lazy='dynamic')
class Item(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
if __name__ == '__main__':
app.run(debug=True)

Related

Issue deploying Python Flask Package, more specifically unable to open database file

The Error message that shows up is sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file (Background on this error at: https://sqlalche.me/e/14/e3q8)
And the Traceback stated the error as fighters = Fighter.query.all()
I have tried different methods of `
fighters.query.get(Fighter)
`
I just tried
fighters = Fighter.query.order_by('id').all()
And i had gotten the same error which leads me to think its an issue initializing the database or possibly the database path.
I am unsure whether it is creating the database is the issue or querying the results.
My code in the run.py file is as follows-
import os
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# DATABASE_URL is by default
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///tmp/test.db')
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, email):
self.email = email
def __repr__(self):
return '<User %r>' % self.email
class Fighter(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120), unique=True)
class Vote(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
user = db.relationship('User', backref=db.backref('votes', lazy='dynamic'))
fighter_id = db.Column(db.Integer, db.ForeignKey('fighter.id'))
fighter = db.relationship('Fighter', backref=db.backref('votes', lazy='dynamic'))
#app.route('/', methods=['GET', 'POST'])
def homepage():
fighters = Fighter.query.all()
return render_template('index.html', fighters=fighters)
if __name__ == '__main__':
app.run(debug=True)
And my init_db.py file goes as follows-
from run import db, Fighter
# Create all the tables
db.create_all()
# create fighters
conor = Fighter(name='Conor McGregor')
floyd = Fighter(name='Floyd Mayweather')
# add fighters to session
db.session.add(conor)
db.session.add(floyd)
# commit the fighters to database
db.session.commit()
try this
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tmp/test.db'
instead of this
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///tmp/test.db')

How can i do a relationship with multiple entities?

How can i link both entities with relationship with flask python?
for example i have this entity, here i am trying to link with user = relationship('User'), so i am getting error relation of relationship (btw: Grant, User, Client are in differents files )
from sqlalchemy.orm import relationship
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Grant(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(
db.Integer, db.ForeignKey('user.id', ondelete='CASCADE')
)
user = relationship('User')
this is the error:
sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Grant->grant, expression 'User' failed to locate a name ('User'). If this is a class name, consider adding this relationship() to the <class 'model.Grant.Grant'> class after both dependent classes have been defined.
note: those are my anothers entities:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(40), unique=True, index=True,
nullable=False)
def check_password(self, password):
return True
and this is the Client.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Client(db.Model):
name = db.Column(db.String(40))
client_id = db.Column(db.String(40), primary_key=True)
this is the error user = relationship('User') please helpme

Tables create using Flask-SQLAlchemy, but they are not shown on sqlite command line (shell)

I am developing a flask application using Flask-SQLAlchemy with the following structure files. When I create the database (db.sqlite3) and write on the sqlite command line sqlite> .tables , the table (columns name) creates into the db.py file is not shown in the shell. There isn't any messagge error. It's only the shell doesn't show anything when I write this command. I have been tried different options I don't know what to do anymore. How can I get the shell show the columns of the tables?
File Tree:
|-PROBATINAS_2 (proyect name)
|-probatina
|- __init__.py
|- db.py
|- db.sqlite3 (database)
|-venv
|- Include
|- Lib
|- Scripts
|-.env
|-app.py
|-config.py
The code written for these files is as follows:
init.py:
from flask import Flask
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config')
db.py:
from probatina import app
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, timedelta
SQLALCHEMY_DATABASE_URI = app.config['SQLALCHEMY_DATABASE_URI']
SQLALCHEMY_TRACK_MODIFICATIONS = app.config['SQLALCHEMY_TRACK_MODIFICATIONS']
db = SQLAlchemy(app)
db.create_all()
#db.init_app(app)
class Customer(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(50), nullable=False)
last_name = db.Column(db.String(50), nullable=False)
address = db.Column(db.String(500), nullable=False)
city = db.Column(db.String(50), nullable=False)
postcode = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(50), nullable=False, unique=True)
orders = db.relationship('Order', backref='customer')
order_product = db.Table('order_product',
db.Column('order_id', db.Integer, db.ForeignKey('order.id'), primary_key=True),
db.Column('product_id', db.Integer, db.ForeignKey('product.id'), primary_key=True)
)
class Order(db.Model):
id = db.Column(db.Integer, primary_key=True)
order_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
shipped_date = db.Column(db.DateTime)
delivered_date = db.Column(db.DateTime)
coupon_code = db.Column(db.String(50))
customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'), nullable=False)
products = db.relationship('Product', secondary=order_product)
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False, unique=True)
price = db.Column(db.Integer, nullable=False)
.env:
FLASK_APP=app.py
FLASK_ENV=development
app.py:
from probatina import app
if __name__ == '__main__':
app()
config.py:
SQLALCHEMY_DATABASE_URI = 'sqlite:///C:/Users/ferna/Documents/Curso Aprender a programar desde cero/probatinas_2/probatina/db.sqlite3'
SQLALCHEMY_TRACK_MODIFICATIONS = False

Flask-marshmallow ImportError: cannot import name fields

I started learning flask a few weeks ago and I followed flask mega tutorial. Now I want to do some programming myself and I tried to return data from database in json format using flask-marshmallow and I got stuck. I got an error saying ImportError: cannot import name fields.
This is full error message
This is models.py module:
followers = db.Table('followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id')))
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
country = db.Column(db.String(140))
nationality = db.Column(db.String(140))
password_hash = db.Column(db.String(128))
# Definisanje veze sa Post tabelom
posts = db.relationship('Post', backref='author', lazy='dynamic')
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime, default=datetime.utcnow())
# Definisanje veze sa followers tabelom
followed = db.relationship(
'User', secondary=followers,
primaryjoin=(followers.c.follower_id == id),
secondaryjoin=(followers.c.followed_id == id),
backref=db.backref('followers', lazy='dynamic'), lazy='dynamic')
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '<Post {}>'.format(self.body)
#Declaring marshmallow ModelSchema
class UserSchema(ma.ModelSchema):
class Meta:
model = User
This is routes.py module:
#app.route('/all_users', methods=['GET'])
def get_all_users():
users = User.query.all()
user_schema = UserSchema(many=True)
out = user_schema.dump(users).data
return jsonify(out)
I didn't include all code but I will provide it if it's necessary.
Since error message point me to microblog.py and init.py, also modules in my app, so I will include these two modules.
microblog.py
from app import app, db
from app.models import User, Post
#app.shell_context_processor
def make_shell_context():
return {'db': db, 'User': User, 'Post': Post}
__init__.py
from flask import Flask
from logging.handlers import RotatingFileHandler
import logging
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
import os
'''Inicijalizacija ekstenzija'''
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
mail = Mail(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
ma = Marshmallow(app)
from app import routes, models, errors
if not app.debug:
if not os.path.exists('logs'):
os.mkdir('logs')
file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240,
backupCount=10)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
app.logger.info('Microblog startup')

python flask sqlalchemy, i can'trun my db_create.py

Ame getting this error of TypeError: init() takes exactly 1 argument (5 given)...where have i gone wrong?? any help i will appreciate ,thanks
thats my db_create.py file
from app import db
from models import post
db.create_all()
db.session.add(post("Good", "i\m good","yes","hae"))
db.session.add(post("Good", "hahaha"))
db.session.add(post("Good", "you"))
db.session.add(post("Good", "hahaha"))
my model.py file is
from app import db
class post(db.Model):
# table name
__tablename__ = "signup"
#columns names
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, nullable=False)
email= db.Column(db.String, nullable=False)
password = db.Column(db.String, nullable=False)
confirm= db.Column(db.String, nullable=False)
def __init__(self, username, email, password, confirm):
self.username = username
self.email = email
self.pasword = password
self.confirm = confirm
def __repr__(self,*args, **kwargs):
return '<username {}'.format(self.username), 'email{}'.format(self.email),'password{}'.format(self.password)
this is my init
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.secret_key = "my previous"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///signup.db'
db = SQLAlchemy(app)
from app import views
You don't need the __init__ method in your post model. Just use the __init__ method inherited from db.Model and you should be fine.
But then I believe you'd need to modify your db_create.py a bit:
For example:
db.session.add(post(username="User", email="user#email.com", password="password", confirm="Yes"))
Also you need to remember to commit your changes:
db.session.commit()

Categories