功能要求:
管理员登录 # 第一天
班级管理 # 第一天
学生管理 # 第一天
学生登录
上传代码(zip文件和.py文件)
查看个人提交记录列表
highchar统计
学生列表上方使用柱状图展示现班级所有人代码总数
学生提交记录列表上方使用折线图展示所有的提交记录
参考表结构(MySQL+pymysql):
管理员表
ID 用户名 密码 邮箱 班级表
ID 班级名称 学生表
ID 学生姓名 班级ID 提交记录表
ID 学生ID 提交日期 代码行数 创建数据库语句
create database statisticalrow;
use statisticalrow create table manager(
id int primary key auto_increment,
name char(32) not null,
password char(32) not null,
email varchar(30) not null); create table student(
id int primary key auto_increment,
name char(20) not null,
password char(32) not null,
class_id int,
foreign key(class_id) references class(id)); create table class(
id int primary key auto_increment,
classname char(40) not null); create table recordchart(
id int primary key auto_increment,
stu_id int,
put_date datetime not null,
row_count int not null);

代码(没有使用blueprint):

import os
import zipfile
from datetime import datetime
from functools import wraps
import pymysql
from pymysql.err import IntegrityError
from flask import Flask,render_template,request,redirect,session # 1.建立数据库连接
conn = pymysql.connect(
host="127.0.0.1",
port=3306,
user="root",
password="",
database="statisticalrow"
) # 2. 生成游标
cursor = conn.cursor()
# 上传文件路径
PROJECT_DIR = os.getcwd()
UPLOAD_FOLDER = 'uploads/demo/'
ALLOWED_EXTENSIONS = set(['txt', 'py', 'zip', 'html', 'js', 'css']) app = Flask(__name__)
app.secret_key = 'salt' def islogin(func):
@wraps(func)
def inner(*args,**kwargs):
if not session.get('username'):
return redirect('/login')
ret = func(*args,**kwargs)
return ret
return inner def auth(func):
@wraps(func)
def inner(*args, **kwargs):
userIdentity = session.get('userIdentity')
if not session.get('username'):
return redirect('/login')
if not userIdentity:
return redirect('/login')
if userIdentity != 1:
return redirect('/authwrong')
ret = func(*args, **kwargs)
return ret
return inner @app.route('/login',methods=["GET","POST"])
def login():
if request.method == 'GET':
return render_template("login.html")
else:
username = request.form.get("username")
password = request.form.get("password")
userIdentity = 0
# 3. 执行sql
# sql = "select * from student where name = '%s' and password = '%s';"%(username,password)
# sql = 'select * from userinfo where name = %s and pwd=%s;'
sql = "select * from student where name = %s and password = %s;" ret = cursor.execute(sql,[username,password]) if not ret:
sql = "select * from manager where name = %s and password = %s;"
ret = cursor.execute(sql, [username, password])
if not ret:
context = {
"msg": "用户名或密码错误"
}
username=""
password=""
userIdentity = 0
return render_template('login.html',**context)
userIdentity = 1 #老师
else:
userIdentity = 2 #学生 # 将用户信息放入cookie和session session['username'] = username
if userIdentity == 2:
cursor.execute("select classname from class where id = (select class_id from student where name = '%s');"%(username))
session['coursename'] = str(cursor.fetchone()[0])
session['userIdentity'] = userIdentity
# print( "学生" if userIdentity == 2 else "老师")
return redirect("/index") #查看所有班级
@app.route("/showclass")
@auth
def showClass():
sql = "select * from class"
cursor.execute(sql)
all_data = cursor.fetchall()
return render_template("showclass.html",all_data=all_data) @app.route("/editclass",methods=["GET","POST"])
@auth
def editClass(): if request.method == "GET":
class_id = request.args.get("class_id")
sql = "select * from class where id = %s"%(class_id)
cursor.execute(sql)
class_data = cursor.fetchall()[0]
return render_template("editclass.html",class_data=class_data) if request.method == "POST":
class_id = request.form.get("class_id")
classname = request.form.get("classname")
sql = "update class set classname = '%s' where id = %s" % (classname,class_id)
cursor.execute(sql)
# 注意:保存结果
conn.commit() return redirect("/showclass") @app.route("/addclass",methods=["GET","POST"])
@auth
def addClass():
if request.method == "GET":
return render_template("addclass.html") classname = request.form.get("classname")
sql = "insert into class (classname) values ('%s')"%(classname)
cursor.execute(sql)
# 注意:保存结果 涉及操作都要提交
conn.commit()
return redirect("/showclass") @app.route("/delclass")
@auth
def delClass():
class_id = request.args.get("class_id")
sql = "delete from class where id=%s;"%(class_id)
cursor.execute(sql)
# 注意:保存结果 涉及操作都要提交
conn.commit()
return redirect("/showclass") #学生管理
@app.route("/showstu")
@auth
def showStu():
sql = "select * from student"
cursor.execute(sql)
all_data = cursor.fetchall() #((1, 'wei', 1, '123'), (2, 'heng', 2, '123'), (3, 'hengheng', 3, '123'))
stu_data = []
for item in all_data:
sql = "select classname from class where id=%s"%(item[2])
cursor.execute(sql)
classname = cursor.fetchone()[0]
stu_data.append((item[0],item[1],classname,item[3]))
return render_template("showStu.html",all_data=stu_data) @app.route("/editstu",methods=["GET","POST"])
@auth
def editStu(): if request.method == "GET":
stu_id = request.args.get("stu_id")
sql = "select * from student where id = %s"%(stu_id)
cursor.execute(sql)
stu_data = cursor.fetchall()[0]
classsql = "select * from class"
cursor.execute(classsql)
class_data = cursor.fetchall() context = {
"stu_data":stu_data,
"class_data":class_data, } return render_template("editstu.html",**context)
if request.method == "POST":
stu_id = request.form.get("stu_id")
classinfo = request.form.get("classinfo") sql = "update student set class_id = '%s' where id = %s" % (classinfo,stu_id)
cursor.execute(sql)
# # 注意:保存结果
conn.commit() return redirect("/showstu") @app.route("/addstu",methods=["GET","POST"])
@auth
def addStu():
if request.method == "GET":
#获取所有的班级
classsql = "select * from class" cursor.execute(classsql)
class_data = cursor.fetchall() context = {
"class_data": class_data,
} return render_template("addstu.html",**context) username= request.form.get("username")
password = request.form.get("password")
classinfo = request.form.get("classinfo")
sql = "insert into student(name,class_id,password) values ('%s','%s','%s')"%(username,classinfo,password)
cursor.execute(sql)
conn.commit() return redirect('/showstu') @app.route("/delstu")
@auth
def delStu():
stu_id = request.args.get("stu_id")
sql = "delete from student where id = '%s'"%(stu_id)
cursor.execute(sql)
conn.commit()
return redirect('/showstu') @app.route('/index')
@islogin
def index():
# 判断是学生,还是老师
# 如果是学生,重定向到 /stuindex
userIdentity = session.get('userIdentity')
if userIdentity == 1:
return redirect('/manindex')
elif userIdentity == 2:
return redirect('/stuindex')
else:
return redirect('/login') @app.route('/stuindex',methods=["GET","POST"])
@islogin
def stuindex():
if request.method == "GET":
return render_template("stuindex.html")
classname = session.get('coursename')
username = session.get('username')
file = request.files['file'] #ALLOWED_EXTENSIONS
filename = file.filename if not filename.split(".")[1] in ALLOWED_EXTENSIONS:
return "文件类型错误" path = PROJECT_DIR + os.sep + UPLOAD_FOLDER
os.chdir(path)
path = os.getcwd() + os.sep + classname + os.sep + username if not os.path.exists(path):
os.makedirs(classname + os.sep + username) save_path = os.path.join(path, filename)
# f = open(save_path, 'wb')
with open(save_path,'wb') as f:
file.save(f) # ret = file.save(f)
# 判断是否是zip包 if filename.split(".")[1] == "zip":
# # 将zip包解压
print(filename)
zippath = path + os.sep + filename
os.chdir(path + os.sep) zipFile = zipfile.ZipFile(""+ filename +"", mode="r")
if not os.path.exists(os.getcwd() + os.sep + filename.split(".")[0]):
os.makedirs(os.getcwd() + os.sep + filename.split(".")[0])
os.chdir(os.getcwd() + os.sep + filename.split(".")[0])
for name in zipFile.namelist():
utf8name = name.encode('cp437').decode('gbk')
# print("Extracting" + utf8name)
pathname = os.path.dirname(utf8name)
if not os.path.exists(pathname) and pathname != "":
os.makedirs(pathname)
data = zipFile.read(name)
if not os.path.exists(utf8name):
fo = open(utf8name, "wb")
fo.write(data)
fo.close()
count = 1
for dirpath, dirnames, filenames in os.walk(os.getcwd()):
for filepath in filenames:
filepath = os.path.join(dirpath, filepath)
print(filepath)
with open(filepath, 'rb') as f:
for line in f.readlines():
print(line)
count = count + 1 stu_id = 0
put_date = "" sql = "select id from student where name = '%s'"%(username)
cursor.execute(sql)
stu_id = cursor.fetchone()[0]
put_date = datetime.strptime('Apr-16-2017 21:01:35', '%b-%d-%Y %H:%M:%S') # sql = "select * from student where name = %s and password = %s;" # ret = cursor.execute(sql, [username, password])
try:
sql2 = "insert into recordchart (stu_id, put_date, row_count) values (%s,%s,%s);"
cursor.execute(sql2,[stu_id,put_date,count]) conn.commit()
except IntegrityError as e:
msg = "今日已提交!"
context={
"msg":msg,
"tag":2
}
return render_template("wrong.html",**context) return "上传成功!,demo行数:" + str(count) count = 0
with open(save_path, 'r') as f:
for line in f.readlines():
count = count + 1 return "上传成功!,demo行数:" + str(count) @app.route('/manindex')
@islogin
def manindex():
return "老师主页" @app.route('/authwrong')
def authwrong():
msg = "权限不足"
context = {
"msg": msg,
"tag": 1
}
return render_template("wrong.html",**context) @app.route('/loginout')
def loginout():
del session['username']
return "删除成功"
if __name__ == "__main__":
app.run()

