Skip to content

Useful tips and tricks in Python #

TEMPLATE or Skeleton script with tips and references #

Generate requirements.txt #

  • JCharisTech1
    1
    2
    3
    4
    5
    pip3 install pipreqs
    pipreqs /path/to/project
    # OR
    pipreqs $(pwd)
    # Manually check the requirements.txt also by installing pip3 install -r requirements.txt
    

Update all pip packages #

1
2
python3 -m pip install --upgrade pip
pip3 list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1  | xargs -n1 pip3 install -U

Global Variables #

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Below "import" <insert_package_names>
timeout = None

def imAFunction():
  if i > timeout:
    print("Greater than timeout")

# Inside function. In this example main()
global timeout 
timeout = args.timeout

URL Encode Python String #

1
2
3
4
import urllib.parse
action = urllib.parse.quote_plus("GET_[TO]-THE")
location = urllib.parse.quote_plus("CHOPP@!")
url = "www.domain.com:2323/whatever?action=%s&location=%s" % (action,location)

Accept custom certificate #

  • When using proxy (i.e. Burp), rather than using verify=False in the request.get or request.post, convert the Burp certificate cacert.der instead to cacert.pem then use in on python requests. 2
  • Most common use case is the usage of burp certificate for python requests SSL error.
    1
    2
    3
    # Converting cacert.der to cacert.pem
    # openssl x509 -in cacert.der -inform DER -outform PEM -out cacert.pem
    r = session.post(burp0_url, headers=burp0_headers, data=burp0_data,proxies=proxies,verify="cacert.pem")
    

Last update: October 10, 2021