Flask web开发-基于python的web应用开发实战

太长了 直接上按照书中做好的。

flask-admin最全面的中文教程

flask_web12百度云链接
包含书中功能:
基本结构【路由、视图、响应、script扩展】、
模板【渲染、变量、控制结构、自定义错误页面、链接、静态文件(只有加入了一个富文本编辑器的jscss样式)】、
表单【表单类Form、表单渲染、视图处理表单、重定向、flash消息】、
mysql数据库【定义模型、创建表、查询删除插入、迁移表更新表 一对多关系、多对多、】
组织代码构建大型程序结构【蓝图】、
用户认证【散列密码,flask-login认证】、
用户角色【角色数据库的设计创建、验证】、
用户资料【请求调度before_app_request,和使用ckeditor编辑器,头像服务】、
博客文章【创建虚拟数据,分页,分页导航】
关注者【多对多自引用关系,感觉复杂】
用户评论【多对多关系】
未包含功能:flask-bootstrap、extends继承和include模板复用,moment本地化时间、详细的请求钩子用法、上下文全局变量、会话、邮件及用户评论后面的几章

1-6章直接忽略,直接从第七章组织代码开始套入前面六章内容。重新复习一遍(加入一些原来书本没有的技术,从“深入理解flask”摘取,相当于两本书的教程合并)

20170529 使用平板

大型应用程序结构

创建flask_web文件夹进入文件夹
创建app文件夹,创建config.py,manage.py文件

#coding=utf-8
"""filename:config.py
Created 2017-05-29
Author: by anaf
"""
import os
basedir = os.path.abspath(os.path.dirname(__file__))


class Config:
    #保护字段,必须设置  
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'strings'
    #sql自动提交
    SQLALCHEMY_COMMIT_ONTRARDOWN = True
    #####
    SQLALCHEMY_TRACK_MODIFICATIONS  = False

    @staticmethod
    def init_app(app):
        pass

#开发配置
class DevelopmentConfig(Config):
    DEBUG = True
    #配置数据库路径从系统变量读取没有就根据字符串中的读取 mysql为例子
    SQLALCHEMY_DATABASE_URI = os.environ.get('dev_database_url') or \
        'mysql://root:@localhost:3306/flask_web'

#测试配置
class TestingConfig(Config):
    TESTING = True
    SQLALCHEMY_DATABASE_URI = os.environ.get('dev_database_url') or \
        'mysql://root:@localhost:3306/flask_web'


class ProductionConfig(Config):
    SQLALCHEMY_DATABASE_URI = os.environ.get('dev_database_url') or \
        'mysql://root:@localhost:3306/flask_web'


config = {
    'development' : DevelopmentConfig,
    'testing': TestingConfig,
    'production': ProductionConfig,
    'default': DevelopmentConfig
}


#coding=utf-8
"""filename:manage.py
Created 2017-05-29
Author: by anaf
"""
import os
from app import create_app,db
from flask.ext.script import Manager,Shell
from flask.ext.migrate import Migrate,MigrateCommand

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app)

def make_shell_context():
    return dict(app=app,db=db)

manager.add_command('shell',Shell(make_context=make_shell_context))
manager.add_command('db',MigrateCommand)

if __name__ == '__main__':
    manager.run()
#coding=utf-8
"""filename:app/__init__.py
Created 2017-05-29
Author: by anaf
note:初始化函数
"""

from flask import Flask,render_template
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config

mail = Mail()
moment = Moment()
db = SQLAlchemy()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)

    return app


#coding=utf-8
"""filename:app/main/__init__.py
Created 2017-05-29
Author: by anaf
note:main/__init__.py  Blueprint蓝图
""" 

from flask import Blueprint

main = Blueprint('main',__name__)

from . import views,errors 

修改函数添加蓝图

#coding=utf-8
"""filename:app/__init__.py
Created 2017-05-29
Author: by anaf
note:初始化函数
"""

from flask import Flask,render_template
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLALChemy
from config import Config

mail = Mail()
moment = Moment()
db = SQLALChemy()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    mail.init_app(app)
    moment.init_app(app)
    db.initt_app(app)

    #添加蓝图main
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app

#coding=utf-8
"""filename:app/main/errors.py
Created 2017-05-29
Author: by anaf
"""
from flask import render_template
from .import main

@main.app_errorhandler(404)
def page_not_found(e):
    return render_template('404.html'),404

@main.app_errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'),500

#coding=utf-8
"""filename:app/main/views.py
Created 2017-05-29
Author: by anaf
"""

from flask import render_template
from . import main
from .. import db
#from ..models import User

@main.route('/',methods=['GET'])
def index():
    return render_template('index.html')

