python高级实践Day01 --动态个人主页的搭建全过程,练手案例

设计网页内容

预览图如下

python高级实践Day01 --动态个人主页的搭建全过程,练手案例_第1张图片

前端编写

主页效果图(简直一模一样/(ㄒoㄒ)/~~)

后端功能实现

计划和笔记内容的读取

计划的添加删除打卡

学习笔记的添加,分专栏查询,内容概要模糊查询

目录结构如下

python高级实践Day01 --动态个人主页的搭建全过程,练手案例_第2张图片

代码如下

frame.py

import json
import logging
import urllib
import requests
import pymysql
import datetime

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s-%(filename)s[line:%(lineno)d]-%(levelname)s:%(message)s',
                    filename='log.txt',
                    filemode="a",
                    encoding="utf-8"
                    )
func_list = {}


def route(data):
    def func_out(func):
        func_list[data] = func

        def func_inner():
            pass

        return func_inner

    return func_out


@route("/index.html")
def index():
    with open("./template/index.html", "rb") as f:
        file_data = f.read()
        return file_data.decode()


@route("/search_plan.html")
def search_plan():
    conn = pymysql.Connect(host="localhost",
                           port=3306,
                           database="gyq",
                           user="root",
                           password="root",
                           charset="utf8"
                           )
    cursor = conn.cursor()
    sql = "SELECT p_content,p_time FROM plan WHERE p_status =0"
    cursor.execute(sql)
    data = cursor.fetchall()
    data_list = [{
        "content": row[0],
        "time": str(row[1]),
    } for row in data]
    json_str = json.dumps(data_list)
    return json_str
    cursor.close()
    conn.close()


@route("/search_done.html")
def search_done():
    conn = pymysql.Connect(host="localhost",
                           port=3306,
                           database="gyq",
                           user="root",
                           password="root",
                           charset="utf8"
                           )
    cursor = conn.cursor()
    sql = "SELECT p_content,p_time FROM plan WHERE p_status =1"
    cursor.execute(sql)
    data = cursor.fetchall()
    data_list = [{
        "content": row[0],
        "time": str(row[1]),
    } for row in data]
    json_str = json.dumps(data_list)
    return json_str
    cursor.close()
    conn.close()


@route("/search_article.html")
def search_article():
    conn = pymysql.Connect(host="localhost",
                           port=3306,
                           database="gyq",
                           user="root",
                           password="root",
                           charset="utf8"
                           )
    cursor = conn.cursor()
    sql = "SELECT a_title,a_href,a_simple,a_time FROM article"
    cursor.execute(sql)
    data = cursor.fetchall()
    data_list = [{
        "title": row[0],
        "time": str(row[3]),
        "simple": row[2],
        "href": row[1],
    } for row in data]
    json_str = json.dumps(data_list)
    return json_str
    cursor.close()
    conn.close()


@route("/search_type.html")
def search_type():
    conn = pymysql.Connect(host="localhost",
                           port=3306,
                           database="gyq",
                           user="root",
                           password="root",
                           charset="utf8"
                           )
    cursor = conn.cursor()
    sql = "SELECT DISTINCT a_type FROM article"
    cursor.execute(sql)
    data = cursor.fetchall()
    data_list = [{
        "type": row[0],
    } for row in data]
    json_str = json.dumps(data_list)
    return json_str
    cursor.close()
    conn.close()


@route("/add_plan.html")
def add_plan(datalist):
    plan = datalist[0];
    time = datalist[1];
    plan = urllib.parse.unquote(plan)
    conn = pymysql.Connect(host="localhost",
                           port=3306,
                           database="gyq",
                           user="root",
                           password="root",
                           charset="utf8"
                           )
    cursor = conn.cursor()
    sql = "INSERT INTO plan(p_content,p_time,p_status) VALUES('" + plan + "','" + time + "',0);"
    cursor.execute(sql)
    cursor.close()
    conn.commit()
    conn.close()
    return "添加成功"


@route("/add_article.html")
def add_article(datalist):
    title = datalist[0];
    simple = datalist[1];
    type = datalist[2];
    href = datalist[3];
    type = urllib.parse.unquote(type)
    title = urllib.parse.unquote(title)
    simple = urllib.parse.unquote(simple)
    href = urllib.parse.unquote(href)
    print(title)
    print(type)
    print(simple)
    print(href)
    conn = pymysql.Connect(host="localhost",
                           port=3306,
                           database="gyq",
                           user="root",
                           password="root",
                           charset="utf8"
                           )
    cursor = conn.cursor()
    sql = 'INSERT INTO article(a_title,a_href,a_simple,a_time,a_type) VALUES("' + title + '","' + href + '","' + simple + '",NOW(),"' + type + '")'
    print(sql)
    cursor.execute(sql)
    cursor.close()
    conn.commit()
    conn.close()
    return "添加成功"


