繁体   English   中英

Python Flask Blockchain 给出“'dict' 对象不可调用”

[英]Python Flask Blockchain giving "'dict' object not callable"

我正在使用 Flask 在 Python 中创建一个区块链,但是现在当我尝试向我发出 HTTP 请求时出现错误。 当前完整代码位于https://github.com/MGedney1/Python-Blockchain/blob/master/blockchain.py 我得到的错误是

TypeError 'dict' 对象不可调用。

相关代码:

from hashlib import sha256      #Imports
import json
from time import time
from textwrap import dedent
from uuid import uuid4
from flask import Flask, jsonify, request

class Blockchain(object):

    def __init__(self):     #Initialising the blockchain
        self.chain = []     
        self.transactions_list = []      

        self.add_block(proof=100,previous_hash=1)       #Genesis block

    def add_block(self, proof, previous_hash=None):
        """
        Creates a new block and adds it to the chain
        Parameters:
            proof (int): The proof given by the Proof of Work algorithm
            previous_hash (str): The hash of the previous block
        Returns:
            block (dict): The new block
        """

        block = {       #Creating the block
            'index': len(self.chain) + 1,
            'timestamp':time(),
            'transactions':self.transactions_list,
            'proof': proof,
            'previous_hash':previous_hash or self.hash(self.chain[-1])      #Finding the previous blocks hash
        }


        self.chain.append(block)        #Appending to the chain
        self.transactions_list = []     #Resetting the list of transactions

        return block


    @staticmethod
    def hash(block):
        """
        Returns a SHA-256 hash of the given block
        Parameters:
            block (dict): The block to find the hash of
        Returns:
            hash (str): The hash of the given block
        """
        block_string = json.dumps(block,sort_keys=True).encode()        #Ordering the block into a string
        hash = sha256(block_string).hexdigest()        #Finding the hash

        return hash

    @property
    def end_block(self):
        """
        Returns the last block in the chain
        Returns:
            last_block (dict): The last block in the chain
        """
        last_block = self.chain[-1]     #Finding the last block in the chain

        return last_block



app = Flask(__name__)       #Initialising flask app

node_id = str(uuid4()).replace('-','')      #Setting a node id

blockchain = Blockchain()

@app.route('/mine', methods=['GET'])
def mine():
    last_block = blockchain.end_block()      #Getting the proof for the block
    last_hash = blockchain.hash(last_block)
    proof = blockchain.proof_of_work(last_hash)

    reward = 1      #Value for the reward
    blockchain.new_transaction(        #Rewarding the miner
        sender = '0',
        recipient = node_id,
        amount = reward,
    )

    block = blockchain.add_block(proof,last_hash)       #Forging the block

    response = ({       #Creating a response 
        'message': "New Block Forged",
        'index': block['index'],
        'transactions': block['transactions'],
        'proof': block['proof'],
        'previous_hash': block['previous_hash'],
    })

    return jsonify(response), 200

完整的错误报告是:


[2020-01-06 18:36:06,213] ERROR in app: Exception on /mine [GET]
Traceback (most recent call last):
  File "C:\Users\mauri\Anaconda3\lib\site-packages\flask\app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\mauri\Anaconda3\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\mauri\Anaconda3\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\mauri\Anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\mauri\Anaconda3\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\mauri\Anaconda3\lib\site-packages\flask\app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "c:/Users/mauri/OneDrive/Documents/GitHub/Python-Blockchain/blockchain.py", line 251, in mine
    last_block = blockchain.end_block()      #Getting the proof for the block
TypeError: 'dict' object is not callable
127.0.0.1 - - [06/Jan/2020 18:36:06] "GET /mine HTTP/1.1" 500 -

您的end_block方法被装饰property 这意味着您应该在访问它时省略括号,例如

last_block = blockchain.end_block  # Parentheses omitted

通过包含括号,您将得到end_block返回的事物( last_block )并尝试将其作为函数调用,就像您执行last_block()

另外,除去@property从装饰end_block

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM