dominik.wronski@gmail.com





Agenda



          #1 Python


          #2 O co chodzi w webdevelopmencie (MVC, etc..)

          #3 Django

                 

   


                 Pythonjęzyk programowania,

                                        interpeteowany,

                                        obiektowy,

                                        ogólnego przeznaczenia,

                                        z intuicyjną składnią



                                            
                     1989 - v. 1
 rekomendowana v. 2.7
                     aktualna  v. 3.4


CPython,
Cython,
Jython,
PyPy,
IronPython,

Syntax


#!bin/env/python

print "Hello World!"

Indentation / Wciecia


if (foo)
if (bar)
something(foo, bar);
else
somethingElse(); 



if (foo) {
if (bar) {
something(foo, bar);
}
else {
somethingElse(); }} 



if (foo):
    if (bar):
        something(foo, bar);
    else:
        somethingElse(); 

Function

def fib(n): 
if n == 0:
return 0
 elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)


def fib(n): 
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a


CLASS

class Shape:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    description = "This shape has not been described yet"
    author = "Nobody has claimed to make this shape yet"

 def area(self): return self.x * self.y

 def perimeter(self): return 2 * self.x + 2 * self.y

 def describe(self,text): self.description = text

    def authorName(self,text):
        self.author = text

class Employee(object):
    """Models real-life employees!"""
    def __init__(self, employee_name):
        self.employee_name = employee_name
   
    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 20.00

class PartTimeEmployee(Employee): def calculate_wage(self, hours): self.hour = hours return hours * 12.00 def full_time_wage(self, hours): return super(PartTimeEmployee, self).calculate_wage()



Error Handling

def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print "division by zero!"
    else:
        print "result is", result
    finally:
        print "executing finally clause" 

import sys 
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except: print "Unexpected error:", sys.exc_info()[0]
 raise

Decorator


def logger(func):
 def inner(*args, **kwargs): print "Arguments were: %s, %s" % (args, kwargs) return func(*args, **kwargs) return inner

@logger def foo1(x, y=1): return x * y >>>foo1(5,4)
Arguments were: (5, 4), {} 20

understanding-python-decorators - link

Code Snippets

#!/usr/bin/env python

# Import the modules import bitlyapi import sys
# Define your API information API_USER = "your_api_username" API_KEY = "your_api_key" b = bitlyapi.BitLy(API_USER, API_KEY)
# Define how to use the program usage = """Usage: python shortener.py [url] e.g python shortener.py http://www.google.com"""
if len(sys.argv) != 2:
    print usage
    sys.exit(0)
longurl = sys.argv[1]
 
response = b.shorten(longUrl=longurl)
 
print response['url'] 

import re
import sys
import urllib2
import BeautifulSoup
 
usage = "Run the script: ./geolocate.py IPAddress"
 
if len(sys.argv)!=2:
    print(usage)
    sys.exit(0)
 
if len(sys.argv) > 1:
    ipaddr = sys.argv[1]
geody = "http://www.geody.com/geoip.php?ip=" + ipaddr
html_page = urllib2.urlopen(geody).read()
soup = BeautifulSoup.BeautifulSoup(html_page)
 
# Filter paragraph containing geolocation info.
paragraph = soup('p')[3]
 
# Remove html tags using regex.
geo_txt = re.sub(r'<.*?>', '', str(paragraph))
print geo_txt[32:].strip() 

import smtplib
  
def sendemail(from_addr, to_addr_list, cc_addr_list,
              subject, message,
              login, password,
              smtpserver='smtp.gmail.com:587'):
    header  = 'From: %s\n' % from_addr
    header += 'To: %s\n' % ','.join(to_addr_list)
    header += 'Cc: %s\n' % ','.join(cc_addr_list)
    header += 'Subject: %s\n\n' % subject
    message = header + message
  
    server = smtplib.SMTP(smtpserver)
    server.starttls()
    server.login(login,password)
    problems = server.sendmail(from_addr, to_addr_list, message)
    server.quit() 



import urllib2
import re
 
#connect to a URL
website = urllib2.urlopen(url)
 
#read html code
html = website.read()
 
#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', html)
 
print links 

CO dalej...

http://www.python.org/

http://learnpythonthehardway.org

http://projecteuler.net/

http://code.activestate.com/recipes/langs/python/

http://codeacademy.com/


http://freepythontips.wordpress.com/2013/09/01/best-python-resources/


https://MODUL_KTRÓRY_NAS_INTERESUJE.readthedocs.org/


Dlaczego tak ? - link 

Django

config.vm.network "forwarded_port", guest: 8000, host: 8888

vagrant up

vagrant ssh

cd /vagrant

touch foo




sublime text


sudo apt-get install python-pip


sudo pip install Django==1.7.4

   python -c "import django; print(django.get_version())"
   django-admin.py startproject mysite

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py


  cd mysite/

  python manage.py migrate

  python manage.py runserver 0.0.0.0:8000 


http://127.0.0.1:8888/

Title


WiT - Ep1 - Python Introduction

By Dominik Wronski

WiT - Ep1 - Python Introduction

  • 3,029