python master class part 1

71
Python Master Class Part 1 By Chathuranga Bandara www.chathuranga.com

Upload: chathuranga-bandara

Post on 09-Feb-2017

105 views

Category:

Software


0 download

TRANSCRIPT

Python Master ClassPart 1

By Chathuranga Bandarawww.chathuranga.com

Today’s Agenda

Introduction to Python

Introduction to Flask

Python

What is Python… really..

Multi Purpose

Object Oriented

Interpreted?

Dynamically Typed and Strong as well

Readability and We are Adults!

Features

Cross Platform

Functional Support as well

Everything is an Object

Many Implementations

Batteries Included

Who Uses Python?

Why Python?

Versions

v2.7.X

v3.X

Some Tax…. i mean Syntax..

Indentation is the Key!

Types?

Not Strongly TypedWhat the f*** that means?

Let’s Discuss Python Memory Management.

What is a C type Variable?

Variable location value

a 0x3FS 101

b 0x3F9 101

unique location These values live in a fixed size bracket hence can only hold same sized data or an overflow happens

When we change one value

Variable location value

a 0x3FS 110

b 0x3F9 101

Data in the memory location get overwritten

Python has Names not Variables

names

references

objects

Name is just a label for an objectIn Python you can have multiple names for a single object

What is a reference?Name or a container pointing to an object

ie:

110

x = 110

x

+1 reference count

110

x = 110y = 110

x

+2 reference count

y

Not sure?

also,

z = [110, 110]

110

x yReference count: 4

Decrease Ref count?

110

x

reference count: 1

y

del will not delete the object but rather delete the reference to the object.

What happens when the ref count is 0?Then it will delete the object. (what the garbage collector does in python)

Different types of objects then?● Numbers● Strings

● dict● list● classes

Because of names

Functions also can have names

Strings

Numbers

None is the new null

Lists

List Comprehension

Dictionaries

Mutable vs Immutable Mutable : can alter

● list, dict, byte array, set

Immutable: otherwise

● Numbers, string, tuples, frozen sets

ie:

Is extremely inefficient

Much efficient

Control Flows - Conditionals

Loops

Functions

CLASSES

What is PIP?pip is the Python package index

$ sudo apt-get install python-pip

Virtual Environment?

$ pip install virtualenv$ cd my_project_folder$ virtualenv name_of_the_virt$ source name_of_the_virt/bin/activate

$ do pip sh*t

$ deactivate

Good practice!Have a folder in root called requirements and inside that have following:

● dev.txt● Prod.txt

Ie: dev.txt

$ pip install -r requirements/dev.txt

pip install Flask

# Import Flask libraryfrom flask import Flask # Initialize the app from Flaskapp = Flask(__name__) # Define a route to hello_world [email protected]('/hello')def hello_world(): return 'Hello World Again!' # Run the app on http://localhost:8085app.run(debug=True,port=8085)

python hello.py

Routing

@app.route('/')

def index():

return 'Index

Page'

@app.route('/hello')

def hello():

return 'Hello, World'

Variables?

@app.route('/user/<username>')

def show_user_profile(username):

# show the user profile for that user

return 'User %s' % username

@app.route('/post/<int:post_id>')

def show_post(post_id):

# show the post with the given id, the id is an integer

return 'Post %d' % post_id

That is sweet, what about the REST?

from flask import request

@app.route('/login', methods=['GET', 'POST'])

def login():

if request.method == 'POST':

do_the_login()

else:

show_the_login_form()

Rendering Templates

from flask import render_template

@app.route('/hello/')

@app.route('/hello/<name>')

def hello(name=None):

return render_template('hello.html', name=name)

Where the f**k is the template then?

<!doctype html>

<title>Hello from Flask</title>

{% if name %}

<h1>Hello {{ name }}!</h1>

{% else %}

<h1>Hello, World!</h1>

{% endif %}

Request Object

from flask import request

@app.route('/login', methods=['POST', 'GET'])

def login():

error = None

if request.method == 'POST':

if valid_login(request.form['username'],

request.form['password']):

return log_the_user_in(request.form['username'])

else:

error = 'Invalid username/password'

# the code below is executed if the request method

# was GET or the credentials were invalid

return render_template('login.html', error=error)

sessions

from flask import Flask, session, redirect, url_for, escape, request

app = Flask(__name__)

@app.route('/')

def index():

if 'username' in session:

return 'Logged in as %s' % escape(session['username'])

return 'You are not logged in'

@app.route('/login', methods=['GET', 'POST'])

def login():

if request.method == 'POST':

session['username'] = request.form['username']

return redirect(url_for('index'))

return ''' <form action="" method="post">

<p><input type=text name=username>

<p><input type=submit value=Login>

</form>

'''

@app.route('/logout')

def logout():

# remove the username from the session if it's there

session.pop('username', None)

return redirect(url_for('index'))

# set the secret key. keep this really secret:

app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

That’s all for today Folks!