上题目:
前面积累了那么多,其实现在要写出来已经是水到渠成的事情。
直接贴客户端和服务端代码:
服务端代码:
服务端代码名字:57-55serversidev2.py
import redis
import re
import json
import time
import cgi
from redis import StrictRedis, ConnectionPool
from flask import Flask,jsonify,request
import requests
from hashlib import blake2b
app = Flask(__name__)
def create_url():
print("Come to the function create_url()")
prefix = "http://127.0.0.1/api/url/"
suffix = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())
url = prefix + suffix
print(url)
print("Come out of the function create_url()")
return url
def dohash(url):
print("----come to function--- dohash(url)")
FILES_HASH_PERSON = b'57challenges' #设置一个key
h = blake2b(digest_size=10,person=FILES_HASH_PERSON) #设置加密长度及指定key
h.update(url.encode())
primkey = h.hexdigest()
print("the hash of {0} is {1}".format(url,primkey))
print("----come out of function--- dohash(url)")
return primkey
def insert_into_redis(primkey,textcontent):
#mock 把数据插入数据库,primkey 和 textcontent
print("----come to function--- insert_into_redis(primkey,textcontent)")
pool = ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True)
r = StrictRedis(connection_pool=pool)
try:
r.hset("document", primkey, json.dumps({"content": textcontent}))
except:
return 0
print("----come out of function--- insert_into_redis(primkey,textcontent)")
return 1
def check_url_if_exist(url):
# mock检查逻辑
print("----come to function---check_url_if_exist(url)")
print("The received url is {0}".format(url))
key = dohash(url)
print("to search this key {0},check if it exist".format(key))
pool = ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True)
r = StrictRedis(connection_pool=pool)
if r.hexists("document",key):
result = 1
print("it exist")
else:
result = 0
print("it not exist")
print("----come out of function---check_url_if_exist(url)")
return result
def get_text(url):
print("----come to function---get_text(url)")
pool = ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True)
r = StrictRedis(connection_pool=pool)
key = dohash(url)
textinfojson = r.hmget("document",key)
print(textinfojson) #debug , 整个信息内容展示
print(type(textinfojson)) # 看看类型,原来是List
print(textinfojson[0]) # 展示list 中第一个元素内容
print(type(textinfojson[0])) # 看看类型是str
print(json.loads(textinfojson[0])["content"]) #把str 类型转为字典,并读取字典里面key 为"content"的内容
textinfo = json.loads(textinfojson[0])["content"]
print("----come out of function---get_text(url)")
return textinfo
"""
1.保存文档:
功能逻辑:接收前端请求,把文字存到数据库,并返回成功信息到后端。
输入: {“text”: "this is the info for test"}
输出: {“info": "information has been successful saved"}
功能逻辑:
1. 获取输入
2. 把输入的text 文档生成一个url
3. 把URL 做hash ,并把hash(url)作为key
4. 把{hash(url): text} 存入数据库
5. 如果存储成功,则返回信息给到客户端
redis 表结构设计: {md5(url): text}
"""
@app.route('/api/storedoc',methods=['POST'])
def store_doc():
textcontent = request.json['text'] # 获取输入
url = create_url()
primkey = dohash(url)
if insert_into_redis(primkey,textcontent) == 1:
info =" insert into redis key {0}
{1} pair success".format(url,textcontent)
else:
info = "something error has happened"
return jsonify({"info":info})
"""
2.编辑文档:
功能逻辑: 收集客户端的编辑请求,进入url 并找到对应的数据,把text 数据展示在前端,
输入:{“edit": "http://127.0.0.1/api/202206100906”}
输出:{“textinfo":"this is the info for test”}
供客户端逻辑把这个text 数据做展示。
2-1: 接收输入的URL
2-2: 把URL做hash,并到数据库查找数据
2-3: 如果存在则返回数据,如果不存在则返回信息告诉不存在 result = 0
"""
@app.route('/api/editdoc',methods=['POST'])
def edit_doc():
url = request.json['edit']
print("We have got the input url, it's {0}".format(url))
if check_url_if_exist(url) == 1:
textinfo = get_text(url)
print(" info: the text info is
{0}".format(textinfo))
return jsonify({"info": "the url is exist","url":url,"textinfo":textinfo})
else:
return jsonify({"info": "the url {0} is not exist".format(url),"url":url,"textinfo":" "})
if __name__ == '__main__':
app.run(host='0.0.0.0',port=8008,debug = True)客户端代码:
客户端代码名字:57-55client.py
from flask import Flask,render_template,request,url_for,redirect
from datetime import date
import requests
def post_url(text):
print("----come to function---post_url(text)")
urlback = "http://127.0.0.1:8008/api/storedoc"
r = requests.post(urlback,json={"text":text})
info = r.json()["info"]
print(info)
print("----come out of the function---post_url(text)")
return info
def edit_url(url):
print("----come to function---edit_url(text)")
urlback = "http://127.0.0.1:8008/api/editdoc"
r = requests.post(urlback,json={"edit":url})
info = r.json()["textinfo"]
print("----come out of the function---edit_url(text)")
#服务端代码需要修改下,增加一个字段回参的: return jsonify({"info": "the url is exist","url":url ,"textinfo": textinfo})
return info
app = Flask(__name__)
"""
1. 保存文档
客户端功能逻辑:接受用户输入,把文字传递到服务端保存,并收集服务端产生的url信息,并展示到客户端。
输入: 在用户主页填入表,并点击保存。
输出: 保存成功,并返回url 在客户端。
1-1. 从前端获取输入;
1-2. 把输入信息提交给后端;
1-3. 后端返回url 给到前端,解析后,展示到display.html 中。
"""
@app.route('/',methods=['GET','POST'])
@app.route('/index')
@app.route('/home')
def index():
if request.method == 'POST':
text = request.form['text']
info = post_url(text)
return render_template('57-55-display.html',info=info)
if request.method == 'GET':
return render_template('57-55-index.html')
"""
2. 打开并编辑保存文档
客户端功能逻辑:用户打开1中对应的链接,打开后即产生一个Post请求到服务端,拿到服务端返回的信息后,重新展现到edit.html中。
逻辑1
输入: 用户点击对应的链接(get请求);
输出: 客户端根据请求做一个redirect 解析到一个新的index2.html中,其中index2里面包含了这个url在服务端的数据;
逻辑2
输入: 用户在index2.html 中做编辑,编辑后点击保存,信息会发送到后端。
输出: 后端能保存这段内容,并产生一个url 信息,
"""
@app.route('/api/url/',methods=['GET'])
def edit(content):
url = request.url
print(url)
print("the content is {0}".format(content))
info = edit_url(url)
print("the info is {0}".format(info))
return render_template('57_55_edit.html', info=info)
@app.route('/api/url/',methods=['POST'])
def save(content2):
url = request.url
text = request.form['text']
info = post_url(text)
return render_template('57-55-display.html', info=info)
if __name__ == '__main__':
app.run(host='0.0.0.0',port=80,debug = True) 客户端的html :57-55index.html
57-55index.html
57-55-display.html
{{info}}
57-55index.html
57-55edit.html
运行效果示意图:
打开页面
1.前端展示
2.键入数据后保存
3.插入成功
3可以看到,产生的url是 http://127.0.0.1/api/url/2022-06-19-09:30:07
4.后台查询这个数据
5.后端日志信息
分享这个url 给第三方,第三方在界面上打开url,看到老数据,这个时候做一个编辑并保存
6. 第三方编辑此url
在下面增加一行:
7.增加一行,并保存
保存后产生一个新的url,http://127.0.0.1/api/url/2022-06-19-09:36:08
8.保存后产生一个新的url
在后台看这个url
http://127.0.0.1/api/url/2022-06-19-09:36:08
9.后台展示保存这个url
后台数据库查询此url
键入url ,能查到这条数据
| 留言与评论(共有 0 条评论) “” |