@route("/change_plan.html")
def change_plan(datalist):
    plan = datalist[0]
    plan = urllib.parse.unquote(plan)
    gettime = datetime.date.today()
    time = str(gettime.year) + "-" + str(gettime.month) + "-" + str(gettime.day)

    conn = pymysql.Connect(host="localhost",
                           port=3306,
                           database="gyq",
                           user="root",
                           password="root",
                           charset="utf8"
                           )
    cursor = conn.cursor()
    sql = 'UPDATE plan SET p_status=1,p_time="' + time + '" WHERE  p_content="' + plan + '"'
    cursor.execute(sql)
    cursor.close()
    conn.commit()
    conn.close()
    return "打卡成功"


@route("/change_article.html")
def change_article(datalist):
    type = datalist[2]
    type = urllib.parse.unquote(type)
    conn = pymysql.Connect(host="localhost",
                           port=3306,
                           database="gyq",
                           user="root",
                           password="root",
                           charset="utf8"
                           )
    cursor = conn.cursor()
    if type == 'all':
        sql = 'SELECT a_title,a_href,a_simple,a_time FROM article'
    else:
        sql = 'SELECT a_title,a_href,a_simple,a_time FROM article WHERE a_type="' + type + '"'
    cursor.execute(sql)
    data = cursor.fetchall()
    data_list = [{
        "title": row[0],
        "href": row[1],
        "simple": row[2],
        "time": str(row[3]),
    } for row in data]
    json_str = json.dumps(data_list)
    return json_str
    cursor.close()
    conn.close()


@route("/find_article.html")
def find_article(datalist):
    type = datalist[2]
    type = urllib.parse.unquote(type)
    conn = pymysql.Connect(host="localhost",
                           port=3306,
                           database="gyq",
                           user="root",
                           password="root",
                           charset="utf8"
                           )
    cursor = conn.cursor()

    sql = 'SELECT a_title,a_href,a_simple,a_time FROM article WHERE a_title LIKE "%' + type + '%" OR a_simple LIKE "%' + type + '%"'
    print(sql)
    cursor.execute(sql)
    data = cursor.fetchall()
    data_list = [{
        "title": row[0],
        "href": row[1],
        "simple": row[2],
        "time": str(row[3]),
    } for row in data]
    json_str = json.dumps(data_list)
    return json_str
    cursor.close()
    conn.close()


@route("/drop_plan.html")
def drop_plan(datalist):
    plan = datalist[0]
    plan = urllib.parse.unquote(plan)
    conn = pymysql.Connect(host="localhost",
                           port=3306,
                           database="gyq",
                           user="root",
                           password="root",
                           charset="utf8"
                           )
    cursor = conn.cursor()
    sql = 'DELETE FROM plan WHERE  p_content="' + plan + '"'
    cursor.execute(sql)
    cursor.close()
    conn.commit()
    conn.close()
    return "删除成功"


def error():
    return "404 ERROR"


def application(requests_path):
    try:
        func = func_list[requests_path]
        return func()
    except Exception as e:
        logging.error("get访问动态资源错误路径:" + str(e))
        return error()


def application1(requests_path, datalist):
    try:
        func = func_list[requests_path]
        return func(datalist)
    except Exception as e:
        logging.error("post访问动态资源错误路径:" + str(e))
        return error()

index.css

body{
    text-align: center;      
}
#sign{
    position:absolute;
    width: 100px;
    float: left;
    left: 10%;
}
hr{
    margin-top: 20px;

}
.title{
    font-size: 45px;
}

#header{
    margin-top: 20px;

}
#body{
    margin-top: 30px;
    width: 100%;
}
th{
    width: 20%;
    font-size: 20px;
}
#navigation,#content,#article{
    width: 100%;
    position:relative;
    margin-top: 10px;
} 
#mid{
    height: 500px;
    background:url("./background.jpg");
}
#bottom{
    width: 100%;
} 
#csdn:visited{
    font-size: 20px;
    color: #000;
}
#csdn{
    font-size: 20px;
    text-decoration: none;
}
#btn{
    position:absolute;
    float: right;
    top: 700px;
    right: 30%;
    color: orangered;
}
#span1{
    position:absolute;
    left: 30%;
}
#span2{
    position:absolute;
    right: 35%;
}
#web{
    width: 5%;
    position: absolute;
    top: 17%;
    left: 8%;
    background-color: rgba(255, 69, 0, 0.7);
    display: block;
}
#plan{
    width: 28%;
    position: absolute;
    top: 17%;
    left: 16%;
    background-color: rgba(255,69,0,0.7);
    display: block;
}
#safe{
    width: 5%;
    position: absolute;
    top: 17%;
    left: 47.5%;
    background-color: rgba(255, 69, 0, 0.7);
    display: block;
}
#play{
    width: 5%;
    position: absolute;
    top: 17%;
    left: 67%;
    background-color: rgba(255, 69, 0, 0.7);
    display: block;
}
.ing>td>a{
    font-size :2px ;
}
#plan>table{
    width: 100%;
}

