Created
November 22, 2019 22:02
-
-
Save doobeh/55bde530d1d5007cfad088c8f5dc3a04 to your computer and use it in GitHub Desktop.
Add self and commit?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask_sqlalchemy import SQLAlchemy | |
from flask import Flask, jsonify | |
db = SQLAlchemy() | |
class User(db.Model): | |
id = db.Column(db.Integer, primary_key=True) | |
name = db.Column(db.String, default="Person") | |
def add(self): | |
db.session.add(self) | |
@staticmethod | |
def save(): | |
db.session.commit() | |
app = Flask(__name__) | |
app.config.from_mapping( | |
SECRET_KEY='SHH', | |
SQLALCHEMY_DATABASE_URI="sqlite://", # in memory | |
SQLALCHEMY_TRACK_MODIFICATIONS=False, | |
) | |
db.init_app(app) | |
@app.before_first_request | |
def create_db(): | |
db.create_all() | |
@app.route('/') | |
def home(): | |
alice = User(name="alice") | |
alice.add() | |
alice.save() | |
return 'User Added...' | |
@app.route('/users') | |
def users(): | |
all_users = [x.name for x in User.query.all()] | |
return jsonify(users=all_users) | |
if __name__ == '__main__': | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment