基本的models.py和controllers.py在Flask中看起来如何?

时间:2017-04-26 23:35:29

标签: flask flask-sqlalchemy

基本的models.py和controllers.py看起来如何,它的基本结构是什么?还是模板?

1 个答案:

答案 0 :(得分:-1)

models.py

from flask_sqlalchemy import SQLAlchemy
from app import db
from werkzeug.security import generate_password_hash, check_password_hash


class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255))
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))

def __init__(self, name, email, password):
    self.name = name
    self.email = email
    self.password = generate_password_hash(password)

def check_password(self, password):
    return check_password_hash(self.password, password)

def to_dict(self):
    return {
        'id' : self.id,
        'name': self.name,
        'email': self.email,
    }

def __repr__(self):
    return "User<%d> %s" % (self.id, self.name)

from flask_sqlalchemy import SQLAlchemy
from app import db

class Todo(db.Model):
    __tablename__ = 'todos'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(255))
    text = db.Column(db.String(1000))
    color = db.Column(db.String(24))
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    done = db.Column(db.Boolean, default=False)

    def __init__(self, title, text, color, user_id):
        self.title = title
        self.text = text
        self.color = color
        self.user_id = user_id

    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'text': self.text,
            'color': self.color,
            'done': self.done,
        }

    def __repr__(self):
        return "Todo<%d> %s" % (self.id, self.title)

controllers.py

from flask import Blueprint, request, session, jsonify
from sqlalchemy.exc import IntegrityError
from app import db
from .models import User

mod_user = Blueprint('user', __name__, url_prefix='/api')


@mod_user.route('/login', methods=['GET'])
def check_login():
    if 'user_id' in session:
        user = User.query.filter(User.id == session['user_id']).first()
        return jsonify(success=True, user=user.to_dict())

    return jsonify(success=False), 401


@mod_user.route('/login', methods=['POST'])
def login():
    try:
        email = request.form['email']
        password = request.form['password']
    except KeyError as e:
        return jsonify(success=False, message="%s not sent in the request" % e.args), 400

    user = User.query.filter(User.email == email).first()
    if user is None or not user.check_password(password):
        return jsonify(success=False, message="Invalid Credentials"), 400

    session['user_id'] = user.id

    return jsonify(success=True, user=user.to_dict())


@mod_user.route('/logout', methods=['POST'])
def logout():
    session.pop('user_id')
    return jsonify(success=True)


@mod_user.route('/register', methods=['POST'])
def create_user():
    try:
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']
    except KeyError as e:
        return jsonify(success=False, message="%s not sent in the request" % e.args), 400

    if '@' not in email:
        return jsonify(success=False, message="Please enter a valid email"), 400

    u = User(name, email, password)
    db.session.add(u)
    try:
        db.session.commit()
    except IntegrityError as e:
        return jsonify(success=False, message="This email already exists"), 400

    return jsonify(success=True)

from flask import Blueprint, request, session, jsonify
from app import db, requires_auth
from .models import Todo

mod_todo = Blueprint('todo', __name__, url_prefix='/api')

@mod_todo.route('/todo', methods=['POST'])
@requires_auth
def create_todo():
    title = request.form['title']
    text = request.form['text']
    color = request.form['color']
    user_id = session['user_id']
    todo = Todo(title, text, color, user_id)
    db.session.add(todo)
    db.session.commit()
    return jsonify(success=True, todo=todo.to_dict())

@mod_todo.route('/todo', methods=['GET'])
@requires_auth
def get_all_todos():
    user_id = session['user_id']
    todos = Todo.query.filter(Todo.user_id == user_id).all()
    return jsonify(success=True, todos=[todo.to_dict() for todo in todos])

@mod_todo.route('/todo/<id>', methods=['GET'])
@requires_auth
def get_todo(id):
    user_id = session['user_id']
    todo = Todo.query.filter(Todo.id == id, Todo.user_id == user_id).first()
    if todo is None:
        return jsonify(success=False), 404
    else:
        return jsonify(success=True, todo=todo.to_dict())

@mod_todo.route('/todo/<id>', methods=['POST'])
@requires_auth
def edit_todo(id):
    user_id = session['user_id']
    todo = Todo.query.filter(Todo.id == id, Todo.user_id == user_id).first()
    if todo is None:
        return jsonify(success=False), 404
    else:
        todo.title = request.form['title']
        todo.text = request.form['text']
        todo.color = request.form['color']
        db.session.commit()
        return jsonify(success=True)

@mod_todo.route('/todo/<id>/done', methods=['POST'])
@requires_auth
def mark_done(id):
    user_id = session['user_id']
    todo = Todo.query.filter(Todo.id == id, Todo.user_id == user_id).first()
    if todo is None:
        return jsonify(success=False), 404
    else:
        todo.done = True
        db.session.commit()
        return jsonify(success=True)


@mod_todo.route('/todo/<id>/delete', methods=['POST'])
@requires_auth
def delete_todo(id):
    user_id = session['user_id']
    todo = Todo.query.filter(Todo.id == id, Todo.user_id == user_id).first()
    if todo is None:
        return jsonify(success=False), 404
    else:
        db.session.delete(todo)
        db.session.commit()
        return jsonify(success=True)