百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

57个挑战之55-制作一个文件编辑器(6)python 实现-客户端+后端

off999 2024-10-19 07:14 13 浏览 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 ,能查到这条数据


相关推荐

每天一个 Python 库:datetime 模块全攻略,时间操作太丝滑!

在日常开发中,时间处理是绕不开的一块,比如:生成时间戳比较两个时间差转换为可读格式接口传参/前端展示/日志记录今天我们就用一个案例+代码+思维导图,带你完全搞定datetime模块的用法!...

字节跳动!2023全套Python入门笔记合集

学完python出来,已经工作3年啦,最近有很多小伙伴问我,学习python有什么用其实能做的有很多可以提高工作效率增强逻辑思维还能做爬虫网站数据分析等等!!最近也是整理了很多适合零基...

为什么你觉得Matplotlib用起来困难?因为你还没看过这个思维导图

前言Matplotlib是一个流行的Python库,可以很容易地用于创建数据可视化。然而,设置数据、参数、图形和绘图在每次执行新项目时都可能变得非常混乱和繁琐。而且由于应用不同,我们不知道选择哪一个图...

Python新手必看!30分钟搞懂break/continue(附5个实战案例)

一、跳转语句的使命当程序需要提前结束循环或跳过特定迭代时,break和continue就是你的代码急刹按钮和跳步指令。就像在迷宫探险中:break=发现出口立即离开continue=跳过陷阱继续前进二...

刘心向学(24)Python中的数据类(python中5种简单的数据类型)

分享兴趣,传播快乐,增长见闻,留下美好!亲爱的您,这里是LearningYard新学苑。今天小编为大家带来文章“刘心向学(24)Python中的数据类”欢迎您的访问。Shareinterest,...

刘心向学(25)Python中的虚拟环境(python虚拟环境安装和配置)

分享兴趣,传播快乐,增长见闻,留下美好!亲爱的您,这里是LearningYard新学苑。今天小编为大家带来文章“刘心向学(25)Python中的虚拟环境”欢迎您的访问。Shareinte...

栋察宇宙(八):Python 中的 wordcloud 库学习介绍

分享乐趣,传播快乐,增长见识,留下美好。亲爱的您,这里是LearingYard学苑!今天小编为大家带来“Python中的wordcloud库学习介绍”欢迎您的访问!Sharethefun,...

AI在用|ChatGPT、Claude 3助攻,1分钟GET高颜值思维导图

机器之能报道编辑:Cardinal以大模型、AIGC为代表的人工智能浪潮已经在悄然改变着我们生活及工作方式,但绝大部分人依然不知道该如何使用。因此,我们推出了「AI在用」专栏,通过直观、有趣且简洁的人...

使用DeepSeek + Python开发AI思维导图应用,非常强!

最近基于Deepseek+PythonWeb技术开发了一个AI对话自动生成思维导图的应用,用来展示下如何基于低门槛的Python相关技术栈,高效结合deepseek实现从应用场景到实际应用的快速落地...

10幅思维导图告诉你 - Python 核心知识体系

首先,按顺序依次展示了以下内容的一系列思维导图:基础知识,数据类型(数字,字符串,列表,元组,字典,集合),条件&循环,文件对象,错误&异常,函数,模块,面向对象编程;接着,结合这些思维导图主要参考的...

Python基础核心思维导图,让你轻松入门

Python基础核心思维导图【高清图文末获取】学习路线图就给大家看到这里了,需要的小伙伴下方获取获取方式看下方图片...

Python基础核心思维导图,学会事半功倍

Python基础核心思维导图【高清图文末获取】学习路线图就给大家看到这里了,需要的小伙伴下方获取获取方式看下方图片...

硬核!288页Python核心知识笔记(附思维导图,建议收藏)

今天就给大家分享一份288页Python核心知识笔记,相较于部分朋友乱糟糟的笔记,这份笔记更够系统地总结相关知识,巩固Python知识体系。文末获取完整版PDF该笔记学习思维导图:目录内容展示【领取方...

Python学习知识思维导图(高效学习)

Python学习知识思维导图python基础知识python数据类型条件循环列表元组字典集合字符串序列函数面向对象编程模块错误异常文件对象#python##python自学##编程#...

别找了!288页Python核心知识笔记(附思维导图,建议收藏)

今天就给大家分享一份288页Python核心知识笔记,相较于部分朋友乱糟糟的笔记,这份笔记更够系统地总结相关知识,巩固Python知识体系。文末获取完整版PDF该笔记学习思维导图:目录内容展示【领取方...

取消回复欢迎 发表评论: