Skip to content

Instantly share code, notes, and snippets.

@cdunklau
cdunklau / .py
Created March 4, 2020 21:25
Alternative constructors with @classmethod
import requests
class QuotesAPIClient:
def __init__(self, baseurl, session):
self._baseurl = baseurl
self._session = session
@classmethod
def default(cls, api_token):
session = requests.Session()
@cdunklau
cdunklau / composed_lineonlyreceiver.py
Last active February 5, 2020 08:30
A reimplementation of Twisted's LineOnlyReceiver with an explicit parser
import collections
from twisted.internet import protocol
class LineParser(object):
def __init__(self, delimiter, max_length):
self.delimiter = delimiter
self.max_length = max_length
self._buffer = b''
@cdunklau
cdunklau / metaclass-fields.py
Last active June 16, 2017 09:59
Type-checking declarative attributes via metaclass shenanigans
import six
class TypedField(object):
def __init__(self, classinfo):
self._classinfo = classinfo
self.fieldname = None # Set by the metaclass
def __get__(self, instance, owner):
try:
@cdunklau
cdunklau / Procfile
Created March 3, 2017 11:03
A Dynamic DNS service using the GoDaddy API, set up to run on Heroku
web: twistd -n web -p $PORT --class=miscserver.resource
@cdunklau
cdunklau / coroutine_limiter.py
Last active October 19, 2017 23:41
Constrain number of simultanous HTTP requests with asyncio
import asyncio
import itertools
import aiohttp
import async_timeout
async def fetch_with_response_delay(session, delay):
if not 0 <= delay <= 10:
raise ValueError('Delay must be between 0 and 10 inclusive')
@cdunklau
cdunklau / foo.py
Last active January 13, 2017 10:28
SQLite3 Injection demonstration
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE user (user_id INTEGER PRIMARY KEY, name TEXT)')
conn.commit()
cursor = conn.cursor()
for name in ['alice', 'bob', 'carol', 'david']:
cursor.execute('INSERT INTO user (name) VALUES (?)', (name,))
@cdunklau
cdunklau / dicegames.py
Last active February 9, 2017 10:22
Dependancy injection demonstration for making random stuff deterministic
import random
def default_diceroller():
return random.randint(1, 6)
class CrapsGame(object):
_diceroller = default_diceroller
# Original
def process_item(self, item, spider):
try:
with self.conn:
query = 'INSERT INTO articles VALUES (?, ?, ?, ?, ?,(CURRENT_TIMESTAMP))'
try:
args = (item['url'], item['title'], item['intro'], item['body'], item['publication_date'])
except KeyError as kerr:
if kerr.args[0] == 'intro':
args = (item['url'], item['title'], "", item['body'], item['publication_date'])
@cdunklau
cdunklau / reqs.py
Last active September 12, 2015 16:00
Basic url processor
import sys
import itertools
import datetime
from twisted.internet import task, defer
from twisted.python import log
import treq
def main(reactor, urls, chunksize):
def investigate_loop()
i = 0
numbers = []
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers