簡體   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