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

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

off999 2024-10-19 07:14 16 浏览 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的GUI可视化工具(python 可视化工具)

在Python基础语法学习完成后,进一步开发应用界面时,就需要涉及到GUI了,GUI全称是图形用户界面(GraphicalUserInterface,又称图形用户接口),采用图形方式显示的计算机操...

教你用Python绘制谷歌浏览器的3种图标

前两天在浏览matplotlib官方网站时,笔者无意中看到一个挺有意思的图片,就是用matplotlib制作的火狐浏览器的logo,也就是下面这个东东(网页地址是https://matplotlib....

小白学Python笔记:第二章 Python安装

Windows操作系统的python安装:Python提供Windows、Linux/UNIX、macOS及其他操作系统的安装包版本,结合自己的使用情况,此处仅记录windows操作系统的python...

Python程序开发之简单小程序实例(9)利用Canvas绘制图形和文字

Python程序开发之简单小程序实例(9)利用Canvas绘制图形和文字一、项目功能利用Tkinter组件中的Canvas绘制图形和文字。二、项目分析要在窗体中绘制图形和文字,需先导入Tkinter组...

一文吃透Python虚拟环境(python虚拟环境安装和配置)

摘要在Python开发中,虚拟环境是一种重要的工具,用于隔离不同项目的依赖关系和环境配置。本文将基于windows平台介绍四种常用的Python虚拟环境创建工具:venv、virtualenv、pip...

小白也可以玩的Python爬虫库,收藏一下

最近,微软开源了一个项目叫「playwright-python」,作为一个兴起项目,出现后受到了大家热烈的欢迎,那它到底是什么样的存在呢?今天为你介绍一下这个传说中的小白神器。Playwright是...

python环境安装+配置教程(python安装后怎么配置环境变量)

安装python双击以下软件:弹出一下窗口需选择一些特定的选项默认选项不需要更改,点击next勾选以上选项,点击install进度条安装完毕即可。到以下界面,证明安装成功。接下来安装库文件返回电脑桌面...

colorama,一个超好用的 Python 库!

大家好,今天为大家分享一个超好用的Python库-colorama。Github地址:https://github.com/tartley/coloramaPythoncolorama库是一...

python制作仪表盘图(python绘制仪表盘)

今天教大家用pyecharts画仪表盘仪表盘(Gauge)是一种拟物化的图表,刻度表示度量,指针表示维度,指针角度表示数值。仪表盘图表就像汽车的速度表一样,有一个圆形的表盘及相应的刻度,有一个指针...

总结90条写Python程序的建议(python写作)

  1.首先  建议1、理解Pythonic概念—-详见Python中的《Python之禅》  建议2、编写Pythonic代码  (1)避免不规范代码,比如只用大小写区分变量、使用容易...

[oeasy]python0137_相加运算_python之禅_import_this_显式转化

变量类型相加运算回忆上次内容上次讲了是从键盘输入变量input函数可以有提示字符串需要有具体的变量接收输入的字符串输入单个变量没有问题但是输入两个变量之后一相加就非常离谱添加图片注释,不超过1...

Python入门学习记录之一:变量(python中变量的规则)

写这个,主要是对自己学习python知识的一个总结,也是加深自己的印象。变量(英文:variable),也叫标识符。在python中,变量的命名规则有以下三点:>变量名只能包含字母、数字和下划线...

掌握Python的&quot;魔法&quot;:特殊方法与属性完全指南

在Python的世界里,以双下划线开头和结尾的"魔法成员"(如__init__、__str__)是面向对象编程的核心。它们赋予开发者定制类行为的超能力,让自定义对象像内置类型一样优雅工...

11个Python技巧 不Pythonic 实用大于纯粹

虽然Python有一套强大的设计哲学(体现在“Python之禅”中),但总有一些情况需要我们“打破规则”来解决特定问题。这触及了Python哲学中一个非常核心的理念:“实用主义胜于纯粹主义”...

Python 从入门到精通 第三课 诗意的Python之禅

导言:Python之禅,英文名是TheZenOfPython。最早由TimPeters在Python邮件列表中发表,它包含了影响Python编程语言设计的20条软件编写原则。它作为复活节彩蛋...

取消回复欢迎 发表评论: