<?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 Deniz Parlak on Medium]]></title>
        <description><![CDATA[Stories by Deniz Parlak on Medium]]></description>
        <link>https://medium.com/@parlak-deniss?source=rss-4c72a9b7380------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MT2Wt1l9korq3GBJ_di1cQ.jpeg</url>
            <title>Stories by Deniz Parlak on Medium</title>
            <link>https://medium.com/@parlak-deniss?source=rss-4c72a9b7380------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:05:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@parlak-deniss/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[Realtime USDT Wallet Analytics with Apache Kafka & Apache Flink - etherscan.io]]></title>
            <link>https://parlak-deniss.medium.com/realtime-usdt-wallet-analytics-with-apache-kafka-apache-flink-etherscan-io-490ab4879156?source=rss-4c72a9b7380------2</link>
            <guid isPermaLink="false">https://medium.com/p/490ab4879156</guid>
            <category><![CDATA[metabase]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[apache-flink]]></category>
            <category><![CDATA[real-time-analytics]]></category>
            <category><![CDATA[etherscan]]></category>
            <dc:creator><![CDATA[Deniz Parlak]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 20:46:41 GMT</pubDate>
            <atom:updated>2024-12-03T20:46:41.110Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, there is too many Cryptocurrency website you can easily track them, create alert and and make some prediction. Today I’m going to show you a simple project that you can analyze token,transaction and wallets with very popular frameworks Apache Kafka and Apache Flink.</p><p>First let me explain general concept and ide of project.</p><p>There is hundred website you can collect crypto transaction data on internet, I choose <a href="http://etherscan.io/">etherscan.io</a> which is very useful. Basically first we have to get data from source which is etherscan.io, then we should play with original data. It means, adjust data just what we need. After that we can do analyze with Apache Flink (real-time) meanwhile we should write data on PostgreSQL as well. Finally we’ll see results on Metabase. When you have time you should try <a href="https://www.metabase.com/">Metabase</a> definitely, it’s very good open-source tool for not just only visualization. It can be use for multipurpose</p><p>Here is the Architecture of Project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMmaeykTrwpAao9l38ErtA.png" /></figure><h4><strong>We’ll try to find answers these 2 questions</strong></h4><p>1-) Top 3 hottest wallet according to sender</p><p>2-) Top 3 wallets receiving USDT transfers</p><p>You can add more questions and creating challenges for yourself.</p><p>I shared the entire Project so you can download and try.</p><p><a href="https://github.com/denizparlak1/etherscan-analytics.git">https://github.com/denizparlak1/etherscan-analytics.git</a></p><p><a href="https://github.com/denizparlak1/etherscan-analytics.git">https://github.com/denizparlak1/etherscan-analytics.git</a></p><p>First of all we need data, if you go etherscan.io and create account you can get free API access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYrnHkaU_UqsUhigWgp03Q.png" /></figure><p>By the way don’t forget to check it documentation. There is too many API request type we can call. But in this article i’ll focus on <strong>Get a list of ‘Normal’ Transactions By Address</strong></p><p><a href="https://docs.etherscan.io/etherscan-v2/api-endpoints/accounts">Accounts | Etherscan</a></p><p>This example i’ll examine USDT with this contract</p><p><strong>0xdAC17F958D2ee523a2206206994597C13D831ec7</strong></p><p>I won’t explain more details about contract, address etc.</p><p>In order to make request we need to write Rest API program. I made with Node.js but you can do it with whatever you want (Flask,go,Spring etc).</p><p>To clarify, after you get data successfully you have to write it in kafka topic because next step we’ll read from kafka for Apache Flink.</p><p>This is docker-compose.yaml for Apache Kafka, Zookeeper, PostgreSQL and Metabase</p><p>Also before start please don’t forget to install Apache Flink</p><p><a href="https://nightlies.apache.org/flink/flink-docs-stable/docs/try-flink/local_installation/">First steps</a></p><pre>version: &#39;3.8&#39;<br><br>services:<br>  kafka-zookeeper:<br>    image: confluentinc/cp-zookeeper:latest<br>    container_name: kafka-zookeeper<br>    environment:<br>      ZOOKEEPER_CLIENT_PORT: 2181<br>      ZOOKEEPER_TICK_TIME: 2000<br>    ports:<br>      - &quot;2181:2181&quot;<br>    networks:<br>      - kafka-network<br><br>  kafka-broker:<br>    image: confluentinc/cp-kafka:latest<br>    container_name: kafka-broker<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: kafka-zookeeper:2181<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092<br>      KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_DELETE_TOPIC_ENABLE: &quot;true&quot;<br>    ports:<br>      - &quot;9092:9092&quot;<br>    depends_on:<br>      - kafka-zookeeper<br>    networks:<br>      - kafka-network<br><br>  postgres-db:<br>    image: postgres:13<br>    container_name: postgres-db<br>    environment:<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: postgres<br>      POSTGRES_DB: analytics<br>    ports:<br>      - &quot;5432:5432&quot;<br>    networks:<br>      - kafka-network<br><br>  metabase:<br>    image: metabase/metabase<br>    container_name: metabase<br>    ports:<br>      - &quot;3000:3000&quot;<br>    depends_on:<br>      - postgres-db<br>    networks:<br>      - kafka-network<br>    environment:<br>      MB_DB_TYPE: postgres<br>      MB_DB_DBNAME: analytics<br>      MB_DB_PORT: 5432<br>      MB_DB_USER: postgres<br>      MB_DB_PASS: postgres<br>      MB_DB_HOST: postgres-db<br><br>networks:<br>  kafka-network:<br>    driver: bridge</pre><p>After those step, lets continue Apache Flink side. You can download code and use or you can create Java (Maven) project from scratch.</p><p>Apache Flink Repo</p><p>Basicly we need couple of things for Flink.</p><p>1-) Config classess for Kafka and PostgreSQL.</p><p>2-) Kafka consumer class to listen topics</p><p>3-) Process class for handle and parse first data from kafka</p><p>4-) Entity model class for PostgreSQL and Kafka</p><p>5-) Class for realtime analytics calculation</p><p>6-) Main for running application</p><p>Long story short, we’re sending data through kafka, Flink read and remove unnecessary areas, parsed transactions sending another topic and meanwhile same parsed transaction saves into PostgreSQL. I won’t share all code because you can check on my github repo. But let me explain important ones.</p><p>TransferProcessor is responsible for process unrefined data from kafka source, send them into new topic and save cassandra.</p><pre>package org.example.processor;<br><br>import com.fasterxml.jackson.databind.JsonNode;<br>import com.fasterxml.jackson.databind.ObjectMapper;<br>import org.apache.flink.api.common.functions.FilterFunction;<br>import org.apache.flink.api.common.functions.RichMapFunction;<br>import org.apache.flink.api.common.serialization.SimpleStringSchema;<br>import org.apache.flink.configuration.Configuration;<br>import org.apache.flink.streaming.api.datastream.DataStream;<br>import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;<br>import org.example.config.KafkaConfig;<br>import org.example.model.Transaction;<br>import org.example.service.TransactionService;<br><br>import java.math.BigDecimal;<br>import java.math.BigInteger;<br>import java.text.SimpleDateFormat;<br><br>public class TransferProcessor {<br><br>    public static void processAndSendTransfers(DataStream&lt;String&gt; stream, KafkaConfig kafkaConfig) {<br>        final TransactionService transactionService = new TransactionService();<br><br>        DataStream&lt;String&gt; processedTransfers = stream<br>                .filter(new TransferFilter())<br>                .map(new TransferMapper(transactionService))<br>                .filter(details -&gt; details != null);<br><br>        String outputTopic = kafkaConfig.getOutputTopic();<br><br>        FlinkKafkaProducer&lt;String&gt; kafkaProducer = new FlinkKafkaProducer&lt;&gt;(<br>                outputTopic,<br>                new SimpleStringSchema(),<br>                kafkaConfig.getProperties()<br>        );<br><br>        processedTransfers.addSink(kafkaProducer);<br>    }<br><br>    public static class TransferFilter implements FilterFunction&lt;String&gt; {<br>        private transient ObjectMapper objectMapper;<br><br>        @Override<br>        public boolean filter(String value) throws Exception {<br>            if (objectMapper == null) {<br>                objectMapper = new ObjectMapper();<br>            }<br><br>            try {<br>                JsonNode node = objectMapper.readTree(value);<br><br>                if (node.has(&quot;functionName&quot;)) {<br>                    String functionName = node.get(&quot;functionName&quot;).asText();<br><br>                    return functionName.contains(&quot;transfer&quot;);<br>                }<br>                return false;<br>            } catch (Exception e) {<br>                e.printStackTrace();<br>                return false;<br>            }<br>        }<br>    }<br><br>    public static class TransferMapper extends RichMapFunction&lt;String, String&gt; {<br>        private transient ObjectMapper objectMapper;<br>        private final TransactionService transactionService;<br><br>        public TransferMapper(TransactionService transactionService) {<br>            this.transactionService = transactionService;<br>        }<br><br>        @Override<br>        public void open(Configuration parameters) throws Exception {<br>            objectMapper = new ObjectMapper();<br>            transactionService.initialize();<br>        }<br><br>        @Override<br>        public String map(String json) throws Exception {<br>            return extractTransferDetailsAndSave(json);<br>        }<br><br>        private String extractTransferDetailsAndSave(String json) throws Exception {<br>            JsonNode node = objectMapper.readTree(json);<br><br>            String from = node.get(&quot;from&quot;).asText();<br>            String input = node.get(&quot;input&quot;).asText();<br>            String timestamp = node.get(&quot;timeStamp&quot;).asText();<br>            String hash = node.get(&quot;hash&quot;).asText();<br>            String functionName = node.get(&quot;functionName&quot;).asText();<br><br>            String toAddress = &quot;&quot;;<br>            BigInteger value = BigInteger.ZERO;<br><br>            String inputData = input.substring(10);<br><br>            if (functionName.contains(&quot;transferFrom&quot;)) {<br>                String fromAddressHex = inputData.substring(0, 64);<br>                String toAddressHex = inputData.substring(64, 128);<br>                String valueHex = inputData.substring(128, 192);<br><br>                toAddress = &quot;0x&quot; + toAddressHex.substring(24);<br>                value = new BigInteger(valueHex, 16);<br>            } else if (functionName.contains(&quot;transfer&quot;)) {<br>                String toAddressHex = inputData.substring(0, 64);<br>                String valueHex = inputData.substring(64, 128);<br><br>                toAddress = &quot;0x&quot; + toAddressHex.substring(24);<br>                value = new BigInteger(valueHex, 16);<br>            } else {<br>                return null;<br>            }<br><br>            int decimals = 6;<br>            BigDecimal tokenValue = new BigDecimal(value).divide(new BigDecimal(BigInteger.TEN.pow(decimals)));<br><br>            long timeInSeconds = Long.parseLong(timestamp);<br>            String readableDate = new SimpleDateFormat(&quot;yyyy-MM-dd HH:mm:ss&quot;)<br>                    .format(new java.util.Date(timeInSeconds * 1000));<br><br>            Transaction transaction = new Transaction();<br>            transaction.setTransactionId(hash);<br>            transaction.setFromAddress(from);<br>            transaction.setToAddress(toAddress);<br>            transaction.setValue(tokenValue.doubleValue());<br>            transaction.setTransactionDate(readableDate);<br><br>            transactionService.saveTransaction(transaction);<br><br>            ObjectMapper jsonMapper = new ObjectMapper();<br>            return jsonMapper.createObjectNode()<br>                    .put(&quot;transactionId&quot;, hash)<br>                    .put(&quot;from&quot;, from)<br>                    .put(&quot;to&quot;, toAddress)<br>                    .put(&quot;value&quot;, tokenValue.doubleValue())<br>                    .put(&quot;date&quot;, readableDate)<br>                    .toString();<br>        }<br>    }<br>}</pre><p>Unrefined data looks like this,</p><pre>{&quot;blockNumber&quot;:&quot;21316896&quot;,&quot;blockHash&quot;:&quot;0x98b28bdda64ce64d279a925c615db43e67131f7df25a05949e0f9719c33236d4&quot;,&quot;timeStamp&quot;:&quot;1733167487&quot;,&quot;hash&quot;:&quot;0xb270006dae606239be295c165106bed5dc19ad1239694b09296140047a5164be&quot;,&quot;nonce&quot;:&quot;2626596&quot;,&quot;transactionIndex&quot;:&quot;120&quot;,&quot;from&quot;:&quot;0x89e51fa8ca5d66cd220baed62ed01e8951aa7c40&quot;,&quot;to&quot;:&quot;0xdac17f958d2ee523a2206206994597c13d831ec7&quot;,&quot;value&quot;:&quot;0&quot;,&quot;gas&quot;:&quot;500000&quot;,&quot;gasPrice&quot;:&quot;30067654575&quot;,&quot;input&quot;:&quot;0xa9059cbb00000000000000000000000028d32cc0e4d60cf3c039c6ac003274d375d11366000000000000000000000000000000000000000000000000000000025355e14c&quot;,&quot;methodId&quot;:&quot;0xa9059cbb&quot;,&quot;functionName&quot;:&quot;transfer(address _to, uint256 _value)&quot;,&quot;contractAddress&quot;:&quot;&quot;,&quot;cumulativeGasUsed&quot;:&quot;6524840&quot;,&quot;txreceipt_status&quot;:&quot;1&quot;,&quot;gasUsed&quot;:&quot;46109&quot;,&quot;confirmations&quot;:&quot;6&quot;,&quot;isError&quot;:&quot;0&quot;}</pre><p>And refined data data look like this;</p><pre>{&quot;transactionId&quot;:&quot;0xb270006dae606239be295c165106bed5dc19ad1239694b09296140047a5164be&quot;,&quot;from&quot;:&quot;0x89e51fa8ca5d66cd220baed62ed01e8951aa7c40&quot;,&quot;to&quot;:&quot;0x28d32cc0e4d60cf3c039c6ac003274d375d11366&quot;,&quot;value&quot;:9988,&quot;date&quot;:&quot;2024-12-02 22:24:47&quot;}</pre><p>The RealtimeAnalytics class utilizes <strong>Apache Flink</strong> to process a continuous stream of blockchain transaction data in real-time. It performs two key analyses to monitor wallet activities:</p><p><strong>Top 3 Most Active Sending Wallets:</strong></p><ul><li><strong>Functionality:</strong> Tracks and identifies the top three wallets that initiate the highest number of transactions.</li><li><strong>Process:</strong> Each transaction is mapped to its sender address, and counts are aggregated to determine the most active senders.</li></ul><p><strong>Top 3 Highest Receiving Wallets by Transfer Value:</strong></p><ul><li><strong>Functionality:</strong> Identifies the top three wallets that receive the largest total value from transfers.</li><li><strong>Process:</strong> Transactions are grouped by the recipient address, and the total transferred value is summed to find the highest receivers.</li></ul><p><strong>How It Works:</strong></p><ul><li><strong>Data Ingestion:</strong> The system ingests JSON-formatted transaction data streams.</li><li><strong>Mapping Transactions:</strong> Using the TransactionMapper, each JSON string is converted into an AnalyticsTransaction object, extracting essential details like sender (from), receiver (to), transfer value (value), and timestamp (date).</li><li><strong>State Management:</strong> Leveraging Flink’s MapState, the system maintains running counts and total values for each wallet address.</li></ul><p><strong>Processing and Ranking:</strong></p><ul><li>For senders, the FinalTopNProcessFunction tallies the number of transactions per address and updates the top three active senders.</li><li>For receivers, the TopReceivingAddressesFunction aggregates the total value received by each address to determine the top three highest receivers.</li></ul><p><strong>Database Integration:</strong> The identified top wallets are periodically updated in a PostgreSQL database, ensuring that analytics remain current and can be easily accessed for reporting or visualization.</p><pre>package org.example.analytics;<br><br>import com.fasterxml.jackson.databind.ObjectMapper;<br>import org.apache.flink.api.common.functions.RichMapFunction;<br>import org.apache.flink.api.common.state.MapState;<br>import org.apache.flink.api.common.state.MapStateDescriptor;<br>import org.apache.flink.api.common.typeinfo.Types;<br>import org.apache.flink.api.java.tuple.Tuple2;<br>import org.apache.flink.configuration.Configuration;<br>import org.apache.flink.streaming.api.datastream.DataStream;<br>import org.apache.flink.streaming.api.functions.KeyedProcessFunction;<br>import org.apache.flink.util.Collector;<br>import org.example.model.AnalyticsTransaction;<br>import org.example.model.TopAddress;<br>import org.example.model.TopReceivingAddress;<br>import org.example.service.TopAddressService;<br>import org.example.service.TopReceivingAddressService;<br>import java.util.ArrayList;<br>import java.util.Comparator;<br>import java.util.List;<br>import java.util.Map;<br><br>public class RealtimeAnalytics {<br><br>    public static void analyzeTransactions(DataStream&lt;String&gt; stream) {<br>        DataStream&lt;AnalyticsTransaction&gt; transactionStream = stream<br>                .map(new TransactionMapper());<br><br>        transactionStream<br>                .map(transaction -&gt; new Tuple2&lt;&gt;(transaction.getFrom(), 1L))<br>                .returns(Types.TUPLE(Types.STRING, Types.LONG))<br>                .keyBy(tuple -&gt; &quot;global&quot;)<br>                .process(new FinalTopNProcessFunction(3));<br><br>        transactionStream<br>                .keyBy(transaction -&gt; &quot;global&quot;)<br>                .process(new TopReceivingAddressesFunction(3));<br>    }<br><br>    public static class TransactionMapper extends RichMapFunction&lt;String, AnalyticsTransaction&gt; {<br>        private transient ObjectMapper objectMapper;<br><br>        @Override<br>        public void open(Configuration parameters) throws Exception {<br>            objectMapper = new ObjectMapper();<br>        }<br><br>        @Override<br>        public AnalyticsTransaction map(String value) throws Exception {<br>            return objectMapper.readValue(value, AnalyticsTransaction.class);<br>        }<br>    }<br><br>    public static class FinalTopNProcessFunction extends KeyedProcessFunction&lt;String, Tuple2&lt;String, Long&gt;, String&gt; {<br>        private final int topSize;<br>        private transient MapState&lt;String, Long&gt; state;<br>        private transient List&lt;Tuple2&lt;String, Long&gt;&gt; lastTopN;<br>        private transient boolean timerRegistered;<br><br>        private transient TopAddressService topAddressService;<br><br>        public FinalTopNProcessFunction(int topSize) {<br>            this.topSize = topSize;<br>        }<br><br>        @Override<br>        public void open(Configuration parameters) throws Exception {<br>            MapStateDescriptor&lt;String, Long&gt; descriptor = new MapStateDescriptor&lt;&gt;(<br>                    &quot;addressCounts&quot;,<br>                    Types.STRING,<br>                    Types.LONG<br>            );<br>            state = getRuntimeContext().getMapState(descriptor);<br>            lastTopN = new ArrayList&lt;&gt;();<br>            timerRegistered = false;<br><br>            topAddressService = new TopAddressService();<br>            topAddressService.initialize();<br>        }<br><br>        @Override<br>        public void processElement(Tuple2&lt;String, Long&gt; value, Context ctx, Collector&lt;String&gt; out) throws Exception {<br>            String address = value.f0;<br>            Long count = state.get(address);<br>            if (count == null) {<br>                count = value.f1;<br>            } else {<br>                count += value.f1;<br>            }<br>            state.put(address, count);<br><br>            if (!timerRegistered) {<br>                ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 1000);<br>                timerRegistered = true;<br>            }<br>        }<br><br>        @Override<br>        public void onTimer(long timestamp, OnTimerContext ctx, Collector&lt;String&gt; out) throws Exception {<br>            List&lt;Tuple2&lt;String, Long&gt;&gt; allCounts = new ArrayList&lt;&gt;();<br>            for (Map.Entry&lt;String, Long&gt; entry : state.entries()) {<br>                allCounts.add(new Tuple2&lt;&gt;(entry.getKey(), entry.getValue()));<br>            }<br><br>            if (allCounts.isEmpty()) {<br>                return;<br>            }<br><br>            allCounts.sort(Comparator.comparingLong(o -&gt; -o.f1));<br>            List&lt;Tuple2&lt;String, Long&gt;&gt; topN = allCounts.subList(0, Math.min(topSize, allCounts.size()));<br><br>            if (!topN.equals(lastTopN)) {<br>                updateDatabase(topN);<br><br>                lastTopN = new ArrayList&lt;&gt;(topN);<br>            }<br><br>            ctx.timerService().registerProcessingTimeTimer(timestamp + 1000);<br>        }<br><br>        private void updateDatabase(List&lt;Tuple2&lt;String, Long&gt;&gt; topN) {<br>            List&lt;String&gt; newAddresses = new ArrayList&lt;&gt;();<br>            int rank = 1;<br><br>            for (Tuple2&lt;String, Long&gt; entry : topN) {<br>                TopAddress topAddress = new TopAddress();<br>                topAddress.setRank(rank);<br>                topAddress.setAddress(entry.f0);<br>                topAddress.setCount(entry.f1);<br><br>                topAddressService.saveOrUpdate(topAddress);<br><br>                newAddresses.add(entry.f0);<br>                rank++;<br>            }<br><br>            List&lt;TopAddress&gt; existingTopAddresses = topAddressService.getAllTopAddresses();<br><br>            for (TopAddress existingAddress : existingTopAddresses) {<br>                if (!newAddresses.contains(existingAddress.getAddress())) {<br>                    topAddressService.deleteTopAddress(existingAddress);<br>                }<br>            }<br>        }<br>    }<br><br>    public static class TopReceivingAddressesFunction extends KeyedProcessFunction&lt;String, AnalyticsTransaction, String&gt; {<br>        private final int topSize;<br>        private transient MapState&lt;String, Long&gt; state;<br>        private transient List&lt;Tuple2&lt;String, Long&gt;&gt; lastTopN;<br>        private transient boolean timerRegistered;<br><br>        private transient TopReceivingAddressService topReceivingAddressService;<br><br>        public TopReceivingAddressesFunction(int topSize) {<br>            this.topSize = topSize;<br>        }<br><br>        @Override<br>        public void open(Configuration parameters) throws Exception {<br>            MapStateDescriptor&lt;String, Long&gt; descriptor = new MapStateDescriptor&lt;&gt;(<br>                    &quot;addressValues&quot;,<br>                    Types.STRING,<br>                    Types.LONG<br>            );<br>            state = getRuntimeContext().getMapState(descriptor);<br>            lastTopN = new ArrayList&lt;&gt;();<br>            timerRegistered = false;<br><br>            topReceivingAddressService = new TopReceivingAddressService();<br>            topReceivingAddressService.initialize();<br>        }<br><br>        @Override<br>        public void processElement(AnalyticsTransaction value, Context ctx, Collector&lt;String&gt; out) throws Exception {<br>            String address = value.getTo();<br>            Long totalValue = state.get(address);<br>            if (totalValue == null) {<br>                totalValue = value.getValue();<br>            } else {<br>                totalValue += value.getValue();<br>            }<br>            state.put(address, totalValue);<br><br>            if (!timerRegistered) {<br>                ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 1000);<br>                timerRegistered = true;<br>            }<br>        }<br><br>        @Override<br>        public void onTimer(long timestamp, OnTimerContext ctx, Collector&lt;String&gt; out) throws Exception {<br>            List&lt;Tuple2&lt;String, Long&gt;&gt; allValues = new ArrayList&lt;&gt;();<br>            for (Map.Entry&lt;String, Long&gt; entry : state.entries()) {<br>                allValues.add(new Tuple2&lt;&gt;(entry.getKey(), entry.getValue()));<br>            }<br><br>            if (allValues.isEmpty()) {<br>                return;<br>            }<br><br>            allValues.sort(Comparator.comparingLong(o -&gt; -o.f1));<br>            List&lt;Tuple2&lt;String, Long&gt;&gt; topN = allValues.subList(0, Math.min(topSize, allValues.size()));<br><br>            if (!topN.equals(lastTopN)) {<br>                updateDatabase(topN);<br><br>                lastTopN = new ArrayList&lt;&gt;(topN);<br>            }<br><br>            ctx.timerService().registerProcessingTimeTimer(timestamp + 1000);<br>        }<br><br>        private void updateDatabase(List&lt;Tuple2&lt;String, Long&gt;&gt; topN) {<br>            List&lt;String&gt; newAddresses = new ArrayList&lt;&gt;();<br>            int rank = 1;<br><br>            for (Tuple2&lt;String, Long&gt; entry : topN) {<br>                TopReceivingAddress topReceivingAddress = new TopReceivingAddress();<br>                topReceivingAddress.setRank(rank);<br>                topReceivingAddress.setAddress(entry.f0);<br>                topReceivingAddress.setTotalValue(entry.f1);<br><br>                topReceivingAddressService.saveOrUpdate(topReceivingAddress);<br><br>                newAddresses.add(entry.f0);<br>                rank++;<br>            }<br><br>            List&lt;TopReceivingAddress&gt; existingTopReceivingAddresses = topReceivingAddressService.getAllTopReceivingAddresses();<br><br>            for (TopReceivingAddress existingAddress : existingTopReceivingAddresses) {<br>                if (!newAddresses.contains(existingAddress.getAddress())) {<br>                    topReceivingAddressService.deleteTopReceivingAddress(existingAddress);<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Example output</p><pre>Final Top 3 `from` Addresses&gt; Top 3 Addresses:<br>Address: 0x46340b20830761efd32832a74d7169b29feb9758, Count: 87<br>Address: 0x89e51fa8ca5d66cd220baed62ed01e8951aa7c40, Count: 81<br>Address: 0xdfd5293d8e347dfe59e90efd55b2956a1343963d, Count: 46</pre><p>After all of this stuff, just you need to go <a href="http://localhost:3000/">http://localhost:3000/</a> and adjust visualization settings for the results (I won’t explain here because it’s not that complicated).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bm0bTD1kAefirS0zU7zVDA.gif" /></figure><p>If you want to run this code on terminal (without IDE), you can compile with maven then run like;</p><pre>./bin/flink run -c org.example.flinkjob /path/to/your/flinkjob-jar.jar</pre><p>You can reach the code here,</p><p><a href="https://github.com/denizparlak1/etherscan-analytics.git">https://github.com/denizparlak1/etherscan-analytics.git</a></p><p><a href="https://github.com/denizparlak1/etherscan-analytics.git">https://github.com/denizparlak1/etherscan-analytics.git</a></p><p>And that’s all, if you have any question you can always touch with me</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=490ab4879156" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python File Upload to S3 with Celery]]></title>
            <link>https://parlak-deniss.medium.com/python-file-upload-to-s3-with-celery-df4b3eb5ef90?source=rss-4c72a9b7380------2</link>
            <guid isPermaLink="false">https://medium.com/p/df4b3eb5ef90</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[celery]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Deniz Parlak]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 10:50:02 GMT</pubDate>
            <atom:updated>2024-11-04T10:50:02.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*eGGqR8M1AYxjmQGZqU6hIg.png" /></figure><p><strong>Introduction to problem</strong></p><p>The worst thing for the end-user (or frontend side) is to wait after clicking some button or upload, download, or any similar operation.</p><p>Especially it’s a nightmare, the backend saves (or sends) huge sizes of files somewhere. Some modern frameworks, such as FastAPI and Flask, have some background tasks (libs), which help to wage them in the background without blocking regular operation. But it comes with a problem: It specifically makes the main application heavier because you’re sending every heavy operation to the background. Also if the process could not complete or got some error or your main app stopped (or crashed for some reason) you could lose that operation.</p><p><strong>Solution</strong></p><p>So what should we do?</p><p>If we find some solution to run heavy operations (It depends sometimes heavy for memory, sometimes heavy for network, etc.) in separate place, we can safely run our program without any thought.</p><p>The keyword is <strong>Celery</strong>.</p><p>What is Celery, I just copy-pasted from the original</p><blockquote>Task queues are used as a mechanism to distribute work across threads or machines.</blockquote><blockquote>A task queue’s input is a unit of work called a task. Dedicated worker processes constantly monitor task queues for new work to perform.</blockquote><blockquote>Celery communicates via messages, usually using a broker to mediate between clients and workers. To initiate a task the client adds a message to the queue, the broker then delivers that message to a worker.</blockquote><blockquote>A Celery system can consist of multiple workers and brokers, giving way to high availability and horizontal scaling.</blockquote><blockquote>Celery is written in Python, but the protocol can be implemented in any language. In addition to Python there’s <a href="https://github.com/mher/node-celery">node-celery</a> and <a href="https://github.com/IBM/node-celery-ts">node-celery-ts</a> for Node.js, and a <a href="https://github.com/gjedeer/celery-php">PHP client</a>.</blockquote><blockquote>Language interoperability can also be achieved exposing an HTTP endpoint and having a task that requests it (webhooks).</blockquote><p>Action speaks louder than words, let&#39;s start coding</p><p>You can fork the repository but I’ll write even so.</p><p><a href="https://github.com/denizparlak1/celery-app.git">https://github.com/denizparlak1/celery-app.git</a></p><p>Let’s create FastAPI project from scratch. I’m using poetry for package management it’s the best one in my opinion. If you don’t have it yet, just check the documentation <a href="https://python-poetry.org/"><strong>https://python-poetry.org/</strong></a></p><pre>mkdir celery-app<br>cd celery-app</pre><pre>poetry init<br>poetry add fastapi,uvicorn,celery,redis,python,pydantic-settings,boto3,python-multipart,logging</pre><p>Brief summary, we need 3 things;</p><p>To send a request we have to create a controller, service for s3 implementation, config for celery, and .env, and finally task function for celery.</p><p>This is our file structure. I tried to keep it simple. I’m not saying this is the best structure, it depends on the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*0CcncAv3M8p4GG08foxAUw.png" /></figure><pre>from celery import Celery<br><br>celery_app = Celery(<br>    &#39;worker&#39;,<br>    broker=&#39;redis://redis:6379/0&#39;,<br>    backend=&#39;redis://redis:6379/0&#39;<br>)<br><br>celery_app.autodiscover_tasks([&#39;tasks.uploads&#39;], force=True)</pre><p><strong>Important thing. tasks.upload to represent where your task function is created.</strong></p><p>Otherwise, celery won’t run properly.</p><pre>from pydantic_settings import BaseSettings<br><br>class Settings(BaseSettings):<br>    AWS_ACCESS_KEY_ID: str<br>    AWS_SECRET_ACCESS_KEY: str<br>    AWS_S3_BUCKET_NAME: str<br>    AWS_REGION: str<br><br>    class Config:<br>        env_file = &quot;.env&quot;<br><br>settings = Settings()</pre><p>We created a Settings class to handle environment management.</p><pre>import io<br>import boto3<br>from fastapi import Depends<br>from service.s3.s3_config import S3Config<br>from service.s3.s3_config import get_s3_config<br><br><br>class S3Service:<br>    &quot;&quot;&quot;Service for handling operations with Amazon S3.&quot;&quot;&quot;<br><br>    def __init__(self, config: S3Config):<br>        &quot;&quot;&quot;Initialize the S3 client and set the bucket name.&quot;&quot;&quot;<br>        self.client = boto3.client(<br>            &#39;s3&#39;,<br>            aws_access_key_id=config.aws_access_key_id,<br>            aws_secret_access_key=config.aws_secret_access_key,<br>            region_name=config.region_name<br>        )<br>        self.bucket_name = config.bucket_name<br><br>    def upload_file(self, file_path: str, file_content: bytes, content_type: str = None) -&gt; str:<br>        &quot;&quot;&quot;Upload a file to S3.<br><br>        Args:<br>            file_path (str): The path where the file will be stored in the S3 bucket.<br>            file_content (bytes): The content of the file to be uploaded.<br>            content_type (str, optional): The content type of the file.<br><br>        Returns:<br>            str: The path of the uploaded file.<br><br>        Raises:<br>            Exception: If the upload fails.<br>        &quot;&quot;&quot;<br>        try:<br>            self.client.upload_fileobj(<br>                io.BytesIO(file_content),<br>                self.bucket_name,<br>                file_path,<br>                ExtraArgs={&quot;ContentType&quot;: content_type}<br>            )<br>            return file_path<br>        except Exception as e:<br>            raise Exception(f&quot;Failed to upload file to S3: {e}&quot;) from e<br><br><br>def get_s3_service(config: S3Config = Depends(get_s3_config)) -&gt; S3Service:<br>    &quot;&quot;&quot;Dependency injection for S3Service.<br><br>    Args:<br>        config (S3Config): The S3 configuration object.<br><br>    Returns:<br>        S3Service: An instance of the S3Service.<br>    &quot;&quot;&quot;<br>    return S3Service(config)</pre><pre>from config.enviroment.env_config import settings<br><br>class S3Config:<br>    def __init__(self):<br>        self.aws_access_key_id = settings.AWS_ACCESS_KEY_ID<br>        self.aws_secret_access_key = settings.AWS_SECRET_ACCESS_KEY<br>        self.region_name = settings.AWS_REGION<br>        self.bucket_name = settings.AWS_S3_BUCKET_NAME<br><br><br>def get_s3_config() -&gt; S3Config:<br>    return S3Config()</pre><p>S3 class and S3 config for connecting bucket and send file to s3 bucket.</p><pre>import logging<br>from fastapi import Depends<br>from config.celery.celery_config import celery_app<br>from service.s3.s3_config import S3Config<br>from service.s3.s3_service import S3Service<br><br><br>@celery_app.task<br>def upload_file_to_s3(file_content: bytes, filename: str,content_type: str):<br>    &quot;&quot;&quot;Upload a file to S3 using the S3Service.<br><br>    Args:<br>        file_content (bytes): The content of the file to be uploaded.<br>        filename (str): The name of the file to be uploaded.<br><br>    Returns:<br>        str: The path of the uploaded file.<br>        :param filename:<br>        :param content_type:<br>    &quot;&quot;&quot;<br>    s3_config = S3Config()<br>    s3_service = S3Service(s3_config)<br>    try:<br>        uploaded_file_path = s3_service.upload_file(filename, file_content,content_type)<br>        return uploaded_file_path<br>    except Exception as e:<br>        logging.error(f&quot;Error during file upload: {e}&quot;)<br>        raise</pre><p>This is our task for celery, so basically this will run in queue and separated worker.</p><pre>from tasks.uploads.upload_tasks import upload_file_to_s3</pre><p>We also need to add it to the __init__.py file so that the cerelery configuration can see this function.</p><pre>from fastapi import APIRouter,UploadFile,File,Depends,HTTPException<br>from tasks.uploads.upload_tasks import upload_file_to_s3<br>from service.s3.s3_service import get_s3_service<br>from service.s3.s3_config import get_s3_config<br>from service.s3.s3_config import S3Config<br>import logging<br>router = APIRouter()<br><br><br>@router.post(&quot;/upload/&quot;)<br>async def upload_file(file: UploadFile = File(...)):<br>    &quot;&quot;&quot;Upload a file and trigger a Celery task to process it.&quot;&quot;&quot;<br>    file_content = await file.read()<br><br>    try:<br>        uploaded_file_path = upload_file_to_s3.delay(file_content, file.filename,file.content_type)<br>        return {&quot;message&quot;: &quot;File uploaded successfully!&quot;, &quot;task_id&quot;: uploaded_file_path.id}<br>    except Exception as e:<br>        logging.error(f&quot;Error during file upload: {e}&quot;)<br>        raise HTTPException(status_code=500, detail=&quot;File upload failed&quot;)</pre><p>Controller for sending request.</p><p>I’m using router so we have to add include_router line in main.py</p><pre>from fastapi import FastAPI<br>from controller.s3 import s3_controller<br>app = FastAPI()<br><br><br>app.include_router(s3_controller.router, prefix=&quot;/api/content&quot;,tags=[&quot;File Upload&quot;])</pre><p>Finally let’s create Dockerfile and docker-compose file. So we can run all system in container.</p><pre>services:<br>  fastapi:<br>    build: .<br>    container_name: fastapi_app<br>    command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload<br>    volumes:<br>      - .:/app<br>    ports:<br>      - &quot;8000:8000&quot;<br>    depends_on:<br>      - redis<br>      - celery_worker<br><br>  redis:<br>    image: redis:6.2<br>    container_name: redis<br>    ports:<br>      - &quot;6379:6379&quot;<br><br>  celery_worker:<br>    build: .<br>    container_name: celery_worker<br>    command: celery -A config.celery.celery_config.celery_app worker --loglevel=DEBUG<br>    volumes:<br>      - .:/app<br>    depends_on:<br>      - redis</pre><pre>FROM python:3.9<br><br>WORKDIR /app<br><br>COPY pyproject.toml poetry.lock* /app/<br><br>RUN pip install poetry<br><br>RUN poetry config virtualenvs.create false &amp;&amp; poetry install --no-dev<br><br>COPY . /app<br><br>CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>Let’s start the application.</p><pre> docker-compose up --build</pre><p>Then send the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nW6hZWgx00RxKi7kVAJaKw.png" /></figure><p>After that check the console, you should see similar output like this,</p><pre>fastapi_app    | INFO:     192.168.97.1:58732 - &quot;POST /api/content/upload/ HTTP/1.1&quot; 200 OK<br>celery_worker  | [2024-11-04 10:21:33,495: INFO/MainProcess] Task tasks.uploads.upload_tasks.upload_file_to_s3[44368494-d85d-4a92-a399-511915e9b36a] received<br>celery_worker  | [2024-11-04 10:21:33,505: DEBUG/MainProcess] TaskPool: Apply &lt;function fast_trace_task at 0xffffbbcb2d30&gt; (args:(&#39;tasks.uploads.upload_tasks.upload_file_to_s3&#39;, &#39;44368494-d85d-4a92-a399-511915e9b36a&#39;, {&#39;lang&#39;: &#39;py&#39;, &#39;task&#39;: &#39;tasks.uploads.upload_tasks.upload_file_to_s3&#39;, &#39;id&#39;: &#39;44368494-d85d-4a92-a399-511915e9b36a&#39;, &#39;shadow&#39;: None, &#39;eta&#39;: None, &#39;expires&#39;: None, &#39;group&#39;: None, &#39;group_index&#39;: None, &#39;retries&#39;: 0, &#39;timelimit&#39;: [None, None], &#39;root_id&#39;: &#39;44368494-d85d-4a92-a399-511915e9b36a&#39;, &#39;parent_id&#39;: None, &#39;argsrepr&#39;:... kwargs:{})<br>celery_worker  | [2024-11-04 10:21:33,535: DEBUG/ForkPoolWorker-8] Event choose-service-name: calling handler &lt;function handle_service_name_alias at 0xffffbadad700&gt;<br>celery_worker  | [2024-11-04 10:21:33,550: DEBUG/ForkPoolWorker-8] Event creating-client-class.s3: calling handler &lt;function add_generate_presigned_post at 0xffffbab8e160&gt;<br>celery_worker  | [2024-11-04 10:21:33,550: DEBUG/ForkPoolWorker-8] Event creating-client-class.s3: calling handler &lt;function lazy_call.&lt;locals&gt;._handler at 0xffffba331940&gt;<br>celery_worker  | [2024-11-04 10:21:33,551: DEBUG/ForkPoolWorker-8] Event creating-client-class.s3: calling handler &lt;function add_generate_presigned_url at 0xffffbab8cee0&gt;<br>celery_worker  | [2024-11-04 10:21:33,553: DEBUG/ForkPoolWorker-8] Looking for endpoint for s3 via: environment_service<br>celery_worker  | [2024-11-04 10:21:33,553: DEBUG/ForkPoolWorker-8] Looking for endpoint for s3 via: environment_global<br>celery_worker  | [2024-11-04 10:21:33,553: DEBUG/ForkPoolWorker-8] Looking for endpoint for s3 via: config_service<br>celery_worker  | [2024-11-04 10:21:33,553: DEBUG/ForkPoolWorker-8] Looking for endpoint for s3 via: config_global<br>celery_worker  | [2024-11-04 10:21:33,554: DEBUG/ForkPoolWorker-8] No configured endpoint found.<br>celery_worker  | [2024-11-04 10:21:33,558: DEBUG/ForkPoolWorker-8] Setting s3 timeout as (60, 60)<br>celery_worker  | [2024-11-04 10:21:33,581: DEBUG/ForkPoolWorker-8] Registering retry handlers for service: s3<br>celery_worker  | [2024-11-04 10:21:33,581: DEBUG/ForkPoolWorker-8] Registering S3 region redirector handler<br>celery_worker  | [2024-11-04 10:21:33,582: DEBUG/ForkPoolWorker-8] Registering S3Express Identity Resolver<br>celery_worker  | [2024-11-04 10:21:33,582: DEBUG/ForkPoolWorker-8] Opting out of CRT Transfer Manager. Preferred client: auto, CRT available: False, Instance Optimized: False.<br>celery_worker  | [2024-11-04 10:21:33,582: DEBUG/ForkPoolWorker-8] Using default client. pid: 15, thread: 281473870299168<br>celery_worker  | [2024-11-04 10:21:33,584: DEBUG/ForkPoolWorker-8] Acquiring 0<br>celery_worker  | [2024-11-04 10:21:33,589: DEBUG/ForkPoolWorker-8] UploadSubmissionTask(transfer_id=0, {&#39;transfer_future&#39;: &lt;s3transfer.futures.TransferFuture object at 0xffffba5e6c10&gt;}) about to wait for the following futures []<br>celery_worker  | [2024-11-04 10:21:33,590: DEBUG/ForkPoolWorker-8] UploadSubmissionTask(transfer_id=0, {&#39;transfer_future&#39;: &lt;s3transfer.futures.TransferFuture object at 0xffffba5e6c10&gt;}) done waiting for dependent futures<br>celery_worker  | [2024-11-04 10:21:33,590: DEBUG/ForkPoolWorker-8] Executing task UploadSubmissionTask(transfer_id=0, {&#39;transfer_future&#39;: &lt;s3transfer.futures.TransferFuture object at 0xffffba5e6c10&gt;}) with kwargs {&#39;client&#39;: &lt;botocore.client.S3 object at 0xffffb9a801f0&gt;, &#39;config&#39;: &lt;boto3.s3.transfer.TransferConfig object at 0xffffba553550&gt;, &#39;osutil&#39;: &lt;s3transfer.utils.OSUtils object at 0xffffbaaaf9a0&gt;, &#39;request_executor&#39;: &lt;s3transfer.futures.BoundedExecutor object at 0xffffbaaafd90&gt;, &#39;transfer_future&#39;: &lt;s3transfer.futures.TransferFuture object at 0xffffba5e6c10&gt;}<br>celery_worker  | [2024-11-04 10:21:33,590: DEBUG/ForkPoolWorker-8] Submitting task PutObjectTask(transfer_id=0, {&#39;bucket&#39;: &#39;&#39;, &#39;key&#39;: &#39;INVOICE.pdf&#39;, &#39;extra_args&#39;: {&#39;ContentType&#39;: &#39;application/pdf&#39;}}) to executor &lt;s3transfer.futures.BoundedExecutor object at 0xffffbaaafd90&gt; for transfer request: 0.<br>celery_worker  | [2024-11-04 10:21:33,590: DEBUG/ForkPoolWorker-8] Acquiring 0<br>celery_worker  | [2024-11-04 10:21:33,592: DEBUG/ForkPoolWorker-8] PutObjectTask(transfer_id=0, {&#39;bucket&#39;: &#39;&#39;, &#39;key&#39;: &#39;INVOICE.pdf&#39;, &#39;extra_args&#39;: {&#39;ContentType&#39;: &#39;application/pdf&#39;}}) about to wait for the following futures []<br>celery_worker  | [2024-11-04 10:21:33,593: DEBUG/ForkPoolWorker-8] PutObjectTask(transfer_id=0, {&#39;bucket&#39;: &#39;&#39;, &#39;key&#39;: &#39;INVOICE.pdf&#39;, &#39;extra_args&#39;: {&#39;ContentType&#39;: &#39;application/pdf&#39;}}) done waiting for dependent futures<br>celery_worker  | [2024-11-04 10:21:33,593: DEBUG/ForkPoolWorker-8] Executing task PutObjectTask(transfer_id=0, {&#39;bucket&#39;: &#39;&#39;, &#39;key&#39;: &#39;INVOICE.pdf&#39;, &#39;extra_args&#39;: {&#39;ContentType&#39;: &#39;application/pdf&#39;}}) with kwargs {&#39;client&#39;: &lt;botocore.client.S3 object at 0xffffb9a801f0&gt;, &#39;fileobj&#39;: &lt;s3transfer.utils.ReadFileChunk object at 0xffffbadd28b0&gt;, &#39;bucket&#39;: &#39;&#39;, &#39;key&#39;: &#39;INVOICE.pdf&#39;, &#39;extra_args&#39;: {&#39;ContentType&#39;: &#39;application/pdf&#39;}}<br>celery_worker  | [2024-11-04 10:21:33,593: DEBUG/ForkPoolWorker-8] Event before-parameter-build.s3.PutObject: calling handler &lt;function validate_ascii_metadata at 0xffffbaac40d0&gt;<br>celery_worker  | [2024-11-04 10:21:33,594: DEBUG/ForkPoolWorker-8] Releasing acquire 0/None<br>celery_worker  | [2024-11-04 10:21:33,594: DEBUG/ForkPoolWorker-8] Event before-parameter-build.s3.PutObject: calling handler &lt;function sse_md5 at 0xffffbaac54c0&gt;<br>celery_worker  | [2024-11-04 10:21:33,594: DEBUG/ForkPoolWorker-8] Event before-parameter-build.s3.PutObject: calling handler &lt;function convert_body_to_file_like_object at 0xffffbaac49d0&gt;<br>celery_worker  | [2024-11-04 10:21:33,594: DEBUG/ForkPoolWorker-8] Event before-parameter-build.s3.PutObject: calling handler &lt;function validate_bucket_name at 0xffffbaac5430&gt;<br>celery_worker  | [2024-11-04 10:21:33,594: DEBUG/ForkPoolWorker-8] Event before-parameter-build.s3.PutObject: calling handler &lt;function remove_bucket_from_url_paths_from_model at 0xffffbaac3310&gt;<br>celery_worker  | [2024-11-04 10:21:33,594: DEBUG/ForkPoolWorker-8] Event before-parameter-build.s3.PutObject: calling handler &lt;bound method S3RegionRedirectorv2.annotate_request_context of &lt;botocore.utils.S3RegionRedirectorv2 object at 0xffffbaaaf8b0&gt;&gt;<br>celery_worker  | [2024-11-04 10:21:33,594: DEBUG/ForkPoolWorker-8] Event before-parameter-build.s3.PutObject: calling handler &lt;bound method ClientCreator._inject_s3_input_parameters of &lt;botocore.client.ClientCreator object at 0xffffba6883a0&gt;&gt;<br>celery_worker  | [2024-11-04 10:21:33,594: DEBUG/ForkPoolWorker-8] Event before-parameter-build.s3.PutObject: calling handler &lt;function generate_idempotent_uuid at 0xffffbaac5280&gt;<br>celery_worker  | [2024-11-04 10:21:33,595: DEBUG/ForkPoolWorker-8] Event before-endpoint-resolution.s3: calling handler &lt;function customize_endpoint_resolver_builtins at 0xffffbaac34c0&gt;<br>celery_worker  | [2024-11-04 10:21:33,595: DEBUG/ForkPoolWorker-8] Event before-endpoint-resolution.s3: calling handler &lt;bound method S3RegionRedirectorv2.redirect_from_cache of &lt;botocore.utils.S3RegionRedirectorv2 object at 0xffffbaaaf8b0&gt;&gt;<br>celery_worker  | [2024-11-04 10:21:33,595: DEBUG/ForkPoolWorker-8] Calling endpoint provider with parameters: {&#39;Bucket&#39;: &#39;&#39;, &#39;Region&#39;: &#39;&#39;, &#39;UseFIPS&#39;: False, &#39;UseDualStack&#39;: False, &#39;ForcePathStyle&#39;: False, &#39;Accelerate&#39;: False, &#39;UseGlobalEndpoint&#39;: False, &#39;Key&#39;: &#39;INVOICE.pdf&#39;, &#39;DisableMultiRegionAccessPoints&#39;: False, &#39;UseArnRegion&#39;: True}<br>celery_worker  | [2024-11-04 10:21:33,595: DEBUG/ForkPoolWorker-8] Endpoint provider result:<br>celery_worker  | [2024-11-04 10:21:33,595: DEBUG/ForkPoolWorker-8] Selecting from endpoint provider&#39;s list of auth schemes: &quot;sigv4&quot;. User selected auth scheme is: &quot;None&quot;<br>celery_worker  | [2024-11-04 10:21:33,595: DEBUG/ForkPoolWorker-8] Selected auth type &quot;v4&quot; as &quot;v4&quot; with signing context params: {&#39;region&#39;: &#39;, &#39;signing_name&#39;: &#39;s3&#39;, &#39;disableDoubleEncoding&#39;: True}<br>celery_worker  | [2024-11-04 10:21:33,598: DEBUG/ForkPoolWorker-8] Event before-call.s3.PutObject: calling handler &lt;function conditionally_calculate_checksum at 0xffffbac03dc0&gt;<br>celery_worker  | [2024-11-04 10:21:33,601: DEBUG/ForkPoolWorker-8] Event before-call.s3.PutObject: calling handler &lt;function add_expect_header at 0xffffbaac5790&gt;<br>celery_worker  | [2024-11-04 10:21:33,601: DEBUG/ForkPoolWorker-8] Adding expect 100 continue header to request.<br>celery_worker  | [2024-11-04 10:21:33,601: DEBUG/ForkPoolWorker-8] Event before-call.s3.PutObject: calling handler &lt;bound method S3ExpressIdentityResolver.apply_signing_cache_key of &lt;botocore.utils.S3ExpressIdentityResolver object at 0xffffbaaaf3a0&gt;&gt;<br>celery_worker  | [2024-11-04 10:21:33,601: DEBUG/ForkPoolWorker-8] Event before-call.s3.PutObject: calling handler &lt;function add_recursion_detection_header at 0xffffbaac7e50&gt;<br>celery_worker  | [2024-11-04 10:21:33,601: DEBUG/ForkPoolWorker-8] Event before-call.s3.PutObject: calling handler &lt;function inject_api_version_header_if_needed at 0xffffbaac4af0&gt;<br>celery_worker  | [2024-11-04 10:21:33,601: DEBUG/ForkPoolWorker-8] Making request for OperationModel(name=PutObject) with params: {&#39;url_path&#39;: &#39;/INVOICE.pdf&#39;, &#39;query_string&#39;: {}, &#39;method&#39;: &#39;PUT&#39;, &#39;headers&#39;: {&#39;Content-Type&#39;: &#39;application/pdf&#39;, &#39;User-Agent&#39;: &#39;Boto3/1.35.54 md/Botocore#1.35.54 ua/2.0 os/linux#6.10.12-orbstack-00282-gd1783374c25e md/arch#aarch64 lang/python#3.9.20 md/pyimpl#CPython cfg/retry-mode#legacy Botocore/1.35.54&#39;, &#39;Content-MD5&#39;: &#39;ia1vZMnLrvWuEx8LzM8CDQ==&#39;, &#39;Expect&#39;: &#39;100-continue&#39;}, &#39;body&#39;: &lt;s3transfer.utils.ReadFileChunk object at 0xffffbadd28b0&gt;, &#39;auth_path&#39;: &#39;//INVOICE.pdf&#39;, &#39;url&#39;: &#39;/INVOICE.pdf&#39;, &#39;context&#39;: {&#39;client_region&#39;: &#39;&#39;, &#39;client_config&#39;: &lt;botocore.config.Config object at 0xffffb9a80340&gt;, &#39;has_streaming_input&#39;: True, &#39;auth_type&#39;: &#39;v4&#39;, &#39;unsigned_payload&#39;: None, &#39;s3_redirect&#39;: {&#39;redirected&#39;: False, &#39;bucket&#39;: &#39;&#39;, &#39;params&#39;: {&#39;Bucket&#39;: &#39;&#39;, &#39;Key&#39;: &#39;INVOICE.pdf&#39;, &#39;Body&#39;: &lt;s3transfer.utils.ReadFileChunk object at 0xffffbadd28b0&gt;, &#39;ContentType&#39;: &#39;application/pdf&#39;}}, &#39;input_params&#39;: {&#39;Bucket&#39;: &#39;&#39;, &#39;Key&#39;: &#39;INVOICE.pdf&#39;}, &#39;signing&#39;: {&#39;region&#39;: &#39;&#39;, &#39;signing_name&#39;: &#39;s3&#39;, &#39;disableDoubleEncoding&#39;: True}, &#39;endpoint_properties&#39;: {&#39;authSchemes&#39;: [{&#39;disableDoubleEncoding&#39;: True, &#39;name&#39;: &#39;sigv4&#39;, &#39;signingName&#39;: &#39;s3&#39;, &#39;signingRegion&#39;: &#39;eu-north-1&#39;}]}}}<br>celery_worker  | [2024-11-04 10:21:33,602: DEBUG/ForkPoolWorker-8] Event request-created.s3.PutObject: calling handler &lt;function signal_not_transferring at 0xffffb9ab2940&gt;<br>celery_worker  | [2024-11-04 10:21:33,602: DEBUG/ForkPoolWorker-8] Event request-created.s3.PutObject: calling handler &lt;bound method RequestSigner.handler of &lt;botocore.signers.RequestSigner object at 0xffffb9a802b0&gt;&gt;<br>celery_worker  | [2024-11-04 10:21:33,602: DEBUG/ForkPoolWorker-8] Event choose-signer.s3.PutObject: calling handler &lt;function set_operation_specific_signer at 0xffffbaac50d0&gt;<br>celery_worker  | [2024-11-04 10:21:33,602: DEBUG/ForkPoolWorker-8] Event before-sign.s3.PutObject: calling handler &lt;function remove_arn_from_signing_path at 0xffffbaac3430&gt;<br>celery_worker  | [2024-11-04 10:21:33,602: DEBUG/ForkPoolWorker-8] Event before-sign.s3.PutObject: calling handler &lt;bound method S3ExpressIdentityResolver.resolve_s3express_identity of &lt;botocore.utils.S3ExpressIdentityResolver object at 0xffffbaaaf3a0&gt;&gt;<br>celery_worker  | [2024-11-04 10:21:33,602: DEBUG/ForkPoolWorker-8] Calculating signature using v4 auth.<br>celery_worker  | [2024-11-04 10:21:33,602: DEBUG/ForkPoolWorker-8] CanonicalRequest:<br>celery_worker  | PUT<br>celery_worker  | /INVOICE.pdf<br>celery_worker  | <br>celery_worker  | content-md5:ia1vZMnLrvWuEx8LzM8CDQ==<br>celery_worker  | content-type:application/pdf<br>celery_worker  | host:.amazonaws.com<br>celery_worker  | x-amz-content-sha256:UNSIGNED-PAYLOAD<br>celery_worker  | x-amz-date:20241104T102133Z<br>celery_worker  | <br>celery_worker  | content-md5;content-type;host;x-amz-content-sha256;x-amz-date<br>celery_worker  | UNSIGNED-PAYLOAD<br>celery_worker  | [2024-11-04 10:21:33,602: DEBUG/ForkPoolWorker-8] StringToSign:<br>celery_worker  | AWS4-HMAC-SHA256<br>celery_worker  | 20241104T102133Z<br>celery_worker  | 20241104/eu-north-1/s3/aws4_request<br>celery_worker  | b3a6aa06ac572dc376aa47aea1987a0ee93724103bead2c9dedb636abc322e6e<br>celery_worker  | [2024-11-04 10:21:33,603: DEBUG/ForkPoolWorker-8] Signature:<br>celery_worker  | eafd210245ac82fa88e83fc2f637772c6c2962e76fcb0baa2ffd2ea91df3e550<br>celery_worker  | [2024-11-04 10:21:33,603: DEBUG/ForkPoolWorker-8] Event request-created.s3.PutObject: calling handler &lt;function signal_transferring at 0xffffb9ab29d0&gt;<br>celery_worker  | [2024-11-04 10:21:33,603: DEBUG/ForkPoolWorker-8] Event request-created.s3.PutObject: calling handler &lt;function add_retry_headers at 0xffffbaac3280&gt;<br>celery_worker  | [2024-11-04 10:21:33,603: DEBUG/ForkPoolWorker-8] Sending http request: &lt;AWSPreparedRequest stream_output=False, method=PUT, url=https://north-1.amazonaws.com/INVOICE.pdf, headers={&#39;Content-Type&#39;: b&#39;application/pdf&#39;, &#39;User-Agent&#39;: b&#39;Boto3/1.35.54 md/Botocore#1.35.54 ua/2.0 os/linux#6.10.12-orbstack-00282-gd1783374c25e md/arch#aarch64 lang/python#3.9.20 md/pyimpl#CPython cfg/retry-mode#legacy Botocore/1.35.54&#39;, &#39;Content-MD5&#39;: b&#39;ia1vZMnLrvWuEx8LzM8CDQ==&#39;, &#39;Expect&#39;: b&#39;100-continue&#39;, &#39;X-Amz-Date&#39;: b&#39;20241104T102133Z&#39;, &#39;X-Amz-Content-SHA256&#39;: b&#39;UNSIGNED-PAYLOAD&#39;, &#39;Authorization&#39;: b&#39;AWS4-HMAC-SHA256 Credential=AKIAZQ3DUZRN2FHZ2A6K/20241104/eu-north-1/s3/aws4_request, SignedHeaders=content-md5;content-type;host;x-amz-content-sha256;x-amz-date, Signature=eafd210245ac82fa88e83fc2f637772c6c2962e76fcb0baa2ffd2ea91df3e550&#39;, &#39;amz-sdk-invocation-id&#39;: b&#39;445175a4-f8a3-47d6-acde-daabfb644591&#39;, &#39;amz-sdk-request&#39;: b&#39;attempt=1&#39;, &#39;Content-Length&#39;: &#39;549743&#39;}&gt;<br>celery_worker  | [2024-11-04 10:21:33,604: DEBUG/ForkPoolWorker-8] Certificate path: /usr/local/lib/python3.9/site-packages/certifi/cacert.pem<br>celery_worker  | [2024-11-04 10:21:33,605: DEBUG/ForkPoolWorker-8] Starting new HTTPS connection (1): 1.amazonaws.com:443<br>celery_worker  | [2024-11-04 10:21:33,856: DEBUG/ForkPoolWorker-8] Waiting for 100 Continue response.<br>celery_worker  | [2024-11-04 10:21:33,957: DEBUG/ForkPoolWorker-8] 100 Continue response seen, now sending request body.<br>celery_worker  | [2024-11-04 10:21:34,481: DEBUG/ForkPoolWorker-8] https://amazonaws.com:443 &quot;PUT /INVOICE.pdf HTTP/1.1&quot; 200 0<br>celery_worker  | [2024-11-04 10:21:34,482: DEBUG/ForkPoolWorker-8] Event before-parse.s3.PutObject: calling handler &lt;function _handle_200_error at 0xffffbaac3790&gt;<br>celery_worker  | [2024-11-04 10:21:34,482: DEBUG/ForkPoolWorker-8] Event before-parse.s3.PutObject: calling handler &lt;function handle_expires_header at 0xffffbaac35e0&gt;<br>celery_worker  | [2024-11-04 10:21:34,482: DEBUG/ForkPoolWorker-8] Response headers: {&#39;x-amz-id-2&#39;: &#39;rtnQgYRDKADz4t/MqdRPLtXV/YOD1N1evlGBU3987M5kgSh7Noqbuv4ntF9HW5tFcFTs/HdfiIE=&#39;, &#39;x-amz-request-id&#39;: &#39;62GMVRASSY9DEVMA&#39;, &#39;Date&#39;: &#39;Mon, 04 Nov 2024 10:21:34 GMT&#39;, &#39;x-amz-server-side-encryption&#39;: &#39;AES256&#39;, &#39;ETag&#39;: &#39;&quot;89ad6f64c9cbaef5ae131f0bcccf020d&quot;&#39;, &#39;Server&#39;: &#39;AmazonS3&#39;, &#39;Content-Length&#39;: &#39;0&#39;}<br>celery_worker  | [2024-11-04 10:21:34,482: DEBUG/ForkPoolWorker-8] Response body:<br>celery_worker  | b&#39;&#39;<br>celery_worker  | [2024-11-04 10:21:34,484: DEBUG/ForkPoolWorker-8] Event needs-retry.s3.PutObject: calling handler &lt;function _update_status_code at 0xffffbaac38b0&gt;<br>celery_worker  | [2024-11-04 10:21:34,484: DEBUG/ForkPoolWorker-8] Event needs-retry.s3.PutObject: calling handler &lt;botocore.retryhandler.RetryHandler object at 0xffffb9b3ae20&gt;<br>celery_worker  | [2024-11-04 10:21:34,484: DEBUG/ForkPoolWorker-8] No retry needed.<br>celery_worker  | [2024-11-04 10:21:34,484: DEBUG/ForkPoolWorker-8] Event needs-retry.s3.PutObject: calling handler &lt;bound method S3RegionRedirectorv2.redirect_from_error of &lt;botocore.utils.S3RegionRedirectorv2 object at 0xffffbaaaf8b0&gt;&gt;<br>celery_worker  | [2024-11-04 10:21:34,485: DEBUG/ForkPoolWorker-8] Releasing acquire 0/None<br>celery_worker  | [2024-11-04 10:21:34,493: INFO/ForkPoolWorker-8] Task tasks.uploads.upload_tasks.upload_file_to_s3[44368494-d85d-4a92-a399-511915e9b36a] succeeded in 0.9695482780007296s: &#39;INVOICE.pdf&#39;<br><br></pre><p>Good luck..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df4b3eb5ef90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastApi Authentication with google oauth 2.0]]></title>
            <link>https://parlak-deniss.medium.com/fastapi-authentication-with-google-oauth-2-0-9bb93b784eee?source=rss-4c72a9b7380------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bb93b784eee</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[google-auth]]></category>
            <dc:creator><![CDATA[Deniz Parlak]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 22:14:17 GMT</pubDate>
            <atom:updated>2024-10-11T22:14:17.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2TN8bBplknWMdNo9XU8Dw.jpeg" /></figure><p>Hi, in this article i’ll try to explain how to make authentication with google, aka “<strong>Sign in with Google</strong>”.</p><p>I’m going to keep very short and simple example, so please don’t expect sign in and save to database then remember etc. Maybe in the next article i can show that details or you can implement whatever you want for your own business logic.</p><p>Be able to reach and examine code, you can fork my repo.</p><p><a href="https://github.com/denizparlak1/fastapi-google-auth.git">https://github.com/denizparlak1/fastapi-google-auth.git</a></p><p>First, let’s create a project, I am using macOS but the steps will be the same for every operating system.</p><pre>mkdir fastapi-google-oauth2</pre><pre>cd fastapi-google-oauth2</pre><pre>python3 -m venv env </pre><pre>source env/bin/activate</pre><p>If yo’re using IDE such as PyCharm you don’t need to do those stepst, you can easily create project from scratch.</p><p>Also if you created with IDE, libraries could be come pre installed. But if you didn’t, you have to install manually.</p><pre>pip install fastapi google-auth Jinja2 httpx python-dotenv uvicorn</pre><p>To select and log in with our google account we should create login.html</p><p>This part is not very important you can find any HTML code, just we need the backend implementation. In Python projects, generally (Flask, Fastapi, etc.) html,css files are stored under the static directory.</p><pre>mkdir -P static/pages/login<br>touch login.html</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Login&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css&quot;&gt;<br>    &lt;style&gt;<br>        body {<br>            font-family: &#39;Arial&#39;, sans-serif;<br>            background-color: #f4f4f4;<br>            display: flex;<br>            justify-content: center;<br>            align-items: center;<br>            height: 100vh;<br>            margin: 0;<br>        }<br>        .container {<br>            background-color: white;<br>            border-radius: 10px;<br>            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);<br>            padding: 30px;<br>            width: 90%;<br>            max-width: 400px;<br>            text-align: center;<br>        }<br>        h2 {<br>            margin-bottom: 25px;<br>            color: #333;<br>        }<br>        input[type=&quot;email&quot;],<br>        input[type=&quot;password&quot;] {<br>            width: 100%;<br>            padding: 12px;<br>            margin: 10px 0;<br>            border: 1px solid #ccc;<br>            border-radius: 5px;<br>            transition: border-color 0.3s;<br>            box-sizing: border-box;<br>        }<br>        input:focus {<br>            border-color: #4285F4;<br>            outline: none;<br>        }<br>        button {<br>            width: 100%;<br>            padding: 12px;<br>            margin-top: 10px;<br>            border: none;<br>            border-radius: 5px;<br>            cursor: pointer;<br>            font-size: 16px;<br>            display: flex;<br>            align-items: center;<br>            justify-content: center;<br>            transition: background-color 0.3s;<br>        }<br>        .google-login {<br>            background-color: #db4437;<br>            color: white;<br>        }<br>        .google-login:hover {<br>            background-color: #c13529;<br>        }<br>        .apple-login {<br>            background-color: #000;<br>            color: white;<br>            margin-top: 10px;<br>        }<br>        .apple-login:hover {<br>            background-color: #444;<br>        }<br>        .icon {<br>            margin-right: 10px;<br>        }<br>        .alternative-login {<br>            text-align: center;<br>            margin-top: 15px;<br>            font-size: 14px;<br>            color: #666;<br>        }<br>        .alternative-login span {<br>            margin: 0 5px;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;h2&gt;Login&lt;/h2&gt;<br>        &lt;form method=&quot;post&quot; action=&quot;/api/authentication/login&quot;&gt;<br>            &lt;input type=&quot;email&quot; placeholder=&quot;Email&quot; required&gt;<br>            &lt;input type=&quot;password&quot; placeholder=&quot;Password&quot; required&gt;<br>            &lt;button type=&quot;submit&quot;&gt;Login&lt;/button&gt;<br>        &lt;/form&gt;<br>        &lt;div class=&quot;alternative-login&quot;&gt;<br>            &lt;span&gt;Or&lt;/span&gt;<br>        &lt;/div&gt;<br>        &lt;button class=&quot;google-login&quot; onclick=&quot;window.location.href=&#39;/api/authentication/login&#39;&quot;&gt;<br>            &lt;i class=&quot;fab fa-google icon&quot;&gt;&lt;/i&gt; Sign in with Google<br>        &lt;/button&gt;<br>        &lt;button class=&quot;apple-login&quot; onclick=&quot;event.preventDefault();&quot;&gt;<br>            &lt;i class=&quot;fab fa-apple icon&quot;&gt;&lt;/i&gt; Sign in with Apple<br>        &lt;/button&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>When the user clicks <strong>Sign in with Google </strong>/api/authentication/login<strong> </strong>APIs should handle our request.</p><p>In order to see login.html and other many html and css files we need to implement them on main.py</p><pre>import os<br>from fastapi import FastAPI,Request<br>from fastapi.templating import Jinja2Templates<br>from api.auth import auth<br>from starlette.middleware.sessions import SessionMiddleware<br><br><br>app = FastAPI()<br>app.include_router(auth.router, prefix=&quot;/api/authentication&quot;, tags=[&quot;auth&quot;])<br>app.add_middleware(SessionMiddleware, secret_key=os.getenv(&quot;SECRET_KEY&quot;, &quot;default_secret_key&quot;))<br><br>templates = Jinja2Templates(directory=&quot;static/&quot;)<br><br>@app.get(&quot;/&quot;)<br>async def login(request: Request):<br>    &quot;&quot;&quot;<br>    :param request: An instance of the `Request` class, representing the incoming HTTP request.<br>    :return: A TemplateResponse object rendering the &quot;login.html&quot; template with the given request context.<br>    &quot;&quot;&quot;<br>    return templates.TemplateResponse(&quot;pages/login/login.html&quot;, {&quot;request&quot;: request})</pre><p>Let me explain what is doing this code.</p><p>auth router is the file we’ll write for endpoints and necessary callback functions. Prefix means we’ll call those all APIs starting with /api/authentication/</p><p>Also, this is a very good option for writing clean and structural code</p><pre>app.include_router(auth.router, prefix=&quot;/api/authentication&quot;, tags=[&quot;auth&quot;])</pre><p>To add google oauth we have to add session middleware, you can read the secret key from your environment.</p><pre>app.add_middleware(SessionMiddleware, secret_key=os.getenv(&quot;SECRET_KEY&quot;, &quot;default_secret_key&quot;))</pre><p>I used the Jinja2 template, it’s common for Python developers, I’m telling to FastAPI I’ll use Jinja template on the static directory.</p><pre>templates = Jinja2Templates(directory=&quot;static/&quot;)</pre><p>Then we can write the main page api call which is,</p><pre>@app.get(&quot;/&quot;)<br>async def login(request: Request):<br>    &quot;&quot;&quot;<br>    :param request: An instance of the `Request` class, representing the incoming HTTP request.<br>    :return: A TemplateResponse object rendering the &quot;login.html&quot; template with the given request context.<br>    &quot;&quot;&quot;<br>    return templates.TemplateResponse(&quot;pages/login/login.html&quot;, {&quot;request&quot;: request})</pre><p>This route location could be changed on your requirements, for test purposes, I put it on main.py but generally should not</p><p>Now let’s write in auth.py</p><pre>mkdir -p api/auth</pre><pre>touch auth.py</pre><pre>import os<br>import httpx<br>from fastapi import APIRouter, Request, HTTPException<br>from fastapi.responses import RedirectResponse<br>from google.oauth2 import id_token<br>from google.auth.transport import requests<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>router = APIRouter()<br><br>GOOGLE_CLIENT_ID = os.getenv(&quot;GOOGLE_CLIENT_ID&quot;)<br>GOOGLE_CLIENT_SECRET = os.getenv(&quot;GOOGLE_CLIENT_SECRET&quot;)<br><br><br>@router.get(&quot;/login&quot;)<br>async def login(request: Request):<br>    redirect_uri = request.url_for(&#39;auth_callback&#39;)<br>    google_auth_url = f&quot;https://accounts.google.com/o/oauth2/auth?client_id={GOOGLE_CLIENT_ID}&amp;redirect_uri={redirect_uri}&amp;response_type=code&amp;scope=openid email profile&quot;<br><br>    return RedirectResponse(url=google_auth_url)<br><br><br><br>@router.get(&quot;/callback&quot;)<br>async def auth_callback(code: str, request: Request):<br>    token_request_uri = &quot;https://oauth2.googleapis.com/token&quot;<br>    data = {<br>        &#39;code&#39;: code,<br>        &#39;client_id&#39;: GOOGLE_CLIENT_ID,<br>        &#39;client_secret&#39;: GOOGLE_CLIENT_SECRET,<br>        &#39;redirect_uri&#39;: request.url_for(&#39;auth_callback&#39;),<br>        &#39;grant_type&#39;: &#39;authorization_code&#39;,<br>    }<br><br>    async with httpx.AsyncClient() as client:<br>        response = await client.post(token_request_uri, data=data)<br>        response.raise_for_status()<br>        token_response = response.json()<br><br>    id_token_value = token_response.get(&#39;id_token&#39;)<br>    if not id_token_value:<br>        raise HTTPException(status_code=400, detail=&quot;Missing id_token in response.&quot;)<br><br>    try:<br>        id_info = id_token.verify_oauth2_token(id_token_value, requests.Request(), GOOGLE_CLIENT_ID)<br><br>        name = id_info.get(&#39;name&#39;)<br>        request.session[&#39;user_name&#39;] = name<br><br>        return RedirectResponse(url=request.url_for(&#39;welcome&#39;))<br><br>    except ValueError as e:<br>        raise HTTPException(status_code=400, detail=f&quot;Invalid id_token: {str(e)}&quot;)<br><br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=&quot;Internal Server Error&quot;)<br><br></pre><p>First things first, to implement google oauth2 we need client_id and client_secret key, But I&#39;ll show you then.</p><pre>@router.get(&quot;/login&quot;)<br>async def login(request: Request):<br>    redirect_uri = request.url_for(&#39;auth_callback&#39;)<br>    google_auth_url = f&quot;https://accounts.google.com/o/oauth2/auth?client_id={GOOGLE_CLIENT_ID}&amp;redirect_uri={redirect_uri}&amp;response_type=code&amp;scope=openid email profile&quot;<br><br>    return RedirectResponse(url=google_auth_url)</pre><p>When you click the Sign in with Google button, the button triggers that api. Then api will go to the sign-in page which is a classical google login.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eqUj2A1Y0U6a7gQntgaVaA.png" /></figure><p>So you should write the correct email and password. After going further, that function is calling the callback route, which authenticates your Google account. If it’s not a valid google account it’ll return an error.</p><pre>redirect_uri = request.url_for(&#39;auth_callback&#39;)</pre><p>If everything goes successfully, this API redirects to the welcome API.</p><pre>return RedirectResponse(url=request.url_for(&#39;welcome&#39;))</pre><p>Let’s create the welcome API, I’m gonna put it on main.py again.</p><pre>@app.get(&quot;/welcome&quot;)<br>async def welcome(request: Request):<br>    &quot;&quot;&quot;<br>    :param request: The incoming HTTP request containing session data.<br>    :return: A TemplateResponse object that renders the welcome page with the user&#39;s name or &#39;Guest&#39; if not found.<br>    &quot;&quot;&quot;<br>    name = request.session.get(&#39;user_name&#39;, &#39;Guest&#39;)<br>    context = {&quot;request&quot;: request, &quot;name&quot;: name}<br>    return templates.TemplateResponse(&quot;pages/welcome/welcome.html&quot;, context)</pre><p>It returns welcome.html with the account name. If no successful login it returns the “Guest” name</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Welcome&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css&quot;&gt;<br>    &lt;style&gt;<br>        body {<br>            font-family: &#39;Arial&#39;, sans-serif;<br>            background-color: #f4f4f4;<br>            display: flex;<br>            justify-content: center;<br>            align-items: center;<br>            height: 100vh;<br>            margin: 0;<br>        }<br>        .container {<br>            background-color: white;<br>            border-radius: 10px;<br>            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);<br>            padding: 30px;<br>            width: 90%;<br>            max-width: 400px;<br>            text-align: center;<br>        }<br>        h2 {<br>            margin-bottom: 25px;<br>            color: #333;<br>        }<br>        .message {<br>            font-size: 18px;<br>            margin-bottom: 15px;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;h2&gt;Welcome!&lt;/h2&gt;<br>        &lt;div class=&quot;message&quot;&gt;Authentication successful!&lt;/div&gt;<br>        &lt;div class=&quot;message&quot;&gt;Welcome, {{ name }}!&lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now for the client and secret key go to <a href="http://console.cloud.google.com/">console.cloud.google.com</a></p><p>Find the Credentials section under the API &amp; Services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*4givcWNntjbRGXbix5mrQA.png" /></figure><p>Create a new OAuth client id</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrgCA9aY8eVRPClA5f-OXg.png" /></figure><p>The most important thing, is don’t forget to add an Authorized redirect URL which is our callback API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwF4XXFiJ1eCxu8GsQfbEg.png" /></figure><p>That’s it. Add the values ​​returned after creation to your .env file and start the project</p><pre>uvicorn main:app --host 127.0.0.1 --port 8000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sl1oZg5Cg62J6cON_LOKQw.gif" /></figure><p>Thank you for reading, have a good day ☀️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bb93b784eee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy FastAPI on Cloud Run]]></title>
            <link>https://parlak-deniss.medium.com/deploy-fastapi-on-cloud-run-8341d1235dac?source=rss-4c72a9b7380------2</link>
            <guid isPermaLink="false">https://medium.com/p/8341d1235dac</guid>
            <category><![CDATA[cloudrun]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Deniz Parlak]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 21:24:06 GMT</pubDate>
            <atom:updated>2023-06-03T21:24:06.169Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will tell you how to deploy your FastAPI application on Cloud Run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wptZbznyhyxnGfel7c_xvw.jpeg" /></figure><p>The dependencies of the application may vary, but the overall structure will be similar.</p><p>First you should create requirements.txt</p><pre>pip freeze &gt; requirements.txt</pre><p>This will be create a library list for use our project.</p><p>Then we create a Dockerfile. As i told you before if your application need more complex Dockerfile you should edit</p><p>This is a basic Dockerfile.</p><pre>FROM python:3.9<br><br>WORKDIR /usr/src/app<br><br>COPY requirements.txt ./<br><br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY . .<br><br>EXPOSE 8000<br><br>CMD [ &quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>Now I want to mention an important part. From here it will be very simple to get the application on Cloud Run, however, if there are critical data such as database connection information etc. in our application, it will be necessary to take action regarding them.</p><p>In this example I am storing the database connection information via Secret Manager on GCP, ithink this was the most accurate way google suggested.</p><p>I created secret for my database information (for the privacy of the project you can’t see the full url right now).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VTBEfPpPSAJRR-uSSSpCw.png" /></figure><pre>from google.cloud import secretmanager<br>from dotenv import load_dotenv<br>import os<br><br>load_dotenv()<br>secret_db = os.environ[&#39;SECRET_PROJECT_URL&#39;]<br><br><br><br># Create a Secret Manager client<br>client = secretmanager.SecretManagerServiceClient()<br><br>response = client.access_secret_version(request={&quot;name&quot;: secret_db})<br>credentials = response.payload.data.decode(&quot;UTF-8&quot;)<br>credentials = json.loads(credentials)<br><br><br>engine = create_engine(<br>    f&quot;mysql+pymysql://{credentials[&#39;user&#39;]}:{credentials[&#39;password&#39;]}@{credentials[&#39;host&#39;]}:{credentials[&#39;port&#39;]}/{credentials[&#39;schema&#39;]}&quot;<br>)<br><br><br>Sessions = sessionmaker(bind=engine)</pre><p>Thus, you can safely read your database connection information through the secret manager.</p><p>Let’s move on to the last stage, if you publish your project on github, a new version will be released automatically every time google cloud receives a push to your repo.</p><p>The most important thing to note here is that you must show Secret Manager as env on Cloud Run so that the container can read it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Toi_B27W6nqG8_B4v0kuNQ.png" /></figure><p>Also, don’t forget to enter the container port correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wnK_tLH73K63CcjA4O0FzQ.png" /></figure><p>Nice coding..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8341d1235dac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI JWT Role Based Decorator]]></title>
            <link>https://parlak-deniss.medium.com/fastapi-jwt-role-based-decorator-66a202b64b73?source=rss-4c72a9b7380------2</link>
            <guid isPermaLink="false">https://medium.com/p/66a202b64b73</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Deniz Parlak]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 18:20:16 GMT</pubDate>
            <atom:updated>2023-06-03T18:20:16.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*JxNI4Upmvxm1KxWtwUE4XQ.png" /></figure><p>Hello, I will show you a method that you can apply for role-based control of APIs in your FastAPI application. At the moment fastapi itself does not have a library’s available. If you do not want to use any 3rd party library, this article may be useful to you.</p><p>I assume you have created your project in the first stage and come to a certain place.</p><pre>import jwt<br>from fastapi import Depends, HTTPException<br>from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer<br>from pydantic import BaseModel<br><br>security = HTTPBearer()<br><br><br># define a base model for the token<br>class TokenPayload(BaseModel):<br>    sub: str = None<br>    role: str = None<br><br><br># function to check the user&#39;s role based on the bearer token<br>async def check_user_role(credentials: HTTPAuthorizationCredentials = Depends(security)):<br>    if not credentials:<br>        raise HTTPException(status_code=401, detail=&quot;Bearer token missing&quot;)<br>    try:<br>        token = credentials.credentials<br>        payload = jwt.decode(token, &quot;secret&quot;, algorithms=[&quot;HS256&quot;])<br>        token_data = TokenPayload(**payload)<br>        if token_data.role not in [&quot;user&quot;, &quot;admin&quot;]:<br>            raise HTTPException(status_code=403, detail=&quot;Not authorized to access this resource&quot;)<br>        return token_data<br>    except jwt.exceptions.InvalidTokenError:<br>        raise HTTPException(status_code=401, detail=&quot;Invalid token&quot;)</pre><p>In the above code block, if the role from jwt is not admin or user, the called api will be interrupted and throw an error.</p><p>However, it should be noted that while the user is logging in or registering the user to the system, we need to load the role part into the jwt token.</p><p>In the example below, we can get the role from jwt after the user logs in.</p><pre>from fastapi import HTTPException, APIRouter<br>import jwt<br>from db.db import Sessions<br>from model.User import User<br>from schemas.Response import LoginResponse, UserOut<br>from schemas.schema import UserLogin<br>from security.security import verify_password<br><br>router = APIRouter()<br><br><br>@router.post(&quot;/login&quot;)<br>async def login(credentials: UserLogin):<br>    session = Sessions()<br><br>    if not credentials.email or not credentials.password:<br>        raise HTTPException(status_code=400, detail=&quot;Incorrect email or password&quot;)<br><br>    user = User.get_user(session, email=credentials.email)<br><br>    if not user:<br>        raise HTTPException(status_code=400, detail=&quot;Incorrect email or password&quot;)<br><br>    if verify_password(credentials.password, user.hashed_password):<br>        # Generate a JWT token<br>        access_token = jwt.encode({&quot;sub&quot;: credentials.email, &quot;role&quot;: user.role}, &quot;secret&quot;, algorithm=&quot;HS256&quot;)<br><br>        # Return the access token and user details<br>        return LoginResponse(<br>            token=access_token,<br>            user=UserOut(<br>                id=user.id,<br>                username=user.username,<br>                email=user.email,<br>                is_active=True,<br>                discount=0.0,<br>                role=user.role<br>            ),<br>        )<br>    else:<br>        raise HTTPException(status_code=400, detail=&quot;Incorrect email or password&quot;)</pre><p>Finally, you can integrate the API that we want to implement role-based as follows.</p><pre>@router.post(&quot;/filter&quot;)<br>async def filter_api(product: FilterProduct, token_data: TokenPayload = Depends(check_user_role)):<br>    # Rest of the code..</pre><p>Have a nice day..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66a202b64b73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustered ElasticSearch Installation on Google Cloud VM Instances]]></title>
            <link>https://parlak-deniss.medium.com/clustered-elasticsearch-installation-on-google-cloud-vm-instances-370abcfd4186?source=rss-4c72a9b7380------2</link>
            <guid isPermaLink="false">https://medium.com/p/370abcfd4186</guid>
            <category><![CDATA[cluster]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[filebeat]]></category>
            <dc:creator><![CDATA[Deniz Parlak]]></dc:creator>
            <pubDate>Fri, 05 Nov 2021 14:26:43 GMT</pubDate>
            <atom:updated>2021-11-05T14:26:43.060Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, today we will install elasticsearch as 1 master and 2 nodes. It is important to be able to set up clusters. We may have to deal with many settings and configurations. The most important of these is that the machines we install are communicating.</p><p>In this article, we will install the Ubuntu 20.04 machines that we will create on Google Cloud.</p><p>Let’s begin,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20yTn7K6c6vcmEdgwAgjSA.png" /></figure><h3><strong>Create Google Cloud VM</strong></h3><p>We need 3 different machines, here I show the installation of 1, do the same for the remaining 2 machines.</p><p>Let’s go inside the Google VM and create a virtual machine, We name the machine we will create, I gave the names of the master and datanode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHAReFS5SjIOCGVZM_ACDw.png" /></figure><p>Click on the blue arrow and select the operating system of the machine. Let’s allow HTTP and HTTPS traffic, it will be required later for Kibana interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wiEHg8lMX7E7Jw6RCV9btA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5jme1IWX1hi6ZzSSVt3kQ.png" /></figure><p>After the installations are completed, you should obtain machines similar to the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mr0ifKqJZwES_Idch5E_9Q.png" /></figure><p>Let’s connect to our first master machine and install elasticsearch. We can connect via the browser by clicking the SSH button that appears in the picture.</p><h3>ElasticSearch Installation</h3><p>After connecting via SSH, we need to update the machine and install java.</p><p><strong>Do these operations for each node</strong></p><pre>sudo apt-get update</pre><pre>sudo apt-get install default-jre<br></pre><p>First, you need to add Elastic’s signing key so that the downloaded package can be verified (skip this step if you’ve already installed packages from Elastic):</p><p><strong>Do these operations for each node</strong></p><pre>wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -</pre><pre>sudo apt-get install apt-transport-https</pre><pre>echo &quot;deb https://artifacts.elastic.co/packages/6.x/apt stable main&quot; | sudo tee -a /etc/apt/sources.list.d/elastic-6.x.list</pre><pre>sudo apt-get update <br>sudo apt-get install elasticsearch</pre><h3>Configuring Elastic Cluster</h3><p>We have installed Elasticsearch. Now we start the important part, we have to show the master and datanodes in the configuration file. We will do this configuration process for each node.</p><p><strong>For Master Node:</strong></p><p>Let’s edit<strong> /etc/elasticsearch/elasticsearch.yml</strong> as root</p><p><strong>cluster.name: my-cluster</strong></p><p><strong>node.name: master-1</strong></p><p><strong>node.master: true<br>node.data: false<br>node.ingest: false</strong></p><p><strong>network.host: 0.0.0.0</strong></p><p><strong>http.port: 9200</strong></p><p><strong>discovery.zen.ping.unicast.hosts: [“10.128.0.29”,”10.128.0.30&quot;,”10.128.0.31&quot;]</strong></p><p>The IP addresses written here are the Internal IP addresses of Google VM Instances on the same network. Since they are on the same network, they can communicate over Internal IP.</p><p><strong>For Data Nodes:</strong></p><p>Let’s edit<strong> /etc/elasticsearch/elasticsearch.yml</strong> as root</p><p>cluster.name: my-cluster</p><p>node.name: datanode-1</p><p>node.master: false<br>node.data: true<br>node.ingest: false</p><p>network.host: 0.0.0.0<br>http.port: 9200</p><p>discovery.zen.ping.unicast.hosts: [“10.128.0.29”,”10.128.0.30&quot;,”10.128.0.31&quot;]</p><p>If you have made the correct settings for each node, we can run the service.</p><pre>sudo service elasticsearch start</pre><p>Let’s check it via terminal,</p><pre>curl -XGET &#39;localhost:9200/_cluster/health?pretty&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*UWlwxgmf9qMvz8YIqvU0FQ.png" /></figure><pre>curl -XGET &#39;localhost:9200/_cluster/state?pretty&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*PoqmrNN15sJZiQ_x2dhuhg.png" /></figure><p>1 Master and 2 Datanodes are working actively.</p><p>Besides, let’s install kibana and set up security settings for elasticsearch.</p><h3>Kibana Installation</h3><p>You can also install it on a separate machine. In this article, I am installing on the Master machine.</p><pre>wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -</pre><pre>sudo apt-get install apt-transport-https</pre><pre>echo &quot;deb https://artifacts.elastic.co/packages/7.x/apt stable main&quot; | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list</pre><pre>sudo apt-get update &amp;&amp; sudo apt-get install kibana</pre><pre>sudo -i service kibana start</pre><p>You can now access the installed machine’s IP address from the 5601 port.</p><p>Since we have an Advance installation, let’s activate the security setting for elasticsearch and add an SSL certificate.</p><h3>ElasticSearch Security Configuration</h3><p>First of all, let’s stop all our services</p><pre>sudo -i service kibana stop<br>sudo service elasticsearch stop</pre><p>For security settings, we need to add the necessary parameters in the elasticsearch.yml file and show the location of the certificate file.</p><p>First of all, let’s create the required certificate and set it up in the elasticsearch.yml file.</p><pre>cd /usr/share/elasticsearch<br>bin/elasticsearch-certutil ca<br>ENTER<br>ENTER<br>bin/elasticsearch-certutil cert --ca elastic-stack-ca.p12<br>ENTER<br>ENTER</pre><pre>mv elastic-stack-ca.p12 /etc/elasticsearch<br>cd /etc/elasticsearch</pre><pre>clown root:elasticsearch elastic-stack-ca.p12<br>chmod 660 elastic-stack-ca.p12</pre><pre>vim elasticsearch.yml</pre><p>Add this line to elasticsearch.yml file (each node),</p><pre>xpack.security.enabled: true</pre><pre>xpack.security.transport.ssl.enabled: true</pre><pre>xpack.security.transport.ssl.verification_mode: certificate</pre><pre>xpack.security.transport.ssl.keystore.path: elastic-certificates.p12</pre><pre>xpack.security.transport.ssl.truststore.path: elastic-certificates.p12</pre><pre>xpack.security.http.ssl.enabled: true</pre><pre>xpack.security.http.ssl.keystore.path: elastic-certificates.p12</pre><pre>xpack.security.http.ssl.truststore.path: elastic-certificates.p12</pre><pre>xpack.security.http.ssl.client_authentication: optional</pre><p>We need to copy the SSL file we created to other servers. Let’s put this SSL file in Google Storage and download it on other machines.</p><pre>gcloud auth login</pre><p>Enter verification code to terminal and you will log in</p><p>gsutil cp elastic-stack-ca.p12 gs://bucket_name</p><p>Go to your Datanode server and download the file from this domain</p><p><strong>SSH Datanodes</strong></p><pre>cd /etc/elasticsearch</pre><pre>gsutil cp gs://elasticsearch00/elastic-certificates.p12 /etc/elasticsearch</pre><p>Add this line to elasticsearch.yml (each datanode)</p><pre>xpack.security.enabled: true</pre><pre>xpack.security.transport.ssl.enabled: true</pre><pre>xpack.security.transport.ssl.verification_mode: certificate</pre><pre>xpack.security.transport.ssl.keystore.path: elastic-certificates.p12</pre><pre>xpack.security.transport.ssl.truststore.path: elastic-certificates.p12</pre><pre>xpack.security.http.ssl.enabled: true</pre><pre>xpack.security.http.ssl.keystore.path: elastic-certificates.p12</pre><pre>xpack.security.http.ssl.truststore.path: elastic-certificates.p12</pre><pre>xpack.security.http.ssl.client_authentication: optional</pre><p>Now let’s restart Elasticsearch and set the necessary user password settings.</p><pre>sudo service elasticsearch start</pre><p>Let’s run the following codes on the master machine</p><pre>cd /usr/share/elasticsearch/<br>bin/elasticsearch-setup-passwords interactive</pre><p>Create password for each incoming user,</p><h3>Kibana Configuration</h3><pre>cd /etc/elasticsearch</pre><pre>openssl pkcs12 -in elastic-certificates.p12 -out security.crt.pem -clcerts -nokeys</pre><pre>openssl pkcs12 -in elastic-certificates.p12 -out security.key.pem -nocerts -nodes</pre><pre>mv security.* /etc/kibana</pre><pre>cd /etc/kibana<br>chown root:kibana security.*<br>chmod 660 security.*</pre><pre>vim kibana.yml</pre><p>Open the kibana.yml file and make the following settings</p><pre>elasticsearch.hosts : [&quot;https://127.0.0.1:9200&quot;]<br>elasticsearch.username : &quot;kibana&quot;<br>elasticsearch.password : &quot;kibana&quot;<br>server.ssl.enabled : true<br>server.ssl.certificate : /etc/kibana/security.crt.pem<br>server.ssl.key : /etc/kibana/security.key.pem<br>elasticsearch.ssl.verificationMode : none<br></pre><p>Restart kibana</p><pre>sudo service restart kibana</pre><p>Go to machine IP:5601 and you’ll picture as following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EwK2U1RXjjbhry8nG_qZ2Q.png" /></figure><p>When you want to curl Elasticsearch, it will no longer be possible to do without specifying username and password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4fQ-J8RbFfVM0Pm4mU4QA.png" /></figure><p>Try this one,</p><pre>curl -u elastic:admin1 -XGET &#39;localhost:9200/_cluster/health?pretty&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YdeuxRKgM_cm5-9ZfeEPDA.png" /></figure><p>I hope you can successfully install and use it. If you have any problems feel free to email.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=370abcfd4186" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum Transaction Stream with Pub/Sub & Apache Nifi]]></title>
            <link>https://medium.com/i%CC%87stanbuldatascienceacademy/ethereum-transaction-stream-with-pub-sub-apache-nifi-533b77a6b104?source=rss-4c72a9b7380------2</link>
            <guid isPermaLink="false">https://medium.com/p/533b77a6b104</guid>
            <category><![CDATA[projects]]></category>
            <dc:creator><![CDATA[Deniz Parlak]]></dc:creator>
            <pubDate>Mon, 14 Jun 2021 18:38:50 GMT</pubDate>
            <atom:updated>2021-07-13T11:28:48.540Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, there has been a significant surge in public’s attention towards cryptocurrency in social media, which caused cryptocurrency trading numbers to skyrocket.</p><p>In this article, I will show a flow where we receive transaction traffic on Apache Nifi by using the <a href="https://etherscan.io/">etherscan.io</a> site’s API.</p><figure><img alt="Niagara Waterfall" src="https://cdn-images-1.medium.com/max/1024/1*QJrvVy4i_RI795-WjVACGA.jpeg" /></figure><p>In the project, incoming data goes to Pub/Sub topic in Google Cloud. This topic is consumed over Nifi and the incoming raw data is first split and then parsed.</p><p>The parsed data will be written to Elastic Cloud (Only greater than 100 eth) as a result of the following rule(see below), I also store all the incoming data in the HDFS file system. Then, we will track this data over Kibana.</p><p>In conclusion, the final state version of the project will be as in the picture follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzprE0OCWbdk_w-1ccYrMw.png" /></figure><h3><strong>Consume Google Cloud Topic</strong></h3><p>I will need “ConsumeGCP PubSub” Processor to consume from kafka topic in GCP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*alIVjmPzpCGCfZJRD-iLrQ.png" /></figure><p>When I enter the details of the processor, I will need to make 3 setting adjustments. These adjustments are the project id in GCP, the subscription, and the necessary controller for Nifi to connect to the GCP enviroment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeN7-19EwYnD6InnUrkUyQ.png" /></figure><p>To connect to the GCP enviroment, I need to download the service account file from the IAM interface in GCP. Then, I must enter the directory where this json file is located in the Service Account JSON File field, or I can paste the contents of the file into the Service Account JSON part.</p><p>In the picture below, you can see the sample creation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2ZGtfDK6WmcYW8ZR1Dj1A.png" /></figure><p>After I am done with the settings, I can go ahead and enable the state of the processor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4LImjQLSfVJeg6In78FDw.png" /></figure><h3>Split Json</h3><p>The reason I use this processor is that transactions come as a single json data in the data we receive from kafka.</p><p>If we try to parse the data without splitting, all incoming transactions (for example 500) will be in a single json file and we would not be able to control it.</p><p>In order to split the incoming data, we need to name the containing object in the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dg6RDDVQuv7QZZTPJE3UDw.png" /></figure><p>In this example I used the word “<strong>result”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g_6zgaqXg3xssbrYgzmqYg.png" /></figure><h3>Jolt Transform Json</h3><p>This is the most important part of the project. I took what I wanted from the incoming data and converted it to the desired type.</p><p>The sample data is shown in the picture above, here I just got the values <strong>”has”, </strong>“<strong>from”, </strong>“<strong>to”,”timeStamp”, </strong>“<strong>value”.</strong><br> In addition, “value” comes as a string, I set its type to float.</p><p>After clicking on the processor, I click on the “Advance” button and write the special Jolt Specification I want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FcL7QYxHwdNjm2EYg30yKQ.png" /></figure><p>Writing a Jolt Specification is not difficult. It can be easily understood by going through a couple of examples.</p><p>In the first “spec” part I determined what values I will get and what their “alias” are. (for example we updated “value” to “eth_value”)</p><p>In the second “spec” part, I divided the “eth_value”, which came as a string, by 1000000000000000000 and made it float. I did this with the “=divide” command.</p><p>After the transform operations, I get only the parts I want and the division of the “eth_value”.</p><p>You can also put it in the processor and see the expected output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhGXTgLC__9X1H0DCitoFA.png" /></figure><h3>Evaluate Json Path</h3><p>For the next step, I choose the variable to write the rule and the variables to send.</p><p>“<strong>$.”</strong> to select the data from the previous step I use it and assign it to the properties we created.</p><p>** Don’t forget to do <strong>flowfile-attribute</strong> in Destination</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZLDGwGV5Iyuo7Dwu61NPw.png" /></figure><h3>Route on Attribute</h3><p>I wrote a rule to the “eth_value” that comes with the final data, so that transactions greater than 100 eth will be written to Elastich Search and the rest of my data will be written to the hdfs file system.</p><p>I created a property called “check_anomaly” and wrote a boolean expression using <a href="https://nifi.apache.org/docs/nifi-docs/html/expression-language-guide.html"><strong>Nifi Expression Language</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZYvwSmTQmMHWY2xawq-yQ.png" /></figure><h3>Put Elastic Search Record</h3><p>In the last step, I sent the data returned from the rule to Elastich Search.<br> I worked on elastic cloud in this project. You can simply create clusters in <a href="https://cloud.elastic.co/">elastic cloud</a>.</p><ul><li>The red box shows the index name I will create in Elastic Serach.</li><li>I write the type I will create in the blue box.</li><li>Pink box controller class required to connect to Elastic Cloud</li><li>The green box is the controller required to read the data from the previous step. I don’t need to make any additional adjustments for the green box.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tzg2P7iEfGPriQ28NdrMgQ.png" /></figure><h4>ElasticSearchClientServiceImpl</h4><p>If you created an account on the elastic cloud, a username and password were created for you in the initial step.</p><p>Also, you need Elastic Search’s endpoint to be able to send the data. You can copy the endpoint from the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-KP6l4EGytAZKDWjrQxRg.png" /></figure><p>If you have all the information, go inside the controller and fill in the required fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_EQZcpZY_P6xdve621OD8A.png" /></figure><p>Don’t forget to enable the configuration at the end..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iz-2JsEPlwz4taZcxA0Sgw.png" /></figure><h3>Update Attribute</h3><p>While this processor sends data to HDFS file system, it updates the filenames to timeStamp format. I can search easily when searching HDFS file system in the future</p><p>I write a <strong>Nifi Expression Language</strong> where the green arrow indicates, and assign the time_stamp format from the previous step to the filename properties.</p><p>I need to pay attention to giving the field name a “filename” when I add a new field.<br> This is because it updates the filename when exporting to HDFS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_F-OUm3-RebUAqWMGJAVyQ.png" /></figure><h3>Put HDFS</h3><p>In this step, I just need to set my core-site-xml file and where I want to dump the incoming data.</p><p>If I don’t know where core-site.xml is, I use the following command to find it</p><pre><strong>sudo find / -iname core-site.xml</strong></pre><p>You can find my configurations below. If you do not have an eth-data folder in the HDFS file system, don’t worry, it will create it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJJUuIk5ax3w7XDun1llzg.png" /></figure><h3>Start All Processor</h3><p>After making all my configurations, I run the processors at the same time. With the application I wrote, I receive the data from the API requests to the kafka topic in the background.</p><p>If the data from the API is not written to the kafka topic, the flow will not work successfully.</p><p>After all the processors are running, I first check the hdfs file system by ssh to the machine.</p><pre>hdfs dfs -ls /eth-data/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxOUwTeoaEJVIh7pMXvi4w.png" /></figure><p>Successfully written data to hdfs.</p><h3>Put Slack</h3><p>If I consider transactions larger than 100 ETH in the project as fraud, I may also want to receive them as notifications on slack.</p><p>I use the Put Slack processor for this. When I look at the settings of the processor, I see Web Hook URL and Text inputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKF8UeaP8lx2orQERcZJ1Q.png" /></figure><p>I need to get the URL specially produced for the application that I created on my slack page in the Web Hook URL section.</p><p>The text part contains the body of the message I want to send.</p><p>I can also send variety of things like emojis etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPv47qzg53rN_ipbmxeapQ.png" /></figure><h3>Kibana Configuration</h3><p>When you come to the Index management section in the Elastic Search interface, you can see the data from Nifi and the created index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_CkNQgRdhqA2VhfypYc9IA.png" /></figure><p>To view the data in the Kibana interface, click the <strong>Index Pattern</strong> link on the same page and create a new index pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7OjW7ihpCasIKXlHLgz6ow.png" /></figure><p>When you go to Kibana interface and go to Discover, you will be able to view the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IS_PGHBL6nZafkAz82yFAA.png" /></figure><p>If you want, you can also see the data in graph form by using the features of Kibana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FH4XJ4K4UUEcQUzkifnkfg.png" /></figure><p>Finally, check your slack channel and confirm that the message has been received successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5o0pq_lmL89iEeTusoHVBA.png" /></figure><p>See you in different article..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=533b77a6b104" width="1" height="1" alt=""><hr><p><a href="https://medium.com/i%CC%87stanbuldatascienceacademy/ethereum-transaction-stream-with-pub-sub-apache-nifi-533b77a6b104">Ethereum Transaction Stream with Pub/Sub &amp; Apache Nifi</a> was originally published in <a href="https://medium.com/i%CC%87stanbuldatascienceacademy">İstanbul Data Science Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Stream API Json Parse]]></title>
            <link>https://parlak-deniss.medium.com/kafka-stream-api-json-parse-99f88757cff7?source=rss-4c72a9b7380------2</link>
            <guid isPermaLink="false">https://medium.com/p/99f88757cff7</guid>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Deniz Parlak]]></dc:creator>
            <pubDate>Mon, 01 Feb 2021 09:58:51 GMT</pubDate>
            <atom:updated>2021-02-01T10:01:23.900Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, in this article, I will talk about how to process data incoming to Kafka queue with <strong>Kafka stream api</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P-Ymr2JMKVfe-xJP.png" /></figure><p>We can send data from various sources to the Kafka queue,The data waiting in the queue can be in formats such as json, avro, etc. Or only a single string or integer values ​​can come.</p><p>If the incoming data contains one piece of String or Integer values, it is easier for us to process the data.</p><p>I will run this example on my Windows machine using Java. However, after preparing the code and outputting it as jar, you can do it by editing the necessary ports on the hortonworks sandbox.</p><p>To do the example, you must have Apache Kafka installed on your Windows (or Linux) machine.</p><p>I use the Intellij IDE as a code development environment.<br>Let’s create a new maven project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tlgZVwYepMpVFr5nc1AT-w.png" /></figure><p>After the project is created, a screen like the one below will meet us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HgTrQoM2PMkqYn-Fr5f8Q.png" /></figure><p>Let’s go to the maven repositories for our project and add the necessary dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RegS4IKmZdChi-1WOWPp9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIU_eWiAoGqb2SdYaBHpdw.png" /></figure><p>Copy required space and paste it in <strong>pom.xml</strong> file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54AfFVHejWySNdqThZgUaw.png" /></figure><p>After adding Dependencies, refresh the pom.xml file</p><p>Now create a new Java class. Here we will do our work for Producer.</p><p>After creating the Main function, the first thing we need to do is to define Properties to communicate with Kafka.</p><pre>Properties properties = new Properties();<br><br><em><br></em>properties.setProperty(ProducerConfig.<em>BOOTSTRAP_SERVERS_CONFIG</em>, &quot;127.0.0.1:9092&quot;);<br>properties.setProperty(ProducerConfig.<em>KEY_SERIALIZER_CLASS_CONFIG</em>, StringSerializer.class.getName());<br>properties.setProperty(ProducerConfig.<em>VALUE_SERIALIZER_CLASS_CONFIG</em>, StringSerializer.class.getName());</pre><pre><em><br></em>properties.setProperty(ProducerConfig.<em>ACKS_CONFIG</em>, &quot;all&quot;); <em>// strongest producing guarantee<br></em>properties.setProperty(ProducerConfig.<em>RETRIES_CONFIG</em>, &quot;3&quot;);<br>properties.setProperty(ProducerConfig.<em>LINGER_MS_CONFIG</em>, &quot;1&quot;);<br><em><br></em>properties.setProperty(ProducerConfig.<em>ENABLE_IDEMPOTENCE_CONFIG</em>, &quot;true&quot;); <em>// ensure we don&#39;t push duplicates</em></pre><p>Let’s write a small function to generate a random data, the type of this function should be <strong>ProducerRecord&lt;&gt;</strong></p><pre>public static ProducerRecord&lt;String, String&gt; newRandomTransaction(String name) {<br><br>    ObjectNode transaction = JsonNodeFactory.<em>instance</em>.objectNode();<br><br><br>    transaction.put(&quot;name&quot;, &quot;Jack&quot;);<br>    transaction.put(&quot;amount&quot;, 100);<br>    return new ProducerRecord&lt;&gt;(&quot;test2&quot;, name, transaction.toString());<br>}</pre><p>The data we want to send will be in JSON format, so we must create a JsonNodeFactory object.</p><p>Then we put what we want to send into it with the <strong>put ()</strong> method.</p><p>Now all we have to do is create an object from the function we have created and give it to Producer.</p><pre>Producer&lt;String, String&gt; producer = new KafkaProducer&lt;&gt;(properties);<br><br><br>producer.send(<em>newRandomTransaction</em>(&quot;Denis&quot;));<br>producer.close();</pre><p>Very good, now a JSON with <strong>{“name”: “Jack”, “amount”: 100}</strong> will go to Kafka Queue</p><p>Let’s read the data written to the Queue as a stream and move on to the processing step. Create a new class</p><p>Let’s define the properties required to read from the Kafka Queue.</p><pre>Properties props = new Properties();<br>props.put(StreamsConfig.<em>APPLICATION_ID_CONFIG</em>, &quot;test&quot;);<br>props.put(StreamsConfig.<em>BOOTSTRAP_SERVERS_CONFIG</em>, &quot;localhost:9092&quot;);<br>props.put(StreamsConfig.<em>DEFAULT_KEY_SERDE_CLASS_CONFIG</em>, Serdes.<em>String</em>().getClass());<br>props.put(StreamsConfig.<em>DEFAULT_VALUE_SERDE_CLASS_CONFIG</em>, Serdes.<em>String</em>().getClass());<br><em><br></em>props.put(ConsumerConfig.<em>AUTO_OFFSET_RESET_CONFIG</em>, &quot;earliest&quot;);<br>props.put(StreamsConfig.<em>CACHE_MAX_BYTES_BUFFERING_CONFIG</em>, &quot;0&quot;);</pre><p>Since the incoming data will be in JSON format, we will need <strong>Serializer </strong>and <strong>Deserializer </strong>to parse it.</p><pre>final Serializer&lt;JsonNode&gt; jsonNodeSerializer = new JsonSerializer();<br>final Deserializer&lt;JsonNode&gt; jsonNodeDeserializer = new JsonDeserializer();<br>final Serde&lt;JsonNode&gt; jsonNodeSerde = Serdes.<em>serdeFrom</em>(jsonNodeSerializer,jsonNodeDeserializer);</pre><pre>StreamsBuilder builder = new StreamsBuilder();<br>KStream&lt;String,JsonNode &gt; textLines = builder.stream(&quot;test2&quot;, Consumed.<em>with</em>(Serdes.<em>String</em>(),jsonNodeSerde));</pre><p>Going to read “test2” topic. You can organize this place according to your own topic.</p><p>After processing the data read in this section, it determines the JSON format of the new output.</p><p>In this example, I group the people in the incoming data and sum up their account balances.</p><pre>ObjectNode initialbalance = JsonNodeFactory.<em>instance</em>.objectNode();<br>initialbalance.put(&quot;count&quot;,0);<br>initialbalance.put(&quot;balance&quot;,0);</pre><p>I am aggregating each unique person’s own balance with their previous balance.</p><pre>private static JsonNode newBalance(JsonNode transaction, JsonNode balance){<br>    ObjectNode newBalance = JsonNodeFactory.<em>instance</em>.objectNode();<br>    newBalance.put(&quot;count&quot;,balance.get(&quot;count&quot;).asInt()+1);<br>    newBalance.put(&quot;balance&quot;,balance.get(&quot;balance&quot;).asInt()+transaction.get(&quot;amount&quot;).asInt());<br><br>    return newBalance;<br><br>}</pre><p>We come to the most important part of the code piece.</p><ul><li>Data in the incoming JSON format is first subjected to a groupby function.</li><li>Next, the JSON object we created above is pointed out for its new output.</li><li>Then, the data coming with the JSON data is sent as a parameter to the function we have just created and the sumed balance is returned.</li><li>As a result of these operations, the result is written to a new topic with toStream.</li><li>Finally, the stream is started with KafkaStream.</li></ul><pre>KTable&lt;String, JsonNode&gt; bankBanalnce = textLines<br>        .groupByKey(Serialized.<em>with</em>(Serdes.<em>String</em>(), jsonNodeSerde))<br>        .aggregate(<br>                () -&gt; initialbalance,<br>                (key,transaction,balance) -&gt; <em>newBalance</em>(transaction, balance),<br><br>                Materialized.&lt;String, JsonNode, KeyValueStore&lt;Bytes, byte[]&gt;&gt;<em>as</em>(&quot;bank-balance-agg&quot;)<br>                        .withKeySerde(Serdes.<em>String</em>())<br>                        .withValueSerde(jsonNodeSerde)<br>        );<br>bankBanalnce.toStream().to(&quot;out&quot;,Produced.<em>with</em>(Serdes.<em>String</em>(),jsonNodeSerde));<br><br><br><br><br>KafkaStreams streams = new KafkaStreams(builder.build(), props);<br>streams.cleanUp();<br>streams.start();</pre><p>The full version of the Producer Class,</p><pre>import com.fasterxml.jackson.databind.node.JsonNodeFactory;<br>import com.fasterxml.jackson.databind.node.ObjectNode;<br>import org.apache.kafka.clients.producer.KafkaProducer;<br>import org.apache.kafka.clients.producer.Producer;<br>import org.apache.kafka.clients.producer.ProducerConfig;<br>import org.apache.kafka.clients.producer.ProducerRecord;<br>import org.apache.kafka.common.serialization.StringSerializer;<br><br>import java.time.Instant;<br>import java.util.Properties;<br>import java.util.concurrent.ThreadLocalRandom;<br><br>public class ProducerClass{<br><br>    public static void main(String[] args) {<br>        Properties properties = new Properties();<br><br>        <em>// kafka bootstrap server<br>        </em>properties.setProperty(ProducerConfig.<em>BOOTSTRAP_SERVERS_CONFIG</em>, &quot;127.0.0.1:9092&quot;);<br>        properties.setProperty(ProducerConfig.<em>KEY_SERIALIZER_CLASS_CONFIG</em>, StringSerializer.class.getName());<br>        properties.setProperty(ProducerConfig.<em>VALUE_SERIALIZER_CLASS_CONFIG</em>, StringSerializer.class.getName());<br>        <em>// producer acks<br>        </em>properties.setProperty(ProducerConfig.<em>ACKS_CONFIG</em>, &quot;all&quot;); <em>// strongest producing guarantee<br>        </em>properties.setProperty(ProducerConfig.<em>RETRIES_CONFIG</em>, &quot;3&quot;);<br>        properties.setProperty(ProducerConfig.<em>LINGER_MS_CONFIG</em>, &quot;1&quot;);<br>        <em>// leverage idempotent producer from Kafka 0.11 !<br>        </em>properties.setProperty(ProducerConfig.<em>ENABLE_IDEMPOTENCE_CONFIG</em>, &quot;true&quot;); <em>// ensure we don&#39;t push duplicates<br><br>        </em>Producer&lt;String, String&gt; producer = new KafkaProducer&lt;&gt;(properties);<br><br><br>        producer.send(<em>newRandomTransaction</em>(&quot;Jack&quot;));<br>        producer.close();<br>    }<br>    public static ProducerRecord&lt;String, String&gt; newRandomTransaction(String name) {<br><br>        ObjectNode transaction = JsonNodeFactory.<em>instance</em>.objectNode();<br><br><br>        transaction.put(&quot;name&quot;, &quot;Jack&quot;);<br>        transaction.put(&quot;amount&quot;, 100);<br>        return new ProducerRecord&lt;&gt;(&quot;test5&quot;, name, transaction.toString());<br>    }<br>}</pre><p>The full version of Stream Class,</p><pre>import com.fasterxml.jackson.databind.JsonNode;<br>import com.fasterxml.jackson.databind.node.JsonNodeFactory;<br>import com.fasterxml.jackson.databind.node.ObjectNode;<br><br>import org.apache.kafka.clients.consumer.ConsumerConfig;<br>import org.apache.kafka.common.serialization.Deserializer;<br>import org.apache.kafka.common.serialization.Serde;<br>import org.apache.kafka.common.serialization.Serdes;<br>import org.apache.kafka.common.serialization.Serializer;<br>import org.apache.kafka.common.utils.Bytes;<br>import org.apache.kafka.connect.json.JsonDeserializer;<br>import org.apache.kafka.connect.json.JsonSerializer;<br>import org.apache.kafka.streams.KafkaStreams;<br>import org.apache.kafka.streams.StreamsBuilder;<br>import org.apache.kafka.streams.StreamsConfig;<br>import org.apache.kafka.streams.kstream.*;<br>import org.apache.kafka.streams.state.KeyValueStore;<br>import java.util.Properties;<br><br><br>public class KafkaStream {<br><br>    public static void main(final String[] args) throws Exception {<br>        Properties props = new Properties();<br>        props.put(StreamsConfig.<em>APPLICATION_ID_CONFIG</em>, &quot;test2&quot;);<br>        props.put(StreamsConfig.<em>BOOTSTRAP_SERVERS_CONFIG</em>, &quot;localhost:9092&quot;);<br>        props.put(StreamsConfig.<em>DEFAULT_KEY_SERDE_CLASS_CONFIG</em>, Serdes.<em>String</em>().getClass());<br>        props.put(StreamsConfig.<em>DEFAULT_VALUE_SERDE_CLASS_CONFIG</em>, Serdes.<em>String</em>().getClass());<br>        <em>//props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG,StreamsConfig.EXACTLY_ONCE);<br>        </em>props.put(ConsumerConfig.<em>AUTO_OFFSET_RESET_CONFIG</em>, &quot;earliest&quot;);<br>        props.put(StreamsConfig.<em>CACHE_MAX_BYTES_BUFFERING_CONFIG</em>, &quot;0&quot;);<br><br><br>        final Serializer&lt;JsonNode&gt; jsonNodeSerializer = new JsonSerializer();<br>        final Deserializer&lt;JsonNode&gt; jsonNodeDeserializer = new JsonDeserializer();<br>        final Serde&lt;JsonNode&gt; jsonNodeSerde = Serdes.<em>serdeFrom</em>(jsonNodeSerializer,jsonNodeDeserializer);<br><br><br>        StreamsBuilder builder = new StreamsBuilder();<br>        KStream&lt;String,JsonNode &gt; textLines = builder.stream(&quot;test5&quot;, Consumed.<em>with</em>(Serdes.<em>String</em>(),jsonNodeSerde));<br><br>        ObjectNode initialbalance = JsonNodeFactory.<em>instance</em>.objectNode();<br>        initialbalance.put(&quot;count&quot;,0);<br>        initialbalance.put(&quot;balance&quot;,0);<br><br><br>        KTable&lt;String, JsonNode&gt; bankBanalnce = textLines<br>                .groupByKey(Serialized.<em>with</em>(Serdes.<em>String</em>(), jsonNodeSerde))<br>                .aggregate(<br>                        () -&gt; initialbalance,<br>                        (key,transaction,balance) -&gt; <em>newBalance</em>(transaction, balance),<br><br>                        Materialized.&lt;String, JsonNode, KeyValueStore&lt;Bytes, byte[]&gt;&gt;<em>as</em>(&quot;bank-balance-agg&quot;)<br>                                .withKeySerde(Serdes.<em>String</em>())<br>                                .withValueSerde(jsonNodeSerde)<br>                );<br>        bankBanalnce.toStream().to(&quot;out4&quot;,Produced.<em>with</em>(Serdes.<em>String</em>(),jsonNodeSerde));<br><br>        bankBanalnce.toStream().print(Printed.<em>toSysOut</em>());<br><br><br>        KafkaStreams streams = new KafkaStreams(builder.build(), props);<br>        streams.cleanUp();<br>        streams.start();<br>    }<br>    private static JsonNode newBalance(JsonNode transaction, JsonNode balance){<br>        ObjectNode newBalance = JsonNodeFactory.<em>instance</em>.objectNode();<br>        newBalance.put(&quot;count&quot;,balance.get(&quot;count&quot;).asInt()+1);<br>        newBalance.put(&quot;balance&quot;,balance.get(&quot;balance&quot;).asInt()+transaction.get(&quot;amount&quot;).asInt());<br><br>        return newBalance;<br><br>    }<br><br>}</pre><p>Let’s test it now</p><p>1-) First run the kafka consumer from cmd.</p><p>kafka-console-consumer.bat — bootstrap-server localhost:9092 — topic out2 — from-beginning — formatter kafka.tools.DefaultMessageFormatter — property print.key=true — property print.value=true — property key.deserializer=org.apache.kafka.common.serialization.StringDeserializer — property value.deserializer=org.apache.kafka.common.serialization.StringDeserializer</p><p>2-) Run the stream class, then run the Producer class 3 times and watch the consumer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkIY0irGeX2u6LZUgDASYA.png" /></figure><p>Everything seems successful.</p><p>I hope it was useful.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99f88757cff7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Book Recommendation System (Apache Spark & ALS)]]></title>
            <link>https://parlak-deniss.medium.com/book-recommendation-system-apache-spark-als-76ee6e300c82?source=rss-4c72a9b7380------2</link>
            <guid isPermaLink="false">https://medium.com/p/76ee6e300c82</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Deniz Parlak]]></dc:creator>
            <pubDate>Mon, 12 Oct 2020 12:54:16 GMT</pubDate>
            <atom:updated>2020-10-12T12:54:16.697Z</atom:updated>
            <content:encoded><![CDATA[<p>In this project, I wanted to develop an alternative solution for who wanted to read a book but couldn’t decide what to read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-owlr_5mLv2m_gScMX6RPQ.png" /></figure><p>The project consists of 3 stages. Collecting data, developing a model and making it ready for production.</p><p>I will not share where I get the data, I have stored this data in mongodb on the cloud. About 60,000 books and their details are available</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEmbkliA3P2QZUkLikwSIA.png" /></figure><p>To be able to recommend books, my data sets should have data about the users to be recommended books. Therefore, users who will enter the site for the first time, first select the books they have read before and score them, and they receive a suggestion according to this result.</p><p>Once they do this, users’ <strong>ip addresses</strong> and their selections are saved in the <strong>mysql</strong> database. Then, when they want to get a book recommendation, they are matched in the database according to the ip address and a suggestion is made according to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*__DTOdPvswP5r94WZlghOw.png" /></figure><p>After reading the recommended book, the reader can submit a rating to indicate whether they like it or not.</p><h4>Recommendation Model</h4><p>I used Spark’s ALS model for Recommendation. ALS model takes <strong>userID</strong>, <strong>bookID </strong>and <strong>rating </strong>parameters.<br>I applied parameter grid and CrossValidator to get better results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*tMVGxWSSzoEcra9s3LDbIw.png" /></figure><p>Since the data source remains the same, I convert it to spark dataframe instead of getting it from mongodb and it is more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*JJcwc67FcvfnyLbIwKelzA.png" /></figure><p>It is not possible to deploy on <strong>heroku </strong>as it works with spark in this project. So I haven’t deployed yet. You can see how the system works in the picture.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkOxNDwsxstE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkOxNDwsxstE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkOxNDwsxstE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/55c168fde8bc6ab633f3e0ebe3788403/href">https://medium.com/media/55c168fde8bc6ab633f3e0ebe3788403/href</a></iframe><p>The books on the right; The highest rated are listed as most read in Award-winning children’s books and Science books. I get results by quickly grouping the books in the data set with Spark</p><p>On the left, we rate one or more books we have read and ask for a new book proposal.</p><p>At the bottom, we evaluate the recommended book.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fz9-vfvcg9gAAUDzEY9UrA.gif" /></figure><p>You can find the detailed codes of the project on my github address.</p><p><a href="http://You can find the detailed codes of the project on my github address.">https://github.com/denizparlak1/Recomandation</a></p><p>Thank you for listening.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76ee6e300c82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Influence of Inflation on Interest in Public Banks]]></title>
            <link>https://parlak-deniss.medium.com/influence-of-inflation-on-interest-in-public-banks-43af3b2e39c1?source=rss-4c72a9b7380------2</link>
            <guid isPermaLink="false">https://medium.com/p/43af3b2e39c1</guid>
            <dc:creator><![CDATA[Deniz Parlak]]></dc:creator>
            <pubDate>Sun, 22 Mar 2020 20:58:31 GMT</pubDate>
            <atom:updated>2020-03-22T21:00:07.242Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, in this article i will explain my second project in Istanbul Data Science Academy. As you can see of the title, i work on Inflation and interest data.</p><p>Data available on <a href="https://www.tcmb.gov.tr/"><strong>https://www.tcmb.gov.tr/</strong></a><strong>. </strong>Just you need merge !</p><p>Banks are affected by inflation rate while regulating interest rates. In this context, it is possible to estimate the inflation rate by using bank interest rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*RRK4qU_rjrnHCK7tM-kqng.png" /></figure><p>To understand the data, a short EDA can be made first.</p><p>I have listed the steps to be taken when developing a model for estimation as follows:</p><ul><li>Careful to overfit or underfit</li><li>Feature Engineering</li><li>Choose best model (Ridge-Lasso, etc)</li><li>Develop model</li></ul><p>I put the data into a Linear model without making any changes, this process remains very simple, but I will improve the result.</p><p>First r² = 0.809</p><p>Not bad for first try.</p><p>There is another important point to note, NaN values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*aVzEpYtdsTk7hXEyt1booQ.png" /></figure><p>We need to take action for NaN data, the process here should be smart. I have averaged the column to fill NaN data. However, a different process can be applied.</p><p>After the data preparation, i continued model selection.</p><p>Let’s look at corolation for “dep variable”. Then let’s go to ML model with important columns. The important point here is at the result for several different models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*tpU9kZo7ZDFI-FjTu5ighQ.png" /></figure><p>Whichever model gives higher results (Lasso, Ridge, Polynomial, Lineer regression) , i use it.</p><p>As a result Linear Regression gave high r2, This model provides a more successful predict.</p><p>For the codes of the project:</p><p><a href="https://github.com/denizparlak1/datascience-project/tree/master/project-2">https://github.com/denizparlak1/datascience-project/tree/master/project-2</a></p><p>Have a good day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43af3b2e39c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>