FAQ Database Discussion Community


Flask/SQLAlchemy - Difference between association model and association table for many-to-many relationship?

flask,sqlalchemy,many-to-many,flask-sqlalchemy,model-associations
I started learning this stuff from the Flask Mega Tutorial. When he gets into Many-to-Many relationships, he creates an association table like this: followers = db.Table('followers', db.Column('follower_id', db.Integer, db.ForeignKey('user.id')), db.Column('followed_id', db.Integer, db.ForeignKey('user.id')) ) As I was searching for ways to add some metadata regarding a specific association between models, I...

How to enforce constraints in `flask-admin`?

python,flask,flask-sqlalchemy,flask-admin
We're using http://flask-admin.readthedocs.org/ for a quick admin interface. Our model has constraints defined as follows: __table_args__ = ( db.UniqueConstraint(user_id, role, domain_id), db.UniqueConstraint(user_id, role, customer_id), ) When saving a record that violates a constraint while in debug mode, the app stops with a traceback. If not in debug mode, it reports...

Does db.create_all() check if the database exists?

flask,flask-sqlalchemy
I checked the docs but it didn't say anything much about it, weirdly. If I call db.create_all(), does there need to be some sort of check as to whether the database already exists, lest it be overwritten?...

Best association approach to connect Sensor model to others

sqlalchemy,flask-sqlalchemy
I'm trying to implement the following with Flask+SQLAlchemy: I have two database models containing information about bee apiaries and bee hives. I would like to add feature to somehow connect both of them to Sensor model. Those can be attached to one of apiaries or one of bee hives. Here...

flask sqlalchemy update error - update() missing 1 required positional argument: 'self'

python,flask,flask-sqlalchemy,flask-restful
I am building a restful-api with flask-restful. The code below is the [PUT]users/ api, which accepts variable named email through json, and parses through reqparse, which is a method given by flask-restful. class UserAPI(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('email', type=str, help='No Email Provided', location='json') super(UserAPI, self).__init__() def put(self,id): args...

Copying oldtable to newtable with slight differences in newtable?

python,postgresql,sqlalchemy,flask-sqlalchemy
I have two tables, oldtable and newtable, oldtable looks like: id | type | name ----+------+------ 1 | 1 | dog 2 | 2 | bird 3 | 1 | cat I want newtable to have its own id field and I want to insert all of oldtable's fields (including...

How to form complex mysql query that has left outer join, aggregate data with group by using SQLAlchemy?

mysql,sqlalchemy,flask-sqlalchemy
How to write the following query using SQLAlchemy? SELECT i.itemid, sum(i.quantitysold) total_quantity_sold, max(t.createdAt) last_sale_time FROM ItemList i LEFT OUTER JOIN ItemTransactions t ON i.itemid = t.itemid WHERE i.active = 'y' GROUP BY i.itemid ORDER BY total_quantity_sold asc; This is what I ended up writing: from sqlalchemy.sql import func as sa_func...

SQLAlchemy extension isn't registered when running app with Gunicorn

nginx,flask,flask-sqlalchemy,gunicorn
I have an application that works in development, but when I try to run it with Gunicorn it gives an error that the "sqlalchemy extension was not registered". From what I've read it seems that I need to call app.app_context() somewhere, but I'm not sure where. How do I fix...

Flask with SQLAlchemy tables doesn't link

python,flask,sqlalchemy,flask-sqlalchemy
I have been struggling with this little SQLAlchemy problem. It tells me that City.address referencing columns aren't associated with a ForeignKeyConstraint. Here is my Models #Address model class Address(db.Model): id = db.Column(db.Integer, primary_key=True) address = db.Column(db.String(100), nullable=False) company_id = db.Column(db.Integer, db.ForeignKey('company.id')) city_id = db.Column(db.Integer, db.ForeignKey('city.id'), nullable=False) event = db.relationship('Address', backref='event',...

How teardown_request() works with Python- Flask?

python,flask,flask-sqlalchemy
I received internal error with message: "TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30" and searching online gave teardown_request() solution : @app.teardown_request def checkin_db(exc): try: print "Removing db session." db.session.remove() except AttributeError: pass Now timeout error is gone. But I didn't understand teardown_request completely,...

How to create a user 'programmatically' with Flask-user extension?

python,flask,flask-sqlalchemy
I have this extension used in my project: https://pythonhosted.org/Flask-User/index.html I also have a REST API and a register() function there which accepts JSON-object and should be able to create a new user. How can I achieve this with Flask-user API? UPDATE: I have a fully created User model. Basically I...

Linking tables in SQLAclhemy foreign_keys error [Flask]

json,flask,one-to-many,flask-sqlalchemy
I got two models Post and Category. class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80)) body = db.Column(db.Text) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) body_html = db.Column(db.Text) comments = db.relationship('Comment', backref='post', lazy='dynamic') category_id = db.Column(db.Integer, db.ForeignKey('categories.id')) category = db.relationship('Category',...

SQLAlchemy: Specifying session to use for model

flask,sqlalchemy,flask-sqlalchemy
I am using Flask-SQLAlchemy and I need to create a session without auto-flushing for an operation. However, the default scoped session that is created by Flask-SQLAlchemy which is accessed using db.session has auto-flushing turned on. I'm doing bulk updates for 100k rows, and the auto-flushing is causing severe performance issues....

Get inserted key before commit session

python,flask,sqlalchemy,flask-sqlalchemy
class Parent(db.Model): id = db.Column(db.Integer, primary_key=True) class Child(db.Model): id = db.Column(db.Integer, primary_key=True) parent_id = db.Column(db.Integer, db.ForeignKey('parent.id')) parent = Parent() db.session.add(parent) child = Child() child.parent_id = parent.id db.session.add(child) db.session.commit() I want to INSERT into both parent and child tables inside a session considering that the parent_id must be included in the...

Flask and sqlalchemy: Get uploaded file using path stored on database

python,flask,flask-sqlalchemy,flask-wtforms
I'm using flask and sqlalchemy and I'm having issues regarding file uploading. I'm uploading the file with a form and storing the URL to the DB, so I can display it inside on the page. Here's the form's code: boxart = request.files['boxart'] if boxart: filename = secure_filename(boxart.filename) boxart_path = os.path.join(app.config['UPLOAD_FOLDER']+"boxart/",...

SQLAlchemy: How to use order_by based on a calculated value?

python,sqlalchemy,flask-sqlalchemy
So I have the following database model: class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(64), nullable=False, unique=True) ... tasks = db.relationship('Task', backref='author', lazy='dynamic') def number_of_tries(self): return Task.query.filter_by(user_id=self.id).count() def correct_answers(self): return Task.query.filter_by(user_id=self.id).filter_by(correct=True).count() def percentage(self): try: return '{:.2%}'.format(self.correct_answers()/self.number_of_tries())...

