AttributeError: 'scoped_session' object has no attribute 'session' - python

I am trying to insert new data to my database but my web application returns this error.
My codes are as follows:
models.py
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
...
class Patient(db.Model):
__tablename__ = "patients"
id = db.Column(db.Integer, primary_key=True)
lname = db.Column(db.String, nullable=False)
fname = db.Column(db.String, nullable=False)
mname = db.Column(db.String, nullable=True)
address = db.Column(db.String, nullable=False)
birthdate = db.Column(db.Date, nullable=False)
date_modified = db.Column(db.DateTime, nullable=False)
modified_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
date_created = db.Column(db.DateTime, nullable=False)
created_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
def __init__(self, fname, mname, lname):
self.fname = fname
self.mname = mname
self.lname = lname
application.py
import os
from flask import *
from flask_session import Session
from sqlalchemy import *
from sqlalchemy.orm import scoped_session, sessionmaker
from models import *
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
# Check for environment variable
if not os.getenv("DATABASE_URL"):
raise RuntimeError("DATABASE_URL is not set")
app.secret_key = '######'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
...
#app.route("/submitpatient", methods=["POST"])
def submitpatient():
fname = request.form.get("fname")
mname = request.form.get("mname")
lname = request.form.get("lname")
patient = Patient(fname=fname, mname=mname, lname=lname)
db.session.add(patient)
db.session.commit()
return redirect(url_for('index'))
I'm new to python and I have been trying to find the error in my code for hours but I can't seem to find anything that would help me.

I guess the problem that u missed to create a constructor "Session" after using it,
The code will be:
# create a configured "Session" class
Session = scoped_session(sessionmaker(bind=engine))
#app.route("/submitpatient", methods=["POST"])
def submitpatient():
fname = request.form.get("fname")
mname = request.form.get("mname")
lname = request.form.get("lname")
patient = Patient(fname=fname, mname=mname, lname=lname)
#create a Session
session = Session()
session.add(patient)
session.commit()
return redirect(url_for('index'))
for more information, see this

What if you just add and commit as follows,
db.add(patient)
db.commit()

Use Session object with SQLAlchemy's declarative way
I know this answer is not exactly related to the questioner's scenario but a similar issue can arise if you are using flask-security's user model with sqlalchemy in a declarative way.
In this case, your user_datastore should be as below:
user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role) not SQLAlchemyUserDatastore
For more explanation:
database.py
import importlib
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine("sqlite:///crm.sqlite3")
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def create_db(all_microservices_names = []):
_ = importlib.import_module("database.models.all_models")
Base.metadata.create_all(bind=engine)
all_models.py
import sqlalchemy as sa
from database.database import Base
from flask_security import RoleMixin, UserMixin
class User(Base, UserMixin):
id = sa.Column(sa.Integer(), primary_key=True)
public_id = sa.Column(sa.String(length=255), unique=True, nullable=False)
username = sa.Column(sa.String(20), unique=True, nullable=False)
#...
datastore.py
from flask_security import SQLAlchemySessionUserDatastore
from database.database import db_session
from database.models.user_models import User, Role
user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role)
app.py will contain the initialization of these elements including login_manager and attach it to the Flask app.

Related

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship

