teleren/devto huggingface dataset:
Python FastAPI middleware to modify request and response
Tags: python, fastapi, starlette, middleware
Published: 2024-02-26 18:27:28

A "middleware" is a function that works with every request before it is processed by any specific path operation. And also with every response before returning it.

I am sharing this recipe because I struggled to find right information for myself on the internet for developing a custom FastAPI middleware that can modify the incoming request body (for POST, PUT) as well as the output response content. 

There are several middlewares included in the FastAPI for common use cases. Check [here](https://fastapi.tiangolo.com/advanced/middleware/) for details. [Starlette](https://www.starlette.io/middleware/) has lot more middlewares that work with FastAPI applications too. However if none of them meet your requirements then you can easily develop a custom middleware. 

In this article I am going to share a boilerplate code for the custom middleware.

The example code shared here is written for JSON content type. But the code can be extended to support the other content mime-types. 

The below diagram show the flow of HTTP requests from the client application which is intercepted by the middleware:

![HTTP request flow with custom middleware](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bc0z5zss379gbr0g23so.png)

Here is the code for implementing this custom middleware:

```python
import json
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
from starlette.types import Message

class MyMiddleware(BaseHTTPMiddleware):
    async def set_body(self, request: Request):
        receive_ = await request._receive()

        body = receive_.get('body')
        body['new_field'] = "new data" # modify the body here

        async def receive() -> Message:
            receive_["body"] = body
            return receive_

        request._receive = receive

    async def get_body(self, request: Request) -> bytes:
        body = await request.body()
        self.set_body(request)
        return body

    async def dispatch(self, request, call_next):

        if request.method == 'POST':
            self.set_body(request)

        response = await call_next(request)
        response_body = b""
        async for chunk in response.body_iterator:
            response_body += chunk
        response_json = json.loads(response_body.decode("utf-8"))
        response_json["new_field"] = "new data" # modify response here

        modified_response = json.dumps(response_json).encode("utf-8")
        response.headers['Content-Length'] = str(len(modified_response))
        return Response(content=json.dumps(response_json).encode("utf-8"), status_code=response.status_code,
            headers=dict(response.headers), media_type=response.media_type)
```

Now add this middleware to the FastAPI application as shown here:

```python
from fastapi import FastAPI
from my_middleware import MyMiddleware

def create_app():
    app = FastAPI()

    # Add the middleware
    app.add_middleware(MyMiddleware)

    return app
```
Happy coding!
Plane Cards?
Tags: watercooler
Published: 2024-02-26 18:23:09

So, I have another project in the books. I am planning to make a Plane Cards game. What in the world even are “Plane Cards”? Well, you know how in games you can unlock cards with enough coins, XP, etc.? Well, my plan is to make an RNG game like that, for airplanes. We will start with airlines, slowly adding models, then a combo of both. I am still learning how to make things like this, so it will start very basic. This is a wheel to spin (https://spinthewheel.app/airlines). Put a screenshot (and prove it was yours please) in the comments with what you landed on, and that card will be saved in a database (link soon). Just add a username to the comment for your name to be saved, and for you to have a log of cards. It will be a long time before this grows, but hopefully it will.
When it will get over?
Published: 2024-02-26 18:16:30

Nothing just feeling little bit depressive, thought about doing many things but the first step always seems to be difficult, no matter how much shorter the journey is supposed to be. It seems like i am the only one remaining in friend circle left behind still thinking about what to do , James seems to be hiding his something ,wasn't I helpful to him when there was no one listening him. Maybe helping others has set a limit to my growth nothing seems joyful nowadays , wasting time on scrolling on web surfaces . nothing just depressed with whatever you might call , well doesn't matters to anyone everyone has to look out for themselves after all they deserve a moment of relief too. Nothing left in pockets too its my 3rd day of sleeping with nothing in this trash can even the shopkeeper is getting tired of me asking him to charge this old piece of trash which has an very rare extinct cable , might be a little awkward ,depressing ,hopeless or whatever you it. But only the suffering one knows how it is to be at this stage of life aha made someone a little sad. Please be hopeful no one deserves to be here . I helped James what if he didn't helped me , it doesn't matters i will help him again if he needs me. the fact is that no one deserves to be left alone. thinking why you reading this shit friend you have the same story as mine maybe you are the James or me. Well at least You have hope an i don't........(wont read it again to look out for mistake's)
Vue 3 - Pico.css - Agregar el Minimal CSS Framework a Nuxt 3
Published: 2024-02-26 18:14:57

## Introducción

En este artículo, mostraré cómo agregar Pico.css a un proyecto hecho con Nuxt 3. Tengo que aclarar que esta es una manera que encontré yo de que funcione, porque realicé una larga búsqueda y no encontré otro articulo que enseñe como añadirlo (quería compartirlo por si alguien quiere usarlo en algún proyecto que esté realizando). Este será un artículo breve ya que no requiere mucho trabajo. 

PD: Asumo que el proyecto hecho con nuxt ya está creado, pero sino, es solo ir a la [documentación oficial](https://nuxt.com/docs/getting-started/installation) y corremos el comando en la consola (en el directorio que quieran) `npx nuxi@latest init <project-name>` para crear un nuevo proyecto inicial (Se necesita tener instalado Node.js - v18.0.0 o más reciente).

## Instalar Pico.css
Vamos a la pagina oficial, y buscamos la sección "Getting Started"

> https://picocss.com/

Vamos a la sección `Install with NPM` y elegimos el comando que queramos para instalar la dependencia en el proyecto, segun el gestor de paquetes que estemos usando (npm, yarn, pnpm)

Una vez instalado, lo podemos verificar en nuestro `package.json`:
```json
{
   "@picocss/pico": "^2.0.3",
}
```

## Añadirlo al proyecto con Nuxt
Como sabemos, cuando instalamos una dependencia, esta se agrega a los `node_modules`, es algo a tener en cuenta para después.

Antes que nada, hay que crear un archivo dentro de esta estructura:
`assets/css/app.css` (Esto dentro de la raíz del proyecto).
Dentro de este archivo, hay que escribir lo siguiente:
```css
@import("");
```

Dentro de ese import tenemos que poner la ruta de un archivo "pico.css" que se encuentra dentro del node_modules. Quedaría algo así:
```css
@import url('@picocss/pico/css/pico.css')
```

Ahora ya podemos arrancar nuestro proyecto, en mi caso con `pnpm run dev`, y tendremos ya el estilo de Pico:

![Preview aplicación corriendo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6w9a1hnt51j6lhe7ow8z.png)

Espero que les haya funcionado. Hasta el próximo blog. 👋
Tilde or Caret in package.json - Stop copying and start choosing
Tags: node, npm, yarn
Published: 2024-02-26 18:14:23

## TL;DR

| Syntax      | Versions | Dependency | Impacts|
| ----------- | ----------- | ----------- | ----------- |
| tilde (~)      | 1.6.X       | ~1.6.7 | only bug fix can be upgrade | 
| caret(^)   | 1.X.X        | ^1.6.7 | backwards compatible, deprecated and operational functionally, refactors, bug fix  |

- **Tilde (~):** Use it for libraries where stability is crucial. Example: express framework.
- **Caret (^):** Use it for libraries where you want to benefit from new features and bug fixes. Example: Jest, Prettier.

## SEMVER 

SemVer is a convention, not a law. What happens when each number changes:
- **Major:** Something big has changed, and previous versions maybe will not work. 
- **Minor:** New features or improvements, things should still work mostly the same.
- **Patch:** Solves small issues without changing the structure.

## Tilde (~)

- Only allows **patch updates**.
- Useful for getting the latest bug fixes and security patches while maintaining stability.
- Use it for libraries where stability is crucial. Example: express framework.

## Caret (^)

- Allow **both minor and patch updates**.
- Useful for staying up-to-date with new features and improvements, however, we have a risk of potentially breaking changes.
- Use it for libraries where you want to benefit from new features and bug fixes. Example: Jest, Prettier.

## How to update my dependencies?

```
npm outdated
```

This command will scan your code for outdated packages compare with the latest version in the [npm registry](https://www.npmjs.com/) and no extra downloads needed because it is built into npm.

```
npm update
```

This command will update the dependencies in package.json and package-lock.json using the "wanted" version.

## Resources

[Semantic Versioning 2.0.0](https://semver.org/#semantic-versioning-200)
[Node.js - Peer Dependencies](https://nodejs.org/en/blog/npm/peer-dependencies)
[Node.js - An introduction to the npm package manager](https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager)
[Thanks to masahiro miyagi @masamasa3 for making this photo available on Unsplash 🎁](https://unsplash.com/photos/q20F_rFKdCw)
5 tools to improve your productivity as a developer (that are not AI dependent - yes, some still exist) 🤖
Tags: tooling, programming, productivity
Published: 2024-02-26 17:57:00

I've listed a few tools that I use personally or heard good things from users. Hopefully, they might help some of you!

> I prefer to say that I'm the founder of n°4, but even if it was not my baby, I'd love it as much (honestly). 

## 1. [Timely](https://timelyapp.com/)

![Timely screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r90mn9zvm60b3j1kfjtq.png)

Automates time tracking. It helps you & your time focus on what's important - it's super helpful if you're a freelancer. 
 
We don't use it within my team, but I've heard a lot of good things!
 
## 2. [Tuple](https://tuple.app/)


![Tuple screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/syp9xkqfv1xhqpvgmpcm.png)


Enables pair programming in a remote workplace. It includes a thoughtful screen-sharing interface and low-latency remote machine control. 
 
Who said that distance was an issue? Pair programming is nice, I don't use it every day but I know teams that can live without it.
 
## 3. [Raycast](https://www.raycast.com/)


![Raycast screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vx7yvdcxr5tb15o0sw32.png)


It is a blazingly fast, totally extendable launcher. It lets you complete tasks, calculate, share common links, and much more. When they say "supercharge productivity", they mean it. 
 
It's one of the few apps that makes me think a Mac would be useful. 

Yes, I'm on PC (and everything works fine don't worry).

 
## 4. [Axolo](https://axolo.co/)

![Axolo screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4s3dit36p38e38f0ytaw.png)


It is the most complete GitHub (GitLab) and Slack integration for pull requests. We've been working on it for the past three years, and help developers review thousands of pull requests every day. 
 
(I can't imagine a PR without Axolo today)
 
## 5. [f.lux](https://justgetflux.com/)

f.lux is a color display application that varies based on your needs and the time of day.
 
As developers, we spend a significant amount of time in front of screens. The brightness of a screen can interfere with how our bodies normally work, particularly when it comes to sleep, so if you don't already have such a tool, give it a try!

Also, they have a fun project where you can adapt your environment light while f.lux updates your screen.
 
What other tools should I add?

I'll write a blog post with all the links I receive, so please share some with me!
مقاله بازار | maghalehbazar.com
Tags: maghalehbazar
Published: 2024-02-26 17:54:58

مقاله بازار: نگارش، پذیرش و چاپ مقاله maghalehbazar.com شماره تماس 09125185739 مهیار امینی؛ واتساپ و تلگرام 00989125185739 [https://maghalehbazar.com](https://maghalehbazar.com)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zvtr6ldqcvf479ycc5w0.jpg)
What is Artificial General Intelligence, or AGI? And How Close Are We to Singularity?
Tags: ai, news, learning, chatgpt
Published: 2024-02-26 17:25:51

_Are you ready for a mind-bending journey into the future? 🤯 Join me on the latest episode of Tech Setters where we explore the fascinating concepts of Artificial General Intelligence (AGI) and the Technological Singularity._

What does it mean for a machine to be as adaptable as a human? Could AI develop a consciousness beyond our understanding? How close are we to a technological explosion that could change everything? These are just some of the questions we'll explore.

– We'll map the potential for different kinds of intelligence (human, animal, alien, and artificial);
– What's the difference between AI that excels in a narrow task and the versatile thinking of AGI?
– Could machines develop unique forms of consciousness, and how might we recognize them?
– Understand together the Singularity hypothesis;
– Dive into the latest research that hints at more human-like AI;

👉 [**Join me on this exciting exploration**](https://iwooky.substack.com/p/what-is-artificial-general-intelligence) of Singularity and AGI!


[![What is Artificial General Intelligence, or AGI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vb6qma8u11wpowvytz5o.jpg)](https://iwooky.substack.com/p/what-is-artificial-general-intelligence)
Why do library imports and props show errors in React? (Solved)
Tags: react, webdev, discuss, beginners
Published: 2024-02-26 17:21:18

# When I was new to React

I am learning React.js and I've encountered a problem when importing the React library. An error is displayed, but it doesn't affect my output. 😥
Additionally, I encounter the same issue when using 'props' in a function.

**Here is the screenshot:**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rh4bft19x8iw89us4hkk.png)

How can I solve it??

# Solution Explain Here: 
You don't have to do anything; just ignore the error. If you have any unused libraries or variables in your code, then remove them. "eslint" shows errors for missing values and unused libraries.

Thank You 🗨️
Como corrigir problemas de criação de pastas no Disco NTFS no Linux Mint
Tags: linux, ntfs
Published: 2024-02-26 17:20:59

Se você enfrentar problemas para criar pastas em um disco NTFS ao utilizar o Linux Mint, você pode resolver isso seguindo os passos abaixo:

## 1. Executar o comando `ntfsfix`:
   No terminal, digite o seguinte comando, substituindo "/dev/sdxN" pelo caminho do seu dispositivo NTFS (por exemplo, "/dev/sda1"):
   ```
   sudo ntfsfix /dev/sda1
   ```
   Pressione Enter. Este comando tentará corrigir problemas na partição NTFS especificada.

## 2. Reiniciar a máquina:
   Após a execução do comando `ntfsfix`, reinicie o seu computador. Isso garantirá que todas as alterações feitas no sistema de arquivos sejam aplicadas corretamente.

Ao seguir esses passos, você deve ser capaz de resolver o problema e criar pastas no disco NTFS no seu sistema Linux Mint. Lembre-se sempre de fazer backup de seus dados importantes antes de executar operações de reparo ou manutenção em partições de disco.

## Vídeo onde aprendi a resolver o problema

https://youtu.be/1iPxD6AT_Xg?si=QrCSYMz6OTGP42FO
قیمت مقاله نویسی
Tags: maghalehbazar
Published: 2024-02-26 17:20:01

مقاله بازار: نگارش، پذیرش و چاپ مقاله maghalehbazar.com شماره تماس 09125185739 مهیار امینی؛ واتساپ و تلگرام 00989125185739 [https://maghalehbazar.com](https://maghalehbazar.com)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lf6vb7r614adi0mjub8w.jpg)
هزینه نوشتن مقاله isi
Tags: maghalehbazar
Published: 2024-02-26 17:18:58

مقاله بازار: نگارش، پذیرش و چاپ مقاله maghalehbazar.com شماره تماس 09125185739 مهیار امینی؛ واتساپ و تلگرام 00989125185739 [https://maghalehbazar.com](https://maghalehbazar.com)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ktnxd02oztxqkikxs8h2.jpg)
Unleash the Power of JavaScript: Modern Solutions for Your Web Development Needs
Published: 2024-02-26 17:14:06

Are you ready to revolutionize your web development game? Look no further than JavaScript! This versatile programming language has become the backbone of the modern web, offering a myriad of solutions to meet your development needs.

JavaScript is not just another programming language; it's a powerhouse that empowers developers to create dynamic and interactive websites with ease. From simple scripts to complex applications, JavaScript can handle it all.

One of the key advantages of JavaScript is its ability to run seamlessly on both the client and server sides, thanks to frameworks like Node.js. This means that developers can write code once and deploy it anywhere, streamlining the development process and saving precious time and resources.

When it comes to building modern web applications, JavaScript shines brightest. With frameworks like React, Angular, and Vue.js, developers can create stunning user interfaces that are both responsive and intuitive. These frameworks offer a wide range of features and tools to streamline development and enhance productivity.

But JavaScript isn't just for front-end development. With the rise of technologies like Express.js and MongoDB, JavaScript has also become a popular choice for building powerful back-end systems. This allows for seamless communication between the client and server sides, resulting in faster and more efficient web applications.

In addition to its versatility, JavaScript also boasts a vibrant and supportive community. Whether you're a seasoned developer or just starting out, there are endless resources available to help you master the ins and outs of JavaScript development. From online tutorials to community forums, there's no shortage of support and guidance for JavaScript enthusiasts.

So, if you're looking to take your web development skills to the next level, look no further than JavaScript. With its modern solutions and endless possibilities, JavaScript is sure to elevate your projects to new heights. Ready to get started? Explore the world of [JavaScript development services](https://www.clickittech.com/javascript-development-services/
) today and unlock the full potential of this powerful programming language!
نوشتن مقاله isi
Tags: maghalehbazar
Published: 2024-02-26 17:13:23

مقاله بازار: نگارش، پذیرش و چاپ مقاله maghalehbazar.com شماره تماس 09125185739 مهیار امینی؛ واتساپ و تلگرام 00989125185739 [https://maghalehbazar.com](https://maghalehbazar.com)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cvumdmcbu726q5x5h8jn.jpg)
خرید مقاله آماده چاپ
Tags: maghalehbazar
Published: 2024-02-26 17:12:36

مقاله بازار: نگارش، پذیرش و چاپ مقاله maghalehbazar.com شماره تماس 09125185739 مهیار امینی؛ واتساپ و تلگرام 00989125185739 [https://maghalehbazar.com](https://maghalehbazar.com)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rgzyybfe61erks5oycid.jpg)
Let's Talk Youth Basketball: Crafting Future All-Stars
Tags: training, development
Published: 2024-02-26 17:05:43

So, you've stepped into the world of Youth Basketball Development – where we're not just teaching hoops, we're nurturing the next generation of all-stars. Ready for the lowdown on making your young baller a court sensation? Buckle up, we're about to spill the beans!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29fa0ydab7nql3wnzj5a.jpg)

## The Playbook for Success

**1. Skills On Point**
Ever wondered how the pros got so slick? It all starts with the basics! Our training programs? They're the secret sauce for turning rookies into rockstars. We're talking killer shots, slick ball moves, and defense that's on lockdown – thanks to drills and coaching that turn kids into court magicians.

**2. Fit and Furious**
In basketball, a fit body is the real MVP. Our fitness routines? Tailored for boosting endurance, strength, and agility. We're not just dodging injuries; we're building a foundation for peak performance that keeps kids bouncing back for more.

## Mind Games: Basketball Edition

**3. Game-Changing Minds**
Basketball isn't just about slam dunks; it's a mental chess match too. Our programs? Packed with tricks to build resilience, focus, and a winning mindset. Because in this game, being mentally tough is the secret weapon to conquer challenges on and off the court.

**4. Squad Goals**
It's not just about solo moves; teamwork is where it's at. Our training? All about teaching kids to chat, team up, and vibe with their teammates. We're not just molding players; we're crafting team players who know how to bring the good vibes.

## More Than B-Ball

**5. Character MVPs**
Beyond the game, we're shaping more than just ballers – we're shaping leaders. Our programs? They're like character boot camp, instilling values like discipline, responsibility, and respect. Because being a decent human is just as essential as nailing that three-pointer.

**6. Community MVPs**
All-stars aren't just about making the scoreboard light up; they're community heroes too. Our commitment goes beyond the court. We're pushing young athletes to get involved, make an impact, and spread good vibes in their communities.

**Road to All-Star Status**
In a nutshell, our approach to Youth Basketball Development is all about crafting future all-stars. BLSA is a premer [basketball academy in Dubai](https://balllifesportacademy.com/) who mix top-tier skill training with a sprinkle of mental toughness, teamwork vibes, character-building magic, and a side of community spirit. We're not just growing ballers; we're growing awesome humans ready to rock the game of life.
خرید مقاله isi
Tags: maghalehbazar
Published: 2024-02-26 17:01:12

مقاله بازار: نگارش، پذیرش و چاپ مقاله maghalehbazar.com شماره تماس 09125185739 مهیار امینی؛ واتساپ و تلگرام 00989125185739 [https://maghalehbazar.com](https://maghalehbazar.com)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/glykz52afl8wom3qz9hk.jpg)