Last active
June 12, 2018 14:50
-
-
Save ftnext/63279bed7b1d0dbe0ab5015682fb78c0 to your computer and use it in GitHub Desktop.
Web Apps × FlaskでDBを使うときのベストプラクティス?を調べる(Azureもくもく会@新宿 No.20 2018/06/12)Blog: http://nikkie-ftnext.hatenablog.com/entry/2018/06/12/234254
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
# 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 |
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
# config.py | |
class Config(object): | |
SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db' | |
SQLALCHEMY_TRACK_MODIFICATIONS = False |
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
# manage.py | |
from app import myapp | |
myapp.run() |
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
# 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 | |
} |
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
# 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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
フォルダ構成
__init__.py
参考