添加模块:

···python

pip install flask-script
pip install flask-moment
pip install flask-wtf
pip install flask-sqlalchemy
pip install flask-migrate
pip install flask-mail
···
添加html文件:app/template/index.html




    
    index


    index
#加入flash消息显示
{%for message in get_flashed_messages()%}
 {{message}}
{%endfor%}


错别字他多了。。 改了很多错别字打错字母什么的
运行python manage.py runserver

↑第七章完成

第八章用户认证

使用werkzeug实现密码散列

#coding=utf-8
"""filename:app/models.py
Created 2017-05-30
Author: by anaf
note:数据库模型函数
"""

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


"""角色表 一对多,一个角色对应多个用户
db.relationship('User',backref='role')
因为User 还没有定义 所以使用字符串形式指定
"""
class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(64),unique=True)
    users = db.relationship('User',backref='role')

    def __repr__(self):
        return '' % self.name


class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer,primary_ke = True)
    username = db.Column(db.String(64),unique=True,index=True)
    password_hash = db.Column(db.String(128))
    role_id = db.Column(db.Integer,db.ForeignKey('roles.id'))

    def __repr__(self):
        return '' % self.username

    @proprty
    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):
        return check_password_hash(self.password_hash,password)

        
#coding=utf-8
"""filename:app/auth/__init__.py
Created 2017-05-30
Author: by anaf
note:auth初始化函数
"""

from flask import Blueprint

auth = Blueprint('auth',__name__)

from . import views 
#coding=utf-8
"""filename:app/auth/__init__.py
Created 2017-05-30
Author: by anaf
note:auth视图函数
"""
from flask import render_template
from . import auth

@auth.route('/')
def login():
    return render_template('auth/login.html')

创建html文件:template/auth/login.html




    
    login


    login


修改函数:

#coding=utf-8
"""filename:app/__init__.py
Created 2017-05-29
Author: by anaf
note:初始化函数
"""

from flask import Flask,render_template
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config

mail = Mail()
moment = Moment()
db = SQLAlchemy()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)

    #添加蓝图main,auth
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint,url_prefix='/auth')

    return app

安装登陆模块

pip install flask-login

修改models.py

#coding=utf-8
"""filename:app/models.py
Created 2017-05-30
Author: by anaf
note:数据库模型函数
"""

from werkzeug.security import generate_password_hash,check_password_hash
from app import db
from flask.ext.login import UserMixin


"""角色表 一对多,一个角色对应多个用户
db.relationship('User',backref='role')
因为User 还没有定义 所以使用字符串形式指定
"""
class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(64),unique=True)
    users = db.relationship('User',backref='role')

    def __repr__(self):
        return '' % self.name


class User(UserMixin,db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer,primary_ke = True)
    username = db.Column(db.String(64),unique=True,index=True)
    password_hash = db.Column(db.String(128))
    role_id = db.Column(db.Integer,db.ForeignKey('roles.id'))

    def __repr__(self):
        return '' % self.username

    @proprty
    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):
        return check_password_hash(self.password_hash,password)


修改init函数:

#coding=utf-8
"""filename:app/__init__.py
Created 2017-05-29
Author: by anaf
note:初始化函数
"""

from flask import Flask,render_template
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from flask.ext.login import LoginManager

mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
#session_protection属性可以设置None,basic,strong提供不同的安全等级防止用户会话遭篡改
login_manager.session_protection ='strong'
login_manager.login_views = 'auth.login'
login_manager.login_message = u"请登录后访问该页面."

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)

    #添加蓝图main,auth
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint,url_prefix='/auth')

    login_manager.init_app(app)

    return app

修改models.py函数

#coding=utf-8
"""filename:app/models.py
Created 2017-05-30
Author: by anaf
note:数据库模型函数
"""

from werkzeug.security import generate_password_hash,check_password_hash
from app import db
from flask.ext.login import UserMixin
from .import login_manager

"""角色表 一对多,一个角色对应多个用户
db.relationship('User',backref='role')
因为User 还没有定义 所以使用字符串形式指定
"""
class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(64),unique=True)
    users = db.relationship('User',backref='role')

    def __repr__(self):
        return '' % self.name


class User(UserMixin,db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer,primary_key = True)
    username = db.Column(db.String(64),unique=True,index=True)
    password_hash = db.Column(db.String(128))
    role_id = db.Column(db.Integer,db.ForeignKey('roles.id'))

    def __repr__(self):
        return '' % self.username

    @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):
        return check_password_hash(self.password_hash,password)



@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

添加登陆表单,其他不用但是登陆的比较要紧所以用的话比较安全

