基本的models.py和controllers.py怎麼看,它的基本結構是什麼?或模板?基本的models.py和controllers.py如何在Flask中顯示?
-1
A
回答
-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)
相關問題
- 1. 使用SQLAlchemy在Flask中保存和檢索關係的基本示例
- 2. 如何在Flask Restplus文檔中指示基礎URL
- 3. 如何在Flask中顯示每個實體的多個表單?
- 4. 如何在RichTextBox中顯示基本的HTML表格?
- 5. 形式需要顯示從models.py
- 6. 變量未顯示在Flask模板中
- 7. Flask wtforms DecimalField不顯示在HTML中
- 8. 如何在models.py中使用基類,但沒有django爲基類創建表?
- 9. 在NodeJS和ExpressJS中顯示基本的HTML文件
- 10. Flask-Restful基本設置
- 11. 如何在Flask-Admin中顯示角色 - 用戶關係?
- 12. 如何在Flask模板中顯示當前年份?
- 13. Highcharts不顯示csv/json和Flask
- 14. 如何在Flask中獲取HTTP版本
- 15. 如何顯示Jersey Web Application的基本URL中的內容?
- 16. Flask + WTForms - FormList中的顯示字段
- 17. 如何將模板Flask中的對象顯示爲json?
- 18. 如何使用Python/Flask顯示heroku中的index.html頁面
- 19. 如何在Flask的頁面上顯示小部件?
- 20. R中的基本日曆顯示
- 21. 如何在jlabel中顯示網頁中的文本和圖像
- 22. 在Python中顯示圖像代碼和基本乘法
- 23. 如何從models.py的settings.py中引用MEDIA_URL?
- 24. flask-debugtoolbar沒有顯示
- 25. Flask&WTForms:DatePicker Widget顯示日期
- 26. Flask-WTFform:Flash不顯示錯誤
- 27. 基本的jQuery Slider根本不顯示
- 28. 使用Flask-SQLAlchemy在Flask應用程序中使用Alembic檢測對models.py的更改
- 29. 問題和Django Models.py
- 30. SSRS顯示基本信息
下面是一個例子:https://github.com/carpedm20/personal-blog-powered-by-flask/blob/master/app/models.py – bernie