接昨天,发现在python3里面,2次提供相同的url,hash的数值的确是不一致的。google 了一下,发现这个是Python 为了防止恶意攻击做的一个操作。
下面蓝框,如果要解除这个问题,建议使用hashlib 模块。
好吧,直接找了下它的实现:
https://docs.python.org/3/library/hashlib.html
比较喜欢这个blake2b的实现,指定长度,而且加入key 防止被暴力破解。
把这段代码引入到 昨天的代码中,问题解决。贴代码
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}
{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
{0}".format(textinfo))
return jsonify({"info": "the url is exist","url":url})
else:
return jsonify({"info": "the url {0} is not exist".format(url)})
if __name__ == '__main__':
app.run(host='0.0.0.0',port=8008,debug = True)
前端插入效果
后台信息:
看到key 是这个 9265 结尾的。
我用同一个url链接,反向找下对应的数值:
后端的日志:key 没变
操作三次,查看数据库,信息是完备的。
页面更新:2024-03-27
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号