SHARE
TWEET

PythonCRUD

dbarrera Oct 21st, 2019 74 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from flask import Flask, request, render_template, redirect, url_for
  2. from models import *
  3.  
  4. app = Flask(__name__)
  5. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.sqlite'
  6. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  7.  
  8. db.init_app(app)
  9.  
  10. @app.route('/')
  11. def index():
  12.     people = Person.query.all()
  13.     return render_template('index.html', people=people)
  14.  
  15. @app.route('/create', methods=['GET', 'POST'])
  16. def create():
  17.     if request.method == 'POST':
  18.         # Create a person
  19.         name = request.form.get('name')
  20.         email = request.form.get('email')
  21.         person = Person(name=name, email=email)
  22.         db.session.add(person)
  23.         db.session.commit()
  24.         return redirect(url_for('index'))
  25.  
  26.     return render_template('create.html')
  27.  
  28. @app.route('/show/<int:id>')
  29. def show(id):
  30.     person = Person.query.get(id)
  31.     if person is None:
  32.         return render_template('error.html', message='No person with that ID.')
  33.        
  34.     return render_template('show.html', person=person)
  35.  
  36. @app.route('/edit/<int:id>', methods=['GET', 'POST'])
  37. def edit(id):
  38.     person = Person.query.get(id)
  39.     if person is None:
  40.         return render_template('error.html', message='No person with that ID.')
  41.  
  42.     if request.method == 'POST':
  43.         person.name = request.form.get('name')
  44.         person.email = request.form.get('email')
  45.         db.session.commit()
  46.         return redirect(url_for('show', id=person.id))
  47.  
  48.     return render_template('edit.html', person=person)
  49.  
  50. @app.route('/destroy', methods=['POST'])
  51. def destroy():
  52.     id = request.form.get('id')
  53.     person = Person.query.get_or_404(id)
  54.     db.session.delete(person)
  55.     db.session.commit()
  56.     return redirect(url_for('index'))
  57.  
  58. def main():
  59.     db.create_all()
  60.  
  61. if __name__ == '__main__':
  62.     with app.app_context():
  63.         main()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top