Hello1204 潜水
  • 1发帖数
  • 1主题数
  • 0关注数
  • 0粉丝
开启左侧

使用flask开发一个Todo 小玩具-源码

[复制链接]
Hello1204 发表于 2021-10-7 20:59:04 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题
Schedule.py

from flask import Flask,render_template,flash,redirect
from flask.globals import request
from flask.helpers import url_for
from flask_login import UserMixin,LoginManager,login_required,current_user
from flask_login.utils import login_user, logout_user
from sqlalchemy.sql.elements import Null
from werkzeug.security import generate_password_hash, check_password_hash
from flask_sqlalchemy import SQLAlchemy
import os
from werkzeug.security import generate_password_hash, check_password_hash
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.fields.core import DateField
from wtforms.fields.simple import TextAreaField
from wtforms.validators import DataRequired, Required, Length, Email, Regexp, EqualTo
from wtforms import ValidationError
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
SECRET_KEY = os.urandom(32)
app.config['SECRET_KEY'] = SECRET_KEY
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///' + os.path.join(basedir, 'schedule.db')
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.session_protection="string"
login_manager.login_view = 'login'
login_manager.init_app(app)
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key = True)
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
tasks = db.relationship('Task', backref='user', lazy='dynamic')
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
#app.logger.debug('vefify_password %s', password)
#app.logger.debug(self.password_hash)
return check_password_hash(self.password_hash, password)
def __repr__(self):
return '' % self.username
class Task(db.Model):
id = db.Column(db.Integer, primary_key = True)
description = db.Column(db.Text)
done = db.Column(db.Boolean)
start_date = db.Column(db.Date)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)


def __repr__(self):
return '' % (self.description, self.user)


class TaskForm(FlaskForm):
description = TextAreaField('New Task', validators=[DataRequired()])
start_date = DateField()
submit = SubmitField('Add')
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Length(1, 64), Email()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('Keep me logged in')
submit = SubmitField('Log In')
class RegistrationForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Length(1, 64), Email()])
username = StringField('Username', validators=[DataRequired(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0,
'Usernames must have only letters, ''numbers, dots or underscores')])
password = PasswordField('Password', validators=[DataRequired(), EqualTo('password2', message='Passwords must match.')])
password2 = PasswordField('Confirm password', validators=[DataRequired()])
submit = SubmitField('Register')
def validate_email(self, field):
#app.logger.debug('validate_email')
if User.query.filter_by(email=field.data).first():
raise ValidationError('Email already registered.')
def validate_username(self, field):
#app.logger.debug('validate_username')
if User.query.filter_by(username=field.data).first():
raise ValidationError('Username already in use.')


@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route('/', methods=['GET','POST'])
def index():
tasks = []
form = TaskForm()
if form.validate_on_submit():
job = Task(description=form.description.data, start_date = form.start_date.data)
job.user = current_user
db.session.add(job)
db.session.commit()
if current_user.is_authenticated:
tasks = current_user.tasks
return render_template('index.html',form=form, tasks = tasks)
@app.route('/update/')
@login_required
def update(task_id):
return 'update task'
@app.route('/delete/')
@login_required
def delete(task_id):
form = TaskForm()
user = current_user._get_current_object()
task = Task.query.filter_by(id = task_id).first()
if task.user == user:
db.session.delete(task)
db.session.commit()
if current_user.is_authenticated:
tasks = current_user.tasks
return redirect(request.args.get('next') or url_for('index'))


@app.route('/login', methods=['GET','POST'])
def login():
form = LoginForm()
app.logger.debug('login')
if form.validate_on_submit():
app.logger.debug('validate_on_submit success')
user = User.query.filter_by(email = form.email.data).first()
app.logger.debug(user)
app.logger.debug(form.password.data)
if user is not None and user.verify_password(form.password.data):
login_user(user, form.remember_me.data)
return redirect(request.args.get('next') or url_for('index'))
else:
flash('invalid password or username')
return render_template('login.html', form=form)
@app.route('/logout')
@login_required
def logout():
logout_user()
flash('You have been logged out.')
return redirect(url_for('index'))
@app.route('/task',methods=['GET','POST'])
def task():
return 'tasks'


@app.route('/register', methods=['GET','POST'])
def register():
form = RegistrationForm()
app.logger.debug('register')
if form.validate_on_submit():
app.logger.debug('validate_on_submit success')
user = User(email=form.email.data,username=form.username.data,password=form.password.data)
db.session.add(user)
db.session.commit()
return redirect(url_for('login'))
return render_template('register.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
#http_server = HTTPServer(WSGIContainer(app))
#http_server.listen(5000)
#print('run...')
#IOLoop.current().start()
Register.html

{%extends "base.html" %}
{%block title %}Flasky - Login{%endblock %}
{%block page_content %}

Login







{{ form.csrf_token }}

{{form.email.label}}:
{{form.email(class_="form-control", type="email", id="email", placeholder="Enter email")}}
{% for error in form.email.errors %}
{{ error }}

{% endfor %}



{{form.username.label}}:
{{form.username(class_="form-control", type="username", id="username", placeholder="Enter email")}}
{% for error in form.username.errors %}
{{ error }}

{% endfor %}



{{form.password.label}}:
{{form.password(class_="form-control", type="password", id="pwd", placeholder="Enter password")}}
{% for error in form.password.errors %}
{{ error }}

{% endfor %}



{{form.password2.label}}:
{{form.password2(class_="form-control", type="password", id="pwd", placeholder="Enter password")}}
{% for error in form.password.errors %}
{{ error }}

{% endfor %}


Submit





{%endblock %}
Login.html

{%extends "base.html" %}
{%block title %}Flasky - Login{%endblock %}
{%block page_content %}


{{ form.csrf_token }}

{{form.email.label}}:
{{form.email(class_="form-control", type="email", id="email", placeholder="Enter email")}}
{% for error in form.email.errors %}
{{ error }}

{% endfor %}



{{form.password.label}}:
{{form.password(class_="form-control", type="password", id="pwd", placeholder="Enter password")}}
{% for error in form.password.errors %}
{{ error }}

{% endfor %}



{{ form.remember_me(class_="", type="checkbox")}} {{form.remember_me.label}}



New user?

Click here to register



Submit



{%endblock %}
Index.html
{%extends "base.html" %}
{%block title %}Flasky - Login{%endblock %}
{% import "_macros.html" as macros %}
{%block page_content %}
{% if current_user.is_authenticated %}


{{ form.csrf_token }}

{{form.description.label}}:
{{form.description(class_="form-control", type="description", id="description", placeholder="Enter description")}}
{% for error in form.description.errors %}
{{ error }}

{% endfor %}
{{form.start_date.label}}:
{{form.start_date(class_="form-control", type="date", id="date", value="2020-10-01")}}
{% for error in form.start_date.errors %}
{{ error }}

{% endfor %}


Submit




{{ macros.tasks_inner(tasks) }}




{%endif %}
{%endblock %}
{%block js %}

{%endblock %}
Base.html



{% block title %}{{title|default}}{% endblock title %}
{%block css %}





{%endblock %}


{%block navbar %}




Toggle navigation




Flasky





    {%if current_user.is_authenticated %}
  • Sign Out
    {%else %}
  • Sign In
    {%endif %}







{%endblock %}
{%block content %}

{%for message in get_flashed_messages() %}

×
{{ message }}


{%endfor %}
{%block page_content %}{%endblock %}


{%endblock %}


{%block js %}
{%endblock %}
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

猜你喜欢
在线客服邮箱
wxcy#wkgb.net

邮箱地址#换为@

Powered by 创意电子 ©2018-现在 专注资源实战分享源码下载站联盟商城