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

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

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


相关推荐

在NAS实现直链访问_如何访问nas存储数据

平常在使用IPTV或者TVBOX时,经常自己会自定义一些源。如何直链的方式引用这些自定义的源呢?本人基于armbian和CasaOS来创作。使用标准的Web服务器(如Nginx或Apache...

PHP开发者必备的Linux权限核心指南

本文旨在帮助PHP开发者彻底理解并解决在Linux服务器上部署应用时遇到的权限问题(如Permissiondenied)。核心在于理解“哪个用户(进程)在访问哪个文件(目录)”。一、核心...

【Linux高手必修课】吃透sed命令!文本手术刀让你秒变运维大神!

为什么说sed是Linux运维的"核武器"?想象你有10万个配置文件需要批量修改?传统方式要写10万行脚本?sed一个命令就能搞定!这正是运维工程师的"暴力美学"时...

「实战」docker-compose 编排 多个docker 组成一个集群并做负载

本文目标docker-compose,对springboot应用进行一个集群(2个docker,多个类似,只要在docker-compose.yml再加boot应用的服务即可)发布的过程架构...

企业安全访问网关:ZeroNews反向代理

“我们需要让外包团队访问测试环境,但不想让他们看到我们的财务系统。”“审计要求我们必须记录所有第三方对内部系统的访问,现在的VPN日志一团糟。”“每次有新员工入职或合作伙伴接入,IT部门都要花半天时间...

反向代理以及其使用场景_反向代理实现过程

一、反向代理概念反向代理(ReverseProxy)是一种服务器配置,它将客户端的请求转发给内部的另一台或多台服务器处理,然后将响应返回给客户端。与正向代理(ForwardProxy)不同,正向代...

Nginx反向代理有多牛?一篇文章带你彻底搞懂!

你以为Nginx只是个简单的Web服务器?那可就大错特错了!这个看似普通的开源软件,实际上隐藏着惊人的能力。今天我们就来揭开它最强大的功能之一——反向代理的神秘面纱。反向代理到底是什么鬼?想象一下你...

Nginx反向代理最全详解(原理+应用+案例)

Nginx反向代理在大型网站有非常广泛的使用,下面我就重点来详解Nginx反向代理@mikechen文章来源:mikechen.cc正向代理要理解清楚反向代理,首先:你需要搞懂什么是正向代理。正向代理...

centos 生产环境安装 nginx,包含各种模块http3

企业级生产环境Nginx全模块构建的大部分功能,包括HTTP/2、HTTP/3、流媒体、SSL、缓存清理、负载均衡、DAV扩展、替换过滤、静态压缩等。下面我给出一个完整的生产环境安装流程(C...

Nginx的负载均衡方式有哪些?_nginx负载均衡机制

1.轮询(默认)2.加权轮询3.ip_hash4.least_conn5.fair(最小响应时间)--第三方6.url_hash--第三方...

Nginx百万并发优化:如何提升100倍性能!

关注△mikechen△,十余年BAT架构经验倾囊相授!大家好,我是mikechen。Nginx是大型架构的核心,下面我重点详解Nginx百万并发优化@mikechen文章来源:mikechen....

在 Red Hat Linux 上搭建高可用 Nginx + Keepalived 负载均衡集群

一、前言在现代生产环境中,负载均衡是确保系统高可用性和可扩展性的核心技术。Nginx作为轻量级高性能Web服务器,与Keepalived结合,可轻松实现高可用负载均衡集群(HA+LB...

云原生(十五) | Kubernetes 篇之深入了解 Pod

深入了解Pod一、什么是PodPod是一组(一个或多个)容器(docker容器)的集合(就像在豌豆荚中);这些容器共享存储、网络、以及怎样运行这些容器的声明。我们一般不直接创建Pod,而是...

云原生(十七) | Kubernetes 篇之深入了解 Deployment

深入了解Deployment一、什么是Deployment一个Deployment为Pods和ReplicaSets提供声明式的更新能力。你负责描述Deployment中的目标状...

深入理解令牌桶算法:实现分布式系统高效限流的秘籍

在高并发系统中,“限流”是保障服务稳定的核心手段——当请求量超过系统承载能力时,合理的限流策略能避免服务过载崩溃。令牌桶算法(TokenBucket)作为最经典的限流算法之一,既能控制请求的平...

取消回复欢迎 发表评论: