57个挑战之55-制作一个文件编辑器(6)python 实现-客户端+后端
off999 2024-10-19 07:14 21 浏览 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 ,能查到这条数据
相关推荐
- 大文件传不动?WinRAR/7-Zip 入门到高手,这 5 个技巧让你效率翻倍
-
“这200张照片怎么传给女儿?微信发不了,邮箱附件又超限……”62岁的张阿姨对着电脑犯愁时,儿子只用了3分钟就把照片压缩成一个文件,还教她:“以后用压缩软件,比打包行李还方便!”职场人更懂这...
- 电脑解压缩软件推荐——7-Zip:免费、高效、简洁的文件管理神器
-
在日常工作中,我们经常需要处理压缩文件。无论是下载软件包、接收文件,还是存储大量数据,压缩和解压缩文件都成为了我们日常操作的一部分。而说到压缩解压软件,7-Zip绝对是一个不可忽视的名字。今天,我就来...
- 设置了加密密码zip文件要如何打开?这几个方法可以试试~
-
Zip是一种常见的压缩格式文件,文件还可以设置密码保护。那设置了密码的Zip文件要如何打开呢?不清楚的小伙伴一起来看看吧。当我们知道密码想要打开带密码的Zip文件,我们需要用到适用于Zip格式的解压缩...
- 大文件想要传输成功,怎么把ZIP文件分卷压缩
-
不知道各位小伙伴有没有这样的烦恼,发送很大很大的压缩包会受到限制,为此,想要在压缩过程中将文件拆分为几个压缩包并且同时为所有压缩包设置加密应该如何设置?方法一:使用7-Zip免费且强大的文件管理工具7...
- 高效处理 RAR 分卷压缩包:合并解压操作全攻略
-
在文件传输和存储过程中,当遇到大文件时,我们常常会使用分卷压缩的方式将其拆分成多个较小的压缩包,方便存储和传输。RAR作为一种常见的压缩格式,分卷压缩包的使用频率也很高。但很多人在拿到RAR分卷...
- 2个方法教你如何删除ZIP压缩包密码
-
zip压缩包设置了加密密码,每次解压文件都需要输入密码才能够顺利解压出文件,当压缩包文件不再需要加密的时候,大家肯定想删除压缩包密码,或是忘记了压缩包密码,想要通过删除操作将压缩包密码删除,就能够顺利...
- 速转!漏洞预警丨压缩软件Winrar目录穿越漏洞
-
WinRAR是一款功能强大的压缩包管理器,它是档案工具RAR在Windows环境下的图形界面。该软件可用于备份数据,缩减电子邮件附件的大小,解压缩从Internet上下载的RAR、ZIP及其它类...
- 文件解压方法和工具分享_文件解压工具下载
-
压缩文件减少文件大小,降低文件失效的概率,总得来说好处很多。所以很多文件我们下载下来都是压缩软件,很多小伙伴不知道怎么解压,或者不知道什么工具更好,所以今天做了文件解压方法和工具的分享给大家。一、解压...
- [python]《Python编程快速上手:让繁琐工作自动化》学习笔记3
-
1.组织文件笔记(第9章)(代码下载)1.1文件与文件路径通过importshutil调用shutil模块操作目录,shutil模块能够在Python程序中实现文件复制、移动、改名和删除;同时...
- Python内置tarfile模块:读写 tar 归档文件详解
-
一、学习目标1.1学习目标掌握Python内置模块tarfile的核心功能,包括:理解tar归档文件的原理与常见压缩格式(gzip/bz2/lzma)掌握tar文件的读写操作(创建、解压、查看、过滤...
- 使用python展开tar包_python拓展
-
类Unix的系统,打包文件经常使用的就是tar包,结合zip工具,可以方便的打包并解压。在python的标准库里面有tarfile库,可以方便实现生成了展开tar包。使用这个库最大的好处,可能就在于不...
- 银狐钓鱼再升级:白文件脚本化实现GO语言后门持久驻留
-
近期,火绒威胁情报中心监测到一批相对更为活跃的“银狐”系列变种木马。火绒安全工程师第一时间获取样本并进行分析。分析发现,该样本通过阿里云存储桶下发恶意文件,采用AppDomainManager进行白利...
- ZIP文件怎么打开?2个简单方法教你轻松搞定!
-
在日常工作和生活中,我们经常会遇到各种压缩文件,其中最常见的格式之一就是ZIP。ZIP文件通过压缩数据来减少文件大小,方便我们进行存储和传输。然而,对于初学者来说,如何打开ZIP文件可能会成为一个小小...
- Ubuntu—解压多个zip压缩文件.zip .z01 .z02
-
方法将所有zip文件放在同一目录中:zip_file.z01,zip_file.z02,zip_file.z03,...,zip_file.zip。在Zip3.0版本及以上,使用下列命令:将所有zi...
- 如何使用7-Zip对文件进行加密压缩
-
7-Zip是一款开源的文件归档工具,支持多种压缩格式,并提供了对压缩文件进行加密的功能。使用7-Zip可以轻松创建和解压.7z、.zip等格式的压缩文件,并且可以通过设置密码来保护压缩包中的...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- 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)