These are my different files, not all though. Everything works fine until the part where I submit a form. I suspect it has something to do with the linking of the database if that makes sense?
#init.py
import os
from os import path
from venv import create
from flask import Flask, render_template, flash, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from auth import auth
from models import db
from main import app
basedir = os.path.abspath(os.path.dirname(__file__))
DB_NAME = "bookings.sqlite"
app.config\['SECRET_KEY'\] = 'Thisissupposedtobesecret!'
app.config\['SQLALCHEMY_DATABASE_URI'\] = 'sqlite:///' + os.path.join(basedir, DB_NAME)
app.config\['SQLALCHEMY_TRACK_MODIFICATIONS'\] = False
app.register_blueprint(auth, url_prefix="/")
db.init_app(app)
def create_database(app):
if not path.exists('V3/' + DB_NAME ):
db.create_all(app=app)
create_database(app)
if __name__ == '__main__':
app.run(debug=True)
#forms.py
from flask_wtf import FlaskForm
from wtforms import (StringField, BooleanField, DateTimeField,
RadioField,SelectField,
TextAreaField,SubmitField)
from wtforms.validators import DataRequired
class SignUpForm(FlaskForm):
name = StringField("Your FULL Name", validators=\[DataRequired()\])
(form questions)
submit = SubmitField("Book")
#models.py
from main import app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
db = SQLAlchemy(app)
Migrate(app,db)
class Booking(db.Model):
__tablename__ = "bookings"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.Text)
(other colums)
def __init__(self,name):
self.name = name
Tried to submit form which was successful but was not updated in the database
You need to push a context so you can access the database
https://flask.palletsprojects.com/en/2.0.x/appcontext/
def create_database(app):
if not path.exists('V3/' + DB_NAME ):
with app.app_context():
db.create_all()
Under models.py added
def __init__(self,name,x,y,z):
self.name = name
self.x = x
self.y = y
self.z = z
Under auth.py added
if request.method == 'POST':
name = form.name.data
x = form.x.data
y = form.y.data
z = form.z.data
new_booking = Booking(name=name,x=x,y=y,z=z)
db.session.add(new_booking)
db.session.commit()
return redirect(url_for('auth.bookings'))
else:
return render_template('bookings.html', form=form)
this has solved the issue, although i do not exactly understand why but it solved it
Related
I am new to flask and i have been struggling to create an sqlite database but whenever i run the from app import db I get the error message:
NameError: name 'app' is not defined
This is my code:
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
db = SQLAlchemy()
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db.init_app(app)
class Todo:
id = db.Column(db.Integer(), primary_key=True)
content = db.Column(db.String(length=300), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Task %r>' % self.id
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)`
The image below is my directory structure. I don't know if it has anything to do with it: Image of directory structure
I tried import db from app so that I will create the db file.
First u need to replace db.init_app(app) with db = SQLAlchemy(app). The starting code could look like this:
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
Then after your class Todo:
with app.app_context():
db.create_all()
I am new to deploying to aws as well as flask. Basically I have a simple Flask app but every time I make a change and deploy the new code to aws elastic beanstalk, the db gets reset.
from dateutil import parser
from datetime import datetime
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS
import os
application = app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
ma = Marshmallow(app)
cors = CORS(app)
#app.route('/')
def hello():
return 'hello'
.
.
.
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
weight = db.Column(db.Float)
workouts = db.relationship('Workout', backref='user', lazy=True)
def __init__(self, name, weight):
self.name = name
self.weight = weight
class UserSchema(ma.Schema):
class Meta:
fields = ('id', 'name', 'weight')
user_schema = UserSchema(strict=True)
users_schema = UserSchema(many=True, strict=True)
.
.
.
db.create_all()
if __name__ == '__main__':
app.run(debug=True)
I expect that each time I
eb deploy flask-env my db wouldnt get reset but it does. For instance if i create a user and then later change something in the code and deploy, that user is gone.
You should:
Create an EBS Volume
Load the database into that volume
Attach the EBS Volume to your Beanstalk app with an .ebextension. An example can be found here.
With all that being said, this is not a highly available, well architected solution and will deteriorate at scale rapidly.
You will want to replace SQLite with an RDS instance at some point in the future before it becomes a problem.
Hello.
When i'm trying to create new record in model, i'm getting
AttributeError: 'dict' object has no attribute 'compiler'
Possible, that i'm getting this error because using Proxy class, but can't find mistake in my code.
init.py
from flask import Flask
from flask_peewee.db import Proxy
from flask_bootstrap import Bootstrap
from app.config import config_select
db = Proxy()
bootstrap = Bootstrap()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config_select[config_name])
config_select[config_name].init_app(app)
db.initialize(config_select[config_name].DATABASE)
bootstrap.init_app(app)
#register blueprints
from app.blueprint.main import main_bp as main_blueprint
app.register_blueprint(main_blueprint)
return app
models.py
from peewee import *
from app import db
class BaseModel(Model):
class Meta:
database = db
class User(BaseModel):
id = PrimaryKeyField()
username = CharField(default='test', max_length=20)
class Meta:
db_table = 'users'
MODELS_LIST = [User]
Database was created by manager 'generate_db_tables' command
import os
from app import create_app
from flask_script import Manager, Shell
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
def connect_db():
from peewee import SqliteDatabase
db_lite = SqliteDatabase(app.config['DATABASE']['name'])
return db_lite
#manager.command
def generate_db_tables():
from app.models.models import MODELS_LIST
db_lite = connect_db()
for model in MODELS_LIST:
db_lite.create_table(model, safe=True)
print("Db tables created")
and the view function:
from flask import render_template, session, \
redirect, url_for, current_app, flash, request, make_response
from . import main_bp
from .forms import NameForm
from app.models.models import User
#main_bp.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
User.create(username=form.name.data) # <<<< Here is error
return url_for('.index')
return render_template('index.html', form=form)
Before i started to use Proxy class everything worked like a charm.
Seems, that i pass dict
DATABASE = {
'name': 'test.db',
'engine': 'peewee.SqliteDatabase'
}
to db.initialize()
instead of string name of database
DATABASE_INFO = 'test.db'
DATABASE = peewee.SqliteDatabase(DATABASE_INFO)
db.initialize(DATABASE)
I'm new in bluprint, and have problem with importing db into mydatabase.py file which is models file.
I've faced with this error:
ImportError: cannot import name 'db'
The tree of my project
nikoofar/
run.py
bookshelf/
__init__.py
mydatabase.py
main/
controllers.py
__init__.py
run.py
from bookshelf import app
if __name__ == '__main__':
app.run(debug=True, port=8000)
bookshelf / intit.py
from flask import Flask
from bookshelf.main.controllers import main
from flask_sqlalchemy import SQLAlchemy
from mydatabase import pmenu
app = Flask(__name__, instance_relative_config=True)
db = SQLAlchemy(app)
db.init_app(app)
application.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://username:password#localhost/databasename'
app.config.from_object('config')
app.register_blueprint(main, url_prefix='/')
bookshelf / main / controllers.py
from flask import Blueprint
from bookshelf.mydatabase import *
from flask_sqlalchemy import SQLAlchemy
main = Blueprint('main', __name__)
#main.route('/')
def index():
g = pmenu.query.all()
print (g)
return "ok"
The problem backs to from bookshelf import db, and if I delete that, the error will be changed to:
ImportError: cannot import name 'db'
bookshelf / mydatabase.py
from bookshelf import db
class pmenu(db.Model):
__tablename__ = 'p_menu'
id = db.Column(db.Integer, primary_key=True)
txt = db.Column(db.String(80), unique=True)
link = db.Column(db.String(1024))
def __init__(self, txt, link):
self.txt = txt
self.link = link
def __repr__(self):
return "{'txt': " + self.txt + ", 'link':" + self.link + "}"
Any solution?
This is actually a simple, yet frustrating issue. The problem is you are importing main BEFORE you are creating the instance of db in your __init__.py
If move the import to after your db = SQLAlchemy(app), it will work:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://uername:password#localhost/test'
db = SQLAlchemy(app)
from bookshelf.main.controllers import main #<--move this here
app.register_blueprint(main, url_prefix='/')
Hello I have a finished Flask/Flask-SqlAlchemy app working correctly but I wanted to reorganize its structure according to:
http://flask.pocoo.org/docs/0.10/patterns/packages/
My working project has the following structure and files:
folder:monkeyMeRoundTwo:
-app.py
-config.py
-models.py
-monkeyDB.db
-app_test.py
folder:templates:
-edit.html
-friends.html
-layout.html
-login.html
-myProfile.html
-profile.html
-register.html
-users.html
folder:static:
folder:css
folder:images
My app.py file:
from flask import Flask, render_template, redirect, \
url_for, request, session, flash
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# local
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///monkeyDB.db'
# heroku
#import os
app.config.from_object('config.BaseConfig')
#app.config.from_object(os.environ['APP_SETTINGS'])
db = SQLAlchemy(app)
from models import *
#app.route('/')
def index():
if not session.get('logged_in'):
return render_template('login.html')
else:
return redirect(url_for('friendList'))
.......rest of views
if __name__ == '__main__':
app.run(debug=True)
My config.py file:
import os
class BaseConfig(object):
SECRET_KEY = "kjdsbfkjgdf78sft"
My models.py file:
from app import db
from sqlalchemy.orm import relationship, backref
from sqlalchemy import Table, Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
class users(db.Model):
__tablename__ = "Users"
id = db.Column(db.Integer, primary_key=True)
userName = db.Column(db.String, nullable=False)
userEmail = db.Column(db.String, nullable=False)
userPhone = db.Column(db.String, nullable=False)
userPass = db.Column(db.String, nullable=False)
def __init__(self, userName, userEmail, userPhone, userPass):
self.userName = userName
self.userEmail = userEmail
self.userPhone = userPhone
self.userPass = userPass
def __repr__(self):
return '{}-{}-{}-{}'.format(self.id, self.userName, self.userEmail, self.userPhone)
class friendships(db.Model):
__tablename__ = "Friendships"
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('Users.id'), nullable=False)
friend_id = db.Column(db.Integer, db.ForeignKey('Users.id'), nullable=False)
userR = db.relationship('users', foreign_keys='friendships.user_id')
friendR = db.relationship('users', foreign_keys='friendships.friend_id')
def __init__(self, user_id, friend_id):
self.user_id = user_id
self.friend_id = friend_id
def __repr__(self):
return '{}-{}-{}-{}'.format(self.user_id, self.friend_id)
class bestFriends(db.Model):
__tablename__ = "BestFriends"
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('Users.id'), nullable=False)
best_friend_id = db.Column(db.Integer, db.ForeignKey('Users.id'), nullable=False)
user = db.relationship('users', foreign_keys='bestFriends.user_id')
best_friend = db.relationship('users', foreign_keys='bestFriends.best_friend_id')
def __init__(self, user_id, best_friend_id):
self.user_id = user_id
self.best_friend_id = best_friend_id
def __repr__(self):
return '{}-{}-{}-{}'.format(self.user_id, self.best_friend_id)
My app_tests.py file:
import os
import app
import unittest
import tempfile
class AppTestCase(unittest.TestCase):
def setUp(self):
self.db_fd, app.app.config['DATABASE'] = tempfile.mkstemp()
app.app.config['TESTING'] = True
self.app = app.app.test_client()
def tearDown(self):
os.close(self.db_fd)
os.unlink(app.app.config['DATABASE'])
def test_index_page(self):
rv = self.app.get('/')
assert 'Friends' in rv.data
...........rest of tests
if __name__ == '__main__':
unittest.main()
As I mentioned everything works fine and the tests pass all ok but when I attempt to follow the example on:
http://flask.pocoo.org/docs/0.10/patterns/packages/
and change the project to the following structure:
Structure/organization:
folder:monkeyMeRT:
-runserver.py
folder:monkeyMeRT:
-__init__.py
-views.py
-config.py
-models.py
-monkeyDB.db
-app_test.py
folder:templates:
-edit.html
-friends.html
-layout.html
-login.html
-myProfile.html
-profile.html
-register.html
-users.html
folder:static:
folder:css
folder:images
runserver.py file:
from monkeyMeRT import app
app.run(debug=True)
init.py file:
from flask import Flask, render_template, redirect, \
url_for, request, session, flash
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# local
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///monkeyDB.db'
# heroku
#import os
app.config.from_object('config.BaseConfig')
#app.config.from_object(os.environ['APP_SETTINGS'])
db = SQLAlchemy(app)
from models import *
import monkeyMeRT.views
views.py file:
from monkeyMeRT import app
.......here go all the views/functions
models.py file:
from monkeyMeRT import db
from sqlalchemy.orm import relationship, backref
from sqlalchemy import Table, Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
........here go the db classes
config.py file:
import os
class BaseConfig(object):
SECRET_KEY = "kjdsbfkjgdf78sft"
After changes I end up with errors.
Traceback (most recent call last):
File "__init__.py", line 19, in <module>
from models import *
File "/Users/alex/Desktop/PY/monkeyMeRT/monkeyMeRT/models.py", line 1, in <module>
from monkeyMeRT import db
ImportError: No module named monkeyMeRT
I guess I haven't interpreted the example correctly. Would anyone be able to help me out with this I am new to Flask(started learning a month ago) and would like to have an efficient setup of the project with config and views separated like in the example:
http://flask.pocoo.org/docs/0.10/patterns/packages/
Help is very much appreciated!
Thanks in advance.
The traceback is telling you that monkeyMeRT is not a package. To fix this:
Be sure to name your project folder monkeyMeRT
monkeyMeRT needs to contain a file called __init__.py
That init file doesn't have to contain anything, it just needs to exist so that Python knows to treat the directory as a Python package.