文章目录
- Day5
- 404
- 创建管理员
- 管理员登录
- 用户统计
- 防止用户进入admin页面
- gunicorn运行项目
- nginx
- Docker部署服务器
- 建立docker镜像
Day5
404
# 统一返回404页面
@index_bp.route('/404')
@user_login_data
def page_not_found():data = {"user_info": g.user.to_dict() if g.user else ""}return render_template('news/404.html', data=data)
创建管理员
定义方法,创建管理员对象
@manager.option 给manager添加一个脚本运行的方法
python manager.py create_superuser -u 账号 -p 密码
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from flask import current_app# 导入models的作用是让整个应用程序知道有models的存在
from info import create_app, db, models
from info.models import Userapp = create_app('develop')# 创建manager对象, 管理app
manager = Manager(app)# 使用Migrate 关联app, db
Migrate(app, db)# 给manager 添加一条操作命令
manager.add_command("db", MigrateCommand)# 定义方法,创建管理员对象
# @manager.option 给manager添加一个脚本运行的方法
# 参数1:在调用方法的时候传递的参数名称
# 参数2:对参数1的解释
# 参数3:目的参数,用户传递给形式参数使用
@manager.option('-u', '--username', dest='username')
@manager.option('-p', '--password', dest='password')
def create_superuser(username, password):# 1.创建用户对象admin = User()# 2.设置用户属性admin.nick_name = usernameadmin.mobile = usernameadmin.password = passwordadmin.is_admin = True# 3.保存到数据库try:db.session.add(admin)db.session.commit()except Exception as e:current_app.logger.error(e)return '创建失败'return '创建成功'if __name__ == '__main__':manager.run()
管理员登录
# 获取/登陆,管理员登陆
# 请求路径: /admin/login
# 请求方式: GET,POST
# 请求参数:GET,无, POST,username,password
# 返回值: GET渲染login.html页面, POST,login.html页面,errmsg
@admin_bp.route('/login', methods=['GET', 'POST'])
def admin_login():# 1.判断请求方式,如果是GET,直接渲染页面if request.method == 'GET':# 判断管理员是否已经登录过了,如果登录了直接跳转到首页if session.get('is_admin'):return redirect('/admin/index')return render_template('admin/login.html')# 2.如果是POST请求,获取参数username = request.form.get('username')password = request.form.get('password')# 3.为空校验if not all([username, password]):return render_template('admin/login.html', errmsg='参数不全')# 4.根据用户名取出管理员对象,判断管理员是否存在try:admin = User.query.filter(User.mobile == username,User.is_admin == True).first()except Exception as e:current_app.logger.error(e)return render_template('admin/login.html', errmsg='用户查询失败')if not admin:return render_template('admin/login.html', errmsg='管理员不存在')# 5.判断管理员的密码是否正确if not admin.check_password(password):return render_template('admin/login.html', errmsg='密码错误')# 6.管理员的session信息记录session['user_id'] = admin.idsession['is_admin'] = True# 7.重定向到首页展示return redirect('/admin/index')
用户统计
# 用户统计
# 请求路径: /admin/user_count
# 请求方式: GET
# 请求参数: 无
# 返回值:渲染页面user_count.html,字典数据
@admin_bp.route('/user_count')
def user_count():# 1.获取用户总数try:total_count = User.query.filter(User.is_admin == False).count()except Exception as e:current_app.logger.error(e)return render_template("admin/user_count.html",errmsg="获取总人数失败")#2.获取月活人数localtime = time.localtime()try:#2.1先获取本月的1号的0点的, 字符串数据month_start_time_str = "%s-%s-01"%(localtime.tm_year,localtime.tm_mon)#2.2根据字符串,格式化日期对象month_start_time_date = datetime.strptime(month_start_time_str,"%Y-%m-%d")#2.3最后一次登陆的时间大于,本月的1号的0点钟的人数month_count = User.query.filter(User.last_login >= month_start_time_date,User.is_admin == False).count()except Exception as e:current_app.logger.error(e)return render_template("admin/user_count.html", errmsg="获取月活人数失败")#3.获取日活人数try:# 2.1先获取本日的0点, 字符串数据day_start_time_str = "%s-%s-%s" % (localtime.tm_year, localtime.tm_mon,localtime.tm_mday)# 2.2根据字符串,格式化日期对象day_start_time_date = datetime.strptime(day_start_time_str, "%Y-%m-%d")# 2.3最后一次登陆的时间大于,本日0点钟的人数day_count = User.query.filter(User.last_login >= day_start_time_date,User.is_admin == False).count()except Exception as e:current_app.logger.error(e)return render_template("admin/user_count.html", errmsg="获取日活人数失败")#4.获取活跃时间段内,对应的活跃人数active_date = [] # 获取活跃的日期active_count = [] # 获取活跃的人数for i in range(0,31):# 当天开始时间Abegin_date = day_start_time_date - timedelta(days=i)# 当天开始时间, 的后⼀一天Bend_date = day_start_time_date - timedelta(days=i - 1)# 添加当天开始时间字符串串到, 活跃⽇日期中active_date.append(begin_date.strftime("%Y-%m-%d"))# 查询时间A到B这⼀一天的注册⼈人数everyday_active_count = User.query.filter(User.is_admin == False,User.last_login >=begin_date,User.last_login<=end_date).count()# 添加当天注册⼈人数到,获取数量量中active_count.append(everyday_active_count)#为了图表显示方便,将容器反转active_count.reverse()active_date.reverse()#5.携带数据渲染页面data = {"total_count":total_count,"month_count":month_count,"day_count":day_count,"active_date":active_date,"active_count":active_count}return render_template("admin/user_count.html",data=data)
前端
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>新经资讯后台管理</title><link rel="stylesheet" type="text/css" href="../../static/admin/css/reset.css"><link rel="stylesheet" type="text/css" href="../../static/admin/css/main.css"><script type="text/javascript" src="../../static/admin/js/echarts.min.js"></script>
</head>
<body><div class="breadcrub">当前位置:用户管理>用户统计</div><div class="spannels"><div class="spannel scolor01"><em>{{ data.total_count }}</em><span>人</span><b>用户总数</b></div><div class="spannel scolor02"><em>{{ data.month_count }}</em><span>人</span><b>用户月活数</b></div><div class="spannel2 scolor03"><em>{{ data.day_count }}</em><span>人</span><b>用户日活数</b></div></div><div class="pannel"><div id="chart_show" class="chart_show"></div></div><script>var oChart = echarts.init(document.getElementById('chart_show'));var chartopt = {title:{text: '用户登录活跃数',left: 'center',top: '10'},tooltip:{trigger: 'axis'},legend: {data:['active'],top: '40'},toolbox: {show : true,feature : {mark : {show: true},dataView : {show: true, readOnly: false},magicType : {show: true, type: ['line','bar']},restore : {show: true},saveAsImage : {show: true}}},calculable : true,xAxis : [{name: '今天',type : 'category',boundaryGap : false,{#data : ["08:15","09:15","10:15","11:15","12:15","13:15","14:15","15:15","16:15","17:15","18:15","19:15"]#}data : {{ data.active_date | safe}}}],yAxis : [{name: '活跃用户数量',type : 'value'}],series : [{name:'active',type:'line',smooth:true,itemStyle: {normal: {areaStyle: {type: 'default'}, color: '#f80'}, lineStyle: {color: '#f80'}},{#data:[14951,14861,7186,15861,14951,14861,7186,14951,14861,7186,15861,14951]#}data:{{ data.active_count }}}],areaStyle:{normal:{color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{offset: 0,color: 'rgba(0,255,0,0.8)'}, {offset: .34,color: 'rgba(255,180,0,0.25)'},{offset: 1,color: 'rgba(255,0,0,1.00)'}])}}};oChart.setOption(chartopt);</script>
</body>
</html>
防止用户进入admin页面
admin/init.py
# 使用请求钩子,拦截用户的请求,只有访问了admin_bp,所装饰的视图函数需要拦截
# 1.拦截的是访问了非登录页面
# 2.拦截的是普通用户
@admin_bp.before_request
def before_request():# 判断访问的是否是非登录页面if not request.url.endswith('/admin/login'):if not session.get('is_admin'):return redirect('/')
gunicorn运行项目
nginx
upstream new{server 127.0.0.1:6001;}server {listen 6000;server_name 127.0.0.1;location / {proxy_pass http://new;}error_page 500 502 503 504 /50x.html;}
Docker部署服务器
用Navicat连接服务器的 MariDB 数据库,导入 .sql文件失败,在服务器上用 source 命令成功了, what???
建立docker镜像
-
docker build
docker build -t information_flask .
-
docker run
docker run -itd --net=host --name information information_flask