57个挑战之55-制作一个文件编辑器(6)python 实现-客户端+后端
off999 2024-10-19 07:14 38 浏览 0 评论
上题目:
前面积累了那么多,其实现在要写出来已经是水到渠成的事情。
直接贴客户端和服务端代码:
服务端代码:
服务端代码名字: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} \n {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 \n {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/<content>',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/<content2>',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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>57-55index.html</title>
</head>
<body>
<form method = "post">
<label for="text">提供想编辑的文档</label>
<input type="text" name="text" required><br>
<input type="submit" name="submit" value="保存">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>57-55-display.html</title>
</head>
<body>
{{info}}
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>57-55index.html</title>
</head>
<body>
<form method = "post">
<label for="text">提供想编辑的文档</label> <br>
<textarea name="text" cols="30" rows="5"></textarea> <br>
<input type="submit" name="submit" value="保存">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>57-55edit.html</title>
</head>
<body>
<form method = "post">
<label for="text">提供想编辑的文档</label> <br>
<textarea name="text" cols="30" rows="5">{{info}}</textarea>
<input type="submit" name="submit" value="保存">
</form>运行效果示意图:
打开页面
3可以看到,产生的url是 http://127.0.0.1/api/url/2022-06-19-09:30:07
分享这个url 给第三方,第三方在界面上打开url,看到老数据,这个时候做一个编辑并保存
在下面增加一行:
保存后产生一个新的url,http://127.0.0.1/api/url/2022-06-19-09:36:08
在后台看这个url
http://127.0.0.1/api/url/2022-06-19-09:36:08
后台数据库查询此url
键入url ,能查到这条数据
相关推荐
- 安全教育登录入口平台(安全教育登录入口平台官网)
-
122交通安全教育怎么登录:122交通网的注册方法是首先登录网址http://www.122.cn/,接着打开网页后,点击右上角的“个人登录”;其次进入邮箱注册,然后进入到注册页面,输入相关信息即可完...
- 大鱼吃小鱼经典版(大鱼吃小鱼经典版(经典版)官方版)
-
大鱼吃小鱼小鱼吃虾是于谦跟郭麒麟的《我的棒儿呢?》郭德纲说于思洋郭麒麟作诗的相声,最后郭麒麟做了一首,师傅躺在师母身上大鱼吃小鱼小鱼吃虾虾吃水水落石出师傅压师娘师娘压床床压地地动山摇。...
-
- 哪个软件可以免费pdf转ppt(免费的pdf转ppt软件哪个好)
-
要想将ppt免费转换为pdf的话,我们建议大家可以下一个那个wps,如果你是会员的话,可以注册为会员,这样的话,在wps里面的话,就可以免费将ppt呢转换为pdfpdf之后呢,我们就可以直接使用,不需要去直接不需要去另外保存,为什么格式转...
-
2026-02-04 09:03 off999
- 电信宽带测速官网入口(电信宽带测速官网入口app)
-
这个网站看看http://www.swok.cn/pcindex.jsp1.登录中国电信网上营业厅,宽带光纤,贴心服务,宽带测速2.下载第三方软件,如360等。进行在线测速进行宽带测速时,尽...
- 植物大战僵尸95版手机下载(植物大战僵尸95 版下载)
-
1可以在应用商店或者游戏平台上下载植物大战僵尸95版手机游戏。2下载教程:打开应用商店或者游戏平台,搜索“植物大战僵尸95版”,找到游戏后点击下载按钮,等待下载完成即可安装并开始游戏。3注意:确...
- 免费下载ppt成品的网站(ppt成品免费下载的网站有哪些)
-
1、Chuangkit(chuangkit.com)直达地址:chuangkit.com2、Woodo幻灯片(woodo.cn)直达链接:woodo.cn3、OfficePlus(officeplu...
- 2025世界杯赛程表(2025世界杯在哪个国家)
-
2022年卡塔尔世界杯赛程公布,全部比赛在卡塔尔境内8座球场举行,2022年,决赛阶段球队全部确定。揭幕战于当地时间11月20日19时进行,由东道主卡塔尔对阵厄瓜多尔,决赛于当地时间12月18日...
- 下载搜狐视频电视剧(搜狐电视剧下载安装)
-
搜狐视频APP下载好的视频想要导出到手机相册里方法如下1、打开手机搜狐视频软件,进入搜狐视频后我们点击右上角的“查找”,找到自已喜欢的视频。2、在“浏览器页面搜索”窗口中,输入要下载的视频的名称,然后...
- 永久免费听歌网站(丫丫音乐网)
-
可以到《我爱音乐网》《好听音乐网》《一听音乐网》《YYMP3音乐网》还可以到《九天音乐网》永久免费听歌软件有酷狗音乐和天猫精灵,以前要跳舞经常要下载舞曲,我从QQ上找不到舞曲下载就从酷狗音乐上找,大多...
- 音乐格式转换mp3软件(音乐格式转换器免费版)
-
有两种方法:方法一在手机上操作:1、进入手机中的文件管理。2、在其中选择“音乐”,将显示出手机中的全部音乐。3、点击“全选”,选中所有音乐文件。4、点击屏幕右下方的省略号图标,在弹出菜单中选择“...
- 电子书txt下载(免费的最全的小说阅读器)
-
1.Z-library里面收录了近千万本电子书籍,需求量大。2.苦瓜书盘没有广告,不需要账号注册,使用起来非常简单,直接搜索预览下载即可。3.鸠摩搜书整体风格简洁清晰,书籍资源丰富。4.亚马逊图书书籍...
- 最好免费观看高清电影(播放免费的最好看的电影)
-
在目前的网上选择中,IMDb(互联网电影数据库)被认为是最全的电影网站之一。这个网站提供了各种类型的电影和电视节目的海量信息,包括剧情介绍、演员表、评价、评论等。其还提供了有关电影制作背后的详细信息,...
- 孤单枪手2简体中文版(孤单枪手2简体中文版官方下载)
-
要将《孤胆枪手2》游戏的征兵秘籍切换为中文,您可以按照以下步骤进行操作:首先,打开游戏设置选项,通常可以在游戏主菜单或游戏内部找到。然后,寻找语言选项或界面选项,点击进入。在语言选项中,选择中文作为游...
欢迎 你 发表评论:
- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
