Skip to content

Instantly share code, notes, and snippets.

@nicolasramy
Last active August 20, 2019 07:00
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nicolasramy/5668610 to your computer and use it in GitHub Desktop.
Save nicolasramy/5668610 to your computer and use it in GitHub Desktop.
My Python Cheat Sheet :- Installation- Functions- Snippets- Misc- Easter Eggs

#Python Cheat Sheet

Introduction

This is a short list of different packages to install to enhace your production in Python

pip

pip is a tool for installing and managing Python packages

apt-get install python-pip python-dev build-essential

Virtualenv

virtualenv is a tool to create isolated Python environments. There is 2 ways to install it:

With apt if you have an Ubuntu or Debian system

apt-get install python-virtualenv

With pip if you want to ignore your system package tool

pip install virutalenv

If you use pip to install globally virtualenv with just add sudo before

Language specification

Null object

None

Increment

i = 1
i += 1

Database

MySQL

To make the libraries available, you have to add this package first:

apt-get install python-mysqldb

CouchDB

Python Cheat Sheet - Functions

String manipulation

Slugify

import re
import unidecode


def slugify(string):
  string = unidecode.unidecode(string).lower()
  return re.sub(r'\W+', '-', string)

Date & Time manipulation

Convert timestamp to datetime object

import datetime

time_to_convert = float(os.path.getmtime("FILE"))
datetime.datetime.fromtimestamp(time_to_convert).strftime("%Y-%m-%d %H:%M:%S")

Python Cheat Sheet - Snippets

File Handling

List a directory

you can use glob

import glob
import os

os.chdir("/mydir")
for files in glob.glob("*.txt"):
    print files

or simple os.listdir

import os

os.chdir("/mydir")
for files in os.listdir("."):
    if files.endswith(".txt"):
        print files

or if you want to traverse directory

import os

for r,d,f in os.walk("/mydir"):
    for files in f:
        if files.endswith(".txt"):
             print os.path.join(r,files)

List manipulation

Sum of a list

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sum(my_list)
>>> 55

Min of a list

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
min(my_list)
>>> 1

Max of a list

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
max(my_list)
>>> 10

Import

Import modules from parent directory

import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import my_module_in_parent_directory

Python Cheat Sheet - Miscellaneous

Code / Syntax

Declare a default encoding

# -*- coding: utf-8 -*-

Declare a default encoding for scripting

#!/usr/bin/env python
# -*- coding: utf-8 -*-

Access to a Class method from a variable which contains this method name

class Test:


    def hello(self):
        print "hello world"

world = "hello"

getattr(Test(), world)()

String

Declare a string on multiple lines

myString = "Hello world, this is \
a string on multiple line"
print myString
>>> Hello world, this is a string on multiple lines
myString = "Hello world, this is \n\
a string on multiple line"
print myString
>>> Hello world, this is 
>>> a string on multiple lines

Pad a string with zeroes

n = 4
print "%03d" % n
>>> 004
# For Python >= 2.6
print "{0:03d}".format(n)
>>> 004
# For Python 3
print("{0:03d}".format(n))
>>> 004
# zfill method
print str(n).zfill(3)
>>> 004

Django

South

Initiate migrations

python manage.py schemamigration app_name --initial

Update migrations

python manage.py schemamigration app_name --auto

Apply migrations

python manage.py migrate app_name

Fix tests coverage due to FK removal

Add this in settings.py

SOUTH_TESTS_MIGRATE = False

SQL Alchemy

ORM

Connection

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from tables import my_db

my_engine = create_engine("...")
MySession = sessionmaker(bind=my_engine)
my_session = MySession()

Filters

# equals
users = my_session.query(my_db.User).filter(my_db.User.active == 1)

# not equals
users = my_session.query(my_db.User).filter(my_db.User.active != 1)

# like
users = my_session.query(my_db.User).filter(my_db.User.email.like("%@gmail.com")

# in
users = my_session.query(my_db.User).filter(my_db.User.role_id.in_([1, 2, 3]))

# not in
users = my_session.query(my_db.User).filter(~my_db.User.role_id.in_([1, 2, 3]))

# is null
users = my_session.query(my_db.User).filter(my_db.User.activated == None)

# is not null
users = my_session.query(my_db.User).filter(my_db.User.activated != None)

Group By

users = my_session.query(my_db.User).group_by(my_db.User.email)

Order By

Ascending

users = my_session.query(my_db.User).order_by(my_db.User.lastname.asc())

Descending

users = my_session.query(my_db.User).order_by(my_db.User.created.desc())

Limit

users = my_session.query(my_db.User).limit(100)

Release resources

When I try to use SQLAlchemy with multiprocessing Pool and MySQL, I got a lot of "1040: Too many connections". To prevent this error

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from tables import my_db

my_engine = create_engine("...")
MySession = sessionmaker(bind=my_engine)
my_session = MySession()

# To close a session
my_session.close()

# To revoke the engine pool
my_engine.dispose()

Python Cheat Sheet - Easter Eggs

Introduction

Python have some easter eggs, to see them, you have to run this command from a Python shell

Usage

Antigravity

import antigravity

This

import this

Future

from __future__ import braces
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment