<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Neha Ghogale on Medium]]></title>
        <description><![CDATA[Stories by Neha Ghogale on Medium]]></description>
        <link>https://medium.com/@ghogale.neha?source=rss-7dc0cb0b0868------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*l8VtwtZh1ern5kEm.</url>
            <title>Stories by Neha Ghogale on Medium</title>
            <link>https://medium.com/@ghogale.neha?source=rss-7dc0cb0b0868------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:23:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ghogale.neha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Setting Up a Production-Ready IPFS Cluster with Docker Compose: A Complete Guide]]></title>
            <link>https://medium.com/coinmonks/setting-up-a-production-ready-ipfs-cluster-with-docker-compose-a-complete-guide-5180baff0b22?source=rss-7dc0cb0b0868------2</link>
            <guid isPermaLink="false">https://medium.com/p/5180baff0b22</guid>
            <dc:creator><![CDATA[Neha Ghogale]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 10:17:10 GMT</pubDate>
            <atom:updated>2025-02-01T16:35:34.839Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*11ZcjFEawadht4IzScaEiw.png" /></figure><p>As decentralized storage becomes increasingly important in modern applications, IPFS (InterPlanetary File System) has emerged as a leading protocol for content-addressed storage. In this guide, I’ll walk you through setting up a production-ready IPFS cluster using Docker Compose, making it easy to scale and manage your decentralized storage infrastructure.</p><h3>Why IPFS Cluster?</h3><p>Before diving into the technical setup, let’s understand why you might want to use IPFS Cluster:</p><p>- <strong>High Availability</strong>: Multiple IPFS nodes ensure your data remains accessible even if some nodes fail<br>- <strong>Load Distribution</strong>: Spread requests across multiple nodes for better performance<br>- <strong>Data Replication</strong>: Automatically maintain copies of your data across nodes<br>- <strong>Centralized Management</strong>: Manage multiple IPFS nodes from a single control point<br>- <strong>Scalability</strong>: Easily add or remove nodes as your storage needs change</p><h3>Architecture Overview</h3><p>Our setup consists of three main components:</p><p>1. Two IPFS nodes (using Kubo, the Go implementation of IPFS)<br>2. One IPFS Cluster service for coordinating the nodes<br>3. Docker Compose for orchestrating everything</p><p>Here’s how they work together:</p><p>- The IPFS nodes store and serve the actual data<br>- The cluster service manages pinning and data replication across nodes<br>- Docker Compose handles container orchestration and networking</p><h3>Step-by-Step Implementation</h3><h4>1. Setting Up the Directory Structure</h4><p>First, create a project directory with the following structure:</p><pre><br>mkdir ipfs-cluster<br>cd ipfs-cluster<br>mkdir -p ./data/node1 ./data/node2 ./cluster-data<br></pre><h4>2. Creating the Docker Compose Configuration</h4><p>Create a `docker-compose.yaml` file with the following configuration:</p><pre><br>version: ‘3.8’<br>services:<br> ipfs-node1:<br> image: ipfs/kubo:latest<br> container_name: ipfs-node1<br> ports:<br> — “4001:4001”<br> — “5001:5001”<br> — “8080:8080”<br> volumes:<br> — ./data/node1:/data/ipfs<br> environment:<br> — IPFS_PROFILE=server<br> entrypoint: [“/bin/sh”, “-c”]<br> command: &gt;<br> “ipfs init &amp;&amp;<br> ipfs config — json API.HTTPHeaders.Access-Control-Allow-Origin ‘[\”*\”]’ &amp;&amp;<br> ipfs config — json API.HTTPHeaders.Access-Control-Allow-Methods ‘[\”PUT\”, \”POST\”, \”GET\”]’ &amp;&amp;<br> ipfs config Addresses.API /ip4/0.0.0.0/tcp/5001 &amp;&amp;<br> ipfs config Addresses.Gateway /ip4/0.0.0.0/tcp/8080 &amp;&amp;<br> ipfs daemon — migrate”<br> restart: unless-stopped</pre><p># Similar configuration for ipfs-node2…</p><pre>ipfs-cluster:<br> image: ipfs/ipfs-cluster:latest<br> container_name: ipfs-cluster<br> platform: linux/amd64<br> ports:<br> — “9094:9094”<br> — “9096:9096”<br> volumes:<br> — ./cluster-data:/data/ipfs-cluster<br> depends_on:<br> — ipfs-node1<br> — ipfs-node2<br> environment:<br> — CLUSTER_SECRET=your_secret_here<br> — CLUSTER_IPFSHTTP_NODEMULTIADDRESS=/dns4/ipfs-node1/tcp/5001<br> command: [“daemon”]<br> restart: unless-stopped<br></pre><h4>3. Security Considerations</h4><p>Before deploying to production, make sure to:</p><ol><li>Generate a unique cluster secret:</li></ol><pre> openssl rand -hex 32</pre><p>2. Replace the CORS settings with your specific domains instead of `*`</p><p>3. Consider implementing basic authentication for the cluster API</p><p>4. Use Docker secrets for sensitive information</p><h3>Running the Cluster</h3><p>To start your IPFS cluster:</p><pre><br>docker-compose up -d</pre><p>This will:<br>- Initialize both IPFS nodes<br>- Start the cluster service<br>- Set up the necessary network connections</p><h3>Monitoring and Maintenance</h3><p>Health Checks</p><p>Monitor your cluster’s health using the API:</p><pre><br>curl http://localhost:9094/health</pre><h3>Adding Content</h3><p>To add content to your cluster:</p><pre><br>curl -X POST -F file=@/path/to/file “http://localhost:5001/api/v0/add<br></pre><p>The cluster will automatically handle replication across nodes.</p><h3>Performance Tuning</h3><p>For optimal performance in production:</p><p>1. IPFS Node Configuration:<br> — Increase the file descriptor limit<br> — Adjust the garbage collection interval<br> — Configure appropriate swarm connection limits</p><p>2. Resource Allocation:<br> — Allocate sufficient memory to each container<br> — Monitor disk space usage<br> — Consider using volume drivers for better I/O performance</p><h3>Scaling Considerations</h3><p>1. Add more IPFS nodes by duplicating the node configuration<br>2. Adjust port mappings for new nodes<br>3. Update the cluster configuration to recognize new nodes<br>4. Consider using Docker Swarm or Kubernetes for larger deployments</p><h3>Common Issues and Solutions</h3><p>If you see connection refused errors in the cluster logs, ensure:<br>- IPFS nodes are fully initialized before the cluster starts<br>- Network settings are correctly configured<br>- Port mappings are correct</p><h3>Data Persistence</h3><p>- Use named volumes for production<br>- Implement regular backups<br>- Monitor disk space usage</p><h3>Conclusion</h3><p>Setting up an IPFS cluster with Docker Compose provides a robust foundation for decentralized storage. This configuration offers:<br>- High availability through multiple nodes<br>- Easy scaling and management<br>- Automated data replication<br>- Production-ready security settings</p><p>While this setup works well for most use cases, consider your specific requirements for:<br>- Security<br>- Performance<br>- Scalability<br>- Monitoring<br>- Backup strategies</p><h3>Next Steps</h3><p>To further enhance your IPFS cluster:<br>1. Implement monitoring with Prometheus and Grafana<br>2. Set up automated backups<br>3. Configure alerting for critical events<br>4. Consider implementing a CDN for better content delivery</p><p>Stay tuned for more articles on advanced IPFS cluster configurations and optimizations!</p><p>— -</p><p>*Don’t forget to check out our other guides on decentralized technologies and infrastructure setup. Follow us for more technical deep dives!*</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5180baff0b22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/setting-up-a-production-ready-ipfs-cluster-with-docker-compose-a-complete-guide-5180baff0b22">Setting Up a Production-Ready IPFS Cluster with Docker Compose: A Complete Guide</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to develop Ethereum contract using Python Flask?]]></title>
            <link>https://medium.com/coinmonks/how-to-develop-ethereum-contract-using-python-flask-9758fe65976e?source=rss-7dc0cb0b0868------2</link>
            <guid isPermaLink="false">https://medium.com/p/9758fe65976e</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Neha Ghogale]]></dc:creator>
            <pubDate>Mon, 30 Jul 2018 13:34:21 GMT</pubDate>
            <atom:updated>2022-06-24T18:50:47.376Z</atom:updated>
            <content:encoded><![CDATA[<p>Storing data in a database is an integral part of any software application.Whoever has the control of that database is a master of that data. Blockchain technology stores data into the block inside blockchain network.So whenever some node syncs to the network they will get the copy of the data in the block. So there is no particular master of the data in this technology.</p><p>In this tutorial, we will write a smart contract(I will explain this further) for persisting user data on the blockchain. We will use python web3(python library for web3) for making and deploying smart contract. Once we have deployed smart contract on the blockchain. We will interact with smart contract using flask API to store some data/information. <strong>We are storing that on blockchain so that it will be immutable.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Z4x8YPKyFwC38se4nzlXZg.jpeg" /><figcaption>“Ethereum smart contract deployment flow” by Neha <a href="https://github.com/NehaGhogale">Ghogale</a></figcaption></figure><h4>Requirements:</h4><p>Python 3.6</p><h4><strong>Installation:</strong></h4><ol><li>Create a python virtual environment.</li></ol><p><a href="http://virtualenv.readthedocs.io/en/latest/">Virtualenv</a> keeps your Python packages in a virtual environment localized to your project, instead of forcing you to install your packages system-wide.</p><pre><em>$ virtualenv -p /usr/bin/python3.6 venv<br>$ source venv/bin/activate</em></pre><p>2. Now we need ethereum test chain like ganache.</p><p><a href="https://github.com/trufflesuite/ganache-cli/blob/master/README.md">Ganache</a> is a personal blockchain for Ethereum development you can use to deploy contracts, develop your applications, and run tests.</p><p>$ npm install -g ganache-cli</p><p>3. Install python web3.</p><p><a href="https://web3py.readthedocs.io/en/stable/">Web3.py</a> is a python library for interacting with ethereum. Its API is derived from the <a href="https://github.com/ethereum/wiki/wiki/JavaScript-API">Web3.js</a> Javascript API and should be familiar to anyone who has used web3.js.</p><p>$ pip3 install web3</p><p>4. Flask:</p><p><a href="http://flask.pocoo.org/">Flask</a><em> is a microframework for Python</em></p><p>$ pip3 install flask</p><p>5. Flask Restful</p><p><a href="https://flask-restful.readthedocs.io/en/latest/">Flask-RESTful</a> is an extension for Flask that adds support for quickly building REST APIs.</p><p>$ pip3 install flask-restful</p><p>6. Flask Marshmallow</p><p><a href="http://flask-marshmallow.readthedocs.io/en/latest/">Flask marshmallow</a> is an object serialization/deserialization library</p><p>$ pip3 install flask-marshmallow</p><h4>Start Ethereum Test blockchain server.</h4><p>To deploy smart contract we should start test ethereum server. We are using <a href="https://github.com/trufflesuite/ganache-cli/blob/master/README.md">ganache</a> for testing. Type below command in terminal.</p><pre>$ ganache-cli</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*byLtgRTVNhwbxynlB4HIaw.png" /><figcaption>Ganache Account Address</figcaption></figure><p>Ganache gives us 10 default test accounts with 100 fake ethers in each account for transaction. We will use these accounts for deploying and setting values in contracts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*hleX_pkMM8if3NqGudVSXg.png" /><figcaption>Ganache port</figcaption></figure><p>We can see the gas prize and limit along with host:port on which ganache is deployed. We will need this while deploying contract.</p><h4>Create user.sol file</h4><p>Now we will write the smart contract in <a href="http://solidity.readthedocs.io/en/latest/">solidity</a>.Solidity is the language to write smart contract on ethereum.Smart contract consists of data which we are going to store on blockchain with optional validation functions on the data and getter, setter method for accessing data.</p><p>For example, to make an attendance register on blockchain you will have an array of user objects.It will have the getter, setter method for accessing user.Since each user can mark her attendance only once per day, you need a validation function to check it.The smart contract is very similar to the application which we normally develop in any other language.</p><p>In below file, we are building simple user contract with the getter, setter functions.</p><ol><li>Declare <a href="https://solidity.readthedocs.io/en/v0.4.24/layout-of-source-files.html#version-pragma">solidity compiler</a> version in .sol file.</li></ol><p>pragma solidity ^0.4.21;</p><p>To know which compiler version used<br>$ solidity — version</p><p>2. <a href="https://solidity.readthedocs.io/en/v0.4.24/layout-of-source-files.html#importing-other-source-files/">Import library</a> file. we should use libraries for common utility functions.Libraries are only compiled once and used again and again(<a href="http://source https://github.com/ethereum/dapp-bin/tree/master/library/">click here</a> for some good library resources).</p><p>import “stringUtils.sol”;</p><p>3. Declare contract for user<br>contract userRecords {}</p><p>4. Now for the basic demo, we are going to store name and gender information about the user. So initialize this two variables using struct and enum data types.</p><pre>// enum type variable to store user gender <br>enum genderType { male, female } <br>// Actual user object which we will store in ethereum contract <br>struct user{ <br>    string name; genderType gender; <br>}</pre><p>5. Now we will declare user object of type user(struct). You can also declare it as public to access it from outside the contract(For visibility scope <a href="https://solidity.readthedocs.io/en/v0.4.24/contracts.html#visibility-and-getters">click here</a>).</p><pre>user user_obj;</pre><p>6. Now add getter, setter methods for the user object. We are going to persist every user’s information on blockchain.We should always make this method public as we will access them from outside the contract.</p><pre>// set user public function<br>// This is similar to persisting object in db.<br>function setUser(string name, string gender) public {<br>    genderType gender_type = getGenderFromString(gender);<br>    user_obj = user({name:name, gender: gender_type});<br>}</pre><pre>// get user public function<br>// This is similar to getting object from db.<br>function getUser() public returns (string, string) { <br>    return (user_obj.name, getGenderToString(user_obj.gender));<br>}</pre><p>7. Notice that we are using two internal helper functions getGenderFromString() and getGenderToString(). Lets add this internal functions. Declare them internal as we are not going to use them outside.</p><pre>// Internal function to convert genderType enum from string<br>function getGenderFromString(string gender) internal returns(genderType) {<br>    if(StringUtils.equal(gender, &quot;male&quot;)) {<br>        return genderType.male;<br>    } else {<br>        return genderType.female;<br>    }<br>}</pre><pre>// Internal function to convert genderType enum to string<br>function getGenderToString(genderType gender) internal returns (string) {<br>    if(gender == genderType.male) {<br>        return &quot;male&quot;;<br>    } else {<br>        return &quot;female&quot;;<br>    }<br>}</pre><p>We are using stringUtils.equal() library function. As this version of solidity doesn’t support string compare using (==).</p><p>8. Now our contract that is user.sol file will look like below:</p><pre>pragma solidity ^0.4.21;<br>// import library file<br>import &quot;stringUtils.sol&quot;;</pre><pre>contract userRecords {<br>  // enum type variable to store user gender<br>  enum genderType { male, female };<br>  // Actual user object which we will store<br>  struct user{<br>    string name;<br>    genderType gender;<br>  }<br>  // user object<br>  user user_obj;<br>  //Internal function to conver genderType enum from string<br>  function getGenderFromString(string gender) internal returns   (genderType) {<br>    if(StringUtils.equal(gender, &quot;male&quot;)) {<br>      return genderType.male;<br>    } else {<br>      return genderType.female;<br>    }<br>  }</pre><pre>  //Internal function to convert genderType enum to string<br>  function getGenderToString(genderType gender) internal returns (string) {<br>    if(gender == genderType.male) {<br>      return &quot;male&quot;;<br>    } else {<br>      return &quot;female&quot;;<br>    }<br>  }</pre><pre>  // set user public function<br>  // This is similar to persisting object in db.<br>  function setUser(string name, string gender) public {<br>    genderType gender_type = getGenderFromString(gender);<br>    user_obj = user({name:name, gender: gender_type});<br>  }<br>  <br>  // get user public function<br>  // This is similar to getting object from db.<br>  function getUser() public returns (string, string) {<br>    return (user_obj.name, getGenderToString(user_obj.gender));<br>  }<br>}</pre><h4>Compile and deploy above solidity file using python script.</h4><ol><li>In the below python script we need to instantiate test ethereum node using python-web3. We are setting ganche url as a test ethereum node. We will use below w3 object for deploying contract.</li></ol><pre>from web3 import Web3<br># web3.py instance<br>w3 = Web3(Web3.HTTPProvider(&quot;http://127.0.0.1:8545&quot;))</pre><p>2. Now we will compile solidity code. To compile solidity code we are using <a href="https://github.com/ethereum/py-solc">py-solc</a> that is python extension for solidity compiler.</p><pre>from solc import compile_files</pre><pre># compile all contract files<br>contracts = compile_files([&#39;user.sol&#39;, &#39;stringUtils.sol&#39;])</pre><pre># separate main file and link file<br>main_contract = contracts.pop(&quot;user.sol:userRecords&quot;)<br>library_link = contracts.pop(&quot;stringUtils.sol:StringUtils&quot;)</pre><p>3. Whenever you compile a .sol file with the import statement. We also need to link deploy address of the import file along with the main contract. So for that deploy all links first by compiling it(If already deployed then save the address) See below image main contract bin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AqzKXtjOiSuMpN5QPjAmNQ.png" /><figcaption>compile contract bin</figcaption></figure><p>When you compile your main contract and if you see bin part of it you will find<em> “_stringUtils.sol:StringUtils___________” for the library(it can be for the contract as well) which we are importing. This part we should replace with the library address by deploying it before contract.</em></p><p>4. Then we will link the library address with the main contract.</p><pre>from solc import link_code</pre><pre>def deploy_contract(contract_interface):<br>    # Instantiate and deploy contract<br>    contract = w3.eth.contract(<br>        abi=contract_interface[&#39;abi&#39;],<br>        bytecode=contract_interface[&#39;bin&#39;]<br>    )<br>    # Get transaction hash from deployed contract<br>    tx_hash = contract.deploy(<br>        transaction={&#39;from&#39;: w3.eth.accounts[1]}<br>    )<br>    # Get tx receipt to get contract address<br>    tx_receipt = w3.eth.getTransactionReceipt(tx_hash)<br>    return tx_receipt[&#39;contractAddress&#39;]</pre><pre>library_address = {<br>    &quot;stringUtils.sol:StringUtils&quot;: deploy_contract(library_link)<br>}<br>main_contract[&#39;bin&#39;] = link_code(<br>    main_contract[&#39;bin&#39;], library_address<br>)</pre><p>After linking see below image of main contract bin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUVfKnZHtlXEgPz6hmDwuw.png" /><figcaption>main contract bin 2</figcaption></figure><p>You will see import library bin has been added.</p><p>5. Now deploy main contract using our w3 object. Use default address from ethereum account <em>{‘from’: w3.eth.accounts[1]} </em>for deployment.</p><pre>def deploy_contract(contract_interface):<br>    # Instantiate and deploy contract<br>    contract = w3.eth.contract(<br>        abi=contract_interface[&#39;abi&#39;],<br>        bytecode=contract_interface[&#39;bin&#39;]<br>    )<br>    # Get transaction hash from deployed contract<br>    tx_hash = contract.deploy(<br>        transaction={&#39;from&#39;: w3.eth.accounts[1]}<br>    )<br>    # Get tx receipt to get contract address<br>    tx_receipt = w3.eth.getTransactionReceipt(tx_hash)<br>    return tx_receipt[&#39;contractAddress&#39;]</pre><pre>contract_address = deploy_contract(main_contract)</pre><p>You will see below lines in the tab where your ganache test server is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*KWSyFE2bXGQxdUhUlYXmwQ.png" /><figcaption>ganache receipt</figcaption></figure><p>This is the same info which you will get in tx_receipt after contract deployment.</p><p>6. Now store abi and contract_address in json file. so that we can use it later in flask api for storing user object in contract.</p><pre># add abi(application binary interface) and transaction reciept in json file<br>with open(&#39;data.json&#39;, &#39;w&#39;) as outfile:<br>    data = {<br>       &quot;abi&quot;: main_contract[&#39;abi&#39;],<br>       &quot;contract_address&quot;: deploy_contract(main_contract)<br>    }<br>    json.dump(data, outfile, indent=4, sort_keys=True)</pre><p>7. Now our complete script will look like below</p><pre>import json<br>from web3 import Web3<br>from solc import compile_files, link_code, compile_source</pre><pre># web3.py instance<br>w3 = Web3(Web3.HTTPProvider(&quot;http://127.0.0.1:8545&quot;))</pre><pre>def deploy_contract(contract_interface):<br>    # Instantiate and deploy contract<br>    contract = w3.eth.contract(<br>        abi=contract_interface[&#39;abi&#39;],<br>        bytecode=contract_interface[&#39;bin&#39;]<br>    )<br>    # Get transaction hash from deployed contract<br>    tx_hash =contract.deploy(transaction{&#39;from&#39;:w3.eth.accounts[1]})<br>    # Get tx receipt to get contract address<br>    tx_receipt = w3.eth.getTransactionReceipt(tx_hash)<br>    return tx_receipt[&#39;contractAddress&#39;]</pre><pre># compile all contract files<br>contracts = compile_files([&#39;user.sol&#39;, &#39;stringUtils.sol&#39;])</pre><pre># separate main file and link file<br>main_contract = contracts.pop(&quot;user.sol:userRecords&quot;)<br>library_link = contracts.pop(&quot;stringUtils.sol:StringUtils&quot;)</pre><pre># print bin part in  console you will see &#39;stringUtils&#39; in that we need to link library address in that bin code.<br># to that we have to deploy library code first then link it<br>library_address = {<br>    &quot;stringUtils.sol:StringUtils&quot;: deploy_contract(library_link)<br>}<br>main_contract[&#39;bin&#39;] = link_code(<br>    main_contract[&#39;bin&#39;], library_address)</pre><pre># add abi(application binary interface) and transaction reciept in json file<br>with open(&#39;data.json&#39;, &#39;w&#39;) as outfile:<br>    data = {<br>        &quot;abi&quot;: main_contract[&#39;abi&#39;],<br>        &quot;contract_address&quot;: deploy_contract(main_contract)<br>    }<br>    json.dump(data, outfile, indent=4, sort_keys=True)</pre><h4>Create flask api to store different values for user.</h4><p>You will deploy contract only once. But using its address you will store data again and again. Similarly, in the world of DB, you will define model/schema only once but you will add different rows/document in db.</p><ol><li>We will make flask post api to get user info from the user and return success.</li></ol><pre>from flask import Flask, Response, request, jsonify<br>from marshmallow import Schema, fields, ValidationError</pre><pre>def check_gender(data):<br>    valid_list = [&quot;male&quot;, &quot;female&quot;]<br>    if data not in valid_list:<br>        raise ValidationError(<br>            &#39;Invalid gender. Valid choices are&#39;+ valid_list<br>        )</pre><pre>#For api validations<br>class UserSchema(Schema):<br>    name = fields.String(required=True)<br>    gender = fields.String(required=True, validate=check_gender)</pre><pre># Initializing flask app<br>app = Flask(__name__)</pre><pre># api to set new user every api call</pre><pre>@app.route(&quot;/blockchain/user&quot;, methods=[&#39;POST&#39;])<br>def user():<br>    body = request.get_json()<br>    result, error = UserSchema().load(body)<br>    if error:<br>        return jsonify(error), 422<br>    return jsonify({&quot;data&quot;: result}), 200</pre><p>As this is not flask tutorial I will not elaborate much on this. Our API user will get data from client(curl request) and validate it and return the same to client(curl request)</p><p>2. Now we will initialize web3 object for communicating with deployed user contract.</p><pre>from web3 import Web3</pre><pre># web3.py instance<br>w3 = Web3(Web3.HTTPProvider(&quot;http://127.0.0.1:8545&quot;))</pre><p>3. Now we will get abi and contract address which we have stored earlier in “data.json” file.</p><pre>with open(&quot;data.json&quot;, &#39;r&#39;) as f:<br>     datastore = json.load(f)<br>     abi = datastore[&quot;abi&quot;]<br>     contract_address = datastore[&quot;contract_address&quot;]</pre><p>4. Chose default account address for transactions. Each time you set new values for user in contract. You will give some gas from your wallet.</p><pre>w3.eth.defaultAccount = w3.eth.accounts[1]</pre><p>5. Finally you will set the values you are getting in api call to user object in ethereum contract.</p><pre>@app.route(&quot;/blockchain/user&quot;, methods=[&#39;POST&#39;])<br>def user():<br>    # Create the contract instance with the newly-deployed address<br>    user = w3.eth.contract(address=contract_address, abi=abi)</pre><pre>    body = request.get_json()<br>    result, error = UserSchema().load(body)<br>    if error:<br>        return jsonify(error), 422</pre><pre>    tx_hash = user.functions.setUser(<br>        result[&#39;name&#39;],result[&#39;gender&#39;]<br>    )<br>    tx_hash = tx_hash.transact()<br>    # Wait for transaction to be mined...<br>    w3.eth.waitForTransactionReceipt(tx_hash)<br>    user_data = user.functions.getUser().call()<br>    return jsonify({&quot;data&quot;: user_data}), 200</pre><p>We are first getting deployed contract using abi and contract_address.</p><pre>user = w3.eth.contract(address=contract_address, abi=abi)</pre><p>Then we can call any contract public functions using the contract instance.After setting values for user we will make it public by using <a href="http://web3py.readthedocs.io/en/stable/contracts.html#web3.contract.ContractFunction.transact">transact()</a> method.This will make new user value added in ethereum block.</p><pre>tx_hash = user.functions.setUser(<br>    result[&#39;name&#39;],result[&#39;gender&#39;]<br>).transact()</pre><p>Now we can get already set values in the contract using <a href="http://web3py.readthedocs.io/en/stable/contracts.html#web3.contract.ContractFunction.call">call()</a> method this will call contract function without adding any block in blockchain.</p><pre>user_data = user.functions.getUser().call()</pre><p>Our final code for api file will look like below. Save this as “app.py”</p><pre>import json<br>from flask import Flask, Response, request, jsonify<br>from marshmallow import Schema, fields, ValidationError<br>from web3 import Web3</pre><pre># web3.py instance<br>w3 = Web3(Web3.HTTPProvider(&quot;http://127.0.0.1:8545&quot;))<br>w3.eth.defaultAccount = w3.eth.accounts[1]</pre><pre># Get stored abi and contract_address<br>with open(&quot;data.json&quot;, &#39;r&#39;) as f:<br>    datastore = json.load(f)<br>    abi = datastore[&quot;abi&quot;]<br>    contract_address = datastore[&quot;contract_address&quot;]</pre><pre>def check_gender(data):<br>    valid_list = [&quot;male&quot;, &quot;female&quot;]<br>    if data not in valid_list:<br>        raise ValidationError(<br>            &#39;Invalid gender. Valid choices are&#39;+ valid_list<br>        )</pre><pre>#For api validations<br>class UserSchema(Schema):<br>    name = fields.String(required=True)<br>    gender = fields.String(required=True, validate=check_gender)</pre><pre># Initializing flask app<br>app = Flask(__name__)</pre><pre># api to set new user every api call</pre><pre>@app.route(&quot;/blockchain/user&quot;, methods=[&#39;POST&#39;])<br>def user():<br>    # Create the contract instance with the newly-deployed address<br>    user = w3.eth.contract(address=contract_address, abi=abi)<br>    body = request.get_json()<br>    result, error = UserSchema().load(body)<br>    if error:<br>        return jsonify(error), 422<br>    tx_hash = user.functions.setUser(<br>        result[&#39;name&#39;],result[&#39;gender&#39;]<br>    ).transact()<br>    # Wait for transaction to be mined...<br>    receipt = w3.eth.waitForTransactionReceipt(tx_hash)<br>    user_data = user.functions.getUser().call()<br>    return jsonify({&quot;data&quot;: user_data}), 200</pre><p>Run below commands to start your server.</p><pre>$ FLASK_APP=app.py flask run</pre><h4>Call api using curl.</h4><pre>$ curl -H &quot;Content-Type: application/json&quot; --request POST -d &#39;{&quot;name&quot;:&quot;John Doe&quot;,&quot;gender&quot;:&quot;male&quot;}&#39; <a href="http://localhost:5000/blockchain/user">http://localhost:5000/blockchain/user</a></pre><p>You can find whole code <a href="https://github.com/NehaGhogale/basic_user_contract">here</a>.</p><p><strong>Resources:</strong></p><ol><li><a href="http://web3py.readthedocs.io/en/stable/quickstart.html">http://web3py.readthedocs.io/en/stable/quickstart.html</a></li><li><a href="https://www.ethereum.org/greeter">https://www.ethereum.org/greeter</a></li><li><a href="http://solidity.readthedocs.io/en/latest/">http://solidity.readthedocs.io/en/latest/</a></li></ol><blockquote>Join Coinmonks<a href="https://t.me/coincodecap"> Telegram Channel</a> and<a href="https://www.youtube.com/c/coinmonks/videos"> Youtube Channel</a> get daily <a href="http://coincodecap.com/">Crypto News</a></blockquote><h4>Also, Read</h4><ul><li><a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">Copy Trading</a> | <a href="https://medium.com/coinmonks/crypto-tax-software-ed4b4810e338">Crypto Tax Software</a></li><li><a href="https://coincodecap.com/grid-trading">Grid Trading</a> | <a href="https://medium.com/coinmonks/the-best-cryptocurrency-hardware-wallets-of-2020-e28b1c124069">Crypto Hardware Wallet</a></li><li><a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">Best Crypto Exchange</a> | <a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Best Crypto Exchange in India</a></li><li><a href="https://medium.com/coinmonks/best-crypto-apis-for-developers-5efe3a597a9f">Best Crypto APIs</a> for Developers</li><li><a href="http://Top 4 Telegram Channels for Crypto Traders">Crypto Telegram Signals</a> | <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">Crypto Trading Bot</a></li><li>Best <a href="https://medium.com/coinmonks/top-5-crypto-lending-platforms-in-2020-that-you-need-to-know-a1b675cec3fa">Crypto Lending Platform</a></li><li>An ultimate guide to <a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a></li><li><a href="https://coincodecap.com/best-vpns-for-crypto-trading">Best VPNs for Crypto Trading</a></li><li><a href="https://coincodecap.com/huobi-crypto-trading-signals">Crypto Trading Signals for Huobi</a> |<a href="https://medium.com/coinmonks/hitbtc-review-c5143c5d53c2"> HitBTC Review</a></li><li><a href="https://coincodecap.com/traderwagon-review">TraderWagon Review</a> | <a href="https://coincodecap.com/kraken-vs-gemini-vs-bityard">Kraken vs Gemini vs BitYard</a></li><li><a href="https://coincodecap.com/ftx-futures-trading">How to trade Futures on FTX Exchange</a></li><li><a href="https://coincodecap.com/okex-kucoin">OKEx vs KuCoin</a> | <a href="https://coincodecap.com/celsius-alternatives">Celsius Alternatives</a> |<a href="https://coincodecap.com/buy-vechain"> How to Buy VeChain</a></li><li><a href="https://coincodecap.com/3commas-vs-pionex-vs-cryptohopper">3Commas vs. Pionex vs. Cryptohopper</a></li><li><a href="https://coincodecap.com/cornix-trading-bot">How to use Cornix Trading Bot</a></li><li><a href="https://coincodecap.com/bitget-review">Bitget Review</a> |<a href="https://coincodecap.com/gemini-vs-blockfi"> Gemini vs BlockFi</a> cmd|<a href="https://coincodecap.com/okex-futures-trading"> OKEx Futures Trading</a></li><li><a href="https://coincodecap.com/buy-crypto-with-credit-card">10 Best Places to Buy Crypto with Credit Card</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9758fe65976e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/how-to-develop-ethereum-contract-using-python-flask-9758fe65976e">How to develop Ethereum contract using Python Flask?</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>