Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Things that make me happy

Things that make me happy

Python + Django y mucho más!

Jorge Bastida

April 01, 2012
Tweet

More Decks by Jorge Bastida

Other Decks in Technology

Transcript

  1. JJJ'.$8%5/'/0.& K06'O63'%P'GQ/0%3L'2Q'K.$'G6/65& R6)1#P1"'.&'26S65'/0)3'1-"Q+ ?T8".4./'.&'26S65'/0)3'.$8".4./+ U.$8"6'.&'26S65'/0)3'4%$8"6T+ V%$8"6T'.&'26S65'/0)3'4%$8".4)/69+ M")/'.&'26S65'/0)3'36&/69+ U8)5&6'.&'26S65'/0)3'963&6+ W6)9)2."./Q'4%13/&+ U864.)"'4)&6&')563X/'&864.)"'63%1-0'/%'256)C'/06'51"6&+

    Y"/0%1-0'85)4#4)"./Q'26)/&'815./Q+ ?55%5&'&0%1"9'36H65'8)&&'&."63/"Q+ Z3"6&&'6T8".4./"Q'&."63469+ [3'/06'P)46'%P')$2.-1./QL'56P1&6'/06'/6$8/)#%3'/%'-16&&+ K0656'&0%1"9'26'%36\\')39'856P65)2"Q'%3"Q'%36'\\%2H.%1&'])Q'/%'9%'./+ Y"/0%1-0'/0)/'])Q'$)Q'3%/'26'%2H.%1&')/'^5&/'13"6&&'Q%1X56'I1/40+ _%]'.&'26S65'/0)3'36H65+ Y"/0%1-0'36H65'.&'%`63'26S65'/0)3'a5.-0/a'3%]+ [P'/06'.$8"6$63/)#%3'.&'0)59'/%'6T8").3L'./X&')'2)9'.96)+ [P'/06'.$8"6$63/)#%3'.&'6)&Q'/%'6T8").3L'./'$)Q'26')'-%%9'.96)+ _)$6&8)46&')56'%36'0%3C.3-'-56)/'.96)'\\'"6/X&'9%'$%56'%P'/0%&6b
  2. class Human(object): def __init__(self, name, sex): self.name = name self.sex

    = sex def say(self, message): print "{0}: {1}".format(self.name, message) 4")&6&+
  3. >>> def gt0(num): ... return num > 0 ^"/65+ >>>

    filter(gt0, [1, -5, 3, -7]) [1, 3]
  4. >>> a = [1,2,3] >>> b = [4,5,6] >>> zip(a,b)

    [(1, 4), (2, 5), (3, 6)] q.8+
  5. >>> nums[0] >>> nums = range(5) >>> nums [0, 1,

    2, 3, 4] >>> nums[::-2] >>> nums[:2] >>> nums[2:] >>> nums[:-1] >>> nums[-1:] >>> nums[::2] >>> nums[::-1] 0 [2, 3, 4] [0, 1] [0, 1, 2, 3] [4] [0, 2, 4] [4, 3, 2, 1, 0] [4, 2, 0]
  6. >>> [i for i in range(5)] [0, 1, 2, 3,

    4] ".&/'4%$856063&.%3&+
  7. >>> [i for i in range(5) if i > 2]

    [3, 4] ".&/'4%$856063&.%3&+
  8. >>> [i**2 for i in range(10) if i % 2]

    [1, 9, 25, 49, 81] ".&/'4%$856063&.%3&+
  9. #include <iostream> int main () { int a = 10;

    int b = 10; std::cout << &a << " " << &b; } $ ./app 0x7fff5fbff4cc 0x7fff5fbff4c4
  10. >>> a = 10 >>> b = 10 >>> print

    id(a), id(b) 4300032496 4300032496
  11. >>> a = 10 >>> b = 10 a b

    10 >>> c = b c >>> b = 5 5
  12. >>> a = [1] >>> b = a a b

    >>> b.append(2) [1] [1,2]
  13. >>> a = "Hello" >>> a[0] = "B" Traceback (most

    recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment
  14. >>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__',

    '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] d.+G&-+D6.#-m
  15. >>> a = "10" >>> [[m, getattr(a, m)()] for m

    in dir(a) if m.startswith("is")] [['isalnum', True], ['isalpha', False], ['isdigit', True], ['islower', False], ['isspace', False], ['istitle', False], ['isupper', False]]
  16. >>> def foo(arg1, arg2="hello"): ... a = arg1 ... b

    = arg2 ... c = arg1 + arg2 ... return 2000 ... >>> foo.func_defaults ('hello',) >>> foo.func_code.co_consts (None, 2000) >>> foo.func_code.co_varnames ('arg1', 'arg2', 'a', 'b', 'c') >>> foo.func_code <code object foo at 0x1004c0cd8, file "<stdin>", line 1>
  17. >>> import dis >>> def sumar(a, b): ... return a

    + b ... >>> dis.dis(sumar) 2 0 LOAD_FAST 0 (a) 3 LOAD_FAST 1 (b) 6 BINARY_ADD 7 RETURN_VALUE
  18. >>> def llenar(lista): ... for i in range(10): ... lista.append(i)

    >>> dis.dis(llenar) 2 0 SETUP_LOOP 33 (to 36) 3 LOAD_GLOBAL 0 (range) 6 LOAD_CONST 1 (10) 9 CALL_FUNCTION 1 12 GET_ITER >> 13 FOR_ITER 19 (to 35) 16 STORE_FAST 1 (i) 3 19 LOAD_FAST 0 (lista) 22 LOAD_ATTR 1 (append) 25 LOAD_FAST 1 (i) 28 CALL_FUNCTION 1 31 POP_TOP 32 JUMP_ABSOLUTE 13 >> 35 POP_BLOCK >> 36 LOAD_CONST 0 (None) 39 RETURN_VALUE B'.3&/5144.%36&
  19. >>> def llenar2(lista): ... op = lista.append ... for i

    in range(10): ... op(i) >>> dis.dis(llenar2) 2 0 LOAD_FAST 0 (lista) 3 LOAD_ATTR 0 (append) 6 STORE_FAST 1 (op) 3 9 SETUP_LOOP 30 (to 42) 12 LOAD_GLOBAL 1 (range) 15 LOAD_CONST 1 (10) 18 CALL_FUNCTION 1 21 GET_ITER >> 22 FOR_ITER 16 (to 41) 25 STORE_FAST 2 (i) 4 28 LOAD_FAST 1 (op) 31 LOAD_FAST 2 (i) 34 CALL_FUNCTION 1 37 POP_TOP 38 JUMP_ABSOLUTE 22 >> 41 POP_BLOCK >> 42 LOAD_CONST 0 (None) 45 RETURN_VALUE t'.3&/5144.%36&
  20. >>> import timeit >>> t = timeit.Timer("llenar([])", """def llenar(lista): ...

    for i in range(10): ... lista.append(i)""") >>> print t.timeit(number=10000000) 24.431292057 >>> t = timeit.Timer("llenar2([])", """def llenar2(lista): ... op = lista.append ... for i in range(10): ... op(i)""") >>> print t.timeit(number=10000000) 20.4608399868
  21. P-6D. E"7A%&" ?Ww ??X fV ;w y+B&@DG60-+D-+@-(9*#-+0*D+9(%"*@#% M.4065%&'Q'V)586/)& 42-&)% W

    ? H6@$*(%. g-(9*#-. u?&'I=)3-%'/)3'&.$8"6'Q'Pk4."'96'1&)5v
  22. p.6]& H.6]&+8Q from django.shortcuts import render, redirect def vista(request): if

    request.method == 'POST': ... return render(request, 'list.html')
  23. V")&&p.6]& H.6]&+8Q from django.views.generic import TemplateView class Vista(TemplateView): template_name =

    "template.html" def get(self, request): return self.render_to_response({...}) def post(self, request): ...
  24. :%96"& $%96"&+8Q from django.db import models class Book(models.Model): name =

    models.CharField(max_length=100) created = models.DateTimeField() available = models.BooleanField(default=True)
  25. :%96"& $%96"&+8Q ! ,%%D*-&H6*D0 ! B&#*)*(H6*D0 ! g$-(H6*D0 ! 4-#*H6*D0

    ! 4-#*567*H6*D0 ! 4*@67-DH6*D0 ! d7-6DH6*D0 ! H6D*H6*D0 ! HD%-#H6*D0 ! B7-)*H6*D0+ ! B!C0(*..H6*D0 ! EDG)H6*D0 ! 5*F#H6*D0 ! 567*H6*D0 ! tPLH6*D0 ! H%(*6&){*" ! J-&"5%J-&"H6*D0 ! O&*5%O&*H6*D0
  26. BEGIN; CREATE TABLE "website_books" ( "id" integer NOT NULL PRIMARY

    KEY, "name" varchar(100) NOT NULL, "created" datetime NOT NULL, "available" bool NOT NULL ); COMMIT; BEGIN; CREATE TABLE "website_books" ( "id" serial NOT NULL PRIMARY KEY, "name" varchar(100) NOT NULL, "created" timestamp with time zone NOT NULL, "available" boolean NOT NULL ); COMMIT;
  27. :%96"&sp.6]& :)C.3-'<165.6& from django.shortcuts import render from app.models import Book

    def vista(request): books = Book.objects.all().order_by('name') return render(request, 'list.html', {'books': books})
  28. from django.db.models import Q Book.objects.filter(Q(name__startswith='What') | Q(name__icontains='dog') wdf from django.db.models

    import Q Book.objects.filter(Q(name__startswith='What') | ~Q(name__icontains='dog') %5'3%/+++
  29. {36K%{36M.6"9 W6")/69'%2=64/& pgM7%+G.-7%.+D-+(*D-@6M&+0*.0*+D-.+6&.#-&@6-.r ? ? class Coche(models.Model): motor = OneToOneField(Motor)

    class Motor(models.Model): ... >>> c.motor <Motor: Motor object> >>> m.coche <Coche: Coche object> [(-@6-.+-+&%.%#(%. [(-@6-.+-+I=)3-%
  30. M%56.-3|6QM.6"9 W6")/69'%2=64/& >>> p.blog <Blog: Blog object> >>> b.post_set.all() [<Post:

    Post object>, ...] pgM7%+G.-7%.+D-+(*D-@6M&+0*.0*+D-.+6&.#-&@6-.r [(-@6-.+-+&%.%#(%. [(-@6-.+-+I=)3-% ? & class Blog(models.Model): ... class Post(models.Model): blog = ForeignKeyField(Blog)
  31. :)3QK%:)3QM.6"9 W6")/69'%2=64/& pgM7%+G.-7%.+D-+(*D-@6M&+0*.0*+D-.+6&.#-&@6-.r & 7 class Post(models.Model): tags = ManyToManyField(Tag)

    class Tag(models.Model): ... >>> p.tags.add(t1, t2) >>> p.tags.all() [<Tag: Tag object>, ...] >>> t.post_set.add(p1, p2) >>> t.post_set.all() [<Post: Post object>, ...] [(-@6-.+-+&%.%#(%. [(-@6-.+-+I=)3-%
  32. K6$8")/6& P%5 ... <ul> {% for book in books %}

    <li>{{ book.name }}</li> {% endfor %} </ul> ... {'books': [book1, book2, book3]...}
  33. K6$8")/6& P%5 ... <ul> <li>El señor de los anillos</li> <li>Los

    Pilares de la tierra</li> <li>Harry Potter</li> </ul> ...
  34. K6$8")/6& .P'>'6"&6 {% if username == "Juan" %} Hola Juan,

    me gustas! {% else %} Hola {{ username }}! {% endif %}
  35. K6$8")/6& ^"/65& {{ username|length }} "63-/0 12 {{ username|cut }}

    41/ Juanesmajo {{ username|slugify }} &"1-.PQ juan-es-majo {{ username|upper }} 18865 JUAN ES MAJO {{ username|wordcount }} ]%594%13/ 3 {'username': 'Juan es majo'} {{ username|default:”Desconocido” }} 96P)1"/ Desconocido {'username': None }
  36. K6$8")/6& ^"/65& {'username': 'Juan es <b>majo, guapo y <em>listo</em></b>'} {{

    username|striptags }} &/5.8/)-& Juan es majo guapo y listo {{ username|truncatewords_html:4 }} /5134)/6]%59&h0/$" Juan es <b>majo guapo</b> ... {{ username|removetags:”em a br” }} 56$%H6/)-& Juan es <b>majo guapo y listo</b>
  37. K6$8")/6& ^"/65& {'value': 123456789} {{ value|add:”1” }} )99 123456790 {{

    value|filesizeformat }} ^"6&.q6P%5$)/ 117.7MB {{ date|timesince }} #$6&.346 4 days, 6 hours {{ date|timeuntil }} #$613#" 1 days, 6 hours {{ date|date:”d M Y” }} 9)/6 11 Sep 2010 {'date': datetime.datetime(2010, 9, 11, 17, 1, 59, 385323) }
  38. K6$8")/6& 065634.) 3-.*:$#7D $62-:$#7D <html> <head> <title>Mi página personal</title> </head>

    <body> {% block content %} Contenido por defecto. {% endblock %} </body> </html> {% extends "base.html" %} {% block content %} Hola desde la portada. {% endblock %}
  39. )88& &%1/0 $k9ee.%G#$:-*(-@%0*:%()e $ python manage.py schemamigration website --initial 456)5'85.$65'&406$)

    $ python manage.py schemamigration website --auto 456)5'e\a'$.-5)4.r3 $ python manage.py migrate )8".4)5'$.-5)4.%36&
  40. )88& 46"65Q from celery.decorators import task @task def add(x, y):

    return x + y >>> result = add.delay(4, 4) >>> result.wait() # wait for and return the result 8
  41. ?=6$8"% from django.utils import simplejson from dajaxice.decorators import dajaxice_register @dajaxice_register

    def my_example(request): return simplejson.dumps({'message':'Hello World'}) Si. es una funcion que retorna json.
  42. ?=6$8"% from dajax.core.Dajax import Dajax def assign_test(request): dajax = Dajax()

    dajax.assign('#list li','innerHTML','Hello!') dajax.add_css_class('#list li','new') ... return dajax.json() tus acciones
  43. -13.4%53 I=)3-% 3-.3T'~gA ]62@ -13.4%53 I=)3-% 3-.3T'~gA ]62e -13.4%53 I=)3-%

    3-.3T'~gA ]623 3-.3T'~gA'~BBt H)53.&0 0)85%TQ P5%3/639@ 3-.3T'~gA'~BBt H)53.&0 0)85%TQ P5%3/639e .8P)."%H65 I68"%Q 3%'/)3'&634.""%
  44. env.user = "example" env.hosts = ["web1.com", "web2.com", "..."] def deploy():

    run('git pull /home/site/') sudo('service supervisord restart')