<?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 Ashwani Kumar on Medium]]></title>
        <description><![CDATA[Stories by Ashwani Kumar on Medium]]></description>
        <link>https://medium.com/@ashwani844959?source=rss-e4aca97240c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ej3oIGxFhafzD_KODRRCzA.jpeg</url>
            <title>Stories by Ashwani Kumar on Medium</title>
            <link>https://medium.com/@ashwani844959?source=rss-e4aca97240c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:21:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashwani844959/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[FastAPI in Action: Building a RESTful API from Scratch]]></title>
            <link>https://medium.com/@ashwani844959/fastapi-in-action-building-a-restful-api-from-scratch-ab703fe43dc5?source=rss-e4aca97240c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab703fe43dc5</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ashwani Kumar]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 12:19:14 GMT</pubDate>
            <atom:updated>2024-10-09T12:19:14.606Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the many great reasons to use Python is the vast amount of mature and stable libraries to choose from. For example, Django and Flask offer a great web development experience and troves of helpful documentation.</p><p>Recently, the Python ecosystem has seen exciting developments powered by new features available only in Python 3+, such as coroutines and optional typing. This new era of libraries and frameworks promises both greater speed and ease of development, bringing Python on par with newer languages like Go and Rust while keeping the core experience that made Python so popular.</p><figure><img alt="FastAPI in Action: Building a RESTful API from Scratch" src="https://cdn-images-1.medium.com/max/1024/1*yUL9YTBls4ZjoD5atV4Ajw.jpeg" /></figure><p>FastAPI is a new Python framework for developing web APIs that has gained popularity over the last few years. If you plan to use Python for web development, it will serve you well to become familiar with FastAPI.</p><p>In this tutorial, you’ll build an API for a database of remote working locations using FastAPI. CodingNomads are always in need of good coffee and wifi while on the road. With this API, you can ask your friends from all over the world to submit their favorite places so that you’ll always know the best place to go.</p><p>In this article you will:</p><ul><li>Create a new FastAPI project from scratch.</li><li>Create an API for fellow CodingNomads to submit remote working locations.</li><li>Save the app’s data to a real database using an ORM.</li><li>Get ready to build your tool to locate the best remote working locations for your fellow travelers, and learn to use the modern Python FastAPI library on the way.</li></ul><h3>Setting up the Project</h3><p>To get started you will go through the usual Python project setup steps. By the end of this setup, you’ll have a base project that can be re-used for other FastAPI projects.</p><p>First, create a new folder for your project. Then, create a new virtual environment inside it:</p><pre>mkdir fastnomads<br>cd fastnomads<br>python3 -m venv env</pre><p>This will ensure the Python packages we install stay isolated to the project.</p><p>Next, activate the virtualenv:</p><pre>source env/bin/activate</pre><p>Now you can install FastAPI and uvicorn, an ASGI server:</p><pre>pip install fastapi uvicorn</pre><p>And now you should be ready to write some code.</p><h3>Starting with “Hello World”</h3><p>Before you delve into coffee shops and libraries, you should have the traditional “Hello World” app up and running in FastAPI. This allows you to prove that your initial setup is working properly.</p><p>Open up your favorite editor and paste the following code into a file called main.py. You’ll use this file for the remainder of your development:</p><pre>from fastapi import FastAPI, Depends<br><br>    app = FastAPI()<br><br>    @app.get(&#39;/&#39;)<br>    async def root():<br>         return {&#39;message&#39;: &#39;Hello World!&#39;}</pre><p>In just these five lines of code, you’ve already created a working API. If you’ve ever used Flask this should look very familiar. The last three lines are the most interesting.</p><p>This is a route:</p><pre>@app.get(&#39;/&#39;)</pre><p>It tells FastAPI that the following method should be run when the user requests the “/” path.</p><p>This is a method declaration:</p><pre>async def root():</pre><p>Notice the async def: this method will be run as a Python3 coroutine! If you’d like to learn more about concurrency and async, FastAPI itself has a great explanation of the whole thing and what makes it so fast.</p><p>Finally, the return statement where we send the data to the browser:</p><pre>return {&#39;message&#39;: &#39;Hello World!&#39;}</pre><p>As you might expect, visiting this endpoint will return a JSON response matching the dictionary above.</p><p>Enough talk, run the server to see it in action!</p><pre>uvicorn main:app --reload</pre><p>Now try visiting <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a> in your browser. You should see this:</p><pre>{ &quot;message&quot;: &quot;Hello World!&quot; }</pre><p>Perfect, but that’s not all! FastAPI also automatically generated fully interactive API documentation that you can use to interact with your new API. Visit <a href="http://127.0.0.1:8000/docs">http://127.0.0.1:8000/docs</a> in your browser. You should see something like this:</p><p>In this image you can see the endpoint that was just defined, and even execute it straight from your browser!</p><p>Since you are creating an API only with no frontend user interface, you’ll be using the interactive documentation as the main method of interacting with the API.</p><h3><strong>Defining Models and Business Logic</strong></h3><p>Now it’s time to take your application beyond the basics and start writing code specific to your goal.</p><p>First you’ll create a Pydantic model to represent a Place. Pydantic is a data validation library that uses some neat tricks from the Python3 type system. FastAPI relies heavily on it to both validate incoming data and serialize outgoing data.</p><p>You’ll also define a route to create a new Place. For now all it will do is return the submitted Place back to you.</p><p>Add the following code so that your main.py looks like this:</p><pre>from fastapi import FastAPI, Depends<br>    from pydantic import BaseModel<br>    from typing import Optional, List<br>    <br>    app = FastAPI()<br>    <br>    class Place(BaseModel):<br>         name: str<br>         description: Optional[str] = None<br>         coffee: bool<br>         wifi: bool<br>         food: food<br>         lat: float<br>         lng: float<br>    <br>         class config:<br>             orm_mode = True<br>    <br>    @app.post(&#39;/places/&#39;)<br>    async def create_place_view(place: Place):<br>         return place<br>    <br>    @app.get(&#39;/&#39;)<br>    async def root():<br>         return {&#39;message&#39;: &#39;Hello World!&#39;}</pre><p>In this code, you created a model that contains the fields you should expect for a place: a name and description, whether the place has coffee, wifi, and/or food, and a latitude and longitude so that you can locate it on a map.</p><p>Don’t worry about the orm_mode bit yet. That’s for use later when you hook up a database.</p><p>The create_place method simply takes a Place as a parameter and returns it. Soon, you’ll actually save it to a database so it persists.</p><p>Try it out in the interactive API docs. Select the /places/ route, and click the try it out button. Fill in some values for the example place (or just use the defaults) and press execute.</p><p>Notice FastAPI also gives you a URL command string for your request, so you can copy and paste it into your terminal or use it in scripts!</p><p>What you have so far demonstrates how to send and receive data from the FastAPI application. The code is still simple, but there is a lot going on including validation and serialization — much of which FastAPI gives us for “free”. You should start to see what makes FastAPI fast (as in fast to develop).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ixu4MhueB8xv15_K43O83Q.png" /></figure><h3><strong>Adding a Database</strong></h3><p>Sending and receiving data to our application is great, and for some applications, that’s all you need to do. However, we’re building a database of remote working locations, so we’ll need to persist the Places to disk somehow. The best way is by using a database.</p><p>Setting up a database is going to require a little more configuration and the installation of some more software. First install SQLAlchemy, a “Python Toolkit and Object Relational Mapper.”:</p><pre>pip install sqlalchemy --pre</pre><p>For this demonstration you’ll be using SQLite3 for your database since it requires no special setup or servers to run. Edit main.py so that it looks like this:</p><pre>from fastapi import FastAPI, Depends<br>    from pydantic import BaseModel<br>    from typing import Optional, List<br>    from sqlalchemy import create_engine<br>    from sqlalchemy.orm import declarative_base, sessionmaker, Session<br>    from sqlalchemy import Boolean, Column, Float, String, Integer<br>    <br>    app = FastAPI()<br>    <br>    #SqlAlchemy Setup<br>    SQLALCHEMY_DATABASE_URL = &#39;sqlite+pysqlite:///./db.sqlite3:&#39;<br>    engine = create_engine(SQLALCHEMY_DATABASE_URL, echo=True, future=True)<br>    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)<br>    Base = declarative_base()<br>    <br>    #Dependency<br>    def get_db():<br>         db = SessionLocal()<br>         try:<br>             yield db<br>         finally:<br>             db.close()<br>    <br>    class Place(BaseModel):<br>        name: str<br>        description: Optional[str] = None<br>        coffee: bool<br>        wifi: bool<br>        food: food<br>        lat: float<br>        lng: float<br>    <br>        class config:<br>            orm_mode = True<br>    <br>    @app.post(&#39;/places/&#39;)<br>    async def create_place_view(place: Place):<br>        return place<br>    <br>    @app.get(&#39;/&#39;)<br>    async def root():<br>        return {&#39;message&#39;: &#39;Hello World!&#39;}</pre><p>That is a lot of code specific to SQLAlchemy. You can check out the documentation if you’d like to know what each individual method does later, but for now just know that the code you wrote:</p><ul><li>Creates a SQLAlchemy database engine definition for SQLite.</li><li>Creates a blueprint for a SQLAlchemy session.</li><li>Defines a base model, which allows you to define Python objects as SQLAlchemy ORM objects.</li><li>Creates a method get_db which will be executed whenever you need access to the database. This method instantiates a Session from the blueprint you defined earlier, and closes it when you are done with it so that you don’t have unused sessions laying around.</li></ul><p>Next, define a Place database SQLAlchemy model along with an instruction to create the table.</p><p>Add the following code just below the get_db() method:</p><pre>class DBPlace(Base):<br>    __tablename__ = &#39;places&#39;<br><br>    id = Column(Integer, primary_key=True, index=True)<br>    name = Column(String(50))<br>    description = Column(String, nullable=True)<br>    coffee = Column(Boolean)<br>    wifi = Column(Boolean)<br>    food = Column(Boolean)<br>    lat = Column(Float)<br>    lng = Column(Float)<br><br>Base.metadata.create_all(bind=engine)</pre><p>You just defined the object that will be used to actually fetch and insert rows into the database.</p><p>Next you should define some methods to insert and fetch places from the database.</p><p>Add the following code Just after your class Place(BaseModel): class:</p><pre>def get_place(db: Session, place_id: int):<br>    return db.query(DBPlace).where(DBPlace.id == place_id).first()<br><br>def get_places(db: Session):<br>    return db.query(DBPlace).all()<br><br>def create_place(db: Session, place: Place):<br>    db_place = DBPlace(**place.dict())<br>    db.add(db_place)<br>    db.commit()<br>    db.refresh(db_place)<br><br>    return db_place</pre><p>These three methods are responsible for getting a single Place, getting all the Places, and creating a new Place.</p><p>The first parameter is always db: its type is a SQLAlchemy session. The rest of the parameters depend on what you’re going to do:</p><ul><li>For retrieving a single place, you just need the place_id.</li><li>For creating a place, you want the entire Pydantic Place model so you can create a record from it.</li><li>For retrieving all places you don’t need any more information, you just return all the Places in the database.</li></ul><p>Finally you should define some routes to perform the actions we need.</p><p>Replace the create_place_view method you created earlier with the following code:</p><pre>@app.post(&#39;/places/&#39;, response_model=Place)<br>    def create_places_view(place: Place, db: Session = Depends(get_db)):<br>    db_place = create_place(db, place)<br>    return db_place<br><br>@app.get(&#39;/places/&#39;, response_model=List[Place])<br>def get_places_view(db: Session = Depends(get_db)):<br>    return get_places(db)<br><br>@app.get(&#39;/place/{place_id}&#39;)<br>def get_place_view(place_id: int, db: Session = Depends(get_db)):<br>    return get_place(db, place_id)</pre><p>Note that both the create_places_view and get_places_view methods are called from the same endpoint: /places/. In this case, the HTTP method determines which function is called. HTTP methods are like verbs: they convey the intent of the client. When a GET request is sent get_places_view is called because we want to get the resource. Conversely when a POST request is sent create_places_view is called because we want to post (like posting a letter in the mail) the resource. It is important to use the correct HTTP methods for your actions.</p><p>All together, your main.py file should look like this:</p><pre>from fastapi import FastAPI, Depends<br>    from pydantic import BaseModel<br>    from typing import Optional, List<br>    from sqlalchemy import create_engine<br>    from sqlalchemy.orm import declarative_base, sessionmaker, Session<br>    from sqlalchemy import Boolean, Column, Float, String, Integer<br>    <br>    app = FastAPI()<br>    <br>    # SqlAlchemy Setup<br>    SQLALCHEMY_DATABASE_URL = &#39;sqlite+pysqlite:///./db.sqlite3:&#39;<br>    engine = create_engine(SQLALCHEMY_DATABASE_URL, echo=True, future=True)<br>    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)<br>    Base = declarative_base()<br>    <br>    def get_db():<br>        db = SessionLocal()<br>        try:<br>            yield db<br>        finally:<br>            db.close()<br>    <br>    # A SQLAlchemny ORM Place<br>    class DBPlace(Base):<br>        __tablename__ = &#39;places&#39;<br>    <br>        id = Column(Integer, primary_key=True, index=True)<br>        name = Column(String(50))<br>        description = Column(String, nullable=True)<br>        coffee = Column(Boolean)<br>        wifi = Column(Boolean)<br>        food = Column(Boolean)<br>        lat = Column(Float)<br>        lng = Column(Float)<br>    <br>    Base.metadata.create_all(bind=engine)<br>    <br>    #A Pydantic Place<br>    class Place(BaseModel):<br>        name: str<br>        description: Optional[str] = None<br>        coffee: bool<br>        wifi: bool<br>        food: food<br>        lat: float<br>        lng: float<br>    <br>        class config:<br>            orm_mode = True<br>    <br>    # Methods for interacting with the database<br>    def get_place(db: Session, place_id: int):<br>        return db.query(DBPlace).where(DBPlace.id == place_id).first()<br>    <br>    def get_places(db: Session):<br>        return db.query(DBPlace).all()<br>    <br>    def create_place(db: Session, place: Place):<br>        db_place = DBPlace(**place.dict())<br>        db.add(db_place)<br>        db.commit()<br>        db.refresh(db_place)<br>    <br>        return db_place<br>    <br>    # Routes for interacting with the API<br>    @app.post(&#39;/places/&#39;, response_model=Place)<br>    def create_places_view(place: Place, db: Session = Depends(get_db)):<br>        db_place = create_place(db, place)<br>        return db_place<br>    <br>    @app.get(&#39;/places/&#39;, response_model=List[Place])<br>    def get_places_view(db: Session = Depends(get_db)):<br>        return get_places(db)<br>    <br>    @app.get(&#39;/place/{place_id}&#39;)<br>    def get_place_view(place_id: int, db: Session = Depends(get_db)):<br>        return get_place(db, place_id)<br>    <br>    @app.get(&#39;/&#39;)<br>    async def root():<br>        return {&#39;message&#39;: &#39;Hello World!&#39;}</pre><p>This code can be broken down into five distinct sections (after imports):</p><ul><li>Setup code for SQLAlchemy for the database connection and initialization.</li><li>A SQLAlchemy ORM Place definition, used when fetching and inserting records into the database.</li><li>A Pydantic Place definition, used with receiving data from the user as well as sending data to the user.</li><li>Methods specific to interacting with the database.</li><li>Routes for interacting with the API corresponding with actions to perform on a Place.</li></ul><p>Open up the auto-generated docs in your browser, you should see these news endpoints listed. You can also interact with them. Try creating a few places using the “Post /places/” endpoint. Once that is done, use the “Get /places/” endpoint to retrieve them.</p><h3><strong>Conclusion</strong></h3><p>In this mini Python FastAPI course you:</p><p>Learned the basics of working with Python FastAPI projects, including FastAPI best practices.</p><p>Created a CRUD app for remote working locations.</p><p>Integrate a database with your application.</p><p>Congratulations! You now have a fully functional Python FastAPI that serves a database of remote working locations. To take this project further to something that real-world CodingNomads could use, you’d probably want to create a client for your API: a website, a phone app, or even another API!</p><p>To go more in depth with FastAPI, including how to deploy your application so that others can use it, check out the excellent <a href="https://fastapi.tiangolo.com/">FastAPI Docs</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab703fe43dc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Python Tips Faster Information]]></title>
            <link>https://medium.com/@ashwani844959/enhancing-python-tips-faster-information-8a4a58c15efc?source=rss-e4aca97240c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a4a58c15efc</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[faster]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ashwani Kumar]]></dc:creator>
            <pubDate>Tue, 28 May 2024 05:30:27 GMT</pubDate>
            <atom:updated>2024-05-28T05:31:50.546Z</atom:updated>
            <content:encoded><![CDATA[<h4>Python is a versatile and powerful language for data science and software development. However, as data sets grow larger and computations become more complex, optimizing Python code for performance becomes crucial. In this guide, we will explore various tips, tricks, and open source tools to help intermediate Python users speed up their data processing workflows.</h4><h3>1. Profiling and Identifying Bottlenecks</h3><p>The first step in optimizing Python performance is identifying bottlenecks and slow parts of your code. Python provides several built-in profiling tools:</p><ul><li><em>cProfile</em>: A built-in profiler that provides detailed statistics on function calls, execution time, and more.</li><li><em>line_profiler</em>: A line-by-line profiler that helps identify the slowest parts of your code.</li><li><em>memory_profiler</em>: A tool to monitor memory usage of Python code.</li></ul><p>Here’s an example of using <em>cProfile </em>to profile a script:</p><p>The output will show the number of function calls, total time spent, and time per call, helping you identify performance bottlenecks.</p><pre>  import cProfile<br><br>  def my_function():<br>  # Code to be profiled<br>  ...<br><br> if __name__ == &#39;__main__&#39;:<br>   cProfile.run(&#39;my_function()&#39;)</pre><h3>2. Vectorization with NumPy</h3><p>NumPy is a fundamental library for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions.</p><p>Vectorization is a technique that allows you to perform operations on entire arrays without the need for explicit loops. This can significantly speed up computations. Here’s an example of vectorizing a loop using NumPy:</p><p>The vectorized approach using NumPy is much faster than the loop-based approach.</p><pre> import numpy as np<br><br>  # Slow loop-based approach<br>  result = []<br>  for i in range(1000000):<br>      result.append(i * 2)<br>  <br>  # Fast vectorized approach<br>  arr = np.arange(1000000)<br>  result = arr * 2</pre><h3>3. Parallel Processing with multiprocessing</h3><p>Python’s <em>multiprocessing </em>module allows you to leverage multiple CPU cores to parallelize computations. This can provide significant speedups for CPU-bound tasks.</p><p>Here’s an example of using <em>multiprocessing </em>to parallelize a function:</p><pre>import multiprocessing<br><br>def process_data(data):<br>  # CPU-intensive data processing<br>  ...<br><br>if __name__ == &#39;__main__&#39;:<br>  pool = multiprocessing.Pool()<br>  data_chunks = [data[i:i+1000] for i in range(0, len(data), 1000)]<br>  results = pool.map(process_data, data_chunks)<br>  pool.close()<br>  pool.join()</pre><p>By dividing the data into chunks and processing them in parallel using a pool of worker processes, you can significantly reduce the overall execution time.</p><h3>4. Cython for Compiled Extensions</h3><p>Cython is an optimizing static compiler that extends Python with additional syntax to enable the compilation of Python code to C or C++. This can lead to substantial performance improvements, especially for computationally intensive tasks.</p><p>Here’s an example of using Cython to optimize a function:</p><pre>  # cython_example.pyx<br>  def sum_squares(int n):<br>  cdef int i, total = 0<br>  for i in range(n):<br>      total += i * i<br>  return total</pre><p>To compile the Cython code, you need to create a setup file:</p><pre>  # setup.py<br>  from distutils.core import setup<br>  from Cython.Build import cythonize<br>  <br>  setup(<br>      ext_modules = cythonize(&quot;cython_example.pyx&quot;)<br>  )</pre><p>Then, compile the code using the following command:</p><pre>python setup.py build_ext --inplace</pre><p>The compiled Cython code can be imported and used like a regular Python module, but with the performance benefits of compiled C code.</p><h3>5. Just-in-Time (JIT) Compilation with Numba</h3><p>Numba is an open source JIT compiler that translates Python functions to optimized machine code at runtime. It is particularly effective for numerical and scientific computing.</p><p>Here’s an example of using Numba to optimize a function:</p><pre>  from numba import jit<br><br>  @jit(nopython=True)<br>  def sum_squares(n):<br>      total = 0<br>      for i in range(n):<br>          total += i * i<br>      return total</pre><p>The <em>@jit </em>decorator with <em>nopython</em>=True tells Numba to compile the function to machine code, resulting in significant speedups.</p><h3>6. Efficient Data Structures and Algorithms</h3><p>Choosing the right data structures and algorithms can have a significant impact on Python performance. Some tips include:</p><ul><li>Use dict or set for fast lookups and membership tests.</li><li>Use list for efficient appending and iteration.</li><li>Use deque from the collections module for efficient insertion and deletion at both ends.</li><li>Use bisect for efficient searching in sorted lists.</li><li>Use generators and lazy evaluation to avoid unnecessary computations.</li></ul><p>Here’s an example of using a generator to efficiently process large data:</p><pre>def process_data(file_path):<br>  with open(file_path) as file:<br>  for line in file:<br>      # Process each line<br>      ...<br>      yield result<br><br># Iterate over the generator<br>for result in process_data(&#39;large_file.txt&#39;):<br>   # Do something with each result</pre><p>Generators allow you to process data incrementally, reducing memory usage and improving performance.</p><h3>7. Memoization and Caching</h3><p>Memoization is a technique that involves caching the results of expensive function calls and returning the cached result when the same inputs occur again. This can help avoid redundant computations.</p><p>Python provides the functools.lru_cache decorator for easy memoization:</p><pre>  from functools import lru_cache<br><br>  @lru_cache(maxsize=None)<br>  def fibonacci(n):<br>      if n &lt; 2:<br>          return n<br>      return fibonacci(n-1) + fibonacci(n-2)</pre><p>The @lru_cache decorator caches the results of the fibonacci function, avoiding redundant recursive calls.</p><h3>8. Asynchronous Programming with asyncio</h3><p>Asynchronous programming allows you to write concurrent code without the need for threads.</p><p>Python’s asyncio module provides support for writing asynchronous code using coroutines and event loops.</p><p>Here’s an example of using asyncio to make asynchronous HTTP requests:</p><pre>  import asyncio<br>  import aiohttp<br><br>  async def fetch(url):<br>      async with aiohttp.ClientSession() as session:<br>          async with session.get(url) as response:<br>              return await response.text()<br>  <br>  async def main():<br>      urls = [<br>          &#39;http://example.com&#39;,<br>          &#39;http://example.org&#39;,<br>          &#39;http://example.net&#39;<br>      ]<br>      tasks = []<br>      for url in urls:<br>          task = asyncio.ensure_future(fetch(url))<br>          tasks.append(task)<br>      results = await asyncio.gather(*tasks)<br>      for result in results:<br>          print(result)<br>  <br>  loop = asyncio.get_event_loop()<br>  loop.run_until_complete(main())</pre><p>Asynchronous programming can significantly improve performance for I/O-bound tasks, such as making HTTP requests or accessing databases.</p><h3>9. Distributed Computing with Desk</h3><p>Dask is an open source library for parallel computing in Python. It provides a flexible interface for working with large datasets and enables distributed computing across clusters of machines.</p><p>Here’s an example of using Dask to parallelize a computation:</p><pre>  import dask.array as da<br><br>  # Create a large array<br>  x = da.random.random((10000, 10000), chunks=(1000, 1000))<br>  <br>  # Compute the mean<br>  result = x.mean().compute()<br>  print(result)</pre><p>Dask automatically distributes the computation across available workers, making it easy to scale computations to large datasets.</p><h3>10. Optimizing I/O Operations</h3><p>I/O operations, such as reading from or writing to files, can be a significant performance bottleneck. Some tips for optimizing I/O include:</p><ul><li>Use buffering to reduce the number of I/O operations.</li><li>Use memory-mapped files for efficient random access to large files.</li><li>Use asynchronous I/O with asyncio for concurrent I/O operations.</li><li>Use specialized file formats, such as HDF5 or Parquet, for efficient storage and retrieval of large datasets.</li></ul><p>Here’s an example of using buffered I/O to efficiently read a large file:</p><pre>  import io<br><br>  with open(&#39;large_file.txt&#39;, &#39;rb&#39;) as file:<br>  buffer = io.BufferedReader(file)<br>  for line in buffer:<br>      # Process each line</pre><p>Buffering reduces the number of I/O operations, improving performance when reading large files.</p><p>Python code example that demonstrates some of the techniques discussed in this guide:</p><pre>  import numpy as np<br>  import multiprocessing<br>  from functools import lru_cache<br>  from numba import jit<br>  <br>  # Vectorized function using NumPy<br>  def vectorized_operation(arr):<br>      return np.sqrt(arr) + np.sin(arr)<br>  <br>  # CPU-bound function for parallel processing<br>  def cpu_bound_operation(n):<br>      total = 0<br>      for i in range(n):<br>          total += i * i<br>      return total<br>  <br>  # Memoized recursive function<br>  @lru_cache(maxsize=None)<br>  def fibonacci(n):<br>      if n &lt; 2:<br>          return n<br>      return fibonacci(n-1) + fibonacci(n-2)<br>  <br>  # JIT-compiled function using Numba<br>  @jit(nopython=True)<br>  def sum_squares(n):<br>      total = 0<br>      for i in range(n):<br>          total += i * i<br>      return total<br>  <br>  # Parallel processing using multiprocessing<br>  def parallel_processing(n):<br>      pool = multiprocessing.Pool()<br>      results = pool.map(cpu_bound_operation, range(n))<br>      pool.close()<br>      pool.join()<br>      return sum(results)<br>  <br>  # Main function<br>  def main():<br>      # Vectorized operation<br>      arr = np.random.rand(1000000)<br>      result = vectorized_operation(arr)<br>      print(&quot;Vectorized operation result:&quot;, result[:10])<br>  <br>      # Parallel processing<br>      n = 1000<br>      result = parallel_processing(n)<br>      print(&quot;Parallel processing result:&quot;, result)<br>  <br>      # Memoized recursive function<br>      n = 30<br>      result = fibonacci(n)<br>      print(&quot;Fibonacci result:&quot;, result)<br>  <br>      # JIT-compiled function<br>      n = 1000000<br>      result = sum_squares(n)<br>      print(&quot;Sum of squares result:&quot;, result)<br>  <br>  if __name__ == &#39;__main__&#39;:<br>      main()</pre><p>This code example showcases the use of <a href="https://numpy.org/">NumPy </a>for vectorized operations, multiprocessing for parallel processing, memoization with lru_cache, and JIT compilation with Numba. It demonstrates how these techniques can be applied to optimize different types of operations and functions in Python.</p><h3>Conclusion</h3><p>Optimizing Python performance is crucial for handling large-scale data processing and computationally intensive tasks. By leveraging open source tools, libraries, and techniques like profiling, vectorization, parallel processing, and asynchronous programming, intermediate Python users can significantly speed up their data processing workflows.</p><p>Remember to profile your code to identify bottlenecks, choose appropriate data structures and algorithms, and take advantage of compiled extensions and JIT compilers when necessary. Continuously measure and iterate on performance optimizations to ensure your Python code remains fast and efficient.</p><p>For more Post visit <a href="https://pythontechno.blogspot.com/">PythonTechnoGyan</a> here. Thank you for reading!</p><p>Be Happy and joyfulll</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a4a58c15efc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benefits of Python Languages and Uses]]></title>
            <link>https://medium.com/@ashwani844959/benefits-of-python-languages-and-uses-d36cb864dca6?source=rss-e4aca97240c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d36cb864dca6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[Ashwani Kumar]]></dc:creator>
            <pubDate>Thu, 23 May 2024 05:10:46 GMT</pubDate>
            <atom:updated>2024-06-05T06:58:45.185Z</atom:updated>
            <content:encoded><![CDATA[<p>A Python designer is an expert who spends significant time recorded as a hard copy server-side web application rationale utilizing the Python programming language. They are capable in utilizing Python and libraries to foster different applications. As well as composing code, Python designers should comprehend the business necessities, client experience, and quality confirmation of the product they produce. They frequently team up with other front-end engineers, programming planners, framework architects, and creators to guarantee the item addresses the client’s issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*8ixjhc4Fgr9PgYHk.png" /></figure><p>Python designers are liable for composing and testing code, troubleshooting projects, and incorporating applications with outsider web administrations. They additionally foster back-end parts, associate the application with other web administrations and backing the front-end engineers by coordinating their work with the Python application. Python designers are additionally liable for composing and keeping up with specialized documentation, guaranteeing the framework performs well, and composing and executing mechanized tests. Also, they should keep awake to-date with new advancements and structures, work together with different groups, and recommend new elements and enhancements to the application.</p><p>A portion of the fundamental instruments for Python designers incorporate Venture Jupyter, Selenium, Python libraries, web structures like Django, data set innovations like PostgreSQL, and improvement and investigating devices like PyCharm. Numerous Python engineers have experience working with rendition control frameworks like Git or SVN and prearranging dialects like Slam or PowerShell for robotization. By utilizing these instruments and advances, Python engineers can make powerful, secure, and effective applications that live up to the assumptions of their clients.</p><p>In a commonplace Nimble improvement group, a Python designer assumes a critical part in the turn of events and conveyance of excellent programming items. The Lithe technique accentuates cooperation, adaptability, and consumer loyalty, and Python designers work intimately with other colleagues to guarantee that the product addresses the client’s issues.</p><h3>Here are a portion of the particular jobs and obligations of a Python designer in a Spry improvement group:</h3><ul><li>Cooperation: Python designers work intimately with other colleagues, including item proprietors, front-end engineers, and quality confirmation engineers, to guarantee that the product addresses the client’s issues. They partake in Coordinated functions, for example, run arranging, day to day stand-ups, run audits, and reviews, to guarantee that the group is working really and proficiently .</li><li>Prerequisites investigation: Python engineers work with item proprietors to dissect and refine necessities, guaranteeing that the product addresses the client’s issues. They give input on the practicality of necessities, propose elective arrangements, and assist with explaining ambiguities.</li><li>Plan and advancement: Python engineers plan and foster superior grade, viable, and adaptable programming utilizing Python and related innovations. They compose spotless, effective, and legitimate code, and they utilize robotized testing and consistent reconciliation to guarantee that the product is dependable and stable.</li><li>Quality confirmation: Python designers work intimately with quality affirmation architects to guarantee that the product satisfies the necessary quality guidelines. They take part in code audits, compose mechanized tests, and team up with quality confirmation specialists to distinguish and fix deserts.</li><li>Persistent improvement: Python engineers are focused on constant improvement, both in their own abilities and in the product advancement process. They partake in reviews, propose new apparatuses and advances, and give criticism on the improvement cycle.</li><li>In outline, a Python designer in a Deft improvement group assumes a basic part in the turn of events and conveyance of top notch programming items. They work together with other colleagues, investigate and refine prerequisites, plan and foster programming, guarantee quality, and ceaselessly work on their abilities and the advancement cycle.</li></ul><p><em>Originally published at </em><a href="https://pythontechno.blogspot.com/2024/04/python-developer.html"><em>https://pythontechno.blogspot.com</em></a><em> on May 23, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d36cb864dca6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>