上要求:
上代码:
服务端:
import redis import re import json import time import cgi from redis import StrictRedis, ConnectionPool from Flask import Flask,jsonify,request import requests app = Flask(__name__) def insert_into_redis(shorturl,longurl): print("----come to function--- insert_into_redis(shorturl,longurl)") # 如果含义为插入,则做插入操作 pool = ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True) # redis 取出的结果默认是字节,我们可以设定 decode_responses=True 改成字符串。 r = StrictRedis(connection_pool=pool) string = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) r.hset("shorttolong",shorturl, json.dumps({"longurl": longurl,"visittime": [], "creattime":string})) r.hset("longtoshort",longurl,shorturl) print("Info: The value {0} is inserted".format(shorturl)) return 1 def check_if_exist(longurl): print("----come to function--- check_if_exist(longurl)") pool = ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True) r = StrictRedis(connection_pool=pool) # 判断是否存在,如果存在则返回1 if r.hexists("longtoshort",longurl): result = 1 else: result = 0 return result def check_shorturl_if_exist(shorturl): print("----come to function--- check_shorturl_if_exist(shorturl)") pool = ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True) r = StrictRedis(connection_pool=pool) # 判断是否存在,如果存在则返回1 if r.hexists("shorttolong",shorturl): result = 1 else: result = 0 return result def get_longurl(shorturl): print("----come to function--- get_longurl(shorturl)") pool = ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True) r = StrictRedis(connection_pool=pool) # 判断是否存在,如果存在则返回1 longurljson = r.hmget("shorttolong",shorturl) longurl = json.loads(longurljson[0])["longurl"] #print(longurljson) #print(longurl) return longurl def update_jumptime(shorturl): print("----come to function--- update_jumptime(shorturl)") pool = ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True) r = StrictRedis(connection_pool=pool) longurljson = r.hmget("shorttolong", shorturl) dic1 = json.loads(longurljson[0]) list1 = dic1["visittime"] #print(list1) string = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) list1.append(string) dic1["visittime"] = list1 r.hset("shorttolong", shorturl, json.dumps(dic1)) print("info: update the visittime of the {0} success".format(shorturl)) return 1 """ 0.判断长链接是否已经存在 在用户端进行创建的时候,要检查长链接是否已经在服务端存在了,如果存在应该忽略。 如何确定服务端存在,通过post 接口来查询。 检查长URL是否有效:通过checkurl(longurl)函数,当longurl 已经存在, 返回json字段{'result':1},不存在则否则返回{'result':0} """ @app.route('/api/checkurl', methods=['POST']) def check_url(): print("----come to function--- check_url() /api/checkurl logic") longurl = request.json['longurl'] result = check_if_exist(longurl) if result == 0: print("Info: The longurl {0} is not exist at serverside storage".format(longurl)) else: print("Info: The longurl {0} is already exist at serverside storage".format(longurl)) return jsonify({'result':result,"longurl":longurl}),200 @app.route('/api/checkshorturl', methods=['POST']) def check_short_url(): print("----come to function--- check_short_url() /api/check_short_url logic") shorturl = request.json['shorturl'] result = check_shorturl_if_exist(shorturl) if result == 0: print("Info: The shorturl {0} is not exist at serverside storage".format(shorturl)) else: print("Info: The shorturl {0} is already exist at serverside storage".format(shorturl)) return jsonify({'result':result,"shorturl":shorturl}),200 """ 1.收集长链接生成短链接: 根据客户端的post 请求,收集客户端发送的shorturl以及longurl,把关联关系插入到redis中 插入的时候,redis表中有两个hash库, "shorttolong" 库,结构为 shorturl:{"longurl":longurl,"visittime",{},"createtime":string} "longtoshort" 库,结构为 longurl:shorturl """ @app.route('/api/shorturlcreate',methods=['POST']) def shorturl_create(): print("----come to function---shorturl_create() /api/shorturlcreate logic") shorturl = request.json['shorturl'] longurl = request.json['longurl'] insert_into_redis(shorturl, longurl) print("info: insert into redis {0}:{1} pair success".format(shorturl,longurl)) return jsonify({"info":"insert into redis "+longurl+shorturl+" pair succuss"}) """ 2.收集短链接做相关跳转: 客户端发出短链接请求, 2-1: 判断短链接是否存在 2-2: 如果存在,则找到对应的长链接 2-3: 返回301 指令,并让客户端做跳转 """ @app.route('/api/shorturljump',methods=['POST']) def shorturl_jump(): print("----come to function---shorturl_jump() /api/shorturljump logic") shorturl = request.json['shorturl'] if check_shorturl_if_exist(shorturl) == 1: # getlongurl mock longurl=get_longurl(shorturl) # 增加一个跳转的时间,对他记录。 # redis_update_jumptime(shorturl) mock update_jumptime(shorturl) # jumpto destination longurl,mock print("info: jump to destination longurl {0} ".format(longurl)) #redirect_to_longurl(longurl) return jsonify({"info": "jump to destionation","longurl":longurl}) else: return jsonify({"info": "the site {0} is not exist".format(shorturl),"longurl":"notexist"}) if __name__ == '__main__': app.run(host='0.0.0.0',port=8008,debug = True)
客户端:
from flask import Flask,render_template,request,url_for,redirect from datetime import date import requests import json import time def check_if_valid(longurl): #检查长链接是否有效,这里mock一下 print("----come to function--- check_if_valid(longurl)") try: r = requests.get("https://"+longurl) statuscode = r.status_code if statuscode == 200 or statuscode == 301: print("The site is reachable on internet") result = 1 else: result = 0 except: result = 0 return result def check_if_exist_url(longurl): print("----come to function--- check_if_exist_url(longurl)") #检查长链接是否在服务端存在,mock一下 print("Process: check if the longurl {0} is exist at serverside redis storage".format(longurl)) r = requests.post("http://127.0.0.1:8008/api/checkurl", json={"longurl": longurl}) textjson = r.json() print("get the return info from the serverside {0}".format(longurl)) print(textjson) print("get the type info of the serverside") print(type(textjson)) print("Get the longurl ") print(textjson["longurl"]) #print(dic2["longurl"]) result = textjson["result"] return result def post_shorturlcreate(shorturl,longurl): #模拟postman,传递数据到服务端。 print("----come to function--- post_shorturlcreate(shorturl,longurl)") print("Process: to deliver create link to serverside redis storage") r = requests.post("http://127.0.0.1:8008/api/shorturlcreate",json={"shorturl":shorturl,"longurl":longurl}) print("get info from serverside n"+ r.text) return 1 def post_shorturljump(shorturl): print("----come to function--- post_shorturljump(shorturl)") print("Process: jump to shorturl") r = requests.post("http://127.0.0.1:8008/api/shorturljump", json={"shorturl": shorturl}) print("get info from serverside n" + r.text) return r def create_shorturl(longurl): print("----come to function--- create_shorturl(longurl)") print("Process: to create shorturl from longurl") #返回shorturl shorturl = "/"+longurl.split(".")[1] print("Process:The short url is "+shorturl) return shorturl def check_shorturl_if_exist(shorturl): print("----come to function--- check_shorturl_if_exist()") print("Process: check if the shorturl {0} is exist at serverside redis storage".format(shorturl)) r = requests.post("http://127.0.0.1:8008/api/checkshorturl", json={"shorturl": shorturl}) textjson = r.json() print("Print the info return from serverside,this is the info") print(textjson) print("Check the type of the info") print(type(textjson)) print("Check the mapping(longurl) of the shorturl {0}".format(shorturl)) print(textjson["shorturl"]) # print(dic2["longurl"]) result = textjson["result"] return result app = Flask(__name__) @app.route('/',methods=['GET','POST']) def index(): if request.method == 'POST': #根据post 表单获取的内容做相关判断 longurl = request.form['longurl'] shorturl = request.form['shorturl'] print("longurl is {0}, shorturl is {1}".format(longurl,shorturl)) if longurl is not None and shorturl == "empty": #当longurl 非空 print("进入第一个逻辑") if check_if_valid(longurl) == 1 and check_if_exist_url(longurl) == 0: #当longurl 可用,且longurl在服务端不存在 shorturl = create_shorturl(longurl) post_shorturlcreate(shorturl, longurl) notes = "the longurl {0} and shorturl {1} pair is created".format(longurl,shorturl) return render_template('display.html', info=notes) else: #否则条件没达到,通知失败 notes = "the longurl is not exist or it's already at serverside" return render_template('display.html', info=notes) if shorturl is not None and longurl == "empty": #当shorturl 非空,执行第二个逻辑 print("进入第二个逻辑") if check_shorturl_if_exist(shorturl) == 1:# 如果短url在服务端存在,则做跳转等逻辑 r = post_shorturljump(shorturl) print(r.json()) print(type(r.json())) longurl = r.json()["longurl"] print(longurl) return redirect("https://" + longurl) else: notes = "the shorturl is not exist" return render_template('display.html', info=notes) if shorturl is not None and longurl == "statics": #当shorturl 非空,且longurl为统计,执行第三个逻辑 print("进入第三个逻辑") visittime = [] if check_shorturl_if_exist(shorturl) == 1:# 如果短url在服务端存在,则收集它的访问时间并存到字典 visittime = else: notes = "the shorturl is not exist" return render_template('display.html', info=notes) else: return render_template('index5.html') @app.route('/api/static',methods=['GET','POST']) def get_static(): print("进入第三个逻辑") print("统计某个短链的访问情况") return render_template('display.html', info="The site info is displayed") if __name__ == '__main__': app.run(host='0.0.0.0',port=80,debug = True)
index5.html
<!DOCTYPE html> <html lang="en"> <script type="text/javascript"> if(form.longurl.value ==''){ form.longurl.value == "empty" } if(form.shorturl.value ==''){ form.shorturl.value == "empty" } </script> <head> <meta charset="UTF-8"> <title>57-54</title> </head> <body> <form method = "post"> <label for="longurl">提供想生成短链接的url</label> <input type="text" name="longurl" required><br> <input type="hidden" name="shorturl" value ="empty"><br> <input type="submit" name="submit" value="记录"> </form> <form> <label for="shorturl">提供想跳转的url</label> <input type="hidden" name="longurl" value="empty"><br> <input type="text" name="shorturl" required><br> <input type="submit" name="submit" value="跳转"> </form> </body> </html>
display.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>57-53</title> </head> <body> {{info}} </body> </html>
前端
键入www.qq.com
点击记录
实现了插入逻辑:
插入逻辑前端日志:
插入逻辑后端日志:
查看数据库:
跳转前逻辑:
键入qq,点击跳转
跳转后:
前端日志:
后端日志:
看访问做了跳转302,
update后,跳转时间做了记录
还没有评论,来说两句吧...