I am facing too many errors in running my flask application which is online invoice app.
I am new to flask, I am not sure where exactly my code is wrong
I am attaching my code here
models.py
`
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Invoice(db.Model):
#__tablename__="invoice_tbl"
invoiceID = db.Column(db.Integer, primary_key=True)
invoiceDate =db.Column(db.DateTime, nullable=False)
totAmt =db.Column(db.Float, nullable=False)
discount =db.Column(db.Float, nullable=False)
taxAmt = db.Column(db.Float, nullable=True)
netAmt =db.Column(db.Float, nullable=False)
userid = db.Column(db.Integer, nullable=True)
class InvoiceDet(db.Model):
#__tablename__="invoiceDet_tbl"
invoiceID = db.Column(db.Integer, primary_key=True)
ItemID =db.Column(db.Integer, db.ForeignKey("Items.itemID"), primary_key=True)
itemQty =db.Column(db.Integer, nullable=False)
item_discount =db.Column(db.Integer, nullable=False)
itemAmt = db.Column(db.Float, nullable=True)
item = db.relationship("Items", backref="itemID", lazy=True)
#user_id = db.Column(db.Integer, db.ForeignKey('user.userid'))
class Users(db.Model):
#__tablename__="usertbl"
userid = db.Column(db.Integer, primary_key=True)
username =db.Column(db.String, nullable=False)
password =db.Column(db.String, nullable=False)
class Items(db.Model):
#__tablename__="Items_tbl"
itemID = db.Column(db.Integer, primary_key=True)
itemDesc =db.Column(db.String, nullable=False)
itemPrice =db.Column(db.Float, nullable=False) `
`
app.py
`
from flask import Flask, render_template, jsonify, request, redirect, session
from models import *
from werkzeug.utils import secure_filename
from models import Users, InvoiceDet, Items, Invoice
from sqlalchemy import create_engine
from sqlalchemy.pool import StaticPool
engine = create_engine(
"sqlite://",
connect_args={"check_same_thread": False},
poolclass=StaticPool
)
folder_name="static"
db = SQLAlchemy()
DB_NAME = "database.db"
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = f'sqlite:///{DB_NAME}'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
#app.config["SESSION_PERMANENT"] = False
#app.config["SESSION_TYPE"] = "filesystem"
db.init_app(app)
app.secret_key = 'admin'
#app.route("/")
def index():
return render_template("index.html")
#app.route("/dashboard",methods=["POST"])
def dashboard():
unam = request.form.get("username")
pwd = request.form.get("password")
session['username']= unam
ulist=Users.query.filter_by(username=unam).first()
if ulist:
uid=ulist.userid
invList=Invoice.query.filter_by(userid=uid).all()
return render_template("dashboard.html",uname=unam,invList=invList, invDet=[], invSel=[])
else:
return render_template("index.html", msg='Wrong Credentials!!')
#app.route("/showInvoice/<int:invID>")
def showInvoice(invID):
unam=session['username']
ulist=Users.query.filter_by(username=unam).first()
invList=Invoice.query.filter_by(userid=ulist.userid).all()
invDet=InvoiceDet.query.filter_by(invoiceID=invID).all()
invSel=Invoice.query.filter_by(invoiceID=invID).first()
return render_template("dashboard.html",uname=unam,invList=invList, invDet=invDet, invSel=invSel)
#app.route("/logout")
def logout():
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)`
I am getting error :
there is no relationship between invoicedet and items
when I am commenting the item column of invoicedet class, I am getting below error
`
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: users
[SQL: SELECT users.userid AS users_userid, users.username AS users_username,
users.password AS users_password
FROM users
WHERE users.username = ?
LIMIT ? OFFSET ?]
[parameters: ('priya', 1, 0)]`
After running my flask app.py , one login page will be rendered which will ask for username and password
I provided username as priya and password as 1234
and once I hit confirm button, the error messages flashesc

Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS

I am trying to create an API in Python that uses a Postgresql database. I am attempting a simple endpoint to pull to check to see if the database can connect and pull data. I am probably missing something simple and need someone to point it out. Below is my main.py file
import psycopg2
import model
import os
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
uname = os.environ['uname']
pas = os.environ['pas']
url = os.environ['url']
port = os.environ['port']
dbase = os.environ['dbase']
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://' + uname + ':' + pas + '#' + url + ':' + port + '/' + dbase
db = SQLAlchemy(app)
#app.route('/test')
def test():
tst = model.Doc.query.filter_by(doc_num=1).first()
return jsonify(tst)
if __name__ == '__main__':
app.run()
I also have a model.py file where my database is modeled out.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String, Date, ForeignKey
from flask_marshmallow import Marshmallow
app = Flask(__name__)
db = SQLAlchemy(app)
ma = Marshmallow(app)
class Aud(db.Model):
__tablename__ = 'aud'
__table_args__ = {'schema': 'cirsx'}
aud_num = Column(Integer, primary_key=True)
aud_name = Column(String, nullable=False, unique=True)
aud_desc = Column(String)
class AudSchema(ma.Schema):
class Meta:
fields = ('aud_num', 'aud_name', 'aud_desc')
class DocTyp(db.Model):
__tablename__ = 'doctyp'
__table_args__ = {'schema': 'cirsx'}
doctyp_num = Column(Integer, primary_key=True)
doctyp_name = Column(String, nullable=False, unique=True)
doctyp_desc = Column(String)
class DocTypSchema(ma.Schema):
class Meta:
fields = ('doctyp_num', 'doctyp_name', 'doctyp_desc')
class Doc(db.Model):
__tablename__ = 'doc'
__table_args__ = {'schema': 'cirsx'}
doc_num = Column(Integer, primary_key=True)
doctyp_num = Column(Integer, ForeignKey('doctyp_num'))
aud_num = Column(Integer, ForeignKey('aud_num'))
doc_path = Column(String, nullable=False)
title = Column(String, nullable=False)
author = Column(String)
keywords = Column(String)
pub_dt = Column(Date)
doc_abs = Column(String)
doc_txt = Column(String)
class DocSchema(ma.Schema):
class Meta:
fields = ('doc_num',
'doctyp_num',
'aud_num',
'doc_path',
'title',
'author',
'keywords',
'pub_dt',
'doc_abs',
'doc_txt')
aud_schema = AudSchema()
aud_schemas = AudSchema(many=True)
doctyp_schema = DocTypSchema()
doctyp_schemas = DocTypSchema(many=True)
doc_schema = DocSchema()
doc_schemas = DocSchema(many=True)
if __name__ == '__main__':
app.run()
Is there something that I am missing to why I am getting this error?

Unable to store data in sqlite db with Python / SQLAlchemy (Flask)

Hello I'm struggling with this error since weeks.
In my python/flask app I need to store a pw in a db table user in SQLite with SQLalchemy.
The table seemds to be correctly created when I check sqlite> .schema the column pwd is there.
When I run the app it returns an error saying the column pwd does not exist (see error below).
I tried several times dropping the table, trying in a new db but nothing, I think the table is created correctly but there must be something wrong in the code? Could also be the db that was messed up but I don't think so.
Here I create the table and define the User class, as per official SQLAlchemy documentation
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from sqlalchemy import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data-users.sqlite'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer(), primary_key = True, autoincrement=True)
username = db.Column(db.String(64), unique = True)
pwd = db.Column(db.String())
def __repr__(self):
return '<User %r>' % self.username
Here I store the user data in the table
from store_user_db import User, db
db.create_all()
DICP_FTP_DESTINATION_PSW=self.submit_pwd()
user = User(id=001,username="ita_itf",pwd=DICP_FTP_DESTINATION_PSW)
db.session.add(user)
db.session.commit()
This is the error:
sqlalchemy.exc.OperationalError
OperationalError: (sqlite3.OperationalError) table user has no column named pwd
[SQL: INSERT INTO user (id, username, pwd) VALUES (?, ?, ?)]
[parameters: (1, 'ita_itf', <read-only buffer for 0x7efe495709f0, size -1, offset 0 at 0x7.....
I don't have much experience flask and SQlAlchemy, but here is a sample app which is working for me.
The Model definitions are taken from the documentation and added a test model during runtime to see if it is still able to create new tables and it did.
If you have a large app, I'd prefer to use flask-migrate library which can create versioned migrations from your models for creating/modifying your tables.
from datetime import datetime
from flask import Flask, request, flash, url_for, redirect, json
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = "user"
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
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def __repr__(self):
return '<Category %r>' % self.name
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80), nullable=False)
body = db.Column(db.Text, nullable=False)
pub_date = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow)
category_id = db.Column(db.Integer, db.ForeignKey('category.id'),
nullable=False)
category = db.relationship('Category',
backref=db.backref('posts', lazy=True))
def __repr__(self):
return '<Post %r>' % self.title
class Test(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def __repr__(self):
return '<Test %r>' % self.name
def insertAdminUser():
admin = User(username='admin', email='admin#example.com')
db.session.add(admin)
db.session.commit()
#app.route('/insert-admin', methods = ['GET'])
def insertAdmin():
insertAdminUser()
return app.response_class(
response=json.dumps({
"message": "inserted"
}),
mimetype='application/json'
)
if __name__ == '__main__':
db.create_all()
app.run(debug = True)

missing user_loader error exception in flask app

I am trying to create a basic blog post website. Everything was going fine until i tried to run the app and it showed me the error:-
"Exception: Missing user_loader or request_loader"
but I have already created the user_loader. so I tried to find solutions and in the process I found that flask db migrate is not creating any table. so I searched online and found a solution to add all my tables in evn.py file in migration folder. I thought that was the problem and I tried to run the app again and this appeared again:-
"Exception: Missing user_loader or request_loader"
This is my __init__py file
# blogpost/__init__.py
import os
import secrets
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = secrets.token_hex(8)
# DATABASE CONFIGURATION #############
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Migrate(app, db)
# LOGIN CONFIGURATION #################
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'users.login'
# IMPORTING BLUEPRINTS #################################
from blogpost.core.views import core
from blogpost.user.views import users
# BLUEPRINTS CONFIGURATION #################################
app.register_blueprint(core)
app.register_blueprint(users)
and this is my models.py file.
from blogpost import db, login_manager
from flask_login import UserMixin
from datetime import datetime
from werkzeug.security import check_password_hash, generate_password_hash
#login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
fav_posts = db.Table('fav_posts',
db.Column('user_id', db.Integer, db.ForeignKey('users.id')),
db.Column('fav_posts_id', db.Integer, db.ForeignKey('posts.id')))
follows = db.Table('follows',
db.Column('user_id', db.Integer, db.ForeignKey('users.id')),
db.Column('follows', db.Integer, db.ForeignKey('users.id')))
fav_tags = db.Table('fav_tags',
db.Column('user_id', db.Integer, db.ForeignKey('users.id')),
db.Column('fav_tags_id', db.Integer, db.ForeignKey('tags.id')))
licked_posts = db.Table('licked_posts',
db.Column('post_id', db.Integer, db.ForeignKey('posts.id')),
db.Column('user_id', db.Integer, db.ForeignKey('users.id')))
tags_included = db.Table('tags_included',
db.Column('post_id', db.Integer, db.ForeignKey('posts.id')),
db.Column('user_id', db.Integer, db.ForeignKey('tags.id')))
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
email = db.Column(db.String, unique=True, index=True)
dob = db.Column(db.Date)
password_hash = db.Column(db.String)
account_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
profile_image = db.Column(db.String)
is_verified = db.Column(db.Boolean, default=False)
posts = db.relationship('Post', backref='author', lazy=True)
favorite_posts = db.relationship('Post', secondary=fav_posts, backref=db.backref('fav_by', lazy='dynamic'))
followers = db.relationship('User', secondary=follows, backref=db.backref('following', lazy='dynamic'))
favorite_tags = db.relationship('Tag', secondary=fav_tags, backref=db.backref('users', lazy='dynamic'))
def __init__(self, email, password, username, dob):
self.email = email
self.username = username
self.dob = dob
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String)
body = db.Column(db.Text)
date_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
likes = db.relationship('User', secondary=licked_posts, backref=db.backref('licked_by', lazy='dynamic'))
tags_includes = db.relationship('Tag', secondary=tags_included,
backref=db.backref('post_including_tag', lazy='dynamic'))
def __init__(self, title, body):
self.title = title
self.body = body
class Tag(db.Model):
__tablename__ = 'tags'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
def __init__(self, name):
self.name = name
can anyone one tell me what should I do to solve this and more importantly what is the cause because I have done same in my previous project but this never happened.
UPDATE:-
I've solved this problem by creating my user_loader inside my init file after the login_manager.login_view = 'users.login' file. I imported the User model after this line and then created the user_loader.
so my guess is that the problem is that flask is not able to find the "models.py" file. if anyone can explain the problem accurately or have a better solution you're most welcome (^-^)
here is another work i did for practice and it worked fine.
#puppycompanyblog/__init__.py
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecretkey'
#DATABASE SETUP##########################
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
db = SQLAlchemy(app)
Migrate(app,db)
#########################################
#LOGIN CONFIGURATIONS####################
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'users.login'
#########################################
from puppycompanyblog.core.views import core
from puppycompanyblog.users.views import users
from puppycompanyblog.blog_posts.views import blog_posts
from puppycompanyblog.error_pages.handlers import error_pages
app.register_blueprint(core)
app.register_blueprint(users)
app.register_blueprint(blog_posts)
app.register_blueprint(error_pages)
and
# puppycompanyblog/models.py
from puppycompanyblog import db, login_manager
from werkzeug.security import check_password_hash, generate_password_hash
from flask_login import UserMixin
from datetime import datetime
#login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
profile_image = db.Column(db.String(64), nullable=False, default='default_profile.png')
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
posts = db.relationship('BlogPost', backref='author', lazy=True)
def __init__(self, email, username, password, ):
self.email = email
self.username = username
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return f"username: {self.username}"
class BlogPost(db.Model):
users = db.relationship(User)
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
title = db.Column(db.String(140), nullable=False)
text = db.Column(db.Text, nullable=False)
def __init__(self, title, text, user_id):
self.title = title
self.text = text
self.user_id = user_id
def __repr__(self):
return f"Post ID: {self.id} -- Date: {self.date} --- {self.title}"
The reason why the user_loader function isn't found is because you are not importing the module in which it is defined. You put it in models.py, so you need to import this module somewhere in the area where you define your application, so that the handler is registered with the Flask-Login extension. You'll also need to import this file so that Flask-SQLAlchemy registers your models.
Based on the code that you posted, you could add import models at the bottom of blogpost/__init__.py and I think that should do it (it needs to be at the bottom to prevent circular imports).

Flask/SQLAlchemy - error creating models with one to many relationship (One or more mappers failed to initialize...)

I am trying to make one to many relationship between these 2 tables ("users" and "planets") but am getting this error:
One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class User->users'. Original exception was: Could not determine join condition between parent/child tables on relationship User.planet - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
I have seen answers to this question but none of them worked, I don't know where is the problem?
I also want to separate the 2 models in 2 different files, how that gonna work in this case?
Thanks so much for your help.
from sqlalchemy import Column, Integer, String, FLOAT
from app import db, ma
# database models:
class User(db.Model):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
email = Column(String, unique=True)
password = Column(String)
planet = db.relationship('Planet', backref='users', lazy='dynamic')
class Planet(db.Model):
__tablename__ = 'planets'
planet_id = Column(Integer, primary_key=True)
planet_name = Column(String)
planet_type = Column(String)
home_star = Column(String)
mass = Column(FLOAT)
radius = Column(FLOAT)
distance = Column(FLOAT)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
class UserSchema(ma.Schema):
class Meta:
fields = ('id', 'first_name', 'last_name', 'email', 'password')
class PlanetSchema(ma.Schema):
class Meta:
fields = ('planet_id', 'planet_name', 'planet_type', 'home_star', 'mass', 'radius', 'distance')
#__init__.py
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
import os
from flask_marshmallow import Marshmallow
from flask_jwt_extended import JWTManager, jwt_required, create_access_token
# from flask_cors import CORS, cross_origin
db = SQLAlchemy()
ma = Marshmallow()
jwt = JWTManager()
def create_app():
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'planets.db')
app.config['JWT_SECRET_KEY']='super_secret'
# cors = CORS(app)
# app.config['CORS_HEADERS'] = 'Content-Type'
db.init_app(app)
ma.init_app(app)
jwt.init_app(app)
# jwt = JWTManager(app)
from views import planet, users
app.register_blueprint(planet.main)
app.register_blueprint(users.users)
return app

Categories

Resources