Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Tuesday, July 26, 2011

Randomizing in Django QuerySet and Python List

Django QuerySet:

my_queryset.order_by('?')

Python List:

import random

random.shuffle(my_list)


And then you can use slice to just keep n elements, e.g.
n = 5
my_queryset.order_by('?')[:n]

Friday, June 17, 2011

Python Webserver Checking SSL Certificates

Python Urllib and Urllib2 have warnings that say:
"Warning: When opening HTTPS URLs, it is not attempted to validate the server certificate. Use at your own risk!"



Add SSL-cert-check thing: `pip install backports.ssl_match_hostname` ... because Django/Python's urllib's urlopen does not check the SSL server certificates [warning on urllib documentation](http://docs.python.org/library/urllib.html), thus becoming vulnerable to Man-In-The-Middle attacks. [Solution source](http://stackoverflow.com/questions/1087227/validate-ssl-certificates-with-python/3946778#3946778)
http://wiki.python.org/moin/Twisted-Examples
--> Twisted, PyOpenSSL, Pycrypto
`svn co svn://svn.twistedmatrix.com/svn/Twisted/trunk`
`cd trunk`
`python setup.py install`

`pip install pyopenssl`

`python setup.py install`

Check in python shell: `import twisted, OpenSSL, Crypto`

Sunday, June 12, 2011

Buffer Overflow w/ Perl/Python multiply the same character, repeat character

$ ./program `python -c "print 'a'*300 + 'A'*20"`
Segmentation fault (core dumped)

$ ./program `perl -e "print 'a'x300 . 'A'x20"`
Segmentation fault (core dumped)

Saturday, March 5, 2011

How to Pass a Python Array as an Argument

Copy the array like this before you pass into the method: arrayName[:], if you don't want your array to be changed inside the method/function.

Example. Compare line 9 with line 16:

Result:
no copy:
before: [1, 1, 1, 1]
in change(): [2, 1, 1, 1]
after: [2, 1, 1, 1]

with copy:
before: [1, 1, 1, 1]
in change(): [2, 1, 1, 1]
after: [1, 1, 1, 1]