Advertisement
Guest User

Untitled

a guest
Jun 29th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. # 6/29 Notes
  2.  
  3. ### Objectives:
  4.  
  5. * Build One to many crud app
  6. * Add flask login
  7. * refactor with blueprints
  8.  
  9. For this exercise, we will have users who have many fish.
  10.  
  11. ### Setup
  12.  
  13. In terminal:
  14.  
  15. ```
  16. take flask-fishes
  17. mkvirtualenv flask-fishes
  18. pip install flask flask_sqlalchemy wtforms psycopg2 flask_bcrypt flask_migrate flask_modus
  19. touch {app,manage,forms}.py
  20. take templates
  21. touch base.html
  22. mkdir fishes
  23. mkdir users
  24. touch fishes/{index,new,show,edit}.html
  25. touch users/{index,new,show,edit}.html
  26. pip freeze > requirements.txt
  27. git init
  28. echo __pycache__ > .gitignore
  29. echo *.pyc >> .gitignore
  30. createdb flask_fishes
  31. ```
  32.  
  33. App.py
  34.  
  35. ```
  36. from flask import Flask
  37. from flask_sqlalchemy import SQLAlchemy
  38. from flask_bcrypt import Bcrypt
  39.  
  40.  
  41. app = Flask(__name__)
  42.  
  43. app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://localhost/flask-fishes'
  44. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  45.  
  46. db = SQLAlchemy(app)
  47.  
  48. class User(db.Model):
  49.  
  50. __tablename__ = 'users'
  51.  
  52. id = db.Column(db.Integer, primary_key = True)
  53. username = db.Column(db.Text(), nullable=False, unique=True)
  54. passwod = db.Column(db.Text(), nullable=False)
  55. fishes = db.relationship('Fish', backref='user', lazy='dynamic')
  56.  
  57. def __init__(self, username, password):
  58. self.username = username
  59. self.password = bcrypt.generate_password_hash(password).decode('utf-8')
  60.  
  61. class Fish(db.Model):
  62.  
  63. __tablename__ = 'fishes'
  64.  
  65. id = db.Column(db.Integer, primary_key = True)
  66. type = db.Column(db.Text()), nullable = False)
  67. weight = db.Column(db.Float, nullable=False)
  68. user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
  69.  
  70. def __init__(self, type, weight, user_id):
  71. self.type = type
  72. self.weight = weight
  73. self.user_id = user_id
  74.  
  75.  
  76. ```
  77.  
  78.  
  79. in manage.py:
  80.  
  81. ```
  82. from app import app,db
  83. from flask_script import Manager
  84. from flask)migrate import Migrate, MigrateCommand
  85.  
  86. manager = Manager(app)
  87.  
  88. manager.add_command('db', MigrateCommand)
  89.  
  90. if __name__ = '__main__':
  91. manager.run()
  92.  
  93. ```
  94.  
  95. in terminal, run:
  96.  
  97. `createdb flask-fishes`
  98. `python manage.py db init`
  99. `python manage.py db migrate`
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement