Skip to content

Instantly share code, notes, and snippets.

View akhenakh's full-sized avatar
🏠
Working from home

Fabrice Aneche akhenakh

🏠
Working from home
View GitHub Profile
@akhenakh
akhenakh / gist:2894704
Created June 8, 2012 09:31
async callback from threads with Tornado
import functools
import time
import threading
import logging
import Queue
import hunspell
import tornado.web
import tornado.websocket
import tornado.locale
@akhenakh
akhenakh / tools.py
Created June 19, 2012 14:47
flask jsonify with support for MongoDB from tools import jsonify
try:
import simplejson as json
except ImportError:
try:
import json
except ImportError:
raise ImportError
import datetime
from bson.objectid import ObjectId
from werkzeug import Response
@akhenakh
akhenakh / slow_server.py
Created June 26, 2012 13:00
An async slow testing server
# pip install tornado then just launch it with python slow_server.py --port=8080
# then call http://localhost:8080/wait/600 for a 600ms request
# Fabrice Aneche https://gist.github.com/2995678
import tornado.web
import tornado.httpserver
import time
import logging
from tornado.options import define, options
@akhenakh
akhenakh / gevent_ses.py
Created June 26, 2012 15:06
Async amazon ses with gevent and pool
# 2012 Fabrice Aneche. https://gist.github.com/2996326
# Gevent rewrite with requests
#
# Copyright 2011 The greplin-tornado-ses Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
@akhenakh
akhenakh / gist:3376839
Created August 17, 2012 07:57
negative float for flask
from werkzeug.routing import NumberConverter, ValidationError
class NegativeFloatConverter(NumberConverter):
regex = r'\-?\d+\.\d+'
num_convert = float
def __init__(self, map, min=None, max=None):
NumberConverter.__init__(self, map, 0, min, max)
app.url_map.converters['float'] = NegativeFloatConverter
@akhenakh
akhenakh / gist:3619525
Created September 4, 2012 10:13
Flask method view logging handler decorator
import traceback
import datetime
import socket
import os
import resource
...
def log_exception(view_func):
""" log exception decorator for a view,
"""
@akhenakh
akhenakh / gist:4623208
Created January 24, 2013 15:34
convert date json entries to datetime objet while loading with json.loads (usefull to import data from Django datadump)
import json
import datetime
import re
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
def datetime_parser(entry):
for k, v in entry.items():
if isinstance(v, basestring) and re.search("^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$", v):
try:
entry[k] = datetime.datetime.strptime(v, DATE_FORMAT)
@akhenakh
akhenakh / gist:4987562
Last active December 13, 2015 22:49
Remove keys from a list of dicts
# list comprehension + dict comprehension should be memory efficient and can remove multiple keys
# but code is ugly
clean_list = [
{k: v
for k, v in dict_to_clean.iteritems()
if k not in ['tid', 'aid']}
for dict_to_clean in my_list]
# lambda can remove only one key and I hate lambdas
map(lambda d: d.pop('tid'), my_list)
@akhenakh
akhenakh / gist:5397538
Last active December 16, 2015 07:19
Simple Bool field for WTForms, True for "set" False for "unset"
class RepeatForm(Form):
action = TextField('Action', validators=[Required()])
def validate_action(form, field):
if field.data == "set":
field.data = True
elif field.data == "unset":
field.data = False
else:
raise ValidationError("Invalid: should be set or unset.")
@akhenakh
akhenakh / gist:5818109
Last active December 18, 2015 17:19
Learning Golang from a Pythonista if "foo" in alist:
// lookup for the users table create it otherwise
// var tables []string and StringSlice are equivalent
var tables sort.StringSlice
err = r.TableList().Run(session).All(&tables)
if err != nil {
log.Panic(err)
}
// I miss python if "users" in tables
exists := false