1. 程式人生 > >Flask小demo---代碼統計系統

Flask小demo---代碼統計系統

lis index 學生管理 __main__ b- userinfo else connect exe

功能要求:
管理員登錄 # 第一天
班級管理 # 第一天
學生管理 # 第一天
學生登錄
上傳代碼(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="123456",
    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---代碼統計系統