专业编程基础技术教程

网站首页 > 基础教程 正文

57个挑战之57(part6):客户端+web前端+服务端代码实现

ccvgpt 2024-10-29 13:21:32 基础教程 16 ℃

上题目:

接前面:

57个挑战之57(part6):客户端+web前端+服务端代码实现

https://www.toutiao.com/article/7131944951776150056/

https://www.toutiao.com/article/7129048315920335399/

https://www.toutiao.com/article/7128604966595920414/

https://www.toutiao.com/article/7128196832081183236/

上一篇:

https://www.toutiao.com/article/7133396498141954595/

上面设计好逻辑之后,主要做代码实现:

代码:57-57clientsidev5.py

import requests
import random
import time
from flask import Flask,request,render_template,url_for,redirect
import redis
from redis import StrictRedis,ConnectionPool
import json
app = Flask(__name__)



def get_data():
    """
    函数作用:从服务端读入题库,以JSON格式返回
    输入:无
    返回:从服务端题库随机读取10个题目,并返回
    """
    print("start process get_data")
    url = "http://127.0.0.1:8008/get"
    ret = requests.post(url)
    dic1 = ret.json()
    print("end process get_data")
    return dic1


def orderlize(questionlist):
    """
    函数作用:读入列表,并把列表做处理,按照列表中每个字典的‘R’(难度) 大小排序。
    输入:问题list列表
    返回:根据'R‘排序后的问题列表
    """
    print("start process orderlize")
    print("列表通过难度值进行排序")
    sortedlist = sorted(questionlist,key = lambda i : i['R'])
    print(sortedlist)
    print("end process orderlize")
    return sortedlist


def randomlize_input(dic1):
    """
    函数作用:输入问题,对这个问题里面的答案和干扰项目做随机化,并返回给展示界面,包含问题、正确答案、随机化的答案+干扰项目
    输入:问题list 列表中的每一个对象(字典对象)
    输出:返回这个字典
    """
    list1 = [dic1['A'], dic1['D1'], dic1['D2'], dic1['D3']]
    listrandom = random.sample(list1,4)
    return dic1['Q'],dic1['A'],listrandom


@app.route('/',methods=['GET','POST'])
def start_html():
    """
    1.get请求打开首页,选择开始答题。
      介绍规则,选择10道题,然后从容易往复杂进行答复,如果答题错误则结束。
    2.post请求 展示开始答题
      跳转到函数答题
    """
    #逻辑1:点击开始答题,读取题库信息

    if request.method == "POST": #这里是web端提交了开始答题,
       name = request.form["name"]
       print("考生名字:{0}".format(name))
       timetitle=time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())
       print("时间:{0}".format(timetitle))
       token = hash(name+timetitle) #根据考生名字和时间产生考号token
       print(token)
       count = 0  #因为是第一次答题,count 初始化为0
       return redirect(url_for('start_question',token=token,count=0))


    if request.method == "GET":
       #1.展示首页,展示"开始答题"
       #1.1 点击开始答题发送请求到后端开始答题
       return render_template('index57.html')


