<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/category/python/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Thu, 21 Mar 2024 10:54:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>Python - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Python Threading and Asynchronous Task examples &#8211; Best Practices</title>
		<link>https://thecodebuzz.com/python-threading-asynchronous-asyncio-best-practices/</link>
					<comments>https://thecodebuzz.com/python-threading-asynchronous-asyncio-best-practices/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 17 Mar 2024 22:01:36 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Best practices for Python multithreading]]></category>
		<category><![CDATA[Comparing Python multithreading techniques]]></category>
		<category><![CDATA[Multithreaded execution in Python]]></category>
		<category><![CDATA[Multithreading with parameters in Python]]></category>
		<category><![CDATA[Python concurrent.futures example]]></category>
		<category><![CDATA[Python multithreading example]]></category>
		<category><![CDATA[Python multithreading performance tips]]></category>
		<category><![CDATA[Python threading best practices]]></category>
		<category><![CDATA[Python threading tutorial]]></category>
		<category><![CDATA[Python threading vs ThreadPoolExecutor]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=30539</guid>

					<description><![CDATA[<p>Python Asyncio &#8211; Multithreading and Asynchronous Best Practices with example Today in this example we will learn how to perform&#160;Python threading with a few examples and we will also learn the Best Practices. We will see how to optimize code execution by performing Python asynchronous code execution. We will cover the below aspects in today’s [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/python-threading-asynchronous-asyncio-best-practices/">Python Threading and Asynchronous Task examples – Best Practices</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Python Asyncio &#8211; Multithreading and Asynchronous Best Practices with example</h1>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="445" src="https://www.thecodebuzz.com/wp-content/uploads/2024/03/python-asyncio-example-multithreading-1024x445.jpg" alt="" class="wp-image-30557" srcset="https://thecodebuzz.com/wp-content/uploads/2024/03/python-asyncio-example-multithreading-1024x445.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-asyncio-example-multithreading-300x130.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-asyncio-example-multithreading-768x334.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-asyncio-example-multithreading.jpg 1326w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">#image_title #separator_sa #post_seo_title</figcaption></figure>



<p>Today in this example we will learn how to perform&nbsp;Python <em><strong>threading </strong></em>with a few examples and we will also learn the Best Practices.</p>



<p>We will see how to optimize code execution by performing Python asynchronous code execution.</p>



<p></p>



<p>We will cover the below aspects in today’s article,</p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-getting-started">Getting Started &#x2013; Multithreading with synchronous(Blocking) and asynchronous(non-bloking) execution</a></li><li><a href="#aioseo-synchronous-operation">Old &#8211; Executing Synchronous method in Python</a></li><li><a href="#aioseo-asynchronous-task-execution">Asynchronous Task execution in Python using Asyncio</a></li><li><a href="#aioseo-increasing-the-load">Increasing the load</a></li></ul></div>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>Asynchronous programming is a programming allows tasks to be executed concurrently and independently of each other, without blocking the execution of the main program. In asynchronous programming, tasks are executed asynchronously, meaning they can start, run, and complete independently of the main program&#8217;s execution flow.</p>



<p>The key concept in asynchronous programming is the use of non-blocking operations, where a program can initiate a task and continue executing other tasks without waiting for the completion of the initiated task. This enables better utilization of resources and improved responsiveness in applications, especially when dealing with I/O-bound operations such as network requests, file I/O, and database queries.</p>
</blockquote>



<p></p>



<h2 class="wp-block-heading" id="aioseo-getting-started">Getting Started – Multithreading with synchronous(Blocking) and asynchronous(non-bloking) execution</h2>



<p></p>



<p>Before we deep dive into the Python multithreading example, please note that there are multiple ways one can obtain Multithreaded execution in Python. </p>



<p>Main techniques inlcues like using Python<em> Threading vs ThreadPoolExecutor Vs Asynco Python</em>.</p>



<p></p>



<p>Let’s take a simple use case using a Python application where I have one operation that needs to be Multithreading with parameters in Python.</p>



<p></p>



<p>I have a requirement to invoke multiple service calls and combine their decisions to display to the user as if like a single operation.</p>



<p></p>



<p>However, the below concept discussed is generic enough and can be applied to&nbsp;any Python business logic as well.</p>



<p></p>



<p>I have the below IDs to be processed asynchronously.</p>



<p></p>



<p>Each of above the&nbsp;<strong>IDs&nbsp;</strong>needs to be processed by calling an HTTP API method.</p>



<p></p>



<p>The below API processes the above IDs and provides the result,</p>



<p></p>



<p>Let’s now see how to launch each request sequentially and parallelly and achieve the result.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-synchronous-operation">Old &#8211; Executing Synchronous method in Python </h2>



<p></p>



<p>I have a simple example where a service request takes a few seconds to execute.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="257" src="https://www.thecodebuzz.com/wp-content/uploads/2024/03/python-multithreading-and-asynchronous-best-practices-with-example-1024x257.jpg" alt="" class="wp-image-30549" srcset="https://thecodebuzz.com/wp-content/uploads/2024/03/python-multithreading-and-asynchronous-best-practices-with-example-1024x257.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-multithreading-and-asynchronous-best-practices-with-example-300x75.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-multithreading-and-asynchronous-best-practices-with-example-768x193.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-multithreading-and-asynchronous-best-practices-with-example-1536x385.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-multithreading-and-asynchronous-best-practices-with-example-2048x514.jpg 2048w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
# Define an synchronous function to be executed
def perform_task(parameter):
    # Start time
    start_time = time.time()
    print(f&quot;Task executing with parameter: {parameter}&quot;)

     # Simulate some asynchronous work by calling Sleep 
    time.sleep(5) 

     # End time
    end_time = time.time()
    elapsed_time = end_time - start_time
    print(f&quot;Operation took {elapsed_time} seconds&quot;)
    print(&quot;Task execution complete&quot;)
</pre></div>


<p>Since we are executing the method synchronously, each operation executes in order and one after the other.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="350" src="https://www.thecodebuzz.com/wp-content/uploads/2024/03/python-multithreading-1-1024x350.jpg" alt="" class="wp-image-30551" srcset="https://thecodebuzz.com/wp-content/uploads/2024/03/python-multithreading-1-1024x350.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-multithreading-1-300x103.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-multithreading-1-768x262.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-multithreading-1-1536x525.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-multithreading-1-2048x700.jpg 2048w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p>Below is the main function </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
def main():
    # Define the parameters
    parameters = &#x5B;&quot;param1&quot;, &quot;param2&quot;, &quot;param3&quot;]
    # Start time
    start_time = time.time()
    # Create and gather tasks for each parameter
     # Perform the task for each parameter
    for param in parameters:
        perform_task(param)
      # End time
    end_time = time.time()
    elapsed_time = end_time - start_time
    print(f&quot;Task execution complete . Total Time taken : {elapsed_time} seconds&quot;)

if __name__ == &quot;__main__&quot;:
      main()
</pre></div>


<p>So short, each call is a blocking call and takes its own time before proceeding to the other.</p>



<p></p>



<p>Each synchronous operation executes, so the total time required to complete the operation is equal to the sum of all requests processed operations.</p>



<p><strong>The total</strong>&nbsp;time required to complete all operations<strong>&nbsp;is ~ 15 second</strong></p>



<p></p>



<p>Below is the code base for Synchronous operation,</p>



<h2 class="wp-block-heading" id="aioseo-asynchronous-task-execution">Asynchronous Task execution in Python using Asyncio</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="547" src="https://www.thecodebuzz.com/wp-content/uploads/2024/03/image-1024x547.png" alt="" class="wp-image-30559" srcset="https://thecodebuzz.com/wp-content/uploads/2024/03/image-1024x547.png 1024w, https://thecodebuzz.com/wp-content/uploads/2024/03/image-300x160.png 300w, https://thecodebuzz.com/wp-content/uploads/2024/03/image-768x410.png 768w, https://thecodebuzz.com/wp-content/uploads/2024/03/image-1536x821.png 1536w, https://thecodebuzz.com/wp-content/uploads/2024/03/image.png 1991w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p></p>



<p>Please add below import statement below in your Python file</p>



<p></p>



<pre class="wp-block-preformatted">import asyncio<br>import time</pre>



<p></p>



<p>Let’s declare the above operation using the <strong>asyncio </strong>Python example</p>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="897" height="383" src="https://www.thecodebuzz.com/wp-content/uploads/2024/03/python-threading-vs-threadpoolexecutor.jpg" alt="" class="wp-image-30555" srcset="https://thecodebuzz.com/wp-content/uploads/2024/03/python-threading-vs-threadpoolexecutor.jpg 897w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-threading-vs-threadpoolexecutor-300x128.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-threading-vs-threadpoolexecutor-768x328.jpg 768w" sizes="auto, (max-width: 897px) 100vw, 897px" /></figure>



<p></p>



<p>A main() method as below,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
async def main():
    # Define the parameters
    parameters = &#x5B;&quot;param1&quot;, &quot;param2&quot;, &quot;param3&quot;]
    # Start time
    start_time = time.time()
    # Create and gather tasks for each parameter
    tasks = &#x5B;perform_task(param) for param in parameters]
    await asyncio.gather(*tasks)
      # End time
    end_time = time.time()
    elapsed_time = end_time - start_time
    print(f&quot;Task execution complete . Total Time taken : {elapsed_time} seconds&quot;)

if __name__ == &quot;__main__&quot;:
    asyncio.run(main())
</pre></div>


<p></p>



<p></p>



<p>In this example:</p>



<ul class="wp-block-list">
<li>We define an asynchronous method perform_task that represents the asynchronous task to be executed by each coroutine. </li>



<li>We use <code>asyncio.gather()</code> to run all coroutines concurrently.</li>



<li>We used <code>asyncio.run()</code> to run the <code>main</code> coroutine.</li>



<li>We measure the total time taken for the execution by recording the start time before running the <code>main</code> coroutine and the end time after it completes. Then, we calculate and print the elapsed time.</li>
</ul>



<p></p>



<p>Finally, the result is displayed below,</p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="240" src="https://www.thecodebuzz.com/wp-content/uploads/2024/03/python-concurrent.futures-example-1024x240.jpg" alt="" class="wp-image-30553" srcset="https://thecodebuzz.com/wp-content/uploads/2024/03/python-concurrent.futures-example-1024x240.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-concurrent.futures-example-300x70.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-concurrent.futures-example-768x180.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-concurrent.futures-example-1536x360.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2024/03/python-concurrent.futures-example-2048x480.jpg 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p>Each operation executes parallel and the maximum time taken by any operation would be the actual time taken by the whole operation. </p>



<p>So all the method execution gets completed or content around the same time as one of the operations.</p>



<p></p>



<p>However, timing may vary depending on <a href="https://www.thecodebuzz.com/autoscaling-cloud-best-practices-azure-aws-google/" target="_blank" rel="noopener" title="Autoscaling in a Cloud – Best Practices">CPU</a>, CORE, and RAM memory GB size as needed.</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-increasing-the-load">Increasing the load</h2>



<p></p>



<p>Now even if I increase the request load by putting more request execution you will see the total time required would remain near the same time of execution and allowing us to get better throughout overall.</p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="867" src="https://www.thecodebuzz.com/wp-content/uploads/2024/03/best-practices-for-python-multithreading-1024x867.jpg" alt="" class="wp-image-30554" srcset="https://thecodebuzz.com/wp-content/uploads/2024/03/best-practices-for-python-multithreading-1024x867.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2024/03/best-practices-for-python-multithreading-300x254.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2024/03/best-practices-for-python-multithreading-768x650.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2024/03/best-practices-for-python-multithreading.jpg 1417w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">#image_title #separator_sa #post_seo_title</figcaption></figure>



<p><em>However, as highlighted above this also depends on the CPU load at the time of code execution and also depends on the&nbsp;<strong>CPU&nbsp;</strong>used by the machine, and its&nbsp;<strong>hardware&nbsp;</strong>configuration</em></p>



<pre class="wp-block-preformatted">Note- Use must use <strong><code>async</code> </strong>and <strong><code>await</code> </strong>throughout your codebase consistently get the full benefit of asynchronous execution.</pre>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/python-threading-asynchronous-asyncio-best-practices/">Python Threading and Asynchronous Task examples – Best Practices</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/python-threading-asynchronous-asyncio-best-practices/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python &#8211; PySpark Connect to MongoDB</title>
		<link>https://thecodebuzz.com/python-pyspark-connect-to-mongodb/</link>
					<comments>https://thecodebuzz.com/python-pyspark-connect-to-mongodb/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 31 Dec 2023 01:41:45 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Python-How to]]></category>
		<category><![CDATA[PySpark Connect to MongoDB]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=29800</guid>

					<description><![CDATA[<p>Python &#8211; PySpark Connect to MongoDB Today in this article, we will see how to use PySpark Connect to MongoDB using Python code examples. We will make use of MongoDB Spark Connector which helps connect to MongoDB and allows us to read and write data between PySpark and MongoDB. Here&#8217;s a basic example demonstrating how [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/python-pyspark-connect-to-mongodb/">Python – PySpark Connect to MongoDB</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading"><strong>Python &#8211; PySpark Connect to MongoDB</strong></h1>



<figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="836" height="753" src="https://www.thecodebuzz.com/wp-content/uploads/2024/01/Python-PySpark-to-connect-MongoDB-2.webp" alt="" class="wp-image-29826" style="width:580px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2024/01/Python-PySpark-to-connect-MongoDB-2.webp 836w, https://thecodebuzz.com/wp-content/uploads/2024/01/Python-PySpark-to-connect-MongoDB-2-300x270.webp 300w, https://thecodebuzz.com/wp-content/uploads/2024/01/Python-PySpark-to-connect-MongoDB-2-768x692.webp 768w, https://thecodebuzz.com/wp-content/uploads/2024/01/Python-PySpark-to-connect-MongoDB-2-577x520.webp 577w" sizes="auto, (max-width: 836px) 100vw, 836px" /><figcaption class="wp-element-caption">#image_title #separator_sa #post_seo_title</figcaption></figure>



<p>Today in this article, we will see how to use PySpark Connect to MongoDB using Python code examples.</p>



<p></p>



<p>We will make use of MongoDB Spark Connector which helps connect to MongoDB and allows us to read and write data between PySpark and MongoDB.</p>



<p></p>



<p>Here&#8217;s a basic example demonstrating how to read data from MongoDB, perform a transformation, and then write the results back to MongoDB.</p>



<p></p>



<p>We have below MongoDB collection,</p>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="454" height="630" src="https://www.thecodebuzz.com/wp-content/uploads/2024/01/Python-PySpark-to-connect-MongoDB-read-write-.jpg" alt="" class="wp-image-29828" srcset="https://thecodebuzz.com/wp-content/uploads/2024/01/Python-PySpark-to-connect-MongoDB-read-write-.jpg 454w, https://thecodebuzz.com/wp-content/uploads/2024/01/Python-PySpark-to-connect-MongoDB-read-write--216x300.jpg 216w, https://thecodebuzz.com/wp-content/uploads/2024/01/Python-PySpark-to-connect-MongoDB-read-write--375x520.jpg 375w" sizes="auto, (max-width: 454px) 100vw, 454px" /><figcaption class="wp-element-caption">#image_title #separator_sa #post_seo_title</figcaption></figure>



<p></p>



<h2 class="wp-block-heading">Install the MongoDB Spark Connector</h2>



<p></p>



<p>Please install MongoDB Spark Connector using the below command.</p>



<p></p>



<p><strong>Command</strong></p>



<p></p>



<pre class="wp-block-preformatted"><code>pip install pyspark</code></pre>



<p></p>



<p>For more details, please visit the official MongoDB website: </p>



<p><a href="https://www.mongodb.com/products/spark-connector" target="_blank" rel="noopener" title="">https://www.mongodb.com/products/spark-connector</a></p>



<p></p>



<h2 class="wp-block-heading">Create a <code>SparkSession</code> Object</h2>



<p></p>



<p>Once you have PySpark running, you can use the below command to create a PySpark  session object as below,</p>



<p></p>



<pre class="wp-block-code"><code>from pyspark.sql import SparkSession


my_spark = SparkSession 
    .builder 
    .appName("TheCodeBuzz") 
    .config("spark.mongodb.input.uri", "mongodb://host/TheCodeBuzz.Orders") 
    .config("spark.mongodb.output.uri", "mongodb://host/TheCodeBuzz.Orders") 
    .getOrCreate()</code></pre>



<p></p>



<p>We create a Spark session with the MongoDB connector configurations. </p>



<p></p>



<p>We will use the above <code>SparkSession</code> object to read, and write data to MongoDB, etc.</p>



<p></p>



<h2 class="wp-block-heading">Read Data from MongoDB using PySpark</h2>



<p></p>



<p>You must specify the following configuration settings to read from MongoDB:</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
dataFrame = spark.read
                 .format(&quot;mongodb&quot;)
                 .option(&quot;database&quot;, &quot;TheCodeBuzz&quot;)
                 .option(&quot;collection&quot;, &quot;Orders&quot;)
                 .load()
</pre></div>


<p></p>



<p></p>



<p>Above spark.read()  function returns a <em><code>DataFrameReader</code> </em>object, which you can use to specify the format and other <a href="https://www.thecodebuzz.com/read-get-configuration-value-from-appsetting-json-in-asp-net-core-guidelines/">configuration settings for batch read</a> operation.</p>



<p></p>



<h2 class="wp-block-heading">Write data to MongoDB using PySpark</h2>



<p></p>



<p>To write data from MongoDB, call the write function on your SparkSession object. </p>



<p></p>



<p>You must specify the following configuration settings to write the data to MongoDB,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
data = &#x5B;
  {

    &quot;Order&quot;: &quot;journal2&quot;,
    &quot;qty&quot;: 25,
    &quot;books&quot;: &#x5B;
      &quot;white&quot;
    ],
    &quot;domain&quot;: &#x5B;
      14
    ],
    &quot;Link&quot;: &quot;https://www.thecodebuzz.com/order/23456&quot;
  },
  {

    &quot;Order&quot;: &quot;journal1&quot;,
    &quot;qty&quot;: 25,
    &quot;books&quot;: &#x5B;
      &quot;black&quot;
    ],
    &quot;domain&quot;: &#x5B;
      15
    ],
    &quot;Link&quot;: &quot;https://www.thecodebuzz.com/order/2324&quot;
  }
]
</pre></div>

<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
dataFrame = spark.read.json(sc.parallelize(&#x5B;data]))


dataFrame.write.format(&quot;mongodb&quot;)
               .mode(&quot;append&quot;)
                .option(&quot;database&quot;, &quot;TheCodeBuzz&quot;)
                .option(&quot;collection&quot;, &quot;Orders&quot;)
                .option(&quot;upertDocument&quot;, &quot;true&quot;)
                .save()
</pre></div>


<p></p>



<p>The above example createDataFrame() function creates a DataFrame object from JSON input and saves it to MongoDB.</p>



<p></p>



<p>That&#8217;s all! Happy coding!</p>



<p></p>



<p>Does this help you fix your issue? </p>



<p></p>



<p>Do you have any better solutions or suggestions? Please sound off your comments below.</p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/python-pyspark-connect-to-mongodb/">Python – PySpark Connect to MongoDB</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/python-pyspark-connect-to-mongodb/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python MongoDB &#8211; Replace String in Pymongo with example</title>
		<link>https://thecodebuzz.com/python-mongodb-replace-string-pymongo-example/</link>
					<comments>https://thecodebuzz.com/python-mongodb-replace-string-pymongo-example/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 24 Dec 2023 02:04:54 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=29407</guid>

					<description><![CDATA[<p>Pymongo &#8211; Replace Substring in Document using Python example Today this article will learn to write query using Python MongoDB &#8211; Replace String in Pymongo with example. We will replace a string in the Mongo document with the input string using a simple and easy approach i.e using $replaceOne aggregation operator using Pymongo driver code. [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/python-mongodb-replace-string-pymongo-example/">Python MongoDB – Replace String in Pymongo with example</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Pymongo &#8211; Replace Substring in Document using Python example</h1>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="315" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/python-replace-string-mongodb-pymongo-1024x315.jpg" alt="#image_title #separator_sa #post_seo_title" class="wp-image-29439" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/python-replace-string-mongodb-pymongo-1024x315.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/12/python-replace-string-mongodb-pymongo-300x92.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/python-replace-string-mongodb-pymongo-768x236.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/12/python-replace-string-mongodb-pymongo-785x241.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/12/python-replace-string-mongodb-pymongo.jpg 1340w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Today this article will learn to write query using Python MongoDB &#8211; Replace String in Pymongo with example.</p>



<p></p>



<p>We will replace a string in the Mongo document with the input string using a simple and easy approach i.e using $<strong><em><code>replaceOne</code> </em></strong>aggregation operator using Pymongo driver code.</p>



<p></p>



<p>We will cover below aspects,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-getting-started">Getting started &#8211; Pymongo</a></li><li><a href="#aioseo-mongo-field-length-query-using-cli-or-compass-ui">Python Replace Substring in MongoDB &#8211; $replaceOne Aggregator</a><ul><li><a href="#aioseo-what-is-replaceone">What is $replaceOne</a></li></ul></li><li><a href="#aioseo-query-pattern-replace-using-replaceone">PyMongo- Query Pattern using $replaceOne</a></li><li><a href="#aioseo-example-using-replaceone">Example using $replaceOne</a></li><li><a href="#aioseo-define-pymongo-replace-query">Define PyMongo Replace query</a></li></ul></div>



<p>&nbsp;</p>



<p></p>



<p>We already looked at a simple way of adding or updating a new field to the document in our previous&nbsp;<strong><a href="https://www.thecodebuzz.com/mongodb-add-new-field-every-document-in-mongodb-collection/" target="_blank" rel="noreferrer noopener">MongoDB sample series</a>.</strong></p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-getting-started">Getting started &#8211; Pymongo</h2>



<p></p>



<p>Here below is a sample schema or document we shall use,</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="508" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1024x508.jpg" alt="Python MongoDB - Replace String in Pymongo with example" class="wp-image-29398" style="width:813px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1024x508.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-300x149.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-768x381.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1536x762.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-785x390.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document.jpg 1926w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<pre class="wp-block-code"><code>
</code></pre>



<h2 class="wp-block-heading" id="aioseo-mongo-field-length-query-using-cli-or-compass-ui">Python Replace Substring in MongoDB &#8211; $replaceOne Aggregator </h2>



<p></p>



<p>We are going to use a newly introduced aggregate operator to replace easily a string with matching criteria with part of the string.</p>



<p></p>



<div data-schema-only="false" class="wp-block-aioseo-faq" id="aioseo-what-is-replaceone"><h3 class="aioseo-faq-block-question">What is <code>$replaceOne</code></h3><div class="aioseo-faq-block-answer">
<p><a href="https://www.mongodb.com/docs/upcoming/reference/operator/aggregation/replaceOne/#mongodb-expression-exp.-replaceOne" target="_blank" rel="noopener" title=""><code>$replaceOne</code></a> is aggregation operator which helps replace the first instance of a search string in an input string with a replacement string.</p>



<p></p>



<p>This operator usage&nbsp;is <em>case-sensitive</em>.</p>



<p></p>
</div></div>



<h2 class="wp-block-heading" id="aioseo-query-pattern-replace-using-replaceone">PyMongo- Query Pattern using $replaceOne</h2>



<p></p>



<pre class="wp-block-code has-medium-font-size"><code>{ 

$replaceOne: { 
    input: &lt;expression&gt;, 
    find: &lt;expression&gt;, 
    replacement: &lt;expression&gt;}
}
</code></pre>



<p>In the above query,</p>



<p></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>input</td><td>Input string with search criteria.</td></tr><tr><td>find</td><td>Find the document with matching input string criteria.</td></tr><tr><td>replacement</td><td>The string to use to replace the first matched instance from input</td></tr></tbody></table></figure>



<p></p>



<p>You can replace the existing Mongo field using any other fields from the document using the above approach + using the approach discussed <a href="https://www.thecodebuzz.com/mongodb-add-padding-logic-with-prefix-or-suffix-examples/" target="_blank" rel="noopener" title="MongoDB – Add Padding logic with prefix or suffix examples">here</a>.</p>



<p></p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-example-using-replaceone">Example using $replaceOne</h2>



<p></p>



<p>In the below example, we will replace &#8220;total-order&#8221; with &#8220;order&#8221; in the mongo field.</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="508" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1-1024x508.jpg" alt="Pymongo Replace String" class="wp-image-29403" style="width:840px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1-1024x508.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1-300x149.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1-768x381.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1-1536x762.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1-785x390.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1.jpg 1926w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p></p>



<p>Please add below using the <strong>namespace </strong>in your code,</p>



<p></p>



<pre class="wp-block-code"><code>import re

from pymongo import MongoClient</code></pre>



<p></p>



<p></p>



<p>For more details on Pymongo installation and details, please visit  <a href="https://api.mongodb.com/python/current" target="_blank" rel="noopener" title="">https://api.mongodb.com/python/current</a></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-define-pymongo-replace-query">Define PyMongo Replace query </h2>



<p></p>



<p>Let&#8217;s define the filter using $<strong>replaceOne</strong> as below,</p>



<p></p>



<pre class="wp-block-code"><code>filter= {
    'Link': {
        '$regex': re.compile(r"total-order")
    }
},&#91;
    {
        '$set': {
            'Link': {
                '$replaceOne': {
                    'input': '$Link', 
                    'find': 'total-order', 
                    'replacement': 'order'
                }
            }
        }
    }
]</code></pre>



<p></p>



<p>Above we are defining regex to find all the document where string matches with &#8220;total-order&#8221;.</p>



<p></p>



<p>This match will filter only records with matching criteria and hence fasten the search.</p>



<p></p>



<p></p>



<p>Below is the complete code with example?</p>



<p></p>



<pre class="wp-block-code"><code>import re
from pymongo import MongoClient

client = MongoClient('your connection string')

filter= {
    'Link': {
        '$regex': re.compile(r"total-order")
    }
},&#91;
    {
        '$set': {
            'Link': {
                '$replaceOne': {
                    'input': '$Link', 
                    'find': 'total-order', 
                    'replacement': 'order'
                }
            }
        }
    }
]

result = client&#91;'TheCodeBuzz']&#91;'Orders'].find(
  filter=filter
)</code></pre>



<p></p>



<pre class="wp-block-code"><code>

</code></pre>



<p></p>



<p>Below is the schema post-update,</p>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="600" height="299" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-query.jpg" alt="Python Replace Substring in MongoDB" class="wp-image-29399" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-query.jpg 600w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-query-300x150.jpg 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /></figure>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/python-mongodb-replace-string-pymongo-example/">Python MongoDB – Replace String in Pymongo with example</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/python-mongodb-replace-string-pymongo-example/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>PyMongo &#8211; Insert datetime as ISODate in Python</title>
		<link>https://thecodebuzz.com/pymongo-insert-datetime-as-isodate-in-python/</link>
					<comments>https://thecodebuzz.com/pymongo-insert-datetime-as-isodate-in-python/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 17 Dec 2023 17:29:50 +0000</pubDate>
				<category><![CDATA[MongoDB and Mongoose]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python-How to]]></category>
		<category><![CDATA[PyMongo - Insert datetime as ISODate in Python]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=29348</guid>

					<description><![CDATA[<p>PyMongo &#8211; Insert datetime into Mongodb as ISODate Today in this article, we will see how to perform PyMongo &#8211; Insert datetime as ISODate in Python. We will use Mongo Driver called pymongo to insert the date in the collection in the ISO format. Getting started Here below is a sample schema or document we [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/pymongo-insert-datetime-as-isodate-in-python/">PyMongo – Insert datetime as ISODate in Python</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">PyMongo &#8211; Insert datetime into Mongodb as ISODate </h1>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="315" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-1024x315.jpg" alt="#image_title #separator_sa #post_seo_title" class="wp-image-29350" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-1024x315.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-300x92.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-768x236.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-785x241.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python.jpg 1340w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Today in this article, we will see how to perform PyMongo &#8211; Insert datetime as ISODate in Python.</p>



<p></p>



<p>We will use Mongo Driver called <em>pymongo </em>to insert the date in the collection in the ISO format.</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-getting-started">Getting started</h2>



<p></p>



<p>Here below is a sample schema or document we shall use for the date range query,</p>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="636" height="535" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-update_many-in-PyMongo.jpg" alt="" class="wp-image-29357" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-update_many-in-PyMongo.jpg 636w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-update_many-in-PyMongo-300x252.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-update_many-in-PyMongo-618x520.jpg 618w" sizes="auto, (max-width: 636px) 100vw, 636px" /></figure>



<h2 class="wp-block-heading" id="aioseo-install-pymongo-pcakge">Install PyMongo package</h2>



<p></p>



<p>Please install the PyMongo driver package to get support for the MongoClient connection class and properties.</p>



<p></p>



<p>For more details visit-<a href="https://api.mongodb.com/python/current" target="_blank" rel="noreferrer noopener"> <em>https://api.mongodb.com/python/current</em></a></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-add-pymongo-import-statements">Add PyMongo Import statements</h2>



<p></p>



<p>Please add below using namespaces,</p>



<p></p>



<pre class="wp-block-preformatted">from pymongo import MongoClient

from datetime import datetime</pre>



<p></p>



<p>If you need support for date <strong>time zone s</strong>upport in <strong>UTC, ETC, </strong>etc, please add below other import statements.</p>



<p></p>



<pre class="wp-block-preformatted">from datetime import datetime, tzinfo, timezone</pre>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-mongo-date-query-using-cli-or-compass-ui">Define MongoDB Connection</h2>



<p></p>



<pre class="wp-block-code"><code>client = MongoClient('mongodb://localhost:27017/')
db = client&#91;'your_database']
collection = db&#91;'your_collection']


</code></pre>



<h2 class="wp-block-heading" id="aioseo-date-greater-than-query">Python – Insert Date Time in ISO format</h2>



<p></p>



<h3 class="wp-block-heading" id="aioseo-define-the-date-for-the-query">Define the date for the query</h3>



<p></p>



<pre class="wp-block-code"><code>
date = datetime(2023, 1, 1)
</code></pre>



<p></p>



<p>OR</p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-date-time-using-time-zone">Date time using time zone</h3>



<p></p>



<pre class="wp-block-code"><code>date = datetime(2023, 1, 1, tzinfo=timezone.utc)
</code></pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong><em>Note</em></strong>:  When used with <strong>datetime</strong>, <em><strong>MongoDB by default uses ISO format to insert</strong></em> any date in the mongo collection.</p>
</blockquote>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-define-the-filter">Define the filter</h3>



<p></p>



<pre class="wp-block-code"><code>filter =  { //define any filter as needed }
</code></pre>



<p></p>



<p></p>



<h3 class="wp-block-heading">Define the update operation</h3>



<p></p>



<p>Please define the update operation (<code>update_operation</code>) to fit your data structure and update requirements as needed. </p>



<p></p>



<p>Below we are setting the &#8220;Date&#8221; the date field with ISO date in all the documents in the collection.</p>



<p></p>



<p></p>



<pre class="wp-block-code"><code># Define the update operation

update_operation = {
    '$set': {
        'ModifiedDate': date
    }
}
</code></pre>



<p></p>



<h2 class="wp-block-heading">Perform update_many to insert the ISO date</h2>



<p></p>



<p>Let&#8217;s perform the update_many operations as below. <code>update_many</code> in PyMongo permits you to update multiple documents that match a specified filter.</p>



<p></p>



<p>We simplification purposes, we will insert the ISO date in every document using <code>update_many</code>.</p>



<p></p>



<pre class="wp-block-code"><code>result = collection.update_many({},update_operation)

</code></pre>



<p>Above I have defined an empty filter.</p>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1005" height="576" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-est.jpg" alt="PyMongo - Insert datetime as ISODate" class="wp-image-29352" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-est.jpg 1005w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-est-300x172.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-est-768x440.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-est-785x450.jpg 785w" sizes="auto, (max-width: 1005px) 100vw, 1005px" /><figcaption class="wp-element-caption">#image_title #separator_sa #post_seo_title</figcaption></figure>



<p></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/pymongo-insert-datetime-as-isodate-in-python/">PyMongo – Insert datetime as ISODate in Python</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/pymongo-insert-datetime-as-isodate-in-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python RSA Key pair Encryption and Decryption with examples</title>
		<link>https://thecodebuzz.com/python-rsa-key-pair-encryption-and-decryption-rsa-examples/</link>
					<comments>https://thecodebuzz.com/python-rsa-key-pair-encryption-and-decryption-rsa-examples/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 05 Aug 2023 17:37:22 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Python-How to]]></category>
		<category><![CDATA[RSA Key pair Encryption and Decryption with examples]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=28078</guid>

					<description><![CDATA[<p>Python RSA Key pair Encryption and Decryption Today in this article we will learn Python RSA Key pair Encryption and Decryption with examples. We will use a Python package called PyMySQL and configure the connection parameters to include the public key for encryption and the private key for decryption. PyMySQL supports connecting to a MySQL [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/python-rsa-key-pair-encryption-and-decryption-rsa-examples/">Python RSA Key pair Encryption and Decryption with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading"><strong>Python RSA Key pair Encryption and Decryption</strong></h1>



<figure class="wp-block-image size-large"><a href="https://www.thecodebuzz.com/how-to-install-python-pymysql-with-rsa-keys/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="1024" height="428" src="https://www.thecodebuzz.com/wp-content/uploads/2023/08/pymysql-rsa-key-pair-private-key-pubic-key-1024x428.jpg" alt="Python RSA Key pair for Encryption and Decryption" class="wp-image-28080" srcset="https://thecodebuzz.com/wp-content/uploads/2023/08/pymysql-rsa-key-pair-private-key-pubic-key-1024x428.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/08/pymysql-rsa-key-pair-private-key-pubic-key-300x125.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/08/pymysql-rsa-key-pair-private-key-pubic-key-768x321.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/08/pymysql-rsa-key-pair-private-key-pubic-key-785x328.jpg 785w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure>



<p>Today in this article we will learn Python RSA Key pair Encryption and Decryption with examples.</p>



<p></p>



<p>We will use a <strong><em>Python </em></strong>package called <strong>PyMySQL </strong>and configure the connection parameters to include the public key for encryption and the private key for decryption. </p>



<p></p>



<p><strong><em>PyMySQL </em></strong>supports connecting to a MySQL server using RSA keys for secure communication.</p>



<p></p>



<p>Here&#8217;s how you can use RSA keys with PyMySQL.</p>



<p></p>



<h2 class="wp-block-heading">Generate RSA key Pair &#8211; public and private keys</h2>



<p></p>



<p>First, we will generate an RSA key pair (public and private keys). </p>



<p></p>



<p>Lets the OpenSSL library generate the keys. </p>



<p></p>



<p>Open a terminal or command prompt and run the following commands.</p>



<p></p>



<h3 class="wp-block-heading">Generate Private Keys</h3>



<p></p>



<p>Let&#8217;s create a private key with a 2048-bit key length.</p>



<p></p>



<pre class="wp-block-preformatted">openssl genpkey -algorithm RSA -out privatekey.pem -pkeyopt rsa_keygen_bits:2048

</pre>



<h3 class="wp-block-heading">Generate Public Keys</h3>



<p></p>



<pre class="wp-block-preformatted"><a href="https://www.openssl.org/" target="_blank" rel="noopener" title="">openssl</a> rsa -pubout -in privatekey.pem -out publickey.pem</pre>



<p></p>



<h2 class="wp-block-heading">Install PyMySQL with RSA</h2>



<p></p>



<p>Please install the <a href="https://pypi.org/project/cryptography/" target="_blank" rel="noopener" title=""><code>cryptography</code> </a>package,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size"><code>pip install cryptography</code></pre>



<p></p>



<h2 class="wp-block-heading">Use RSA keys in your Python code</h2>



<p></p>



<p>Kindly add below import statements </p>



<p></p>



<pre class="wp-block-preformatted">import pymysql.cursors 
from cryptography.hazmat.backends import default_backend 
from cryptography.hazmat.primitives import serialization

</pre>



<h2 class="wp-block-heading" id="block-1dc8c1ab-94a8-48eb-b715-e46844959bcf">Read RSA keys in Python code</h2>



<p></p>



<p>Let&#8217;s read files from the files using the below code,</p>



<p></p>



<h3 class="wp-block-heading">Read private keys</h3>



<p></p>



<pre class="wp-block-preformatted">with open("privatekey.pem", "rb") as f:
    private_key = serialization.load_pem_private_key(
        f.read(), password=None, backend=default_backend()
    )
</pre>



<p></p>



<h3 class="wp-block-heading">Read public keys</h3>



<p></p>



<pre class="wp-block-preformatted">with open("publickey.pem", "rb") as f:
    public_key = serialization.load_pem_public_key(
        f.read(), backend=default_backend()
    )</pre>



<p></p>



<p></p>



<h3 class="wp-block-heading">Connect using RSA keys with PyMySQL</h3>



<p></p>



<p></p>



<p><strong>Connect to the database</strong></p>



<p></p>



<pre class="wp-block-preformatted">connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             database='db',
                             cursorclass=pymysql.cursors.DictCursor,
                             "ssl": {
        "ca": "/path/../server-ca.pem",  # Path Server CA certificate (optional)
        "cert": "/path/../client-cert.pem", # Path client certificate(optional)
        "key": "/path/../client-key.pem",  # Path private key (optional)
        "cipher": "TLSv1.2",
        "keyfile": public_key,  # Use public key for encryption
        "certfile": private_key,  # Use private key for decryption
    })</pre>



<p></p>



<p>In the above,</p>



<p></p>



<p>The <strong><code>ssl</code> </strong>property includes the paths to the server CA certificate, client certificate, and client private key. </p>



<p></p>



<p>It uses the RSA keys for encryption and decryption by setting the <strong><code>keyfile</code> </strong>and <strong><code>certfile</code> </strong>to the respective loaded keys.</p>



<p></p>



<p><strong>Read from the database</strong></p>



<p></p>



<p>Let’s perform read operations on the MySQL Database,</p>



<p></p>



<pre class="wp-block-preformatted">  with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `College`, `Name` FROM `Employee` WHERE `ID`=%s"
        cursor.execute(sql)
        result = cursor.fetchone()
        print(result)</pre>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1024" height="359" src="https://www.thecodebuzz.com/wp-content/uploads/2023/08/image.jpg" alt="Python RSA Key pair Encryption and Decryption with examples" class="wp-image-28087" srcset="https://thecodebuzz.com/wp-content/uploads/2023/08/image.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/08/image-300x105.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/08/image-768x269.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/08/image-785x275.jpg 785w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/python-rsa-key-pair-encryption-and-decryption-rsa-examples/">Python RSA Key pair Encryption and Decryption with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/python-rsa-key-pair-encryption-and-decryption-rsa-examples/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
