{"id":204083,"date":"2025-05-29T09:34:36","date_gmt":"2025-05-29T01:34:36","guid":{"rendered":"https:\/\/server.hk\/cnblog\/204083\/"},"modified":"2025-05-29T09:34:36","modified_gmt":"2025-05-29T01:34:36","slug":"%e4%bd%bf%e7%94%a8-vue%e3%80%81python-%e5%92%8c-flask-%e8%bf%9b%e8%a1%8c%e5%8c%ba%e5%9d%97%e9%93%be","status":"publish","type":"post","link":"https:\/\/server.hk\/cnblog\/204083\/","title":{"rendered":"\u4f7f\u7528 Vue\u3001Python \u548c Flask \u8fdb\u884c\u533a\u5757\u94fe"},"content":{"rendered":"<p><b><\/b>     <\/p>\n<h1>\u4f7f\u7528 Vue\u3001Python \u548c Flask \u8fdb\u884c\u533a\u5757\u94fe<\/h1>\n<p>\u6b22\u8fce\u5404\u4f4d\u5c0f\u4f19\u4f34\u6765\u5230\uff0c\u76f8\u805a\u4e8e\u6b64\u90fd\u662f\u7f18\u54c8\u54c8\u54c8\uff01\u4eca\u5929\u6211\u7ed9\u5927\u5bb6\u5e26\u6765<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\">\u300a\u4f7f\u7528 Vue\u3001Python \u548c Flask \u8fdb\u884c\u533a\u5757\u94fe\u300b<\/span>\uff0c\u8fd9\u7bc7\u6587\u7ae0\u4e3b\u8981\u8bb2\u5230<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\"><\/span>\u7b49\u7b49\u77e5\u8bc6\uff0c\u5982\u679c\u4f60\u5bf9<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\">\u6587\u7ae0<\/span>\u76f8\u5173\u7684\u77e5\u8bc6\u975e\u5e38\u611f\u5174\u8da3\u6216\u8005\u6b63\u5728\u81ea\u5b66\uff0c\u90fd\u53ef\u4ee5\u5173\u6ce8\u6211\uff0c\u6211\u4f1a\u6301\u7eed\u66f4\u65b0\u76f8\u5173\u6587\u7ae0\uff01\u5f53\u7136\uff0c\u6709\u4ec0\u4e48\u5efa\u8bae\u4e5f\u6b22\u8fce\u5728\u8bc4\u8bba\u7559\u8a00\u63d0\u51fa\uff01\u4e00\u8d77\u5b66\u4e60\uff01<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.17golang.com\/uploads\/20241027\/1730000751671db76fa5972.jpg\" class=\"aligncenter\"><\/p>\n<p>\u4f7f\u7528 vue.js \u524d\u7aef\u548c python \u540e\u7aef\u521b\u5efa\u5b8c\u6574\u7684\u533a\u5757\u94fe\u5e94\u7528\u7a0b\u5e8f\u3002<br \/> \u8ba9\u6211\u4eec\u6982\u8ff0\u57fa\u672c\u7ec4\u4ef6\u5e76\u63d0\u4f9b\u4e00\u4e9b\u793a\u4f8b\u4ee3\u7801\u7247\u6bb5\u6765\u5e2e\u52a9\u60a8\u5165\u95e8\u3002<\/p>\n<ul>\n<li>1.\u540e\u7aef\uff08python \u4e0e flask\uff09 \u521b\u5efa\u4e00\u4e2a\u7b80\u5355\u7684\u533a\u5757\u94fe\u7ed3\u6784\u3002 \u8bbe\u7f6e flask api \u4e0e\u533a\u5757\u94fe\u4ea4\u4e92\u3002<\/li>\n<li>2.\u524d\u7aef (vue.js)<\/li>\n<li>\u521b\u5efa\u4e00\u4e2a\u4e0e flask api \u901a\u4fe1\u7684 vue.js \u5e94\u7528\u7a0b\u5e8f\u3002<\/li>\n<li>\u663e\u793a\u533a\u5757\u94fe\u6570\u636e\u5e76\u5141\u8bb8\u7528\u6237\u4ea4\u4e92\uff08\u4f8b\u5982\u6dfb\u52a0\u65b0\u5757\uff09\u3002 \u7b2c 1 \u6b65\uff1a\u8bbe\u7f6e\u540e\u7aef<\/li>\n<li>\u5b89\u88c5 flask\uff1a\u786e\u4fdd\u5df2\u5b89\u88c5 flask\u3002\u60a8\u53ef\u4ee5\u4f7f\u7528 pip \u6765\u6267\u884c\u6b64\u64cd\u4f5c\uff1a<\/li>\n<\/ul>\n<pre>pip install flask\n<\/pre>\n<ol>\n<li>\u521b\u5efa\u4e00\u4e2a\u57fa\u672c\u7684\u533a\u5757\u94fe\u7c7b\uff1a <\/li>\n<\/ol>\n<pre># blockchain.py\nimport hashlib\nimport json\nfrom time import time\nfrom flask import flask, jsonify, request\n\nclass blockchain:\n    def __init__(self):\n        self.chain = []\n        self.current_transactions = []\n        self.new_block(previous_hash='1', proof=100)\n\n    def new_block(self, proof, previous_hash=none):\n        block = {\n            'index': len(self.chain) + 1,\n            'timestamp': time(),\n            'transactions': self.current_transactions,\n            'proof': proof,\n            'previous_hash': previous_hash or self.hash(self.chain[-1]),\n        }\n        self.current_transactions = []\n        self.chain.append(block)\n        return block\n\n    def new_transaction(self, sender, recipient, amount):\n        self.current_transactions.append({\n            'sender': sender,\n            'recipient': recipient,\n            'amount': amount,\n        })\n        return self.last_block['index'] + 1\n\n    @staticmethod\n    def hash(block):\n        block_string = json.dumps(block, sort_keys=true).encode()\n        return hashlib.sha256(block_string).hexdigest()\n\n    @property\n    def last_block(self):\n        return self.chain[-1]\n\napp = flask(__name__)\nblockchain = blockchain()\n\n@app.route('\/mine', methods=['post'])\ndef mine():\n    values = request.get_json()\n    required = ['proof', 'sender', 'recipient']\n    if not all(k in values for k in required):\n        return 'missing values', 400\n\n    index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])\n    blockchain.new_block(values['proof'])\n    response = {\n        'message': f'new block forged',\n        'index': index,\n        'block': blockchain.last_block,\n    }\n    return jsonify(response), 200\n\n@app.route('\/chain', methods=['get'])\ndef full_chain():\n    response = {\n        'chain': blockchain.chain,\n        'length': len(blockchain.chain),\n    }\n    return jsonify(response), 200\n\nif __name__ == '__main__':\n    app.run(debug=true)\n\n<\/pre>\n<p>\u7b2c 2 \u6b65\uff1a\u8bbe\u7f6e\u524d\u7aef<\/p>\n<ol>\n<li>\u521b\u5efa vue.js \u5e94\u7528\u7a0b\u5e8f\uff1a\u5982\u679c\u60a8\u5c1a\u672a\u521b\u5efa vue.js \u9879\u76ee\uff0c\u60a8\u53ef\u4ee5\u4f7f\u7528 vue cli \u6765\u521b\u5efa\uff1a <\/li>\n<\/ol>\n<pre>vue create my-blockchain-app\n\n<\/pre>\n<ol>\n<li>\u5b89\u88c5 axios \u8fdb\u884c api \u8c03\u7528\uff1a <\/li>\n<\/ol>\n<pre>npm install axios\n<\/pre>\n<ol>\n<li>\u521b\u5efa\u4e00\u4e2a\u7b80\u5355\u7684\u7ec4\u4ef6\uff1a <\/li>\n<\/ol>\n<pre>\/\/ src\/components\/blockchain.vue\n&lt;template&gt;\n  &lt;div&gt;\n    &lt;h1&gt;blockchain&lt;\/h1&gt;\n    &lt;button @click=\"fetchchain\"&gt;fetch blockchain&lt;\/button&gt;\n    &lt;ul&gt;\n      &lt;li v-for=\"block in blockchain\" :key=\"block.index\"&gt;\n        block #{{ block.index }} - {{ block.timestamp }}\n      &lt;\/li&gt;\n    &lt;\/ul&gt;\n  &lt;\/div&gt;\n&lt;\/template&gt;\n\n&lt;script&gt;\nimport axios from 'axios';\n\nexport default {\n  data() {\n    return {\n      blockchain: []\n    };\n  },\n  methods: {\n    fetchchain() {\n      axios.get('http:\/\/localhost:5000\/chain')\n        .then(response =&gt; {\n          this.blockchain = response.data.chain;\n        })\n        .catch(error =&gt; {\n          console.error(error);\n        });\n    }\n  }\n};\n&lt;\/script&gt;\n<\/pre>\n<p>\u8fd0\u884c flask \u540e\u7aef\uff1a\u786e\u4fdd\u60a8\u7684 python \u670d\u52a1\u5668\u6b63\u5728\u8fd0\u884c\uff1a<\/p>\n<pre>python blockchain.py\n\n<\/pre>\n<p>\u8fd0\u884c vue.js \u524d\u7aef\uff1a\u73b0\u5728\uff0c\u8fd0\u884c\u60a8\u7684 vue.js \u5e94\u7528\u7a0b\u5e8f\uff1a<\/p>\n<pre>\nnpm run serve\n<\/pre>\n<p>\u8ba9\u6211\u4eec\u901a\u8fc7\u6dfb\u52a0\u66f4\u591a\u9ad8\u7ea7\u529f\u80fd\u6765\u589e\u5f3a\u533a\u5757\u94fe\u5e94\u7528\u7a0b\u5e8f\uff0c\u4f8b\u5982\uff1a<\/p>\n<ul>\n<li>\u5de5\u4f5c\u91cf\u8bc1\u660e\u673a\u5236\uff1a\u5b9e\u73b0\u57fa\u672c\u7684\u5de5\u4f5c\u91cf\u8bc1\u660e\u7b97\u6cd5\u3002<\/li>\n<li>\u4ea4\u6613\u6c60\uff1a\u5141\u8bb8\u7528\u6237\u521b\u5efa\u4ea4\u6613\u5e76\u5728\u6316\u77ff\u4e4b\u524d\u5728\u6c60\u4e2d\u67e5\u770b\u5b83\u4eec\u3002 -\u8282\u70b9\u53d1\u73b0\uff1a\u5141\u8bb8\u591a\u4e2a\u8282\u70b9\u8fde\u63a5\u5e76\u5171\u4eab\u533a\u5757\u94fe\u3002 -\u6539\u8fdb\u7684\u524d\u7aef\uff1a\u521b\u5efa\u66f4\u5177\u4ea4\u4e92\u6027\u7684\u7528\u6237\u754c\u9762\u6765\u663e\u793a\u533a\u5757\u94fe\u548c\u4ea4\u6613\u3002 \u7b2c 1 \u6b65\uff1a\u589e\u5f3a\u540e\u7aef<\/li>\n<li>\u66f4\u65b0\u533a\u5757\u94fe\u7c7b \u6211\u4eec\u5c06\u5b9e\u73b0\u57fa\u672c\u7684\u5de5\u4f5c\u91cf\u8bc1\u660e\u7b97\u6cd5\u548c\u4ea4\u6613\u6c60\u3002 <\/li>\n<\/ul>\n<pre>\n# blockchain.py\nimport hashlib\nimport json\nfrom time import time\nfrom flask import flask, jsonify, request\nfrom urllib.parse import urlparse\nimport requests\n\nclass blockchain:\n    def __init__(self):\n        self.chain = []\n        self.current_transactions = []\n        self.nodes = set()\n        self.new_block(previous_hash='1', proof=100)\n\n    def new_block(self, proof, previous_hash=none):\n        block = {\n            'index': len(self.chain) + 1,\n            'timestamp': time(),\n            'transactions': self.current_transactions,\n            'proof': proof,\n            'previous_hash': previous_hash or self.hash(self.chain[-1]),\n        }\n        self.current_transactions = []\n        self.chain.append(block)\n        return block\n\n    def new_transaction(self, sender, recipient, amount):\n        self.current_transactions.append({\n            'sender': sender,\n            'recipient': recipient,\n            'amount': amount,\n        })\n        return self.last_block['index'] + 1\n\n    @staticmethod\n    def hash(block):\n        block_string = json.dumps(block, sort_keys=true).encode()\n        return hashlib.sha256(block_string).hexdigest()\n\n    @property\n    def last_block(self):\n        return self.chain[-1]\n\n    def proof_of_work(self, last_proof):\n        proof = 0\n        while not self.valid_proof(last_proof, proof):\n            proof += 1\n        return proof\n\n    @staticmethod\n    def valid_proof(last_proof, proof):\n        guess = f'{last_proof}{proof}'.encode()\n        guess_hash = hashlib.sha256(guess).hexdigest()\n        return guess_hash[:4] == \"0000\"  # adjust difficulty here\n\n    def register_node(self, address):\n        parsed_url = urlparse(address)\n        self.nodes.add(parsed_url.netloc)\n\n    def resolve_conflicts(self):\n        neighbours = self.nodes\n        new_chain = none\n        max_length = len(self.chain)\n\n        for node in neighbours:\n            response = requests.get(f'http:\/\/{node}\/chain')\n            if response.status_code == 200:\n                length = response.json()['length']\n                chain = response.json()['chain']\n                if length &gt; max_length and self.valid_chain(chain):\n                    max_length = length\n                    new_chain = chain\n\n        if new_chain:\n            self.chain = new_chain\n            return true\n        return false\n\n    def valid_chain(self, chain):\n        last_block = chain[0]\n        current_index = 1\n\n        while current_index &lt; len(chain):\n            block = chain[current_index]\n            if block['previous_hash'] != self.hash(last_block):\n                return false\n            if not self.valid_proof(last_block['proof'], block['proof']):\n                return false\n            last_block = block\n            current_index += 1\n        return true\n\napp = flask(__name__)\nblockchain = blockchain()\n\n@app.route('\/mine', methods=['post'])\ndef mine():\n    values = request.get_json()\n    required = ['sender', 'recipient']\n\n    if not all(k in values for k in required):\n        return 'missing values', 400\n\n    last_block = blockchain.last_block\n    last_proof = last_block['proof']\n    proof = blockchain.proof_of_work(last_proof)\n\n    blockchain.new_transaction(sender=values['sender'], recipient=values['recipient'], amount=1)\n    previous_hash = blockchain.hash(last_block)\n    block = blockchain.new_block(proof, previous_hash)\n\n    response = {\n        'message': 'new block forged',\n        'index': block['index'],\n        'block': block,\n    }\n    return jsonify(response), 200\n\n@app.route('\/transactions\/new', methods=['post'])\ndef new_transaction():\n    values = request.get_json()\n    required = ['sender', 'recipient', 'amount']\n\n    if not all(k in values for k in required):\n        return 'missing values', 400\n\n    index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])\n    response = {'message': f'transaction will be added to block {index}'}\n    return jsonify(response), 201\n\n@app.route('\/chain', methods=['get'])\ndef full_chain():\n    response = {\n        'chain': blockchain.chain,\n        'length': len(blockchain.chain),\n    }\n    return jsonify(response), 200\n\n@app.route('\/nodes\/register', methods=['post'])\ndef register_nodes():\n    values = request.get_json()\n    nodes = values.get('nodes')\n\n    if nodes is none:\n        return 'error: please supply a valid list of nodes', 400\n\n    for node in nodes:\n        blockchain.register_node(node)\n\n    response = {\n        'message': 'new nodes have been added',\n        'total_nodes': list(blockchain.nodes),\n    }\n    return jsonify(response), 201\n\n@app.route('\/nodes\/resolve', methods=['get'])\ndef consensus():\n    replaced = blockchain.resolve_conflicts()\n\n    if replaced:\n        response = {\n            'message': 'our chain was replaced',\n            'new_chain': blockchain.chain,\n        }\n    else:\n        response = {\n            'message': 'our chain is authoritative',\n            'chain': blockchain.chain,\n        }\n\n    return jsonify(response), 200\n\nif __name__ == '__main__':\n    app.run(debug=true)\n\n<\/pre>\n<p>\u7b2c 2 \u6b65\uff1a\u589e\u5f3a\u524d\u7aef<\/p>\n<ol>\n<li>\u5728 vue.js \u4e2d\u521b\u5efa\u4ea4\u6613\u8868\u5355 \u6211\u4eec\u73b0\u5728\u5c06\u521b\u5efa\u4e00\u4e2a\u8868\u5355\u4f9b\u7528\u6237\u63d0\u4ea4\u4ea4\u6613\u3002 <\/li>\n<\/ol>\n<pre>\/\/ src\/components\/blockchain.vue\n&lt;template&gt;\n  &lt;div&gt;\n    &lt;h1&gt;blockchain&lt;\/h1&gt;\n    &lt;button @click=\"fetchchain\"&gt;fetch blockchain&lt;\/button&gt;\n\n    &lt;h2&gt;transactions&lt;\/h2&gt;\n    &lt;form @submit.prevent=\"submittransaction\"&gt;\n      &lt;input type=\"text\" v-model=\"sender\" placeholder=\"sender\" required \/&gt;\n      &lt;input type=\"text\" v-model=\"recipient\" placeholder=\"recipient\" required \/&gt;\n      &lt;input type=\"number\" v-model=\"amount\" placeholder=\"amount\" required \/&gt;\n      &lt;button type=\"submit\"&gt;send transaction&lt;\/button&gt;\n    &lt;\/form&gt;\n\n    &lt;h2&gt;blockchain&lt;\/h2&gt;\n    &lt;ul&gt;\n      &lt;li v-for=\"block in blockchain\" :key=\"block.index\"&gt;\n        block #{{ block.index }} - {{ block.timestamp }}\n        &lt;ul&gt;\n          &lt;li v-for=\"transaction in block.transactions\" :key=\"transaction.sender\"&gt;\n            {{ transaction.sender }} -&gt; {{ transaction.recipient }}: {{ transaction.amount }}\n          &lt;\/li&gt;\n        &lt;\/ul&gt;\n      &lt;\/li&gt;\n    &lt;\/ul&gt;\n  &lt;\/div&gt;\n&lt;\/template&gt;\n\n&lt;script&gt;\nimport axios from 'axios';\n\nexport default {\n  data() {\n    return {\n      blockchain: [],\n      sender: '',\n      recipient: '',\n      amount: 0,\n    };\n  },\n  methods: {\n    fetchchain() {\n      axios.get('http:\/\/localhost:5000\/chain')\n        .then(response =&gt; {\n          this.blockchain = response.data.chain;\n        })\n        .catch(error =&gt; {\n          console.error(error);\n        });\n    },\n    submittransaction() {\n      const transaction = {\n        sender: this.sender,\n        recipient: this.recipient,\n        amount: this.amount,\n      };\n\n      axios.post('http:\/\/localhost:5000\/transactions\/new', transaction)\n        .then(response =&gt; {\n          alert(response.data.message);\n          this.fetchchain(); \/\/ refresh the blockchain view\n        })\n        .catch(error =&gt; {\n          console.error(error);\n        });\n    }\n  }\n};\n&lt;\/script&gt;\n<\/pre>\n<p>\u60a8\u53ef\u4ee5\u901a\u8fc7\u5728\u4e0d\u540c\u7aef\u53e3\u4e0a\u8fd0\u884c flask \u5e94\u7528\u7a0b\u5e8f\u7684\u591a\u4e2a\u5b9e\u4f8b\u6765\u6d4b\u8bd5\u5177\u6709\u591a\u4e2a\u8282\u70b9\u7684\u533a\u5757\u94fe\u3002\u4f8b\u5982\uff0c\u60a8\u53ef\u4ee5\u8fd0\u884c\uff1a<\/p>\n<pre>flask_run_port=5001 python blockchain.py\n<\/pre>\n<p>\u7136\u540e\uff0c\u60a8\u53ef\u4ee5\u4f7f\u7528 post \u8bf7\u6c42\u6ce8\u518c\u8282\u70b9\uff1a<\/p>\n<pre>curl -X POST -H \"Content-Type: application\/json\" -d '{\"nodes\": [\"localhost:5001\"]}' http:\/\/localhost:5000\/nodes\/register\n\n<\/pre>\n<p>\u8fd9\u4e2a\u66f4\u5148\u8fdb\u7684\u533a\u5757\u94fe\u5e94\u7528\u7a0b\u5e8f\u5305\u62ec\uff1a<br \/> -\u5de5\u4f5c\u91cf\u8bc1\u660e\uff1a\u6316\u6398\u65b0\u533a\u5757\u7684\u57fa\u672c\u673a\u5236\u3002<br \/> -\u4ea4\u6613\u6c60\uff1a\u7528\u6237\u53ef\u4ee5\u5728\u4ea4\u6613\u88ab\u5f00\u91c7\u4e4b\u524d\u521b\u5efa\u4ea4\u6613\u3002<br \/> -\u8282\u70b9\u53d1\u73b0\uff1a\u652f\u6301\u591a\u4e2a\u8282\u70b9\u548c\u5171\u8bc6\u673a\u5236\u3002<br \/> -\u4ea4\u4e92\u5f0f\u524d\u7aef\uff1a\u7528\u4e8e\u63d0\u4ea4\u4ea4\u6613\u548c\u67e5\u770b\u533a\u5757\u94fe\u7684 vue.js ui\u3002<\/p>\n<p>\u7f16\u7801\u6109\u5feb\uff01<\/p>\n<p>\u672c\u7bc7\u5173\u4e8e\u300a\u4f7f\u7528 Vue\u3001Python \u548c Flask \u8fdb\u884c\u533a\u5757\u94fe\u300b\u7684\u4ecb\u7ecd\u5c31\u5230\u6b64\u7ed3\u675f\u5566\uff0c\u4f46\u662f\u5b66\u65e0\u6b62\u5883\uff0c\u60f3\u8981\u4e86\u89e3\u5b66\u4e60\u66f4\u591a\u5173\u4e8e\u6587\u7ae0\u7684\u76f8\u5173\u77e5\u8bc6\uff0c\u8bf7\u5173\u6ce8\u516c\u4f17\u53f7\uff01<\/p>\n<p>      \u7248\u672c\u58f0\u660e \u672c\u6587\u8f6c\u8f7d\u4e8e\uff1adev.to \u5982\u6709\u4fb5\u72af\uff0c\u8bf7\u8054\u7cfb\u5220\u9664<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u4f7f\u7528 Vue\u3001Python \u548c &#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4925],"tags":[],"class_list":["post-204083","post","type-post","status-publish","format-standard","hentry","category-4925"],"_links":{"self":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/204083","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/comments?post=204083"}],"version-history":[{"count":0,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/204083\/revisions"}],"wp:attachment":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/media?parent=204083"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/categories?post=204083"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/tags?post=204083"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}