Skip to content

Instantly share code, notes, and snippets.

View aryaniyaps's full-sized avatar
🎯
Focusing

Aryan Iyappan aryaniyaps

🎯
Focusing
View GitHub Profile
@nymous
nymous / README.md
Last active November 15, 2024 19:24
Logging setup for FastAPI, Uvicorn and Structlog (with Datadog integration)

Logging setup for FastAPI

This logging setup configures Structlog to output pretty logs in development, and JSON log lines in production.

Then, you can use Structlog loggers or standard logging loggers, and they both will be processed by the Structlog pipeline (see the hello() endpoint for reference). That way any log generated by your dependencies will also be processed and enriched, even if they know nothing about Structlog!

Requests are assigned a correlation ID with the asgi-correlation-id middleware (either captured from incoming request or generated on the fly). All logs are linked to the correlation ID, and to the Datadog trace/span if instrumented. This data "global to the request" is stored in context vars, and automatically added to all logs produced during the request thanks to Structlog. You can add to these "global local variables" at any point in an endpoint with `structlog.contextvars.bind_contextvars(custom

@ThirVondukr
ThirVondukr / main.py
Last active March 14, 2022 11:50
Strawberry GraphQL Cursor Pagination
import base64
import enum
from typing import Any, Optional, Annotated
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import InstrumentedAttribute, DeclarativeMeta
from sqlalchemy.sql import Select
from gql.modules.users._fields import UserOrder
@samuelcolvin
samuelcolvin / webauthn_client.js
Created November 17, 2021 22:32
demo of webauthn using FastAPI
const log_el = document.getElementById('log')
function log(...messages) {
console.log(...messages)
log_el.innerText += '\n' + messages.map(m => JSON.stringify(m, null, 2)).join(' ')
}
function error(message) {
console.error(message)
log_el.innerText += '\n' + message
@donaldpipowitch
donaldpipowitch / README.md
Last active February 18, 2024 09:43
Handle server errors in Formik

Whenever the server returns validation errors and we would set them with setFieldError they would be lost if any field would get a change or blur event. But we want to keep these kind of errors until the specific field changes. Additional we want to handle generic server errors (which are not specific to a field, but the whole form).

With these hooks field specific server side errors should be added like this:

const { setStatus } = useFormikContext();

const errors = {};
// adjust serverErrors to your own responses
// in this case they look like this: Array<{ name: string, error: string }>
@ferndot
ferndot / emails.py
Created October 31, 2018 14:26
django-simple-email-confirmation-drf
from django.conf import settings
from templated_mail.mail import BaseEmailMessage
class VerificationEmail(BaseEmailMessage):
template_name = 'email/email_verification.html'
def get_context_data(self):
# Get context and user
@whoisryosuke
whoisryosuke / nextjs-hoc-authorization-ssr.js
Created August 8, 2018 22:34
NextJS - (better) HOC for authenticating pages using JWT token stored in cookies. HOC checks for cookie, if it doesn't exist, user is redirected using res or Router (ideally also query API to verify token). Wrapped in an optional context provider to pass JWT down.
import React, {Component} from 'react'
import Router from 'next/router'
import TokenContext from '../context/TokenContext'
import { getCookie } from '../utils/Cookies'
import ServerRedirect from 'utils/ServerRedirect'
export default function withAuth(AuthComponent) {
return class Authenticated extends Component {
static async getInitialProps(ctx) {
@iMerica
iMerica / urls.py
Last active July 27, 2023 17:20
Email verification in Django Rest Framework, Django All-Auth, Django Rest-Auth. Suitable for Single Page Applications
urlpatterns = [
url(r'^rest-auth/registration/account-confirm-email/(?P<key>[-:\w]+)/$', ConfirmEmailView.as_view(), name='account_confirm_email'),
]
@pgjones
pgjones / test_flask_cookie.py
Created February 12, 2017 16:00
Example of how to use the Flask `test_request_context` with a cookie set
"""
- Add some settings -
Log in to your sandbox account and get your API keys plus your merchant ID.
"""
BRAINTREE_PRODUCTION = False # We'll need this later to switch between the sandbox and live account
BRAINTREE_MERCHANT_ID = “your_merchant_id”
BRAINTREE_PUBLIC_KEY = “your_public_key”
BRAINTREE_PRIVATE_KEY = “your_private_key”
@dmpayton
dmpayton / django-websockets.py
Created December 4, 2014 08:41
Django WebSockets example using Tornado
#!/usr/bin/env python
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.wsgi
from myapp.wsgi import application as myapp_wsgi
# Javascript Usage: