teleren/devto huggingface dataset:
How to Process Headers using FastAPI
Tags: python, api, fastapi
Published: 2020-05-03 17:33:49

---
title: "How to Process Headers using FastAPI"
published: true
description: FastAPI makes processing Headers very easy, just like everything else. There are two ways to process headers with FastAPI. 
tags: python, api, FastAPI
canonical_url: https://learnings.desipenguin.com/post/headers-fastapi/
---

*This was originally posted on my blog, [here.](https://learnings.desipenguin.com/)*


FastAPI makes processing Headers very easy, just like everything else. There are
two ways to process headers with FastAPI.

## Via Request Object ##

When writing [middleware](/post/middleware-fastapi/) we have direct access to the `Request`, so it is
much easier to write as :

```python
@app.middleware("http")
async def my_middleware(request: Request, call_next):
        headers = request.headers
        if "X-My-Header" in headers:
            # Do something with X-My-Header
```

## As a Function Param ##

When writing normal endpoints, it is easier to process headers. One of your
function parameter could be `Header` itself. FastAPI will do all the work for
you, so that you can focus on the business logic.

See the sample code from FastAPI documentation of this topic.

```python
from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(*, user_agent: str = Header(None)):
    return {"User-Agent": user_agent}
```


Important thing to remember that variable name **must** be in snake_case.

e.g. In the sample code above, we are processing `User-Agent` header. So
variable name **must** be `user_agent`. Names with `-` are invalid in python. So
FastAPI will convert the dashes/hyphens to underscore for you.

But wait ..

If you *really* don't want the auto conversion to underscore. just tell FastAPI
that via `convert_underscores=False`

See documentation below for details.

## Resources ##

* [Header Param](https://fastapi.tiangolo.com/tutorial/header-params/)
Why I built a bot to find delivery slots (UK)
Tags: bot, sideprojects
Published: 2020-05-03 18:26:56

Since the lockdown it has been difficult to get a delivery slot from a supermarket. Some grocery stores have implemented a queuing system to access the site (Ocado) or even stopped letting new users register (Sainsbury).

After another unsuccessful day of refreshing, I thought there must be an easier way. Therefore, with all this extra time at home, I decided to build a bot to alert me to available groceries slots. To my surprise, it really wasn’t too difficult at all.

## Looking at requests

Depending on the site, you can see what sort of requests are made when viewing the delivery booking page by using Chrome inspector and looking in the network tab. From there it’s a just a matter of saving the cookies and automating the requests.

![Request example](https://dev-to-uploads.s3.amazonaws.com/i/7jbdo9ody4nkxexnekqf.png)

When the cookies expired the request would be denied. So, I added a headless browser function to login and save the cookies automatically for next time.

## Hosting

I built the bot to be hosted with AWS Lambda functions, so I didn't need to leave my computer on all night or have an instance running 24/7. This was very easy to set up and deploy using Serverless.

## Captcha

Unsurprisingly, the captcha code would come up for some sites when the bot was trying to log in. There wasn’t much I could do about this, so I just skipped the stores that had this implemented (Ocado and Morrisons).

![Captcha](https://dev-to-uploads.s3.amazonaws.com/i/p0pfe1vkz2ajnmeg8lnh.png)

## Alerts

I got my bot working with Asda and Tesco, and it would check every 10 minutes for any available slots. I found this interval to be enough, because unlike concert tickets, delivery slots don’t sell out as soon as they became available, plus I didn’t want to spam the site with traffic. 

![Alert screenshot](https://dev-to-uploads.s3.amazonaws.com/i/qh2r7k8ke863hq9dadco.png)

## Conclusion

This was fun to build, but by no means necessary. There are now quite a few local and smaller grocery stores providing delivery service. I would encourage you to check those out if you can.

If you still want to use one of the main supermarkets, try a bit later at night or in the morning. Friday and Saturday almost always have no slots available, but some free slots start showing up on Sunday afternoon.

Disclaimer: I only booked one slot per week to ensure I wasn’t taking up slots unnecessarily.
Day-20 Guess Number Higher or Lower 👩‍💻
Tags: python, challenge
Published: 2020-05-03 18:59:53

For the last 19 days, I am making sure to solve at least a problem a day. I got stuck at optimizing a problem named Rotate Array yesterday. And, as a result, couldn't solve a problem, could not write. I am still stuck at the same problem. Meanwhile, I solved a new one.

##### Background
This problem statement is a part of LeetCode's learn card titled Binary Search. Under the sub-heading Binary Search Template-I.

##### Problem Statement
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
```
-1 : My number is lower
 1 : My number is higher
 0 : Congrats! You got it!
```
##### Example
```
Input: n = 10, pick = 6
Output: 6
```
##### Solution Approach
1. start = 1, end = n+1. (See the problem statement. Numbers from 1 to n. Hence, make sure both are inclusive).
2. calculate mid. mid = int((start+end)/2)
3. Now pass mid as parameter to the guess API. 
4. Divide the list based on the value returned by API.

```
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:

class Solution:
    def guessNumber(self, n: int) -> int:
        start = 1
        end = n+1
        while start < end:
            mid = int((start+end)/2)
            if guess(mid) == -1:
                end = mid
            elif guess(mid) == 1:
                start = mid + 1
            elif guess(mid) == 0:
                return mid
        return -1
```

##### Learnings
1. The time complexity of the above solution is - O(logn).
2. When in the problem statement it is already mentioned sorted array think binary search.
3. Time complexity of Binary Search - O(logn). Time complexity of Linear Search - O(n). Binary search is more efficient.
memoization
Tags: ruby, beginners
Published: 2020-05-04 01:35:28


You've seen it before: `||=`. 

This is Ruby's way of **caching** data. Take the contrived example below that involves zero caching.


```ruby
class Account
  ...

  private

  def retrieve_credit_card
    if purchasing_account.present?
      purchasing_account.credit_card
    end
  end

  def purchasing_account
    Account.find(id)
  end
end
```

Here's why this sucks: we hit the database twice. When invoking `#retrieve_credit_card`, we ask for the account twice. This gets expensive on the database and a bad thing working in larger codebases with lots of data.

Cache the `Account#find` query like so.

```ruby
class Account
  def retrieve_credit_card
    if purchasing_account.present?
      purchasing_account.credit_card
    end
  end

  private

  def purchasing_account
    @purchasing_account ||= Account.find(id)
  end
end
```

This implementation is more efficient. When asking if a purchasing_account is present.. that's the first hit to the database. However, this time we ask that same instance (our cached version) for the its credit card. This saves us a roundtrip to the database. Optimization for the win!

Also, this is an actual example of a commit by yours truly. I was digging through my old pull requests and discovered I wrote this commit at work. Embarrassing to say the least, but it's fun to point fingers at your younger, simple minded self. Get cachin', ya'll.
CSS Font-display and how to use it
Tags: css, fonts
Published: 2020-05-04 06:36:57

Yesterday we included a [custom Google Font](http://daily-dev-tips.com/posts/how-to-use-google-fonts/) on our website and briefly mentioned the `font-display` option.
Let's dive deeper into what it is and how it works.

As we saw yesterday, custom fonts tend to load slowly and block the browser from defining when your website is ready.
This, in turn, makes Google think your website is slow, and nobody wants that.

So in modern browsers, we can use the `font-display` function.

## Font Display options

- `auto`: This is the default value, and leaves the decision up to the browser, in most cases, it will be `block`
- `block`: This tells the browser to hide the text until the font has fully loaded. This is the flash you see when it swaps on some sites.
- `swap`: Swap, as the name suggests, will start with the fallback font and swap once the font is loaded.
- `fallback`: This is a compromise between `auto` and `swap`. It will start with hiding the font for a brief period and then go into the `swap` routine.
- `optional`: This is much like the `fallback` method. It tells the browser to start with a hide and then transition into the fallback font. The nice option here is that it allows the browser to see if the custom font is even used at all. If, for instance, a slow connection appears, they are less likely even to see the custom font.

## How to use font-display

As seen in the previous example, we can use it as such:

```css
h1 {
  font-size: 40px;
  font-family: 'Amatic SC', cursive;
  font-display: swap;
}
```

## What is a fallback font?

So we talked about fallback fonts quite a bit, but what are those even?

```css
h1 {
  font-family: 'Amatic SC', 'Times New Roman', Times, serif;
}
```

So in the above example, the custom font is `Amatic SC` the system font is `Times New Roman` or `Times`, so in the case of using `swap`, we will first see `Times New Roman` and when the custom font has loaded it will show `Amatic SC`.

## Browser Support

Not all browsers support this, but I encourage you to use `font-display`. The browsers that don't support it will decide for you.

![3d transform support](https://caniuse.bitsofco.de/image/font-loading.png)

### Thank you for reading, and let's connect!

Thank you for reading my blog, feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
AssemblyLift: a Framework for running WebAssembly on AWS Lambda
Tags: webassembly, serverless, rust, showdev
Published: 2020-05-10 20:18:35

Today, I finally opened a pet project of mine up to the public!

I call it [AssemblyLift](https://github.com/akkoro/assemblylift), and it is (and/or will become) a framework for writing serverless cloud apps using WebAssembly and Rust. Currently it supports AWS Lambda as a backend target, and provides a custom Lambda runtime that you can deploy to a layer or bundle with your functions.

As of writing it's still a very bare-bones proof-of-concept, but it all _technically_ works, and I'm very excited about that :).

For now the [README](https://github.com/akkoro/assemblylift/blob/mainline/README.md) can give a slightly more detailed overview of current and planned features. I plan on writing a longer post here after I clean some things up and put together a few examples.

I'm also hoping to articulate a roadmap in the coming weeks...ideally one that's more coherent than the one in my head 🙃.

If any of what I've briefly described sounds interesting, drop me a comment or reach out on [GitHub](https://github.com/akkoro/assemblylift)!
React Hooks
Tags: react
Published: 2020-05-11 01:34:16

If you've been using functional components in your react project that contain a lot of logic and realized too late you need state, React Hooks is here to help!

In the early history of React, creating classes was a built-in method in React and at the time Javascript didn't have a way to natively build classes, until ES6. After ES6, React embraced classes in Javascript and made it so you can use native Javascript classes to create your components. 

There were early problems with this, involving the complex nature of javascript classes like inheritance and the "this" keyword. In every class, because of ES6 standard,  you had to remember to pass "props" to your super inside of your constructor method before you were able to use the "this" keyword. 

On top of that, autobinding had to be done manually as opposed to the earlier "React.createClass()" method. For every method, you had to remember to bind each method to the object. 

This quickly became a nuisance. Shortly after, thankfully, class fields were introduced which solved the problem of calling super. Additionally, using arrow functions solved the problem of autobinding. 

This leads us to a question: why use function components? 

##Syntax friendly for javascript users

A function component is just a function. Easy to read and understand, there's no need to get confused with React syntax. It also inherently solved our previous issues with "super(props)" and the "this" keyword. 

##Lifecycle methods

Lifecycle methods are ways that classes manage application state. But with React Hooks, you can simplify the way your components maintain their internal state data, a la useEffect(). componentDidUpdate and componentDidMount can be reduced to one useEffect function. This was a problem since this logic is duplicated amongst those two methods, but with useEffect it is synchronized and only needs to be written once. 

##Sharing non-visual logic

React couples UI to a component, and the only way way to share logic between them was to use complicated patterns like Higher-order components and Render props. But React Hooks have an answer to that: custom hooks. 

You can create custom hooks that are decoupled from any UI. As stated in the React documentation: "Unlike a React component, a custom Hook doesn’t need to have a specific signature. We can decide what it takes as arguments, and what, if anything, it should return. In other words, it’s just like a normal function. Its name should always start with use so that you can tell at a glance that the rules of Hooks apply to it...Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated."

Having hooks can make your future code simpler and highly reusable, so get out there and start experimenting with hooks!
These jobs are in high demand in the UAE during the Coronavirus pandemic
Tags: coronavirus, covid19, sanjeevnanda, uaejobs
Published: 2020-05-11 07:24:52


1. The Coronavirus pandemic has affected jobs globally, with an estimated 2.7 billion workers out of a job, according to the International Labour Organisation.

2. Despite the worker displacement, there are some industries that are experiencing a spike in demand, with companies hiring aggressively.

3. Find out if your skill set matches any of the professions that industry experts say are in demand.

4. How can you apply for a job - all the portals you need to know of.

Visit: https://gulfnews.com/living-in-uae/ask-us/these-jobs-are-in-high-demand-in-the-uae-during-the-coronavirus-pandemic-1.1588509740058
8 Unfamiliar CSS Pseudo-Classes 
Tags: css, webdev, frontend, html
Published: 2020-05-11 16:05:12

> 'A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s).' - MDN Web Docs

Wait....what? That sounds complicated right? 

What if I told you, you might be surprised to know you are already using them? 

Of course you are! Here's an example of the syntax used, can you think of any pseudo classes you have used before?

```css
selector:pseudo-class {
  property: value;
}
```
Let me guess, you thought of :hover, maybe even ::before and :after? If so, great job! However, there are many others we can use to improve our sites. Lets check out 8 unfamiliar ones below:

# :checked

Selects inputs, radio or options in select tags that have been toggled "on" by a user clicking on them.

```css
/* Any checked element */
:checked {
    color:blue;
}

/* input checkbox example */
input[type="checkbox"]:checked{
    color:red;
    border:none;
}
```

# :empty

Selects any element that is 'empty'.

An element is empty if it has no whitespace, visible content or child elements.

```css
/* style an empty element */
:empty {
    border:1px solid red;
    background:white;
}
```

# :root

Selects the element that represents the root of the document.

:root is identical to using html as a selector, except is has a higher specificity.

```css
/* style the root element */
:root {
    padding:20px;
    background:black;
}
```

# :visited

Selects any link that has already been visited on the page.

It will only select anchor tags that have a href attribute.

```css
/* style a link thats been visited */
a:visited {
    color:red;
    font-weight: bold;
}
```

# :in-range

Used to style elements that have range limitations such as inputs with min and max values.

The style is applied whilst its value is within the range limit.

```css
/* style in-range */
input[type="number"]:in-range{
    background-color:green;
}
```

# :only-child

Selects an element if it is its parents only child.

It can be chained with :hover and ::after.

```css
/*  style only-child */
li:only-child{
    font-weight: bold;
}

/* chained example */
a:only-child:after{
    content: "(Only child)";
    color:red;
}
```

# :required

Selects form elements that have the required attribute set.

<inputs>s, <selects>s and <textarea>s are valid selections.

```css
/*  style required input */
input[type="email"]:required{
    border:2px solid red;
}
```

# ::selection

Selects the area of the document that is highlighted by the user.

Color, background-color and text-shadow are the only CSS properties that can be used.

```css
/* all selectable elements */
::selection{
    color:white;
    background-color:blue;
}

/* specific element */
h4::selection{
    color:red;
    background-color: white;
}
```

The basis of this post stems from the popularity of the tweet linked below. If you found it useful or learnt something new please follow me on [twitter](https://twitter.com/frontenddude) where I post daily tips on HTML, CSS and JavaScript.

{% twitter 1257986890919227392 %}
Simply React | Kent C. Dodds @ Byteconf React 2020 (video)
Tags: react, techtalks, tutorial, webdev
Published: 2020-05-11 15:51:54

> This video is a talk from [*Byteconf React 2020*](https://www.bytesized.xyz/react-2020), a free, live-streamed React conference that aired on May 1st-2nd, 2020. Join our newsletter at the [conference website](https://www.bytesized.xyz/react-2020) to stay in the know about future conferences, videos, and more!

One of the things I love about React is how easy it is to encapsulate UI code into a component or hook. I love this because it makes reuse of those things easy. But is it easy? I've made my fair share of components that had to accept a bunch of props to handle a growing list of different use cases resulting in a complex render function full of conditional statements and a confusing API for people using this "reusable" component. Eventually it becomes too much and I had to make a new version of the same component to handle slightly different use cases. Lots of code/bug duplication there because my reusable component wasn't reusable enough.

There are patterns that have emerged in React that allow you to promote code reuse without sacrificing the simplicity or flexibility of the component. In this talk we'll go over several of these patterns that will make your React components and hooks more useful.

Thanks to [Kent C. Dodds](https://twitter.com/kentcdodds) who presented this talk at [Byteconf React 2020](https://www.bytesized.xyz/react-2020)!

{% youtube 5io81WLgXtg %}

If you enjoyed the video, give it a thumbs-up, and [subscribe to our channel](https://www.youtube.com/channel/UC046lFvJZhiwSRWsoH8SFjg?sub_confirmation=1) for more web dev content every week. We also have a newsletter where we send out what's new and cool in the web development world, every Tuesday – [join here](https://www.bytesized.xyz/newsletter)!
AI Diagnoser System - Pnuemonia
Published: 2020-05-20 05:51:44

I'm so excited to share this with y'all. My final year was really exciting as I got to build a full-fledged project which will create an impact on the medical community. I built an AI Diagnostic System which will help detect Pneumonia from Chest X-Rays. We as a team achieved an accuracy better than the previous best by working day and night and pushed ourselves to the limit. My team members were extremely helpful and co-operative all the time. This was an exciting project to work on because of so many challenges one can face while solving such a problem. Choosing the Image Augmentations, Image Preprocessing, and the right Deep Learning were the biggest tasks for us, and we nailed it after more 50+ different permutations and combinations. We have learned a lot during our research and development phases of our project. Our aim is to put it in practice soon after receiving clearance from the required authorities and bodies in India. Overall, it was a great learning experience and an exciting prospect to work on this project.
Debugging a problem
Tags: debugging, cleancode, codenewbie, javascript
Published: 2020-05-11 18:13:52

"If debugging is the process of removing software bugs, then programming must be the process of putting them in."

- Edsger Dijkstra

I like this quote! Whenever I am asked something like: "How did this bug appear?" my first response would usually be: "Someone just put it there..."
And then we can check!?

However, being in this whole new world for less then a year debugging is currently the hardest part for me! Sometimes you open the console and the error is blunt and obvious like "Cannot read property 'smth...' of undefined" most of the times this type of issue will be pretty easy. Obviously there can be times when you struggle to realize why on earth the object or whatever is undefined, but still, probably this is workable!
Then there are hard errors like object doesn’t support property, Uncaught RangeError, ...is not a function and such! These usually take much more time for me to debug and I definitely need to learn to use debugger in such cases more properly, but about this more in the future!

But then there is hell. And by hell I mean when all the code is loaded, there are no errors in the console, you see what you want to see in the DOM, but... but the functionality isn't working! This is extremely tedious when you know for sure that it was working before.
And this is the type of "bug" that frustrates me the most for now!
When I encounter bugs I usually at the least know where to check, but in cases like this, it is from a to z... So what to do? Dig?

What are your stories with debugging and bugs in general?
Care to share?

P.S. I would like to write an article about my thoughts on design docs next! Would you be interested in reading it?