#coding=utf-8
"""filename:app/auth/forms.py
Created 2017-05-30
Author: by anaf
"""
from flask.ext.wtf import Form
from wtforms import StringField,PasswordField,BooleanField,SubmitField
from wtforms.validators import Required,Length,Email

class LoginForm(Form):
    # email = StringField('Email',validators=[Required(),Length(1,64),Email()])
    username = StringField('Username',validators=[Required(),Length(1,64)])
    password = PasswordField('Password',validators=[Required()])
    remember_me = BooleanField('Keep me logged in ')
    submit = SubmitField('Log In')

修改函数:

#coding=utf-8
"""filename:app/main/views.py
Created 2017-05-29
Author: by anaf
"""

from flask import render_template
from . import main
from .. import db
# from ..models import User
from  flask.ext.login import login_required

@main.route('/')
def index():
    return render_template('index.html')

#需要登陆访问
@main.route('/main_login')
@login_required
def main_login():
    return render_template('main_login.html')


创建main_login.html




    
    main_login


    main_login


修改index.html




    
    index


    index 
{%if current_user is authtenticated %} 退出 {%else%} 登录 注册 {%endif%}

修改函数

#coding=utf-8
"""filename:app/auth/__init__.py
Created 2017-05-30
Author: by anaf
note:auth视图函数
"""
from flask import render_template,redirect,request,url_for,flash
from . import auth
from flask.ext.login import login_user,login_required
from ..models import User
from .forms import LoginForm

@auth.route('/login',methods=['GET'])
def login():
    return render_template('auth/login.html',form=LoginForm())

@auth.route('/login',methods=['POST'])
def login_post():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        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('main.main_login'))
        flash(u'校验数据错误')
    return redirect('.login')

@auth.route('/logout')
@login_required
def logout():
    logout_user()
    flash(u'您已成功退出')
    return redirect('main.index')

修改login.html




    
    login


    
{{form.hidden_tag()}} {{form.username.label}}{{form.username(id='myname')}}
{{form.password.label}}{{form.password}}
{{form.remember_me.label}}{{form.remember_me}}
{{form.submit()}}

添加注册信息





    
    register


    
username:
password
repassword

修改函数

#coding=utf-8
"""filename:app/auth/__init__.py
Created 2017-05-30
Author: by anaf
note:auth视图函数
"""
from flask import render_template,redirect,request,url_for,flash
from . import auth
from flask.ext.login import login_user,login_required
from ..models import User
from .forms import LoginForm

@auth.route('/login',methods=['GET'])
def login():
    return render_template('auth/login.html',form=LoginForm())

@auth.route('/login',methods=['POST'])
def login_post():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        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('main.main_login'))
        flash(u'校验数据错误')
    return redirect('.login')

@auth.route('/logout')
@login_required
def logout():
    logout_user()
    flash(u'您已成功退出')
    return redirect('main.index')


@auth.route('/register')
def register():
    return render_template('auth/register.html')

@auth.route('/register',methods=['POST'])
def register_post():
    username = request.form.get('username')
    passwrod = request.form.get('password')
    repassword = request.form.get('repassword')
    if password !=repassword: 
        flash(u'两次密码不一样')
        return redirect(url_for('.register'))
    user = User.query.filter_by(username=username).first()
    if user is  None and len(username)>=6:
        db.session.add(user)
        flash(u'注册成功')
        return redirect(url_for('.login'))
    return render_template('auth/register.html')

初始化数据库添加数据:

python manage.py shell 
from app import db 
db.create_all()
from app.models import Role,User
admin_role = Role(name = 'admin')
mod_role = Role(name = 'Moderator')
user_role = Role(name = 'User')
user_admin = User(username='admins',role=admin_role)
user_mod = User(username='moderator',role=mod_role)
user_user = User(username='use',role=user_role)
db.session.add(admin_role)
db.session.add(mod_role)
db.session.add(user_role)
db.session.add_all([user_admin,user_mod,user_user])
db.session.commit()

运行python manage.py runserver

就可以登陆 注册了。

第九章 用户角色

修改模型:

#coding=utf-8
"""filename:app/models.py
Created 2017-05-30
Author: by anaf
note:数据库模型函数
"""

from werkzeug.security import generate_password_hash,check_password_hash
from app import db
from flask.ext.login import UserMixin,AnonymousUserMixin
from .import login_manager



#权限
class Permission:
    FOLLOW = 0x01   #关注
    COMMIT = 0x02   #在他人的文章中发表评论
    WRITE_ARTICLES = 0x03   #写文章
    MODERATE_COMMENTS = 0x04 #管理他人发表的评论
    ADMINISTER = 0x99   #管理员