#web>span>a{
    font-size: 1px;
    text-decoration: none;
}
#web>span>a:visited{
    font-size: 1px;
    color: rgb(180, 173, 173);
}
#article>tr>td>a{
    font-size: 15px;
    text-decoration: none;
}
#article>tr>td>a:visited{
    font-size: 15px;
    color: #ed1941;
}
#web>span>img{
    width: 20px;
}
#safe>span>a{
    font-size: 1px;
    text-decoration: none;
}
#safe>span>a:visited{
    font-size: 1px;
    color: rgb(180, 173, 173);
}
#safe>span>img{
    width: 20px;
}
#play>span>a{
    font-size: 1px;
    text-decoration: none;
}
#play>span>a:visited{
    font-size: 1px;
    color: rgb(180, 173, 173);
}
#play>span>img{
    width: 20px;
}
#content{
margin-top:25px;
}
#add_div{
    width: 40%;
    position: absolute;
    top: 62.3%;
    left: 49%;
    background-color: rgba(255,69,0,0.7);
    display: block;
}

index.html




    
    
    
    
    
    
    个人主页




学习笔记



文章标题 文章概要 记录时间
新增计划 计划耗时 添加
进行中 截至日期 处理
已完成 完成日期 处理

server.py

import logging
import socket
import threading
import re
import dynamic.frame
import win32api, win32gui

ct = win32api.GetConsoleTitle()

hd = win32gui.FindWindow(0, ct)

win32gui.ShowWindow(hd, 0)


def handle_client(client_socket):
    client_requests_data = client_socket.recv(1024).decode()
    requests_data = client_requests_data.split(" ")
    if len(requests_data) == 1:
        client_socket.close()
        return
    requests_path = requests_data[1]
    if requests_path.endswith(".html"):
        logging.info("动态资源" + requests_path)
        response_line = "HTTP/1.1 200 OK\r\n"
        response_header = "content-type: text/html; charset=utf-8\r\n"
        if requests_data[0] == "POST":
            requests_data[-1] += 'end'
            str = "plan=(.*?)&"
            plan = re.findall(str, requests_data[-1])
            str2 = "time=(.*?)&"
            time = re.findall(str2, requests_data[-1])
            str3 = "type=(.*?)&"
            type = re.findall(str3, requests_data[-1])
            str4 = "href=(.*?)end"
            href = re.findall(str4, requests_data[-1])
            datalist = [plan[0], time[0], type[0], href[0]]
            response_body = dynamic.frame.application1(requests_path, datalist)
        else:
            response_body = dynamic.frame.application(requests_path)
        response_data = (response_line + response_header + "\r\n" + response_body).encode()
        client_socket.send(response_data)
    else:
        logging.info("静态资源" + requests_path)
        try:
            with open("./static" + requests_path, 'rb') as f:
                file_data = f.read()
        except Exception as e:
            logging.error("访问静态资源错误路径:" + str(e))
            response_line = "HTTP/1.1 404 Not Found\r\n"
            response_header = "Server:pwd\r\n"
            response_body = "404 NOT FOUND"
            response_data = (response_line + response_header + "\r\n" + response_body).encode()
            client_socket.send(response_data)
        else:
            response_line = "HTTP/1.1 200 OK\r\n"
            response_header = "Server:pwd\r\n"
            response_body = file_data
            response_data = (response_line + response_header + "\r\n").encode() + response_body
            client_socket.send(response_data)
        finally:
            client_socket.close()


if __name__ == '__main__':
    tcp_sever_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
    tcp_sever_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    tcp_sever_socket.bind(("", 8081))
    tcp_sever_socket.listen(128)
    while True:
        client_socket, addr = tcp_sever_socket.accept()
        client_thread = threading.Thread(target=handle_client, args=((client_socket,)))
        client_thread.start()

    tcp_server_socket.close()

设置python服务器开机自启动

python程序开机自启动 - 程序猿·胖虎 - 博客园 (cnblogs.com)

设置浏览器打开时页面为https:localhost:8081/index.html

之后打开电脑,打开浏览器首页就是个人主页了,nice!

你可能感兴趣的:(Python高级,python,开发语言,后端)