食品溯源项目代码示例:使用 Python 和区块链实现溯源
食品溯源项目的代码可能因项目的具体需求而有所不同,但我可以给你一个基本的示例代码来说明食品溯源的实现。
在食品溯源项目中,通常会使用区块链技术来确保数据的安全性和透明度。以下是一个简单的示例代码,展示了如何使用 Python 和区块链来实现食品溯源。
import hashlib
import datetime
# 定义食品类
class Food:
def __init__(self, name, producer, timestamp):
self.name = name
self.producer = producer
self.timestamp = timestamp
self.previous_hash = None
self.hash = self.calculate_hash()
def calculate_hash(self):
data = self.name + self.producer + str(self.timestamp)
return hashlib.sha256(data.encode()).hexdigest()
# 定义区块类
class Block:
def __init__(self, food, previous_hash):
self.food = food
self.previous_hash = previous_hash
self.timestamp = datetime.datetime.now()
self.hash = self.calculate_hash()
def calculate_hash(self):
data = self.food.hash + str(self.timestamp) + self.previous_hash
return hashlib.sha256(data.encode()).hexdigest()
# 定义区块链类
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
return Block(Food('Genesis Block', 'Genesis Producer', datetime.datetime.now()), '0')
def get_latest_block(self):
return self.chain[-1]
def add_block(self, new_block):
new_block.previous_hash = self.get_latest_block().hash
new_block.hash = new_block.calculate_hash()
self.chain.append(new_block)
def is_chain_valid(self):
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i - 1]
if current_block.hash != current_block.calculate_hash():
return False
if current_block.previous_hash != previous_block.hash:
return False
return True
# 使用示例
chain = Blockchain()
# 创建食品
food1 = Food('Apple', 'Farm A', datetime.datetime.now())
food2 = Food('Banana', 'Farm B', datetime.datetime.now())
# 创建区块并添加到区块链中
block1 = Block(food1, '')
chain.add_block(block1)
block2 = Block(food2, chain.get_latest_block().hash)
chain.add_block(block2)
# 验证区块链的有效性
print('Is blockchain valid?', chain.is_chain_valid())
# 输出区块链信息
for block in chain.chain:
print('Food:', block.food.name)
print('Producer:', block.food.producer)
print('Timestamp:', block.food.timestamp)
print('Hash:', block.food.hash)
print('Previous Hash:', block.previous_hash)
print('=========================' )
这是一个非常简单的示例,用于说明如何使用区块链来实现食品溯源。实际的项目可能需要更多的功能和验证机制来确保数据的完整性和可靠性。希望这个示例可以对你有所帮助!
原文地址: http://www.cveoy.top/t/topic/bSVY 著作权归作者所有。请勿转载和采集!