Phython Programming Cookbook


------- Contents
        1 CSV Reader / Writer Example 1
1.1 The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Reading and writing dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3 Download the Code Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
        2 Decorator Tutorial 7
2.1 Understanding Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Jumping into decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.3 The Practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.4 Download the Code Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
        3 Threading / Concurrency Example 15
3.1 Python _thread module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.2 Python threading module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.1 Extending Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.2 Getting Current Thread Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.2.3 Daemon Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.2.4 Joining Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.2.5 Time Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.2.6 Events: Communication Between Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.2.7 Locking Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.2.8 Limiting Concurrent Access to Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.2.9 Thread-Specific Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
        4 Logging Example 31
4.1 The Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.1 Log Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.2 Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.1.3 Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.2 The Practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.3 Download the Code Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
        5 Django Tutorial 40
5.1 Creating the project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.2 Creating our application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.3 Database Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.4 The Public Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.5 Style Sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.6 Download the Code Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
        6 Dictionary Example 50
6.1 Define . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
6.2 Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
6.3 Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
6.4 Useful operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
6.4.1 In (keyword) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
6.4.2 Len (built-in function) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
6.4.3 keys() and values() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
6.4.4 items() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
6.4.5 update() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
6.4.6 copy() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
6.5 Download the Code Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
        7 Sockets Example 58
7.1 Creating a Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
7.2 Using a Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
7.3 Disconnecting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
7.4 A Little Example Here . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
7.5 Non-blocking Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
7.6 Download the Code Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
        8 Map Example 64
8.1 Map Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
8.2 Python's Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
8.3 Map Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
8.4 Download the Code Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
        9 Subprocess Example 70
9.1 Convenience Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
9.1.1 subprocess.call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
9.1.2 subprocess.check_call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
9.1.3 subprocess.check_output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
9.2 Popen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
9.3 Download the Code Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
10 Send Email Example 75
10.1 The Basics of smtplib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
10.2 SSL and Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
10.3 Sending HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
10.4 Sending Attachments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
10.5 Download the Code Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Copyright (c) Exelixis Media P.C., 2016
All rights reserved. Without limiting the rights under
copyright reserved above, no part of this publication
may be reproduced, stored or introduced into a retrieval system, or
transmitted, in any form or by any means (electronic, mechanical,
photocopying, recording or otherwise), without the prior written
permission of the copyright owner.
------ Preface
Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes
code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in
languages such as C++ or Java. The language provides constructs intended to enable clear programs on both a small and large scale.
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural
styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard
library. (Source: https://en.wikipedia.org/wiki/Python_%28programming_language%29)
In this ebook, we provide a compilation of Python examples that will help you kick-start your own projects. We cover a wide
range of topics, from multi-threaded programming to web development with Django. With our straightforward tutorials, you will
be able to get your own projects up and running in minimum time.
------ About the Author
Sebastian is a full stack programmer, who has strong experience in Java and Scala enterprise web applications.
He is currently studying Computers Science in UBA (University of Buenos Aires) and working a full time job at a .com company
as a Semi-Senior developer, involving architectural design, implementation and monitoring.
He also worked in automating processes (such as data base backups, building, deploying and monitoring applications).
Chapter 1
---- CSV Reader / Writer Example ----
CSV (comma-separated values) is a standard for exporting and importing data across multiple formats, such as MySQL and excel.
It stores numbers and text in plain text. Each row of the file is a data record and every record consists of one or more fields which
values are separated by commas. The use of the comma to separate every record's fields is the source of the name given to this standard.

Even with this very explicit name, there is no official standard CSVs, and it may denote some very similar delimiter-separated
values, which use a variety of field delimiters (such as spaces and tabs, which are both very popular), and are given the .csv
extension anyway. Such lack of strict terminology makes data exchange very difficult some times.
RFC 4180 provides some rules to this format:

• It's plain text
• Consists of records
• Every record consists of fields separated by a single character delimiter
• Every record has the same sequence of fields
But unless there is additional information about the provided file (such as if the rules provided by RFC were followed), data
exchange through this format can be pretty annoying
---- 1.1 The Basics
Python has native support for CSV readers, and it's configurable (which, as we've seen, is necessary). There is a module csv
which holds everything you need to make a CSV reader/writer, and it follows RFC standards (unless your configuration overrides
them), so by default it should read and write valid CSV files. So, let's see how it works:

csv-reader.py
Here, we are importing csv and opening a file called my.csv, then we call csv.reader passing our file as a parameter and then we
print each row in our reader.
If my.csv looks like this:

my.csv
Then, when you run this script, you will see the following output:
And writing is just as simple as reading:
csv-reader.py
Then, in your csv file you'll see:
my.csv
And in your output:
It's pretty easy to see what is going on in here. We are opening a file in write mode, getting our writer from csv giving our file to
it, and writing each row with it. Making it a little smarter:
csv-reader.py
We ask the user how many columns does he want to write for each row and then ask him for a row as long as he wants to continue,
then we print our raw input and write it to a file called raw.csv, then we read it again and print the data. When we run our script,
the output will look like this:

And, of course, our raw.csv looks like this:
raw.csv

Another rule the CSV format has, is the quote character. As you see, every input has a comma, which is our separator character, so
the writer puts them between quoting marks (the default of the standard) to know that commas between them are not separators,
but part of the column instead.
Now, although I would recommend leaving the configuration with its defaults, there are some cases where you need to change
them, as you don't always have control over the csv's your data providers give you. So, I have to teach you how to do it (beware,
great powers come with great responsibilities).
You can configure the delimiter and the quote character through delimiter and quotechar parameters, like this:
csv-reader.py