Flask小demo---代码统计系统的更多相关文章

  1. 1.6 flask应用: 代码统计系统

    2019-1-6 15:57:18 今天的是做了一个代码统计的demo 使用了数据库的连接池 参考连接 https://www.cnblogs.com/wupeiqi/articles/8184686 ...

  2. 写了一个类似与豆瓣的电影的flask小demo

    先展示页面 基本的功能是都已经实现了,更多那个地方是可以点的.只不过视频上面还用的宏,哎呀,感觉麻烦.有多麻烦呢,需要先定义一个宏,然后进行引用.我们才能是用,以我的观点,还不如直接是一个循环完事.. ...

  3. Android -BLE蓝牙小DEMO

    代码地址如下:http://www.demodashi.com/demo/13890.html 原文地址: https://blog.csdn.net/vnanyesheshou/article/de ...

  4. jsoup爬虫简书首页数据做个小Demo

    代码地址如下:http://www.demodashi.com/demo/11643.html 昨天LZ去面试,遇到一个大牛,被血虐一番,发现自己基础还是很薄弱,对java一些原理掌握的还是不够稳固, ...

  5. 仿百度下拉关键词,和关键词的小demo

    自己做项目时用到的仿百度下拉关键词 代码: $(function(){ var oTxt = document.getElementById('search_text'); oTxt.onkeyup ...

  6. js特效 15个小demo

    js特效和15个小demo 代码如下:images文件夹未上传 1.图片切换: <!DOCTYPE html> <html> <head> <title> ...

  7. 好用的代码统计小工具SourceCounter(下载)

    SourceCounter下载链接 https://pan.baidu.com/s/12Cg51L0hRn5w-m1NQJ-Xlg 提取码:i1cd 很多时候我们需要统计自己所写的代码的数量.举个栗子 ...

  8. Ztree小demo用于系统授权

    本示例只做到指定id用户的拥有的权限回显,并能动态获得ztree中重新选择的权限id.(至于权限的更新,就是后台人员对象和权限对象建立关系的过程,不做展示) 第一步:拼写jsp页面(下载ztree包, ...

  9. Nancy之基于Self Hosting的补充小Demo

    前面把Hosting Nancy with ASP.NET.Self Hosting Nancy和Hosting Nancy with OWIN 以demo的形式简单描述了一下. 这篇是为Self H ...

随机推荐

  1. Alpha 冲刺 —— 十分之三

    队名 火箭少男100 组长博客 林燊大哥 作业博客 Alpha 冲鸭鸭鸭! 成员冲刺阶段情况 林燊(组长) 过去两天完成了哪些任务 协调各成员之间的工作 协助后端界面的开发 搭建项目运行的服务器环境 ...

  2. BZOJ4870 [Shoi2017]组合数问题 【组合数 + 矩乘】

    题目链接 BZOJ4870 题解 \[ans = \sum\limits_{i = 0}^{\infty}{nk \choose ik + r} \pmod p\] 发现实际是求 \[ans = \s ...

  3. 【spoj SUBLEX】 Lexicographical Substring Search

    http://www.spoj.com/problems/SUBLEX/ (题目链接) 题意 给出一个字符串,询问其中字典序第K小的子串. Solution 后缀自动机例题. 构出后缀自动机以后,对每 ...

  4. Raven: 2靶机入侵

    0x00 前言 Raven 2是一个中等难度的boot2root 虚拟靶机.有四个flag需要找出.在多次被攻破后,Raven Security采取了额外措施来增强他们的网络服务器安全以防止黑客入侵. ...

  5. 《Linux内核设计与实现》第18章读书笔记

    第十八章 调试 一.调试开始前的准备 1.准备开始 bug 藏匿bug的版本 相关内核代码的知识 成功调试的关键在于能否将错误重现 2.内核中的bug 其产生原因无数,表象变化也多种多样.从隐藏在源代 ...

  6. 「CodePlus 2017 12 月赛」火锅盛宴(模拟+树状数组)

    1A,拿来练手的好题 用一个优先队列按煮熟时间从小到大排序,被煮熟了就弹出来. 用n个vector维护每种食物的煮熟时间,显然是有序的. 用树状数组维护每种煮熟食物的数量. 每次操作前把优先队列里煮熟 ...

  7. bzoj 4871: [Shoi2017]摧毁“树状图”

    4871: [Shoi2017]摧毁“树状图” Time Limit: 25 Sec  Memory Limit: 512 MBSubmit: 53  Solved: 9[Submit][Status ...

  8. Python之旅:入门

    一 编程与编程语言 python是一门编程语言,作为学习python的开始,需要事先搞明白:编程的目的是什么?什么是编程语言?什么是编程? 编程的目的: #计算机的发明,是为了用机器取代/解放人力,而 ...

  9. where EXISTS (子查询)多对多中通过中间表查对方列表

    用户表A,小组表B,小组和用户是多对多关系,中间有个中间表M 已知 小组 id 即teamId ,想知道这个小组中的用户列表信息,可以如下写sql: select * from A a where E ...

  10. C++下实现同接口下多个类作为参数的调用和传参

    /* 实现同接口下不同类的对象的转移 定义类的接口 定义多个继承该接口的类 定义管理类,把接口当作类型, 传入该接口下各种类的对象,进行操作 */ #include<iostream> # ...