Skip to content

Instantly share code, notes, and snippets.

@ftnext ftnext/__init__.py
Last active Jun 12, 2018

Embed
What would you like to do?
Web Apps × FlaskでDBを使うときのベストプラクティス?を調べる(Azureもくもく会@新宿 No.20 2018/06/12)Blog: http://nikkie-ftnext.hatenablog.com/entry/2018/06/12/234254
# app/__init__.py
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
myapp = Flask(__name__) # appだとフォルダ名と競合すると懸念した
myapp.config.from_object(Config)
db = SQLAlchemy(myapp)
from app import views
# config.py
class Config(object):
SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
# manage.py
from app import myapp
myapp.run()
# app/models.py
from app import db
class User(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)
password_hash = db.Column(db.String(128))
def __repr__(self):
return '<User {}>'.format(self.username)
def init():
db.create_all()
def retrieve_users():
users = User.query.all()
return [create_user_info(u) for u in users]
def create_user_info(user):
return {
'id': user.id,
'username': user.username,
'email': user.email
}
# app/views.py
from flask import jsonify
from app import myapp, db
from app.models import retrieve_users
@myapp.route('/')
def show_users():
return jsonify(retrieve_users())
@ftnext

This comment has been minimized.

Copy link
Owner Author

commented Jun 12, 2018

フォルダ構成

  • ├ config.py
  • ├ manage.py
  • └ app/
    • __init__.py
    • ├ models.py
    • └ views.py

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.