How to fix itsdangerous.BadTimeSignature Signature Error

python,cookies,flask,flask-sqlalchemy,flask-login
Im working on a project(not any co. project, academic) I am having trouble with using itsdangerous and login manager from flask-login. I created a signup form. entered my name email and password and then when I restart the server and I get this: ``` itsdangerous.BadTimeSignature BadTimeSignature: Signature 'GAMjfzQpbKlPraWesdT49W40pA8' does not...

Bulk inserts with Flask-SQLAlchemy

python,flask,sqlalchemy,flask-sqlalchemy
I'm using Flask-SQLAlchemy to do a rather large bulk insert of 60k rows. I also have a many-to-many relationship on this table, so I can't use db.engine.execute for this. Before inserting, I need to find similar items in the database, and change the insert to an update if a duplicate...

flask-sqlalchemy, sql count records in a relationship and then join to a users table

python,postgresql,flask-sqlalchemy
Im querying my users this way with sql: select * from users i get all the users but now i want to query how many friends they have so if i do this i do this: select count(*) from users inner join friendship on users.id = friendship.user and i get...

How to create multiple sqlalchemy connections to the same DB but with different credentials?

mysql,flask,sqlalchemy,flask-sqlalchemy
I have a flask application using sqlalchemy. Currently, I have something like this: from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://[email protected]:3306' db = SQLAlchemy(app) The user1 account has default timeouts for db queries. However, certain API calls are expected to take longer and I...

SQLAlchemy sum of a column btw 2 dates

sqlalchemy,flask-sqlalchemy
I am not sure if this is possible, but I'm looking for a way to use SQLAlchemy func.sum on a column, but only for rows taht are btw 2 dates. To make it clearer, here is the model class Income(db.Model): __tablename__='incomes' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.DateTime) amount =...

with Flask-sqlalchemy, connect models to database without running app

flask,sqlalchemy,flask-sqlalchemy
I used the answer to this question to fix a circular import when setting up Flask-SQLAlchemy. The solution works because you don't have to import the app from the application.py file to get the database URI - it initalizes the connection just before running the app. The issue now is...

Database created empty when models are in a separate file?

python,flask,flask-sqlalchemy
I am reading a book about flask development, and I'm pretty new to python generally. File layout: Project | |-- App | |-- __init__.py | |-- models.py | | main.py Code inside __init__.py: from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy import os from config import...

Tyring to set up modelview with Flask-Admin causes ImportError

python,flask,flask-sqlalchemy,flask-admin
I am trying to add a User model view to Flask-Admin. However, I get ImportError: cannot import name db. Why is this happening and how do I fix it? app/__init__.py: from flask import Flask from flask_sqlalchemy import SQLAlchemy import flask_admin as admin from app.models import User db = SQLAlchemy() admin...

Join two tables and show all combinations

python,flask,sqlalchemy,jinja2,flask-sqlalchemy
I have two models: Company and Contact. A Company can have many Contacts. class Company(db.Model): __tablename__ = 'company' id = db.Column(db.Integer, primary_key=True) companyname = db.Column(db.String()) contacts = db.relationship('Contact', backref='contact', lazy='dynamic') def __init__(self, companyname): self.companyname = companyname def __repr__(self): return '<id {}>'.format(self.id) def company_contacts(self): return Contact.query.join(id = Contact.company_id) class Contact(db.Model): __tablename__...

scoped_session object has no attribute 'create_all'

python,flask,sqlalchemy,flask-sqlalchemy
I have the following code that sets up my database with Flask-SQLAlchemy. I'm getting an exception "AttributeError: scoped_session object has no attribute 'create_all'". Can someone please explain to me why I'm getting the error and how I can fix it? :) __init__.py: from flask import Flask app = Flask(__name__) from...

Flask-SQLAlchemy filter_by and follow multiple backrefs

python,flask,sqlalchemy,flask-sqlalchemy
I would like to extend the schema from the Flask-SQLAlchemy Quickstart Simple Relationships example and add a class called Editor. My schema now looks like this: from datetime import datetime from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class Post(db.Model): id...

SLQAlchemy, Flask: AttributeError: 'module' object has no attribute 'create_all' [closed]

virtualenv,flask-sqlalchemy
I'm having this issue when creating the tables using SQLAlquemy in Flask, in a virtualenv. I do: >>> from mod_db import modelx >>> modelx.create_all() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'create_all' modelx is: from flask import Flask from flask.ext.sqlalchemy...

Flask-Sqlalchemy taking non unique values for a 'unique' integer

python,flask,flask-sqlalchemy
Consider the following code: class User(db.Model): id=db.Column(db.Integer,primary_key=True) email=db.Column(db.String,unique=True) name=db.Column(db.String) password=db.Column(db.String) registration_num=db.Column(db.Integer,unique=True) def __repr__(self): return "<Name %r>, <id %r>" %(self.name,self.id) Here I am trying to create a user with unique email id (later to be used as login id) and unique registration number (later to be used as folder name to...

Base query to work even if parameters not supplied

python,flask,sqlalchemy,flask-sqlalchemy
I have a search with multiples parameters. Some of them optional. In this example i am only using two, for effect of simplicity. If the industry_id is None i will have this error: invalid input syntax for integer: "" LINE 3: WHERE companies_company.industry_id = '' pagination = Company.query.filter((Company.industry_id == industry_id)...

Openshift app with flask, sqlalchemy and sqlite - problems with database reverting

python-3.x,sqlite3,flask,openshift,flask-sqlalchemy
I have a problem pretty much exactly like this: How to preserve a SQLite database from being reverted after deploying to OpenShift? I don't understand his answer fully and clearly not enough to apply it to my own app and since I can't comment his answer (not enough rep) I...

SQLAlchemy with Flask does not commit

python,flask,sqlalchemy,flask-sqlalchemy,flask-wtforms
When I submit my form from webpage, I am not able to commit. Flashing data I need, I see they're there and correct, but something fails when committing. I am sure I am making a mistake somewhere because mostly commit are working except two. This is one of the two...

Flask: Connecting models to files, e.g. profile pictures [closed]

database-design,flask,flask-sqlalchemy,flask-admin,flask-security
If it matters, I use Flask-Security, Flask-SQLAlchemy and Flask-Admin in my application. How should I design my application so that I can connect a row in the database with one or more files, e.g. a user to their profile pictures?...

Speed up updating items individually

python,mysql,sqlalchemy,flask-sqlalchemy
I have 12000 items in a table and I want to update and commit each item individually. items = db.session.query(User).all() for item in items: item.active = 0 # do stuff db.session.commit() I need to commit every iteration so that changes goes to database immediately. If I select all rows in...

change Test database From sqlite to Postgresql

python,postgresql,flask,flask-sqlalchemy,flask-testing
In my flask application I used Sqlite for Test Now I want to change it to postgresql But Got error OperationalError: (OperationalError) FATAL: database "mytest" does not exist None None am I doing it Right? where is the problem , Thanx config.py: class TestingConfig(Config): DEBUG = True TESTING = True...

TypeError: key is not a string

python,flask,flask-sqlalchemy,flask-restful
I am using flask and its flask-restful extension to make a simple restful-api. I am having trouble stuffing data into Question table with User id (reference). The model.py file is the following: class User(UserMixin, SurrogatePK, Model): __tablename__ = 'users' username = Column(db.String(80), unique=True, nullable=False) email = Column(db.String(80), unique=True, nullable=False) #:...

Flask foreign_keys still shows AmbiguousForeignKeysError

python,mysql,flask,foreign-keys,flask-sqlalchemy
I have two foreign keys in an entity that refer to another entity. Here is how it looks class Review(db.Model): __tablename__ = 'Review' id = db.Column(db.Integer, primary_key = True) user_id = db.Column(db.Integer, db.ForeignKey('User.id'), nullable=False) business_user_id = db.Column(db.Integer, db.ForeignKey('User.id'), nullable=False) user = db.relationship('User', foreign_keys=[user_id]) business_user = db.relationship('User', foreign_keys=[business_user_id]) and class User(db.Model):...

backref lazy='dynamic' - does not support object population - eager loading cannot be applied

flask,sqlalchemy,flask-sqlalchemy
How can I get Planes with Bookings between 2 dates specified. I need the Bookings to be filtered down to only be included if they're between 2 dates. I tried this but get the error: 'Plane.bookings' does not support object population - eager loading cannot be applied. Why does this...

Flask-SQLAlchemy - How to append a value to a column?

python-3.x,flask,sqlalchemy,flask-sqlalchemy
My total lack of knowledge in SQL queries is biting me hard right now. In flask-Sqlalchemy, how to you append a value to a column that already has one without replacing the one already present? I tried db.session.merge(user) and db.session.add(user) but both end up replacing the value in the column....

flask wtforms_alchemy object has no attribute

flask,flask-sqlalchemy,flask-wtforms,flask-login,flask-restful
I just started doing flask restful api and trying to register a user by sending a POST request to localhost:5000/api/v1/users. The required fields are email and password. Here's the curl request to create a user curl http://localhost:5000/api/v1/users -d "[email protected]&password=password" -X POST -v But it returns me this error: AttributeError: 'UserCreateForm'...

One to many SQL relationship

python-2.7,flask,flask-sqlalchemy
I am trying to build one-to-many relationship between Project table and Report table. User can create new project, later he can create one or more new reports related to that project. These two tables will be used for reporting issues. For example, if I build a new app, I...

Flask-SQLAlchemy close connection

postgresql,flask,sqlalchemy,flask-sqlalchemy
I am using PostgreSQL and Flas-SQLAlchemy extension for Flask. # app.py app = Flask(__name__) app.config['SQLALCHEMY_POOL_SIZE'] = 20 db = SQLAlchemy(app) # views.py user = User(***) db.session.add(user) db.session.commit() Note that I am not closing the connection as suggested by documentation: You have to commit the session, but you don’t have to...

Flask/SQLalchemy/Jinja2 — nested loop rendering

python,flask,jinja2,flask-sqlalchemy
I am a beginner to Flask. I am building a simple quiz application. I have two tables. One is question table and the other is options table with one right answer. I wanted to show one question and four options, then second question and so on. I searched every where...

one-to-many append attribute error

python-3.x,flask,sqlalchemy,flask-sqlalchemy
Bit of a noob with SQLAlchemy (and Python, though less so). Can't seem to straighten out relationships between my Post and Picture models. Post objects should have a list called 'gallery', a list of related Picture objects. As well there is a Post 'cover', an individual Picture chosen as the...

How can I use ndb outside of appengine?

python,database,flask,flask-sqlalchemy,app-engine-ndb
I really like GAE's object-relational database tools, db and ndb. I am currently preparing to develop a server which needs to be hosted from a local machine outside of Google's cloud environment. Namely, I am planning to use a python flask server. I've used other tools like SQLAlchemy to interact...

Flask-SQLAlchemy using global DB instance

python,flask,sqlalchemy,flask-sqlalchemy
Here is what I did: from flask import Flask from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker dbhost = 'localhost' dbuser = 'user' dbpass = 'password' dbname = 'db' DBUri = 'mysql://%s:%[email protected]%s/%s?charset=utf8'%(dbuser,dbpass,dbhost,dbname) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = (DBUri) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' # an Engine, which the Session will use...

'NoneType' object has no attribute 'owner' when trying to access relationship

python,flask,sqlalchemy,flask-sqlalchemy
I'm trying to load a value on the Toy.owner relationshiop. These are my models: class User(db.Model): __tablename__ = 'User' id = db.Column(db.Integer, primary_key=True) type = db.Column(db.String(50)) nickname = db.Column(db.String(255)) email = db.Column(db.String(255)) password = db.Column(db.String(255)) __mapper_args__ = { "polymorphic_on":type, 'polymorphic_identity':'user', 'with_polymorphic':'*' } class Owner(User): __tablename__ = 'Owner' id = db.Column(db.Integer,...

Problems trying to mock a Model within Flask-SQLAlchemy

testing,flask,mocking,flask-sqlalchemy
I'm testing a Flask application that have some SQLAlchemy models using Flask-SQLAlchemy and I'm having some problems trying to mock a few models to some methods that receive some models as parameters. A toy version of what I'm trying to do is like this. Suppose I have a model given...

sql alchemy: return all unique types of great great grandchildren

sqlalchemy,flask-sqlalchemy,alchemy
I have 6 tables. I am essentially trying to return all unique types of great great grandchildren How do I return a list of all the unique types of sku_numbers in a FreightDomesticOrder? Table Definitions: class FreightOrderDomestic(db.Model): """ A shipment of products from a manufacturer to a fulfillment center """...

Where can I find a list of the Flask SQLAlchemy Column types and options?

python,sqlalchemy,flask-sqlalchemy
I hope the word "Types" is used correctly here. Perhaps I mean "Arguments". Feel free to edit. I am creating a database using Models with Flask with SQLAlchemy, where can I find a list of all the different possible Column arguments such as: account_id = db.Column(db.Integer, nullable=False) I know some...

Isolating py.test DB sessions in Flask-SQLAlchemy

python,unit-testing,flask,flask-sqlalchemy,py.test
I'm trying to build a Flask app with Flask-SQLAlchemy; I use pytest to test the DB. One of the problems seems to be creating isolated DB sessions between different tests. I cooked up a minimal, complete example to highlight the problem, note that test_user_schema1() and test_user_schema2() are the same. Filename:...

Flask-admin separate view for models filtered by foreign key

python,flask,sqlalchemy,flask-sqlalchemy,flask-admin
I have two sql-alchemy classes. One is Quiz and another one is Reply: class Quiz(db.Model): id = db.Column(db.Integer, primary_key=True) quiz_question = db.Column(db.Text) quiz_date = db.Column(db.DateTime) replies = db.relationship("Reply") class Reply(db.Model): id = db.Column(db.Integer, primary_key=True) reply_text = db.Column(db.Text) reply_date = db.Column(db.DateTime) reply_mark = db.Column(db.Integer) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) quiz_id = db.Column(db.Integer,...

Can a Field act as both Foreign and Primary Keys in the same table?

database,foreign-keys,relational-database,primary-key,flask-sqlalchemy
I am working with Flask-SQLAlchemy, but I guess this question cuts across different database implementation platforms. Suppose I have two table models structured as: User (with fields: user_id as PRIMARY KEY, username, email, password) and UserDetails (with fields: f_name, l_name, dob, gender, address, contact, bio and user_id as FOREIGN KEY)....

PUT request not working, Flask-RESTful, SQLAlchemy

flask,sqlalchemy,flask-sqlalchemy,put,flask-restful
I believe the issue is with committing the changes to the database (3rd to last line: db.session.commit()). For example take a user: username="Foo", email="[email protected]". If in the PUT request body I put {"email":"[email protected]"}, printing 'user.email' after the assignment reveals that the value is in fact changed. Afterwards however, upon querying...

Two ways of creating a flask-SQLAlchemy BaseQuery object - only one works, why?

python,flask,sqlalchemy,flask-sqlalchemy
This question is a simplification of "Filter relationships and paginate in Flask-SQLAlchemy", and an answer here would probably yield a solution there too. Say I have a simple model class Design: from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) db = SQLAlchemy(app) class Design(db.Model): __tablename__ = 'design'...

How to order a geospatial query by distance from the query point

sqlalchemy,flask-sqlalchemy,geoalchemy2
I try searching for this problem on the web, but to no avail. Seems like a basic task. I'm using PostGresql through SQLAlchemy with Geoalchemy to do geospatial queries. Technically, I'm using `Flask-SQLAlchemy. I can do a geospatial query. For example: from geoalchemy2 import func cls.db.session.query(cls).filter(func.ST_DWithin(cls.geoLoc, geo, meters)) where cls...

SQLAlchemy - Filter query, exclude parent where one of many children meet criteria

python,sqlalchemy,flask-sqlalchemy
My SQL skills are pretty lacking, so I can't figure out how to form the query I need. I've got two db models with a one to many relationship, defined like this: class Parent(db.Model): __tablename__ = 'parent' id = db.Column(db.Integer, primary_key = True) children = db.relationship('Child', backref = 'parent', lazy...

Secondary Join Condition Ignored in Insert SQL Alchemy

python,sqlalchemy,flask-sqlalchemy
I have the following models (to which I still need to add some appropriate validation): class Participant(db.Model): player_id = db.Column(db.Integer, db.ForeignKey('player.id'), primary_key=True) game_id = db.Column(db.Integer, db.ForeignKey('game.id'), primary_key=True) winner = db.Column(db.Boolean) class Player(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) avatar = db.Column(db.String(120)) skill...

Associate "external' class model with flask sqlalchemy

python,flask,sqlalchemy,flask-sqlalchemy,flask-security
We use a central class model for a wide variety of python modules. This model is defined using SQLAlchemy. The classes all inherit from declarative_base. For example, our model definitions look something like this: Base = declarative_base() class Post(Base): __tablename__ = 'Posts' id = Column(INT, primary_key=True, autoincrement=True) body = Column(TEXT)...

Python sqlalchemy how to deal with null

python,flask-sqlalchemy,flask-wtforms
I made a flask webframe,and execute sql update on UI.now I meet a question an data value is json string content is : {"username":"test","measureid":null} When I use python sqlalchemy to update date: sql="update dh_base_measure_get_10 set json="{\"username\":\"test\",\"measureid\":null}" db.session.execute(sql) but system get an error message: StatementError: A value is required for bind...

how to store binary file recieved by Flask into postgres

python,flask,flask-sqlalchemy,psycopg2,werkzeug
I currently have a Flask route that reveives file content via POST, and that stores it on the file system, ex: @app.route('/upload', methods=['POST']) def upload_file(): def allowed_file(f): return True file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(upload_dir(), filename)) return "", 200 I would like to store it...

Select attributes from different joined tables with Flask and SQLAlchemy

python,orm,flask,sqlalchemy,flask-sqlalchemy
Can't get myself to do something as easy as good ol' SELECT phrase.content, meaning.content FROM phrase JOIN meaning ON phrase.id = meaning.phrase_id All the examples I can find in the documentation/SO are variations of a = Phrase.query.join(Meaning).all() which doesn't really work cause then a is a list of Phrase objects,...

Get “insert_id” for one to one relationship in Flask, SqlAlchemy

flask,flask-sqlalchemy
I'm trying to insert a new row through sqlalchemy. The parent table (Milestone) has a child table called Funding. Both tables share a relationship through a column called milestone_id. It is a one to one relationship. I have looked it up, but I can't figure out how to reference the...

Update many to many association table with derived field

python,flask,sqlalchemy,many-to-many,flask-sqlalchemy
I'm writing a RESTful API using Flask, Flask-SQLalchemy and Flask-Restful. I have models for Contact and Category, and a helper table for mapping a many-to-many relationship between them. contactgrouping = db.Table('CONTACT_GROUPING', db.Column('catid', db.Integer, db.ForeignKey('CATEGORY.catid')), db.Column('contactid', db.Integer, db.ForeignKey('CONTACT.contactid')), db.Column('clientid', db.Integer, db.ForeignKey('CLIENT.clientid')), ) class Contact(db.Model): __tablename__ = 'CONTACT' contactid = db.Column(db.Integer, primary_key=True)...