@app.route('/question',methods=['GET','POST'])
def start_question():
    if request.method == "POST": #其实这个逻辑没有太多变化。
       totalcorrectquestion = request.json["count"]
       info = "total answered correct question is {0}".format(totalcorrectquestion)
       print(info)
       #2.1 接收用户选择,
       return render_template('finish.html',info=info)

    if request.method == "GET":
       # 接收传入的数据,count 及 token,并基于token在redis池中读取数据。
       # 当count 为0的时候,把数据缓存到redis池中。
       # 当count 为1的时候,把数据从redis池中取出。
       valueargs = request.args 
       print(valueargs) #debug
       count = int(valueargs.get('count'))
       token = valueargs.get('token')
       print("we have received 'count', value is {0}".format(count))
       pool = ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True) #连接本地数据库
       r = StrictRedis(connection_pool=pool) #进入连接池
       #如果count为0,调用get_data()函数,并缓存数据到本地redis,
       #读出列表中第一个数据,并展示到web端
       if  count == 0: 
           print("initialize")
           dic1 = get_data() #调用get_data()函数
           print(dic1) #debug
           questionlist = dic1['data'] #缓存返回的list数据
           sortedlist = orderlize(questionlist)  #把返回的list数据做排序
           print(sortedlist) #debug 展示排序后的数据
           r.hset("Qlib",token,json.dumps(sortedlist))#把排序后的数据,sortedlist存储到本地redis
           Q, A, listrandom = randomlize_input(sortedlist[count])  # 取出第count道题,并做排序
           print("it's {0} round,the question is {1} and the answer is {2}".format(count, Q, A))
           return render_template('start_question7.html', Q=Q, A=A, listrandom=listrandom, count=count, token=token) #如果count为0,表示初始化,这个时候传递列表第一个元素到客户端。
        #如果count为不为0,从本地redis读取缓存的数据
        #取列表中第count 个数据,并展示到前端
        else: #如果count不为0,则进入下一个逻辑
           sorted_list_json = r.hget("Qlib", token) #从本地内存中读取数据
           sortedlist = json.loads(sorted_list_json) #把数据存储起来,
           print("come to next question") #跳到下一个问题
           print(sortedlist)
           print(len(sortedlist))
           #从本地读取sortedlist到内存
           if  int(count)<len(sortedlist): #如果count的长度比sortedlist要短,则执行取题的操作
               print(count)
               Q, A, listrandom = randomlize_input(sortedlist[count])  # 取出第count道题,并做排序
           if int(count)==len(sortedlist): #表示所有题目已经做完了,而且都正确了
               info = "Congratulations, user {0} has finished all the question".format(token)
               print(info)
               return render_template('finish.html',info=info)
           print("it's {0} round,the question is {1} and the answer is {2}".format(count, Q, A))
           return render_template('start_question7.html', Q=Q, A=A, listrandom=listrandom, count=count, token=token) #取出题目,并发送到web端



@app.route('/statistic',methods=['GET','POST'])
def take_account():
    # 当到这个界面,表示没有完全做完,这里做个统计即可,表示做完几道题。
    valueargs = request.args
    print(valueargs)  # debug
    count = int(valueargs.get('count'))
    token = valueargs.get('token')
    info = "token {0} : total answered correct question is {1}".format(token,count)
    return render_template('finish.html',info=info)



if __name__ =='__main__':
    app.run(host='0.0.0.0',port=80,debug = True)



几个比较难理解的拿出来单独说一下:

  • sortedlist = sorted(questionlist,key = lambda i : i['R'])

这里表示从questionlist 列表中取出每个元素(是字典元素),并按照字典元素中的['R']进行排序,

  • listrandom = random.sample(list1,4)
  • return redirect(url_for('start_question',token=token,count=0))

函数内部跳转,跳转到start_question 函数,且带上两个参数,toke 和count。

web 端程序:start_question7.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>start_question7.html</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>

问题是:<div id="q"> </div>
<form action="">
   <input type="radio" name="sex" value="0"   id="a1"> <label for="a1" id="c1" onclick="doPost(0)">Huey</label><br>
   <input type="radio" name="sex" value="1"   id="a2"> <label for="a2" id="c2" onclick="doPost(1)">Huey</label><br>
   <input type="radio" name="sex" value="2"   id="a3"> <label for="a3" id="c3" onclick="doPost(2)">Huey</label><br>
   <input type="radio" name="sex" value="3"   id="a4"> <label for="a4" id="c4" onclick="doPost(3)">Huey</label><br>
</form>

