美文网首页区块链
python BlockChain(二) 单链请求

python BlockChain(二) 单链请求

作者: ab64fd4eaee3 | 来源:发表于2018-06-30 15:50 被阅读4次

    安装postman

    1.新建交易

    http://127.0.0.1:5000//transanctions/new

    {
        
              "sender":"liuping",
                "recipient":"lidan",
               "amount":500
    }
    
    image.png
    2.挖矿

    http://127.0.0.1:5000/mine

    2.查看当前链

    http://127.0.0.1:5000/chain

    代码:

    app = Flask(__name__)
    blockchain = BlockChain()
    
    node_identifier = str(uuid4()).replace("-","")
    
    @app.route("/index", methods=['GET'])
    def index():
        return "Hellp BlockChain"
    
    
    @app.route('/transanctions/new', methods=['POST'])
    def new_transaction():
        value = request.get_json()
        requested = ["sender", "recipient", "amount"]
    
        if value is None:
            return "Missing values", 400
    
        if not all(k in value for k in requested):
            return "Missing values", 400
    
        index = blockchain.new_transaction(value["sender"],
                                           value["recipient"],
                                           value["amount"])
    
        reponse = {"message": f'Transaction wille be add in {index}'}
    
        return jsonify(reponse), 201
    
    
    @app.route('/mine', methods=['GET'])
    def mine():
    
        last_block = blockchain.last_block
        last_proof = last_block["proof"]
    
        proof = blockchain.proof_work(last_proof)
        blockchain.new_transaction(sender="0",recipient=node_identifier,                      amount=1 )
        block = blockchain.new_block(proof,None)
    
        reponse = {
            'index': block["index"],
            'timestamp': block['timestamp'],
            'transcations': block['transcations'],
            'proof':  block['proof'],
            'previous_hash': block['previous_hash'],
        }
        return jsonify(reponse), 200
    
    
    @app.route('/chain', methods=['GET'])
    def full_chain():
        reponse = {
            'chain': blockchain.chain,
            'length': len(blockchain.chain)
        }
        return jsonify(reponse), 200
    
    
    if __name__ == '__main__':
        app.run(host="0.0.0.0", port=5000)
    
    

    相关文章

      网友评论

        本文标题:python BlockChain(二) 单链请求

        本文链接:https://www.haomeiwen.com/subject/rowtuftx.html