"""角色表 一对多,一个角色对应多个用户
db.relationship('User',backref='role')
因为User 还没有定义 所以使用字符串形式指定
"""
class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(64),unique=True)
    default = db.Column(db.Boolean,default=False,index=True)
    permissions = db.Column(db.Integer)
    users = db.relationship('User',backref='role',lazy='dynamic')

    def __repr__(self):
        return '' % self.name

    @staticmethod
    def insert_roles():
        roles = {
            'User':(Permission.FOLLOW|
                    Permission.COMMIT|
                    Permission.WRITE_ARTICLES,True),
            'Moderator':(Permission.FOLLOW|
                    Permission..COMMIT|
                    Permission.WRITE_ARTICLES|
                    Permission.MODERATE_COMMENTS,False),
            'Administrator':(0xff,False)
        }
        for r in roles:
            role = Role.query.filter_by(name=r).first()
            if role is None:
                role = Role(name=r)
            role.permissions = roles[r][0]
            role.default = role[r][1]
            db.session.add(role)
        db.session.commit()


class User(UserMixin,db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer,primary_key = True)
    username = db.Column(db.String(64),unique=True,index=True)
    password_hash = db.Column(db.String(128))
    role_id = db.Column(db.Integer,db.ForeignKey('roles.id'))

    def __init__(self,**kwargs):
        super(User,self).__init__(**kwarrgs)
        #赋予角色信息
        if self.role is None:
            if self.username ==current_add.config['SUPERADMIN_NAME']:
                self.role = Role.query.filter_by(permissions=0xff).first()
            if self.role is None:
                self.role = Role.query.filter_by(default=True).first()

    def __repr__(self):
        return '' % self.username

    @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):
        return check_password_hash(self.password_hash,password)

    #验证角色
    def can(self,permissions):
        return self.role is not None and \
            (self.role.permissions & permissions) ==permissions
    #验证角色
    def is_administrator(self):
        return self.can(Permission.ADMINISTER)

#验证角色
class AnonymousUser(AnonymousUserMixin):
    def can(self,permissions):
        return False

    def is_administrator(self):
        return False
#验证角色
login_manager.anonymous_user = AnonymousUser

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

创建自定义装饰器给特定的权限开放

#coding=utf-8
"""filename:decorators.py
Created 2017-05-30
Author: by anaf
note: 让视图函数只对具有特定权限的用户开发 自定义装饰器
"""

from functools import wraps
from flask import abort
from flask.ext.login import current_user

def permission_required(permission):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args,**kwargs):
            if not current_user.can(permission):
                abort(403)
            return f(*args,**kwargs)
        return decorated_function
    return decorator

def admin_required(f):
    return permission_required(Permission.ADMINISTER)(f)

修改函数:

#coding=utf-8
"""filename:app/main/views.py
Created 2017-05-29
Author: by anaf
"""

from flask import render_template
from . import main
from .. import db
# from ..models import User
from  flask.ext.login import login_required
from decorators import admin_required,permission_required
from .models import Permission

@main.route('/')
def index():
    return render_template('index.html')

#需要登陆访问
@main.route('/main_login')
@login_required
def main_login():
    return render_template('main_login.html')


#需要登陆,且需要管理员权限
@main.route('/admin_main')
@login_required
@admin_required
def for_admin_only():
    return "for admin"


#需要登陆,且定义权限的函数
@main.route('/moderator')
@login_required
@permission_required(Permission.MODERATE_COMMENTS)
def for_moderators_only():
    return "for coment moderators"

以上有一些错误,也就是书本的错误,比如没有导入对应的类所以导致变量未定义。上面代码就不改正了

本章结束

第十章用户资料

修改模型,添加字段

class User(UserMixin,db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer,primary_key = True)
    username = db.Column(db.String(64),unique=True,index=True)
    password_hash = db.Column(db.String(128))
    role_id = db.Column(db.Integer,db.ForeignKey('roles.id'))
    name = db.Column(db.String(64))
    location = db.Column(db.String(64))
    about_me = db.Column(db.Text())
    member_since = db.Column(db.Datetime(),default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(),default=datetime.utcnow)
#刷新用户最后访问时间
    def ping(self):
        self.last_seen = datetime.utcnow()
        db.session.add(self)
#coding=utf-8
"""filename:app/auth/__init__.py
Created 2017-05-30
Author: by anaf
note:auth视图函数
"""
#...
@auth.before_app_request
def before_request():
    if current_user.is_authenticated:
        current_user.ping()
        #书本中还代码的  不知道方法有什么用  所以省去也没见有什么变化

你可能感兴趣的:(Flask web开发-基于python的web应用开发实战)