So, now, having this console output :
Our raw.csv will like like this:

raw.csv
As you see, our new separator is the space character, and our quote character is pipe, which our writer is forced to use always as
the space character is pretty common in almost every text data.
The writer's quoting strategy is also configurable, the values available are:
• csv.QUOTE_ALL: quotes every column, it doesn't matter if they contain a delimiter character or not.
• csv.QUOTE_MINIMAL: quotes only the columns which contains a delimiter character.
• csv.QUOTE_NONNUMERIC: quotes all non numeric columns.
• csv.QUOTE_NONE: quotes nothing. It forces you to check whether or not the user inputs a delimiter character in a column,
if you don't, you will read an unexpected number of columns.
---- 1.2 Reading and writing dictionaries
We've seen a very basic example of how to read and write data from a CSV file, but in real life, we don't want our CSV's to be
so chaotic, we need them to give us information about what meaning has each of the columns.
Also, en real life we don't usually have our data in arrays, we have business models and we need them to be very descriptive. We
usually use dictionaries for this purpose, and python gives us the tools to write and read dictionaries from CSV files.
It looks like this:
We are initializing a variable called dictionaries with an array of test data, then we open a file in write mode, we collect
the keys of our dictionary and get a writer of our file with the headers. The first thing we do is write our headers, and then write
a row for every dictionary in our array.
Then we open the same file in read mode, get a reader of that file and print the array of data. You will see an output like:
And our csv file will look like:

my.csv
Now it looks better. The CSV file has our headers information, and each row has the ordered sequence of our data. Notice that
we give the file names to our writer, as dictionaries in python are not ordered so the writer needs that information to write each
row with the same order.
The same parameters apply for the delimiter and the quote character as the default reader and writer.
So, then again, we make it a little smarter:

csv-reader.py
And now when we run this script, we'll see the output:
And our dict.csv will look like:

csv-reader.py
A little side note: As I said before, dictionaries in python are not ordered, so when you extract the keys from one to write its data
to a CSV file you should order them to have your columns ordered always the same way, as you do not know which technology
will your client use to read them, and, of course, in real life CSV files are incremental, so you are always adding lines to them,
not overriding them. Avoid any trouble making sure your CSV will always look the same.
---- 1.3 Download the Code Project
This was an example on how to read and write data from/to a CSV file.
Download You can download the full source code of this example here: python-csv-reader
Chapter 2
---- Decorator Tutorial ----
Sometimes, we encounter problems that require us to extend the behavior of a function, but we don't want to change its implementation.
Some of those problems could be: logging spent time, caching, validating parameters, etc. All these solutions are
often needed in more than one function: you often need to log the spent time of every http connection; you often need to cache
more than one data base entity; you often need validation in more than one function. Today we will solve these 3 mentioned
problems with Python decorators:

• Spent Time Logging: We'll decorate a couple functions to tell us how much time do they take to execute.
• Caching: We'll add cache to prevent a function from executing when its called several times with the same parameters.
• Validating: We'll validate a function's input to prevent run time errors.
---- 2.1 Understanding Functions
Before we can jump into decorators, we need to understand how functions actually work. In essence, functions are procedures
that return a value based on some given arguments.
In Python, functions are first-class objects. This means that functions can be assigned to a variable:
They can be defined inside another functions:
They can be passed as parameters (higher-order functions):
And they can return other functions (also, higher-order functions):
Another thing to notice, is that inner functions have access to the outer scope, that's why we can use the parameter constant
in the inner function of the last example. Also, this access is read-only, we can not modify variables from the outer scope within
an inner function.
---- 2.2 Jumping into decorators
Python decorators provide a nice and simple syntax to call higher-order functions. By definition, a decorator takes a function as a
parameter, and returns a wrapper of that given function to extend its behavior without actually modifying it. Given this definition
we can write somthing like:
And after execution, the output will look like:
So, what is actually happening here? We are defining a higher-order function called decorator that receives a function as a
parameter and returns a wrapper of that function. The wrapper just prints to the console the name of the called function and the
given parameters before executing the wrapped function. And the wrapped functions just replaces the commas with spaces. Now
we have a decorator written here. But it's kind of annoying to define the decorator, the function and then assigning the wrapper
to another variable to finally be able to use it. Python provides some sugar syntax to make it easier to write and read, and if we
re-write this decorator using it:
We just annotate the function we want to wrap with the decorator function and that's it. That function will be decorated, and the
output will look the same.
Now, debugging this can be a real pain, as the replace_commas_with_spaces function is overridden with the wrapper,
so its __name__, __doc__ and __module__ will also be overridden (as seen in the output). To avoid this behavior we will
use functools.wraps, that prevents a wrapper from overriding its inner function properties.
And now the output will be:
So, now we know how decorators work in python. Let's solve our mentioned problems.
---- 2.3 The Practice
So, we need to implement cache, spent time logging and validations. Let's combine them all by solving a bigger problem:
palindromes. Let's make an algorithm that, given a word, will check if it's a palindrome. If it isn't, it will convert it to
palindrome. palindrome.py
Here, we have a function called is_palindrome, which given an input, returns True if its palindrome, or False otherwise.
Then, there is a function called convert_to_palindrome which, given an input, will add just as many characters (reversed,
from the beginning) as necessary to make it palindrome. Also, there is a while that reads the user input until he inputs "exit".
The output looks like:

Untuk lebih lengkapnya bisa download file PDF dibawah ini :

Baca juga artikel dibawah ini :