<script>
    function myFunction(){
    if("undefined" == typeof list1) //如果未定义,字符串取数值
   { var list1 = {{listrandom|tojson}};}
   if("undefined" == typeof question) //如果未定义,问题取数值
   { var question = {{Q|tojson}};}
   console.log("come to myFunction()");
   console.log("The question is "+question)
   document.getElementById("q").innerHTML=question+"()";
   document.getElementById("c1").innerHTML=list1[0];
   document.getElementById("c2").innerHTML=list1[1];
   document.getElementById("c3").innerHTML=list1[2];
   document.getElementById("c4").innerHTML=list1[3];
    }
    window.onload=myFunction();

    function doPost(idnumber){
    console.log("come to collect info first");
    var count = {{count|tojson}};
    var list1 = {{listrandom|tojson}};
    var correct = {{A|tojson}}
    var tokenid ={{token|tojson}}
    var answer = list1[idnumber];
    console.log("come to doPost() function");
    console.log("The choice is "+answer);
    console.log("The correct answer is "+ correct);
    console.log("Your token id is " + tokenid);
    console.log("The count now is "+ count);

    if (answer == correct)//如果答案正确,则跳转到URL2,传递token,以及count+1
       {
         var count = count+1;
         url = "http://127.0.0.1/question";
         url2 = url+"?token="+tokenid+"&count="+count;
         $.ajax({
          type:"GET",
        url:url,
        data:{"count":count,"token":tokenid},
        async:false,
        contentType:"application/json",
        success:function(data)
        {
         window.location.href=url2;
        }
         })
       }
     if(answer !=correct) //如果答案是错误的,则到统计界面,传递token及count
            {
              var jsondoc = {"count":count};
              url ="http://127.0.0.1/question";
              url2 = "http://127.0.0.1/statistic"+"?token="+tokenid+"&count="+count;
             $.ajax({
             type:"POST",
             url:url,
             async:false,
             contentType:"application/json",
             data:JSON.stringify(jsondoc),
             success:function()
              {
               window.location.href=url2;
              }
             });
             }


    }



</script>
</body>
</html>


解释下面的一段JS脚本:

  1. 先通过 list1 = {{ listrandom|tojson}} 收集客户端传递来的数据

if("undefined" == typeof list1) //如果未定义,字符串取数值

{ var list1 = {{listrandom|tojson}};}

if("undefined" == typeof question) //如果未定义,问题取数值

{ var question = {{Q|tojson}};}

2.再通过document.getElementById("c1").innerHTML = list1[2]

来把数据展示到前端。

3.这里 window.onload=myFunction()

表示打开页面后自动调用这个函数。

function myFunction(){
if("undefined" == typeof list1) //如果未定义,字符串取数值
{ var list1 = {{listrandom|tojson}};}
if("undefined" == typeof question) //如果未定义,问题取数值
{ var question = {{Q|tojson}};}
console.log("come to myFunction()");
console.log("The question is "+question)
document.getElementById("q").innerHTML=question+"()";
document.getElementById("c1").innerHTML=list1[0];
document.getElementById("c2").innerHTML=list1[1];
document.getElementById("c3").innerHTML=list1[2];
document.getElementById("c4").innerHTML=list1[3];
}
window.onload=myFunction();


解释下面的一段代码;

  • 首先onclick=doPost(0) 表示在label 上点击鼠标后,会调度doPost()函数,且入参为0,
  • doPost(1),doPost(2),doPost(3) 一样,分别入参为1,2,3。
  • 进入doPost(idnumber)函数,
  1. var answer = list1[idnumber], 选择答案。
  2. correct 为服务端传来的正确答案 correct = {{A|tojson}}
  3. 最后判断用户的选择 answer 和 实际答案 corret是否一致。

如果一致,表示用户选择正确的答案,则跳到下一道题,

否则直接统计。


<form action="">
<input type="radio" name="sex" value="0" id="a1"> <label for="a1" id="c1" onclick="doPost(0)">Huey</label><br>
<input type="radio" name="sex" value="1" id="a2"> <label for="a2" id="c2" onclick="doPost(1)">Huey</label><br>
<input type="radio" name="sex" value="2" id="a3"> <label for="a3" id="c3" onclick="doPost(2)">Huey</label><br>
<input type="radio" name="sex" value="3" id="a4"> <label for="a4" id="c4" onclick="doPost(3)">Huey</label><br>
</form>
function doPost(idnumber){
console.log("come to collect info first");
var count = {{count|tojson}};
var list1 = {{listrandom|tojson}};
var correct = {{A|tojson}}
var tokenid ={{token|tojson}}
var answer = list1[idnumber];
console.log("come to doPost() function");
console.log("The choice is "+answer);
console.log("The correct answer is "+ correct);
console.log("Your token id is " + tokenid);
console.log("The count now is "+ count);
if (answer == correct)//如果答案正确,则跳转到URL2,传递token,以及count+1
{
var count = count+1;
url = "http://127.0.0.1/question";
url2 = url+"?token="+tokenid+"&count="+count;
$.ajax({
type:"GET",
url:url,
data:{"count":count,"token":tokenid},
async:false,
contentType:"application/json",
success:function(data)
{
window.location.href=url2;
}
})
}
if(answer !=correct) //如果答案是错误的,则到统计界面,传递token及count
{
var jsondoc = {"count":count};
url ="http://127.0.0.1/question";
url2 = "http://127.0.0.1/statistic"+"?token="+tokenid+"&count="+count;
$.ajax({
type:"POST",
url:url,
async:false,
contentType:"application/json",
data:JSON.stringify(jsondoc),
success:function()
{
window.location.href=url2;
}
});
}
}


