crud in python flask code example
Example 1: sqlite3 with flask web application CRUD pdf
from forms import DepartmentForm, EmployeeAssignForm, RoleForm
from ..models import Department, Employee, Role
@admin.route('/employees')
@login_required
def list_employees():
"""
List all employees
"""
check_admin()
employees = Employee.query.all()
return render_template('admin/employees/employees.html',
employees=employees, title='Employees')
@admin.route('/employees/assign/<int:id>', methods=['GET', 'POST'])
@login_required
def assign_employee(id):
"""
Assign a department and a role to an employee
"""
check_admin()
employee = Employee.query.get_or_404(id)
if employee.is_admin:
abort(403)
form = EmployeeAssignForm(obj=employee)
if form.validate_on_submit():
employee.department = form.department.data
employee.role = form.role.data
db.session.add(employee)
db.session.commit()
flash('You have successfully assigned a department and role.')
return redirect(url_for('admin.list_employees'))
return render_template('admin/employees/employee.html',
employee=employee, form=form,
title='Assign Employee')
Example 2: sqlite3 with flask web application CRUD pdf
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import app_config
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
db.init_app(app)
return app
Example 3: sqlite3 with flask web application CRUD pdf
from flask import abort, Flask, render_template
def create_app(config_name):
@app.route('/500')
def error():
abort(500)
return app