index57.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>57-index</title>
</head>
<body>

<p>注意,一共10道题,逐题做答复,如果答题成功,则进入下一道题,只到结束。</p>
<p>如果答复失败,则直接退出。并统计所有答复正确的题数。</p>

<form method = "post">
    <input type="text" name="name" value="请输入姓名">
    <input type="submit" name ="submit" value="开始答题">
</form>


</body>
</html>

finish.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>finish.html</title>
</head>
<body>

{{info}}
</body>
</html>

57-serversidev3.py

import copy
import flask,pymongo
from flask import Flask,jsonify,request

app = Flask(__name__)


def insert_mongo(list1):
    myclient = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
    mydb= myclient.client["lukedb5"]
    mycol = mydb["site"]
    x = mycol.insert_many(list1)
    print(x.inserted_ids)
    return "success"


def get_mongo():
    myclient = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
    mydb= myclient.client["lukedb5"]
    mycol = mydb["site"]
    list2 =[]
    for x in mycol.aggregate([{'$sample':{'size':10}}]):
        del x['_id'] #把id项目删除
        list2.append(x)
    print(list2)
    return list2,"success"

def getall_mongo():
    myclient = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
    mydb= myclient.client["lukedb5"]
    mycol = mydb["site"]
    list3 =[]
    for x in mycol.find({},{"_id":0}):#把id项目删除
        list3.append(x)
    print(list3)
    return list3,"success"


def update_mongo(listold,listnew):
    myclient = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
    mydb= myclient.client["lukedb5"]
    mycol = mydb["site"]
    for x in range(0,len(listold)):#把id项目删除
        myquery = listold[x]
        newvalues = {"$set":listnew[x]}
        mycol.update_one(myquery,newvalues)
    return "success"

@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/get',methods=['POST'])
def get():
#调用查询逻辑
    #获取题目10个
    #获取难度3个容易,5个中等,2个难题
    list2,info = get_mongo()
    return jsonify({"info":info,"data":list2})

@app.route('/append',methods=['GET','POST'])
def append():
#调用插入逻辑
    list1 = request.json["list"]
    #dic1 = {"Q":"How old is Republic of China1","A":"73","D1":"72","D2":"74","D3":"111"}
    #list1 =[dic1]
    list2 = copy.deepcopy(list1)
    info = insert_mongo(list1)
    #print(info)
    #print(dic1)
    #print(list2)
    return jsonify({"info":info,"data":list2})

@app.route('/getall', methods=['POST'])
def getall():
# 调用抽取接口,把题库数据读出来
    list3,info = getall_mongo()
    return jsonify({"whole question lib is":list3,"info":info})

@app.route('/update', methods=['POST'])
def update():
# 调用update 接口,修改题目
    listold = request.json["listold"]
    listnew = request.json["listnew"]
    info = update_mongo(listold,listnew)
    return jsonify({"info": info,"oldinfo":listold,"newinfo":listnew})


if __name__ =='__main__':
    app.run(host='0.0.0.0',port=8008,debug = True)

效果图:


前端的日志:


编辑题库的逻辑应该差不多,这里不想重复了。

大体方法也是,先编写逻辑,基于逻辑编写实现代码。

类似这样:编写逻辑

逻辑实现后,直接做代码实现即可。

这两天有点卡在这个题目上了,还好今天close掉了。。

最近发表
标签列表