<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:series="http://organizeseries.com/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>Python Central</title> <link>http://pythoncentral.org</link> <description>Python Programming Examples, Tutorials and Recipes</description> <lastBuildDate>Thu, 16 May 2013 13:50:06 +0000</lastBuildDate> <language>en-US</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=365</generator> <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/PythonCentral" /><feedburner:info uri="pythoncentral" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/2.0/</creativeCommons:license><image><link>http://creativecommons.org/licenses/by-nc-sa/2.0/</link><url>http://creativecommons.org/images/public/somerights20.gif</url><title>Some Rights Reserved</title></image><feedburner:emailServiceId>PythonCentral</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item><title>Hashing Files with Python</title><link>http://feedproxy.google.com/~r/PythonCentral/~3/0F-dMqncJjg/</link> <comments>http://pythoncentral.org/hashing-files-with-python/#comments</comments> <pubDate>Thu, 16 May 2013 13:50:06 +0000</pubDate> <dc:creator>Andres Torres</dc:creator> <category><![CDATA[How Tos]]></category> <category><![CDATA[hashlib]]></category> <category><![CDATA[hashlib.md5]]></category> <category><![CDATA[hashlib.md5.hexdigest]]></category> <category><![CDATA[hashlib.sha1]]></category><guid isPermaLink="false">http://pythoncentral.org/?p=2893</guid> <description><![CDATA[<p>Remember that a hash is a function that takes a variable length sequence of bytes and converts it to a fixed length sequence. Calculating a hash for a file is always useful when you need to check if two files are identical, or to make sure that the contents of a file were not changed, [...]</p><p>The post <a href="http://pythoncentral.org/hashing-files-with-python/">Hashing Files with Python</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p>]]></description> <content:encoded><![CDATA[<p>Remember that a hash is a function that takes a variable length sequence of bytes and converts it to a fixed length sequence. Calculating a hash for a file is always useful when you need to check if two files are identical, or to make sure that the contents of a file were not changed, and to check the integrity of a file when it is transmitted over a network. Sometimes when you download a file on a website, the website will provide the MD5 or SHA checksum, and this is helpful because you can verify if the file downloaded well.</p><h2>Hashing Algorithms</h2><p>The most used algorithms to hash a file are MD5 and SHA-1. They are used because they are fast and they provide a good way to identify different files. The hash function only uses the contents of the file, not the name. Getting the same hash of two separating files means that there is a high probability the contents of the files are identical, even though they have different names.</p><h2>MD5 File Hash in Python</h2><p>The code is made to work with Python 2.7 and higher (including Python 3.x).</p><pre class="brush: python; title: ; notranslate">
import hashlib

hasher = hashlib.md5()
with open('myfile.jpg', 'rb') as afile:
    buf = afile.read()
    hasher.update(buf)
    afile.close()
print(hasher.hexdigest())
</pre><p>The code above calculates the MD5 digest of the file. The file is opened in <code>rb</code> mode, which means that you are going to read the file in binary mode. This is because the MD5 function needs to read the file as a sequence of bytes. This will make sure that you can hash any type of file, not only text files.</p><p>It is important to notice the <code>read</code> function. When it is called with no arguments, like in this case, it will read all the contents of the file and load them into memory. This is dangerous if you are not sure of the file&#8217;s size. A better version will be:</p><h2>MD5 Hash for Large Files in Python</h2><pre class="brush: python; title: ; notranslate">
import hashlib
BLOCKSIZE = 65536
hasher = hashlib.md5()
with open('anotherfile.txt', 'rb') as afile:
    buf = afile.read(BLOCKSIZE)
    while len(buf) &gt; 0:
        hasher.update(buf)
        buf = afile.read(BLOCKSIZE)
print(hasher.hexdigest())
</pre><p>If you need to use another algorithm just change the <code>md5</code> call to another supported function, e.g. SHA1:</p><h2>SHA1 File Hash in Python</h2><pre class="brush: python; title: ; notranslate">
import hashlib
BLOCKSIZE = 65536
hasher = hashlib.sha1()
with open('anotherfile.txt', 'rb') as afile:
    buf = afile.read(BLOCKSIZE)
    while len(buf) &gt; 0:
        hasher.update(buf)
        buf = afile.read(BLOCKSIZE)
print(hasher.hexdigest())
</pre><p>If you need a list of supported hash algorithms in your system use <code>hashlib.algorithms_available</code>. (Only works in Python 3.2 and superior). Finally, for another look into hashing, be sure to checkout the <a href="http://pythoncentral.org/hashing-strings-with-python/" title="Hashing Strings with Python">hashing Python strings</a> article.</p><p>The post <a href="http://pythoncentral.org/hashing-files-with-python/">Hashing Files with Python</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/PythonCentral?a=0F-dMqncJjg:gr7ZAs3rcKc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=0F-dMqncJjg:gr7ZAs3rcKc:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=0F-dMqncJjg:gr7ZAs3rcKc:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/PythonCentral?i=0F-dMqncJjg:gr7ZAs3rcKc:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/0F-dMqncJjg" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pythoncentral.org/hashing-files-with-python/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://pythoncentral.org/hashing-files-with-python/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=hashing-files-with-python</feedburner:origLink></item> <item><title>Hashing Strings with Python</title><link>http://feedproxy.google.com/~r/PythonCentral/~3/ssM-gTPYKQk/</link> <comments>http://pythoncentral.org/hashing-strings-with-python/#comments</comments> <pubDate>Tue, 07 May 2013 16:30:00 +0000</pubDate> <dc:creator>Andres Torres</dc:creator> <category><![CDATA[How Tos]]></category> <category><![CDATA[digest]]></category> <category><![CDATA[hashlib]]></category> <category><![CDATA[hashlib.md5]]></category> <category><![CDATA[hashlib.md5.hexdigest]]></category> <category><![CDATA[hashlib.sha1]]></category> <category><![CDATA[hashlib.sha512]]></category> <category><![CDATA[md5]]></category> <category><![CDATA[sha1]]></category> <category><![CDATA[sha224]]></category> <category><![CDATA[sha256]]></category> <category><![CDATA[sha384]]></category> <category><![CDATA[sha512]]></category><guid isPermaLink="false">http://pythoncentral.org/?p=2891</guid> <description><![CDATA[<p>A hash function is a function that takes input of a variable length sequence of bytes and converts it to a fixed length sequence. It is a one way function. This means if f is the hashing function, calculating f(x) is pretty fast and simple, but trying to obtain x again will take years. The value returned [...]</p><p>The post <a href="http://pythoncentral.org/hashing-strings-with-python/">Hashing Strings with Python</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p>]]></description> <content:encoded><![CDATA[<p>A hash function is a function that takes input of a variable length sequence of bytes and converts it to a fixed length sequence. It is a one way function. This means if <em>f</em> is the hashing function, calculating <em>f(x)</em> is pretty fast and simple, but trying to obtain <em>x</em> again will take years. The value returned by a hash function is often called a hash, message digest, hash value, or checksum. Most of the time a hash function will produce unique output for a given input. However depending on the algorithm, there is a possibility to find a collision due to the mathematical theory behind these functions.</p><p><img class="size-medium wp-image-2951 aligncenter" alt="hash1" src="http://pythoncentral.org/wp-content/uploads/2013/05/hash1-300x108.png?daef55" /></p><p>Now suppose you want to hash the string &#8220;Hello Word&#8221; with the SHA1 Function, the result is <code>0a4d55a8d778e5022fab701977c5d840bbc486d0</code>.</p><p><img class="size-medium wp-image-2952 aligncenter" alt="hash2" src="http://pythoncentral.org/wp-content/uploads/2013/05/hash2-300x65.png?daef55" /></p><p>Hash functions are used inside some cryptographic algorithms, in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more. As a Python programmer you may need these functions to check for duplicate data or files, to check data integrity when you transmit information over a network, to securely store passwords in databases, or maybe some work related to cryptography.</p><p>I want to make clear that hash functions are not a cryptographic protocol, they do not encrypt or decrypt information, but they are a fundamental part of many cryptographic protocols and tools.</p><p>Some of the most used hash functions are:</p><ul><li><strong>MD5</strong>: Message digest algorithm producing a 128 bit hash value. This is widely used to check data integrity. It is not suitable for use in other fields due to the security vulnerabilities of MD5.</li><li><strong>SHA:</strong> Group of algorithms designed by the U.S&#8217;s NSA that are part of the U.S Federal Information processing standard. These algorithms are used widely in several cryptographic applications. The message length ranges from 160 bits to 512 bits.</li></ul><p>The <code>hashlib</code> module, included in The Python Standard library is a module containing an interface to the most popular hashing algorithms. <code>hashlib</code> implements some of the algorithms, however if you have OpenSSL installed, <code>hashlib</code> is able to use this algorithms as well.</p><p>This code is made to work in Python 3.2 and above. If you want to run this examples in Python 2.x, just remove the <code>algorithms_available</code> and <code>algorithms_guaranteed</code> calls.</p><p>First, import the <code>hashlib</code> module:</p><pre class="brush: python; title: ; notranslate">
import hashlib
</pre><p>Now we use <code>algorithms_available</code> or <code>algorithms_guaranteed</code> to list the algorithms available.</p><pre class="brush: python; title: ; notranslate">
print(hashlib.algorithms_available)
print(hashlib.algorithms_guaranteed)
</pre><p>The <code>algorithms_available</code> method lists all the algorithms available in the system, including the ones available trough OpenSSl. In this case you may see duplicate names in the list. <code>algorithms_guaranteed</code> only lists the algorithms present in the module. <code>md5, sha1, sha224, sha256, sha384, sha512</code> are always present.</p><h2>MD5</h2><pre class="brush: python; title: ; notranslate">
import hashlib
hash_object = hashlib.md5(b'Hello World')
print(hash_object.hexdigest())
</pre><p>The code above takes the &#8220;Hello World&#8221; string and prints the HEX digest of that string. <code>hexdigest</code> returns a HEX string representing the hash, in case you need the sequence of bytes you should use <code>digest</code> instead.</p><p>It is important to note the &#8220;b&#8221; preceding the string literal, this converts the string to bytes, because the hashing function only takes a sequence of bytes as a parameter. In previous versions of the library, it used to take a string literal. So, if you need to take some input from the console, and hash this input, do not forget to encode the string in a sequence of bytes:</p><pre class="brush: python; title: ; notranslate">
import hashlib
mystring = input('Enter String to hash: ')
# Assumes the default UTF-8
hash_object = hashlib.md5(mystring.encode())
print(hash_object.hexdigest())
</pre><h2>SHA1</h2><pre class="brush: python; title: ; notranslate">
import hashlib
hash_object = hashlib.sha1(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig)
</pre><h2>SHA224</h2><pre class="brush: python; title: ; notranslate">
import hashlib
hash_object = hashlib.sha224(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig)
</pre><h2>SHA256</h2><pre class="brush: python; title: ; notranslate">
import hashlib
hash_object = hashlib.sha256(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig)
</pre><h2>SHA384</h2><pre class="brush: python; title: ; notranslate">
import hashlib
hash_object = hashlib.sha384(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig)
</pre><h2>SHA512</h2><pre class="brush: python; title: ; notranslate">
import hashlib
hash_object = hashlib.sha512(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig)
</pre><h2>Using OpenSSL Algorithms</h2><p>Now suppose you need an algorithm provided by OpenSSL. Using <code>algorithms_available</code>, we can find the name of the algorithm you want to use. In this case, &#8220;DSA&#8221; is available on my computer. You can then use the <code>new</code> and <code>update</code> methods:</p><pre class="brush: python; title: ; notranslate">
import hashlib
hash_object = hashlib.new('DSA')
hash_object.update(b'Hello World')
print(hash_object.hexdigest())
</pre><h2>Practical example: hashing passwords</h2><p>In the following example we are hashing a password in order to store it in a database. In this example we are using a salt. A salt is a random sequence added to the password string before using the hash function. The salt is used in order to prevent dictionary attacks and rainbow tables attacks. However, if you are making real world applications and working with users&#8217; passwords, make sure to be updated about the latest vulnerabilities in this field. I you want to find out more about secure passwords please refer to this <a href="http://crackstation.net/hashing-security.htm" title="Secure Salted Password Hasing" target="_blank">article</a></p><div id="tab-4o33sl5gbmxg" class="tabbable "><ul class="nav nav-tabs"><li class="active"><a href="#4o33sl5gbmxg_0" data-toggle="tab">Python 3.x</a></li><li class=""><a href="#4o33sl5gbmxg_1" data-toggle="tab">Python 2.x</a></li></ul><div class="tab-content"><div class="tab-pane active" id="4o33sl5gbmxg_0"><pre class="brush: python; title: ; notranslate">
import uuid
import hashlib

def hash_password(password):
    # uuid is used to generate a random number
    salt = uuid.uuid4().hex
    return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
    
def check_password(hashed_password, user_password):
    password, salt = hashed_password.split(':')
    return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()

new_pass = input('Please enter a password: ')
hashed_password = hash_password(new_pass)
print('The string to store in the db is: ' + hashed_password)
old_pass = input('Now please enter the password again to check: ')
if check_password(hashed_password, old_pass):
    print('You entered the right password')
else:
    print('I am sorry but the password does not match')
</pre></div><div class="tab-pane " id="4o33sl5gbmxg_1"><pre class="brush: python; title: ; notranslate">
import uuid
import hashlib

def hash_password(password):
    # uuid is used to generate a random number
    salt = uuid.uuid4().hex
    return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
    
def check_password(hashed_password, user_password):
    password, salt = hashed_password.split(':')
    return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()

new_pass = raw_input('Please enter a password: ')
hashed_password = hash_password(new_pass)
print('The string to store in the db is: ' + hashed_password)
old_pass = raw_input('Now please enter the password again to check: ')
if check_password(hashed_password, old_pass):
    print('You entered the right password')
else:
    print('I am sorry but the password does not match')
</pre></div></div></div><p><script type="text/javascript">jQuery(document).ready(function($) {$("#tab-4o33sl5gbmxg").tab("show")});</script></p><p>The post <a href="http://pythoncentral.org/hashing-strings-with-python/">Hashing Strings with Python</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/PythonCentral?a=ssM-gTPYKQk:6KBLMSUp2pM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=ssM-gTPYKQk:6KBLMSUp2pM:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=ssM-gTPYKQk:6KBLMSUp2pM:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/PythonCentral?i=ssM-gTPYKQk:6KBLMSUp2pM:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/ssM-gTPYKQk" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pythoncentral.org/hashing-strings-with-python/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://pythoncentral.org/hashing-strings-with-python/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=hashing-strings-with-python</feedburner:origLink></item> <item><title>Memory-Mapped (mmap) File Support in Python</title><link>http://feedproxy.google.com/~r/PythonCentral/~3/70CxnbaoI7Y/</link> <comments>http://pythoncentral.org/memory-mapped-mmap-file-support-in-python/#comments</comments> <pubDate>Fri, 26 Apr 2013 07:41:05 +0000</pubDate> <dc:creator>Xiaonuo Gantan</dc:creator> <category><![CDATA[Learn Python Guide]]></category> <category><![CDATA[fileno]]></category> <category><![CDATA[flush]]></category> <category><![CDATA[mmap]]></category> <category><![CDATA[mmap.ACCESS_WRITE]]></category> <category><![CDATA[mmap.mmap]]></category> <category><![CDATA[open]]></category> <category><![CDATA[seek]]></category><guid isPermaLink="false">http://pythoncentral.org/?p=2806</guid> <description><![CDATA[<p>What is a Memory-Mapped File in Python From Python&#8217;s official documentation, be sure to checkout Python&#8217;s mmap module: A memory-mapped file object behaves like both strings and like file objects. Unlike normal string objects, however, these are mutable. Basically, a memory-mapped (using Python&#8217;s mmap module) file object maps a normal file object into memory. This [...]</p><p>The post <a href="http://pythoncentral.org/memory-mapped-mmap-file-support-in-python/">Memory-Mapped (mmap) File Support in Python</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p>]]></description> <content:encoded><![CDATA[<h2>What is a Memory-Mapped File in Python</h2><p>From Python&#8217;s official documentation, be sure to checkout <a href="http://docs.python.org/2/library/mmap.html" title="mmap">Python&#8217;s mmap module</a>:</p><blockquote><p> A memory-mapped file object behaves like both strings and like file objects. Unlike normal string objects, however, these are mutable.</p></blockquote><p>Basically, a memory-mapped (using Python&#8217;s <code>mmap</code> module) file object maps a normal file object into memory. This allows you to modify a file object&#8217;s content directly in memory. Since a memory-mapped file object also behaves like a mutable string object, you can modify the content of a file object like you modify the content of a list of characters:</p><ul><li><code>obj[1] = 'a'</code> &#8211; Assigns a character &#8216;a&#8217; to the the second character of the file object&#8217;s content.</li><li><code>obj[1:4] = 'abc'</code> &#8211; Assigns a character list &#8216;abc&#8217; to a range of three characters starting at the second character of the file object&#8217;s content.</li></ul><p>In a nutshell, memory-mapping a file with Python&#8217;s <code>mmap</code> module us use the operating system&#8217;s virtual memory to access the data on the filesystem directly. Instead of making system calls such as <em>open</em>, <em>read</em> and <em>lseek</em> to manipulate a file, memory-mapping puts the data of the file into memory which allows you to directly manipulate files in memory. This greatly improves <em>I/O</em> performance.</p><h2>Comparison of Memory-Mapped Files vs Normal Files with Python</h2><p>Assume we have a binary file <em>test.out</em> that is larger than 10 MB and there&#8217;s a certain kind of algorithm that requires us to process the data of the file in such a manner that needs us to repeat the process of:</p><ul><li>From the current position, seek 64 bytes and <em>process</em> the data at the beginning of current position.</li><li>From the current position, seek -32 bytes and <em>process</em> the data at the beginning of the current position.</li></ul><p>The actual process of the data is replaced by a <code>pass</code> statement since it does not affect the relative performance comparison between <code>mmap</code> and normal file access. The algorithm keeps processing the data of the file until it reaches a point that is larger than 10MB. The code that uses the normal file objects to perform the algorithm is listed in the file <em>normal_process.py</em>:</p><pre class="brush: python; title: ; notranslate">
import os
import time

f = open('test.out', 'r')
buffer_size = 64
retract_size = -32
start_time = time.time()
while True:
    f.seek(buffer_size, os.SEEK_CUR)
    # Process some data starting at the current position
    pass
    f.seek(retract_size, os.SEEK_CUR)
    # Process some data starting at the current position
    pass
    if f.tell() &gt; 1024 * 1024 * 10:
        break
end_time = time.time()
f.close()
print('Normal time elapsed: {0}'.format(end_time - start_time))
</pre><p>The code that uses <code>mmap</code> to process the data of the file is listed in the file <em>mmap_process.py</em>:</p><pre class="brush: python; title: ; notranslate">
import os
import time
import mmap

f = open('test.out', 'r')
m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
buffer_size = 64
retract_size = -32
start_time = time.time()
while True:
    m.seek(buffer_size, os.SEEK_CUR)
    # process some data starting at the current position
    pass
    m.seek(retract_size, os.SEEK_CUR)
    # process some data starting at the current position
    pass
    if m.tell() &gt; 1024 * 1024 * 10:
        break
end_time = time.time()
m.close()
f.close()
print('mmap time elapsed: {0}'.format(end_time - start_time))
</pre><p>Now you can compare <em>normal_process.py</em> and <em>mmap_process.py</em> in a simple for-loop in your shell:</p><pre class="brush: bash; title: ; notranslate">
for i in {1..3}
do
    python normal_process.py
    python mmap_process.py
done
normal time elapsed: 0.355199098587
mmap time elapsed: 0.296804904938
normal time elapsed: 0.371860027313
mmap time elapsed: 0.290856838226
normal time elapsed: 0.355377197266
mmap time elapsed: 0.305727958679
</pre><p>As you can see, <em>mmap_process.py</em> is about 17% faster than <em>normal_process.py</em> on average, because the <code>seek</code> function calls are performed directly against the memory in <em>mmap_process.py</em> while they are performed using filesystem calls in <em>normal_process.py</em>.</p><h2>Modify a Memory-Mapped File in Python with mmap</h2><p>In the following file <em>mmap_write.py</em>, we modify the content of a file <em>write_test.txt</em> using <code>mmap</code> and <em>flush</em> the changes back to disk:</p><pre class="brush: python; title: ; notranslate">
import os
import mmap

f = open('write_test.txt', 'a+b')
m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_WRITE)
m[0] = 'n'
# Flush changes made to the in-memory copy of the file back to disk
m.flush()
m.close()
f.close()
</pre><p>Suppose <em>write_test.txt</em> contains one line of text:</p><pre class="brush: bash; title: ; notranslate">
$ cat write_test.txt
mmap is a cool feature!
</pre><p>After we run python mmap_write.py, its content will change to (note the first character of the sentence):</p><pre class="brush: bash; title: ; notranslate">
$ cat write_test.txt
nmap is a cool feature!
</pre><h2>mmap Summary and Suggestions</h2><p>Although <code>mmap</code> is a cool feature, keep in mind that <code>mmap</code> has to find a contiguous block of addresses in your process&#8217;s address space that is large enough to fit an entire file object. Suppose you&#8217;re working with large files on a system that does not have enough continuous memory region available to fit those files, then creating a <code>mmap</code> will fail. In additions, <code>mmap</code> does not work on certain special file objects like pipes and ttys.</p><p>The following list summarizes when you should use <code>mmap</code>:</p><ul><li>During multithreaded programming, if you have multiple processes accessing data in a read only way from the same file, then using <code>mmap</code> can save you lots of memory.</li><li><code>mmap</code> allows the operating system to optimize paging operations, which enables the program&#8217;s memory in pages to be efficiently re-used by the operating system.</li></ul><p>The post <a href="http://pythoncentral.org/memory-mapped-mmap-file-support-in-python/">Memory-Mapped (mmap) File Support in Python</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/PythonCentral?a=70CxnbaoI7Y:_4x__hbDnwM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=70CxnbaoI7Y:_4x__hbDnwM:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=70CxnbaoI7Y:_4x__hbDnwM:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/PythonCentral?i=70CxnbaoI7Y:_4x__hbDnwM:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/70CxnbaoI7Y" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pythoncentral.org/memory-mapped-mmap-file-support-in-python/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://pythoncentral.org/memory-mapped-mmap-file-support-in-python/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=memory-mapped-mmap-file-support-in-python</feedburner:origLink></item> <item><title>PySide/PyQt Tutorial: QWebView</title><link>http://feedproxy.google.com/~r/PythonCentral/~3/PFXdiys4Cs4/</link> <comments>http://pythoncentral.org/pyside-pyqt-tutorial-qwebview/#comments</comments> <pubDate>Fri, 26 Apr 2013 07:14:16 +0000</pubDate> <dc:creator>Jason Fruit</dc:creator> <category><![CDATA[Graphical Toolkits]]></category> <category><![CDATA[Library Guides]]></category> <category><![CDATA[PySide/PyQt Guide]]></category> <category><![CDATA[PyQt]]></category> <category><![CDATA[PySide]]></category> <category><![CDATA[QUrl]]></category> <category><![CDATA[QWebFrame]]></category> <category><![CDATA[QWebPage]]></category> <category><![CDATA[QWebView]]></category> <category><![CDATA[QWidget]]></category> <category><![CDATA[WebKit]]></category><guid isPermaLink="false">http://pythoncentral.org/?p=2797</guid> <description><![CDATA[<p>The QWebView is a highly useful control; it allows you to display web pages from URLs, arbitrary HTML, XML with XSLT stylesheets, web pages constructed as QWebPages, and other data whose MIME types it knows how to interpret. It uses the WebKit web browser engine. WebKit is an up-to-date, standards-compliant rendering engine used by Google&#8217;s [...]</p><p>The post <a href="http://pythoncentral.org/pyside-pyqt-tutorial-qwebview/">PySide/PyQt Tutorial: QWebView</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p>]]></description> <content:encoded><![CDATA[<p>The <a target="_blank" href="http://srinikom.github.com/pyside-docs/PySide/QtWebKit/QWebView.html">QWebView</a> is a highly useful control; it allows you to display web pages from URLs, arbitrary HTML, XML with XSLT stylesheets, web pages constructed as QWebPages, and other data whose MIME types it knows how to interpret. It uses the <a target="_blank" href="http://www.webkit.org/">WebKit</a> web browser engine. WebKit is an up-to-date, standards-compliant rendering engine used by Google&#8217;s Chrome, Apple&#8217;s Safari, and soon the Opera browser.</p><h2>Creating and Filling a QWebView</h2><h3>Content from a QWebView&#8217;s URL</h3><p>You instantiate a <code>QWebView</code> like any othe <code>QWidget</code>, with an optional parent. There are a number of ways to put content into it, however. The simplest — and possibly the most obvious — is its <code>load</code> method, which takes a <code>QUrl</code>; the simplest way to construct a <code>QUrl</code> is with a unicode URL string:</p><pre class="brush: python; title: ; notranslate">
web_view.load(QUrl('http://www.pythoncentral.org'))
</pre><p>That loads <a href="http://pythoncentral.org">Python Central</a>&#8216;s main page in the <code>QWebView</code> control. Equivalent would be to use the <code>setUrl</code> method, like so:</p><pre class="brush: python; title: ; notranslate">
web_view.setUrl(QUrl('http://www.pythoncentral.org'))
</pre><h3>Load Arbitrary HTML with QWebView</h3><p>There are other interesting ways to load content into a <code>QWebView</code>. You can load generated HTML into it using the <code>setHtml</code> method. For example, you can do something like this:</p><pre class="brush: python; title: ; notranslate">
html = '''&lt;html&gt;
&lt;head&gt;
&lt;title&gt;A Sample Page&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Hello, World!&lt;/h1&gt;
&lt;hr /&gt;
I have nothing to say.
&lt;/body&gt;
&lt;/html&gt;'''

web_view.setHtml(html)
</pre><p>The <code>setHtml</code> method can take an optional second argument, the base URL of the document &#8211; the URL based on which any relative links contained in the document are resolved.</p><h3>Other QWebView Content Types</h3><p>A <code>QWebView</code>&#8216;s content does not have to be HTML; if you have other browser-viewable content, you can put it in a <code>QWebView</code> using its <code>setContent</code> method, which accepts the content and optionally its MIME type and a base URL. If the MIME type is omitted, it will be assumed that it is <code>text/html</code>; no autodetection of MIME types has been implemented yet, though it is at least tentatively planned. I&#8217;ve not managed to find a list of MIME types that can be handled by the QWebView, but here is an example that works with a PNG file:</p><pre class="brush: python; title: ; notranslate">
app = QApplication([])
win = QWebView()

img = open('myImage.png', 'rb').read()
win.setContent(img, 'image/png')

win.show()
app.exec_()
</pre><h2>Interacting QWebView with JavaScript</h2><p>Presenting a user with web-style content is useful in itself, but that content can be made interactive with JavaScript, which can be initiated from Python code.</p><p>A <code>QWebView</code> contains a <code>QWebFrame</code> object, which is useful to us right now for its <code>evaluateJavaScript</code> method. That method accepts a string of JavaScript, evaluates it in the context of the <code>QWebView</code>&#8216;s content, and returns its value.</p><p>What values can be returned? The <a target="_blank" href="https://deptinfo-ensip.univ-poitiers.fr/ENS/pyside-docs/PySide/QtWebKit/QWebFrame.html#PySide.QtWebKit.PySide.QtWebKit.QWebFrame.evaluateJavaScript">PySide documentation for QWebFrame</a>, like that for PyQt and Qt itself, is not clear on that point. In fact, that information doesn&#8217;t appear to be available on the web at all, so I did some testing.</p><p>It appears that strings and booleans just plain work, and numbers, objects, <code>undefined</code>, and <code>null</code> work with caveats:</p><ul><li>Because JavaScript lacks separate integer and floating-point datatypes, numbers are consistently converted to Python floats.</li><li>Objects are returned as Python dictionaries unless they are functions or arrays; functions are returned as useless empty dictionaries, and arrays become Python lists.</li><li><code>undefined</code> becomes <code>None</code>, sensibly enough.</li><li><code>null</code> becomes, less sensibly, &#8221;. That&#8217;s right — an empty string.</li></ul><p>Note especially the behavior regarding <code>null</code> and functions, as both can cause code that looks right to behave wrong. I see no better option for functions, but <code>null</code> is especially confusing; the <em>only</em> way to detect a null value from <code>evaluateJavaScript</code> is to do the comparison <code>val === null</code> on the JavaScript side <em>before you return it to Python</em>. (It is at this point that we collectively grieve over JavaScript&#8217;s ill-thought-out types.)</p><p>An important caution about <code>evaluateJavaScript</code>: it has all the security implications of JavaScript&#8217;s built-in <code>eval</code>, and should be used with the discretion that is so seldom displayed by front-end JavaScript coders. It would be far too simple, for example, to allow the execution of arbitrary JavaScript by naïvely building a string and sending it to <code>evaluateJavaScript</code>. Be careful, validate user input, and block anything that looks too clever.</p><h3>Example of Evaluating JavaScript in a QWebView</h3><p>Now, let&#8217;s throw caution to the wind and look at a simple example. It will show a form that allows the user to enter a first and last name. There will be a full name entry that is disabled; the user cannot edit it. There is a submit button, but it is hidden. (Don&#8217;t do this in real life, okay?  This form is a usability and cultural-sensitivity disaster, and would be almost insultingly dumb to show in public.)  We&#8217;ll supply a Qt button that fills out the full name entry, shows the submit button, and prints the full name to the console. Here&#8217;s the source of the example:</p><pre class="brush: python; title: ; notranslate">
# Create an application
app = QApplication([])

# And a window
win = QWidget()
win.setWindowTitle('QWebView Interactive Demo')

# And give it a layout
layout = QVBoxLayout()
win.setLayout(layout)

# Create and fill a QWebView
view = QWebView()
view.setHtml('''
  &lt;html&gt;
    &lt;head&gt;
      &lt;title&gt;A Demo Page&lt;/title&gt;

      &lt;script language=&quot;javascript&quot;&gt;
        // Completes the full-name control and
        // shows the submit button
        function completeAndReturnName() {
          var fname = document.getElementById('fname').value;
          var lname = document.getElementById('lname').value;
          var full = fname + ' ' + lname;

          document.getElementById('fullname').value = full;
          document.getElementById('submit-btn').style.display = 'block';

          return full;
        }
      &lt;/script&gt;
    &lt;/head&gt;

    &lt;body&gt;
      &lt;form&gt;
        &lt;label for=&quot;fname&quot;&gt;First name:&lt;/label&gt;
        &lt;input type=&quot;text&quot; name=&quot;fname&quot; id=&quot;fname&quot;&gt;&lt;/input&gt;
        &lt;br /&gt;
        &lt;label for=&quot;lname&quot;&gt;Last name:&lt;/label&gt;
        &lt;input type=&quot;text&quot; name=&quot;lname&quot; id=&quot;lname&quot;&gt;&lt;/input&gt;
        &lt;br /&gt;
        &lt;label for=&quot;fullname&quot;&gt;Full name:&lt;/label&gt;
        &lt;input disabled type=&quot;text&quot; name=&quot;fullname&quot; id=&quot;fullname&quot;&gt;&lt;/input&gt;
        &lt;br /&gt;
        &lt;input style=&quot;display: none;&quot; type=&quot;submit&quot; id=&quot;submit-btn&quot;&gt;&lt;/input&gt;
      &lt;/form&gt;
    &lt;/body&gt;
  &lt;/html&gt;
''')

# A button to call our JavaScript
button = QPushButton('Set Full Name')

# Interact with the HTML page by calling the completeAndReturnName
# function; print its return value to the console
def complete_name():
    frame = view.page().mainFrame()
    print frame.evaluateJavaScript('completeAndReturnName();')

# Connect 'complete_name' to the button's 'clicked' signal
button.clicked.connect(complete_name)

# Add the QWebView and button to the layout
layout.addWidget(view)
layout.addWidget(button)

# Show the window and run the app
win.show()
app.exec_()
</pre><p>Try running it. Fill out a first and last name and click the button. You should see a full name and a submit button appear. Looking at the console, you should see the full name printed there as well.</p><p>This was a very heavily contrived example, but we can do much more interesting things: in the next installment, we&#8217;ll build a simple application that combines HTML in a <code>QWebView</code> and some other Qt widgets to usefully work with a web API.</p><p>The post <a href="http://pythoncentral.org/pyside-pyqt-tutorial-qwebview/">PySide/PyQt Tutorial: QWebView</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/PythonCentral?a=PFXdiys4Cs4:T9-IpsmZMzM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=PFXdiys4Cs4:T9-IpsmZMzM:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=PFXdiys4Cs4:T9-IpsmZMzM:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/PythonCentral?i=PFXdiys4Cs4:T9-IpsmZMzM:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/PFXdiys4Cs4" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pythoncentral.org/pyside-pyqt-tutorial-qwebview/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <series:name><![CDATA[PySide/PyQt Guide]]></series:name> <feedburner:origLink>http://pythoncentral.org/pyside-pyqt-tutorial-qwebview/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=pyside-pyqt-tutorial-qwebview</feedburner:origLink></item> <item><title>Finding Duplicate Files with Python</title><link>http://feedproxy.google.com/~r/PythonCentral/~3/-10FDP7dKaw/</link> <comments>http://pythoncentral.org/finding-duplicate-files-with-python/#comments</comments> <pubDate>Thu, 25 Apr 2013 14:01:26 +0000</pubDate> <dc:creator>Andres Torres</dc:creator> <category><![CDATA[Cookbook Recipes]]></category> <category><![CDATA[hashlib]]></category> <category><![CDATA[hashlib.md5]]></category> <category><![CDATA[hashlib.md5.hexdigest]]></category> <category><![CDATA[md5]]></category> <category><![CDATA[os.walk]]></category><guid isPermaLink="false">http://pythoncentral.org/?p=2777</guid> <description><![CDATA[<p>Sometimes we need to find the duplicate files in our file system, or inside a specific folder. In this tutorial we are going to code a Python script to do this. This script works in Python 3.x. The program is going to receive a folder or a list of folders to scan, then is going [...]</p><p>The post <a href="http://pythoncentral.org/finding-duplicate-files-with-python/">Finding Duplicate Files with Python</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p>]]></description> <content:encoded><![CDATA[<p>Sometimes we need to find the duplicate files in our file system, or inside a specific folder. In this tutorial we are going to code a Python script to do this. This script works in Python 3.x.</p><p>The program is going to receive a folder or a list of folders to scan, then is going to traverse the directories given and find the duplicated files in the folders.</p><p>This program is going to compute a hash for every file, allowing us to find duplicated files even though their names are different. All of the files that we find are going to be stored in a dictionary, with the hash as the key, and the path to the file as the value: <code>{ hash: [list of paths] }</code>.</p><p>To start, <code>import</code> the <code>os, sys</code> and <code>hashlib</code> libraries:</p><pre class="brush: python; title: ; notranslate">
import os
import sys
import hashlib
</pre><p>Then we need a function to calculate the MD5 hash of a given file. The function receives the path to the file and returns the HEX digest of that file:</p><pre class="brush: python; title: ; notranslate">
def hashfile(path, blocksize = 65536):
    afile = open(path, 'rb')
    hasher = hashlib.md5()
    buf = afile.read(blocksize)
    while len(buf) &gt; 0:
        hasher.update(buf)
        buf = afile.read(blocksize)
    afile.close()
    return hasher.hexdigest()
</pre><p>Now we need a function to scan a directory for duplicated files:</p><pre class="brush: python; title: ; notranslate">
def findDup(parentFolder):
    # Dups in format {hash:[names]}
    dups = {}
    for dirName, subdirs, fileList in os.walk(parentFolder):
        print('Scanning %s...' % dirName)
        for filename in fileList:
            # Get the path to the file
            path = os.path.join(dirName, filename)
            # Calculate hash
            file_hash = hashfile(path)
            # Add or append the file path
            if file_hash in dups:
                dups[file_hash].append(path)
            else:
                dups[file_hash] = [path]
    return dups
</pre><p>The <code>findDup</code> function is using <code>os.walk</code> to traverse the given directory. If you need a more comprehensive guide about it, take a look at the <a title="How to Traverse a Directory Tree in Python – Guide to os.walk" href="http://pythoncentral.org/how-to-traverse-a-directory-tree-in-python-guide-to-os-walk/">How to Traverse a Directory Tree in Python</a> article. The <code>os.walk</code> function only returns the filename, so we use <code>os.path.join</code> to get the full path to the file. Then we&#8217;ll get the file&#8217;s hash and store it into the <code>dups</code> dictionary.</p><p>When <code>findDup</code> finishes traversing the directory, it returns a dictionary with the duplicated files. If we are going to traverse several directories, we need a method to merge two dictionaries:</p><pre class="brush: python; title: ; notranslate">
# Joins two dictionaries
def joinDicts(dict1, dict2):
    for key in dict2.keys():
        if key in dict1:
            dict1[key] = dict1[key] + dict2[key]
        else:
            dict1[key] = dict2[key]
</pre><p><code>joinDicts</code> takes 2 dictionaries, iterates over the second dictionary and checks if the key exists in the first dictionary, if it does exist, the method appends the values in the second dictionary to the ones in the first dictionary. If the key does not exist, it stores it in the first dictionary. At the end of the method, the first dictionary contains all the information.</p><p>To be able to run this script from the command line, we need to receive the folders as parameters, and then call <code>findDup</code> for every folder:</p><pre class="brush: python; title: ; notranslate">
if __name__ == '__main__':
    if len(sys.argv) &gt; 1:
        dups = {}
        folders = sys.argv[1:]
        for i in folders:
            # Iterate the folders given
            if os.path.exists(i):
                # Find the duplicated files and append them to the dups
                joinDicts(dups, findDup(i))
            else:
                print('%s is not a valid path, please verify' % i)
                sys.exit()
        printResults(dups)
    else:
        print('Usage: python dupFinder.py folder or python dupFinder.py folder1 folder2 folder3')
</pre><p>The <code>os.path.exists</code> function verifies that the given folder exists in the filesystem. To run this script use <code>python dupFinder.py /folder1 ./folder2</code>. Finally we need a method to print the results:</p><pre class="brush: python; title: ; notranslate">
def printResults(dict1):
    results = list(filter(lambda x: len(x) &gt; 1, dict1.values()))
    if len(results) &gt; 0:
        print('Duplicates Found:')
        print('The following files are identical. The name could differ, but the content is identical')
        print('___________________')
        for result in results:
            for subresult in result:
                print('\t\t%s' % subresult)
            print('___________________')

    else:
        print('No duplicate files found.')
</pre><p>Putting everything together:</p><pre class="brush: python; title: ; notranslate">
# dupFinder.py
import os, sys
import hashlib

def findDup(parentFolder):
    # Dups in format {hash:[names]}
    dups = {}
    for dirName, subdirs, fileList in os.walk(parentFolder):
        print('Scanning %s...' % dirName)
        for filename in fileList:
            # Get the path to the file
            path = os.path.join(dirName, filename)
            # Calculate hash
            file_hash = hashfile(path)
            # Add or append the file path
            if file_hash in dups:
                dups[file_hash].append(path)
            else:
                dups[file_hash] = [path]
    return dups


# Joins two dictionaries
def joinDicts(dict1, dict2):
    for key in dict2.keys():
        if key in dict1:
            dict1[key] = dict1[key] + dict2[key]
        else:
            dict1[key] = dict2[key]


def hashfile(path, blocksize = 65536):
    afile = open(path, 'rb')
    hasher = hashlib.md5()
    buf = afile.read(blocksize)
    while len(buf) &gt; 0:
        hasher.update(buf)
        buf = afile.read(blocksize)
    afile.close()
    return hasher.hexdigest()


def printResults(dict1):
    results = list(filter(lambda x: len(x) &gt; 1, dict1.values()))
    if len(results) &gt; 0:
        print('Duplicates Found:')
        print('The following files are identical. The name could differ, but the content is identical')
        print('___________________')
        for result in results:
            for subresult in result:
                print('\t\t%s' % subresult)
            print('___________________')

    else:
        print('No duplicate files found.')


if __name__ == '__main__':
    if len(sys.argv) &gt; 1:
        dups = {}
        folders = sys.argv[1:]
        for i in folders:
            # Iterate the folders given
            if os.path.exists(i):
                # Find the duplicated files and append them to the dups
                joinDicts(dups, findDup(i))
            else:
                print('%s is not a valid path, please verify' % i)
                sys.exit()
        printResults(dups)
    else:
        print('Usage: python dupFinder.py folder or python dupFinder.py folder1 folder2 folder3')
</pre><p>The post <a href="http://pythoncentral.org/finding-duplicate-files-with-python/">Finding Duplicate Files with Python</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/PythonCentral?a=-10FDP7dKaw:lc3SQ6eK7do:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=-10FDP7dKaw:lc3SQ6eK7do:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=-10FDP7dKaw:lc3SQ6eK7do:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/PythonCentral?i=-10FDP7dKaw:lc3SQ6eK7do:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/-10FDP7dKaw" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pythoncentral.org/finding-duplicate-files-with-python/feed/</wfw:commentRss> <slash:comments>2</slash:comments> <feedburner:origLink>http://pythoncentral.org/finding-duplicate-files-with-python/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=finding-duplicate-files-with-python</feedburner:origLink></item> <item><title>How to Move/Copy a File or Directory (Folder) with a Progress Bar in Python</title><link>http://feedproxy.google.com/~r/PythonCentral/~3/iGVuW81EX_0/</link> <comments>http://pythoncentral.org/how-to-movecopy-a-file-or-directory-folder-with-a-progress-bar-in-python/#comments</comments> <pubDate>Fri, 19 Apr 2013 09:48:57 +0000</pubDate> <dc:creator>Joey Payne</dc:creator> <category><![CDATA[Cookbook Recipes]]></category> <category><![CDATA[shutil.copy]]></category> <category><![CDATA[shutil.copytree]]></category> <category><![CDATA[shutil.move]]></category><guid isPermaLink="false">http://pythoncentral.org/?p=2598</guid> <description><![CDATA[<p>In the last article, titled How to Recursively Copy a Folder (Directory) in Python, I covered how to copy a folder recursively from one place to another. As useful as that is, there is still something else that we could add that would make copying a directory much more user friendly! Enter the progress bar [...]</p><p>The post <a href="http://pythoncentral.org/how-to-movecopy-a-file-or-directory-folder-with-a-progress-bar-in-python/">How to Move/Copy a File or Directory (Folder) with a Progress Bar in Python</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p>]]></description> <content:encoded><![CDATA[<p>In the last article, titled <a title="How to Recursively Copy a Folder (Directory) in Python" href="http://pythoncentral.org/how-to-recursively-copy-a-directory-folder-in-python/">How to Recursively Copy a Folder (Directory) in Python</a>, I covered how to copy a folder recursively from one place to another.</p><p>As useful as that is, there is still something else that we could add that would make copying a directory much more user friendly!</p><p>Enter the progress bar from stage left. It&#8217;s a useful utility that all big name software uses to tell the user something is happening and where it is with the task it is doing.</p><p>So how do we incorporate this into copying a directory? Glad you asked, my question filled friend!</p><h1>The Progress Bar</h1><p>First, we&#8217;ll make a simple class to make printing progress 100 times easier as well as give us a nice reusable class to use in other projects that might need it.</p><p>Here we go. First we&#8217;ll add the <code>__init__</code> method:</p><pre class="brush: python; title: ; notranslate">
# -*- coding: utf-8 -*-
import sys

class ProgressBar(object):
    def __init__(self, message, width=20, progressSymbol=u'▣ ', emptySymbol=u'□ '):
        self.width = width

        if self.width &lt; 0:
            self.width = 0

        self.message = message
        self.progressSymbol = progressSymbol
        self.emptySymbol = emptySymbol
</pre><p>That wasn&#8217;t too hard! We pass in the message we want to print, the width of the progress bar, and the two symbols for progress done and empty progress. We check that the width is always greater that or equal to zero, because we can&#8217;t have a negative length! <img src="http://pythoncentral.org/wp-includes/images/smilies/icon_smile.gif?daef55" alt=':)' class='wp-smiley' /></p><p>Simple stuff.</p><p>Alright, on to the hard part. We have to figure out how to update and render the progress bar to the output window without printing a new line every single time.</p><p>That&#8217;s where the carriage return (<code>\r</code>) comes in. The carriage return is a special character that allows the printed message to start at the beginning of a line when printed. Every time we print something, we&#8217;ll just use it at the beginning of our line and it should take care of our needs just fine. The only limitation this has is that if the progress bar happens to wrap in the terminal, the carriage return will not work as expected and will just output a new line.</p><p>Here is our <code>update</code> function that will print the updated progress:</p><pre class="brush: python; title: ; notranslate">
    def update(self, progress):
        totalBlocks = self.width
        filledBlocks = int(round(progress / (100 / float(totalBlocks)) ))
        emptyBlocks = totalBlocks - filledBlocks

        progressBar = self.progressSymbol * filledBlocks + \
                      self.emptySymbol * emptyBlocks

        if not self.message:
            self.message = u''

        progressMessage = u'\r{0} {1}  {2}%'.format(self.message,
                                                    progressBar,
                                                    progress)

        sys.stdout.write(progressMessage)
        sys.stdout.flush()


    def calculateAndUpdate(self, done, total):
        progress = int(round( (done / float(total)) * 100) )
        self.update(progress)
</pre><p>What we just did is calculate the number of filled blocks using the total blocks needed. It looks a little complicated, so let me break it down. We want the number of filled blocks to be the <code>progress</code> divided by 100% divided by the total number of blocks. The <code>calculateAndUpdate</code> function is just to make our life a little easier. All it does is calculate and print the percentage done given the current number of items and the total number of items.</p><pre class="brush: python; title: ; notranslate">
filledBlocks = int(round(progress / (100 / float(totalBlocks)) ))
</pre><p>That call to <code>float</code> is there to make sure the calculation is done with floating point precision, and then we round up the floating point number with <code>round</code> and make it an integer with <code>int</code>.</p><pre class="brush: python; title: ; notranslate">
emptyBlocks = totalBlocks - filledBlocks
</pre><p>Then the empty blocks are simply the <code>totalBlocks</code> minus the <code>filledBlocks</code>.</p><pre class="brush: python; title: ; notranslate">
progressBar = self.progressSymbol * filledBlocks + \
              self.emptySymbol * emptyBlocks
</pre><p>We take the number of filled blocks and multiply it by the <code>progressSymbol</code> and add it to the <code>emptySymbol</code> multiplied by the number of empty blocks.</p><pre class="brush: python; title: ; notranslate">
progressMessage = u'\r{0} {1}  {2}%'.format(self.message,
                                            progressBar,
                                            progress)
</pre><p>We use the carriage return at the beginning of the message to set the print position to the beginning of the line and make a message formatted like: &#8220;Message! ▣ ▣ ▣ □ □ □ 50%&#8221;.</p><pre class="brush: python; title: ; notranslate">
sys.stdout.write(progressMessage)
sys.stdout.flush()
</pre><p>And, finally, we print the message to the screen. Why don&#8217;t we just use the <code>print</code> function? Because the <code>print</code> function adds a new line to the end of our message and that&#8217;s not what we want. We want it printed just as we set it.</p><p>On with the show! To the copying a directory function!</p><h2>Copying a Directory (Folder) with Progress in Python</h2><p>In order to know our progress, we&#8217;ll have to sacrifice some speed. We need to count all of the files that we&#8217;re copying to get the total amount of progress left, and this requires us to recursively search the directory and count all of the files.</p><p>Let&#8217;s write a function to do that.</p><pre class="brush: python; title: ; notranslate">
import os

def countFiles(directory):
    files = []

    if os.path.isdir(directory):
        for path, dirs, filenames in os.walk(directory):
            files.extend(filenames)

    return len(files)
</pre><p>Pretty straight forward. We just checked if the directory passed in is a directory, then if it is, recursively walk the directories and add the files in the directories to the files list. Then we just return the length of the list. Simple.</p><p>Next is the copying directories function. If you looked at the article mentioned at the top of this article, you&#8217;ll notice that I used the <code>shutil.copytree</code> function. Here we can&#8217;t do that because <code>shutil</code> doesn&#8217;t support progress updates, so we&#8217;ll have to write our own copying function.</p><p>Let&#8217;s do it!</p><p>First we create an instance of our <code>ProgressBar</code> class.</p><pre class="brush: python; title: ; notranslate">
p = ProgressBar('Copying files...')
</pre><p>Next, we define a function to make directories that don&#8217;t exist yet. This will allow us to create the directory structure of the source directory.</p><pre class="brush: python; title: ; notranslate">
def makedirs(dest):
    if not os.path.exists(dest):
        os.makedirs(dest)
</pre><p>If the directory doesn&#8217;t exist, we create it.</p><p>Now for the copy function. This one is a bit of a doozy, so I&#8217;ll put it all down in one place, then break it down.</p><pre class="brush: python; title: ; notranslate">
import shutil

def copyFilesWithProgress(src, dest):
    numFiles = countFiles(src)

    if numFiles &gt; 0:
        makedirs(dest)

        numCopied = 0

        for path, dirs, filenames in os.walk(src):
            for directory in dirs:
                destDir = path.replace(src,dest)
                makedirs(os.path.join(destDir, directory))
            
            for sfile in filenames:
                srcFile = os.path.join(path, sfile)

                destFile = os.path.join(path.replace(src, dest), sfile)
                
                shutil.copy(srcFile, destFile)
                
                numCopied += 1
                
                p.calculateAndUpdate(numCopied, numFiles)
        print
</pre><p>Firstly, we count the number of files.</p><pre class="brush: python; title: ; notranslate">
def copyFilesWithProgress(src, dest):
    numFiles = countFiles(src)
</pre><p>Nothing too difficult about that.</p><p>Next, if there are actually files to copy, we create the destination folder if it doesn&#8217;t exist and initialize a variable to count the current number of files copied.</p><pre class="brush: python; title: ; notranslate">
    if numFiles &amp;gt; 0:
        makedirs(dest)

        numCopied = 0
</pre><p>Then, we walk the directory tree and create all the directories needed.</p><pre class="brush: python; title: ; notranslate">
        for path, dirs, filenames in os.walk(src):
            for directory in dirs:
                destDir = path.replace(src, dest)
                makedirs(os.path.join(destDir, directory))
</pre><p>The only tricky part here is that I replaced the source directory string in path, which is the root path, with the destination folder path.</p><p>Next, we copy files and update progress!</p><pre class="brush: python; title: ; notranslate">
        for path, dirs, filenames in os.walk(src):
            (...)
            for sfile in filenames:
                srcFile = os.path.join(path, sfile)

                destFile = os.path.join(path.replace(src, dest), sfile)
                
                shutil.copy(srcFile, destFile)
                
                numCopied += 1
                
                p.calculateAndUpdate(numCopied, numFiles)
</pre><p>Here, we go through all the files, copy them, update the number of files copied so far, and then draw our progress bar.</p><p>That&#8217;s it! We&#8217;re done! Now you have a nice copying function that will alert you of the progress while copying files.</p><h2>Moving a Directory (Folder) with Progress in Python</h2><p>As a note, you may also change the <code>shutil.copy</code> function call in <code>copyFilesWithProgress</code> to <code>shutil.move</code> and have a move progress bar instead. All the other code would be the same, so I&#8217;m not going to rewrite it here. I&#8217;ll leave that up to you! <img src="http://pythoncentral.org/wp-includes/images/smilies/icon_smile.gif?daef55" alt=':)' class='wp-smiley' /></p><p>Until the next time, I bid you adieu.</p><p>The post <a href="http://pythoncentral.org/how-to-movecopy-a-file-or-directory-folder-with-a-progress-bar-in-python/">How to Move/Copy a File or Directory (Folder) with a Progress Bar in Python</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/PythonCentral?a=iGVuW81EX_0:vPc74CKrJGo:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=iGVuW81EX_0:vPc74CKrJGo:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=iGVuW81EX_0:vPc74CKrJGo:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/PythonCentral?i=iGVuW81EX_0:vPc74CKrJGo:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/iGVuW81EX_0" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pythoncentral.org/how-to-movecopy-a-file-or-directory-folder-with-a-progress-bar-in-python/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://pythoncentral.org/how-to-movecopy-a-file-or-directory-folder-with-a-progress-bar-in-python/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=how-to-movecopy-a-file-or-directory-folder-with-a-progress-bar-in-python</feedburner:origLink></item> <item><title>Introductory Tutorial of Python’s SQLAlchemy</title><link>http://feedproxy.google.com/~r/PythonCentral/~3/bYV2--Tw8Io/</link> <comments>http://pythoncentral.org/introductory-tutorial-python-sqlalchemy/#comments</comments> <pubDate>Fri, 19 Apr 2013 09:11:53 +0000</pubDate> <dc:creator>Xiaonuo Gantan</dc:creator> <category><![CDATA[Databases]]></category> <category><![CDATA[SQLAlchemy]]></category> <category><![CDATA[sqlite]]></category> <category><![CDATA[sqlite3]]></category><guid isPermaLink="false">http://pythoncentral.org/?p=2742</guid> <description><![CDATA[<p>Python&#8217;s SQLAlchemy and Object-Relational Mapping A common task when programming any web service is the construction of a solid database backend. In the past, programmers would write raw SQL statements, pass them to the database engine and parse the returned results as a normal array of records. Nowadays, programmers can write Object-relational mapping (ORM) programs [...]</p><p>The post <a href="http://pythoncentral.org/introductory-tutorial-python-sqlalchemy/">Introductory Tutorial of Python&#8217;s SQLAlchemy</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p>]]></description> <content:encoded><![CDATA[<h2>Python&#8217;s SQLAlchemy and Object-Relational Mapping</h2><p>A common task when programming any web service is the construction of a solid database backend. In the past, programmers would write raw SQL statements, pass them to the database engine and parse the returned results as a normal array of records. Nowadays, programmers can write <em>Object-relational mapping</em> (<em>ORM</em>) programs to remove the necessity of writing tedious and error-prone raw SQL statements that are inflexible and hard-to-maintain.</p><p><em>ORM</em> is a programming technique for converting data between incompatible type systems in object-oriented programming languages. Usually, the type system used in an <em>OO</em> language such as Python contains types that are non-scalar, namely that those types cannot be expressed as primitive types such as integers and strings. For example, a <code>Person</code> object may have a list of <code>Address</code> objects and a list of <code>PhoneNumber</code> objects associated with it. In turn, an <code>Address</code> object may have a <code>PostCode</code> object, a <code>StreetName</code> object and a <code>StreetNumber</code> object associated with it. Although simple objects such as <code>PostCode</code>s and <code>StreetName</code>s can be expressed as strings, a complex object such as a <code>Address</code> and a <code>Person</code> cannot be expressed using only strings or integers. In addition, these complex objects may also include instance or class methods that cannot be expressed using a type at all.</p><p>In order to deal with the complexity of managing <em>objects</em>, people developed a new class of systems called <em>ORM</em>. Our previous example can be expressed as an <em>ORM</em> system with a <code>Person</code> class, a <code>Address</code> class and a <code>PhoneNumber</code> class, where each class maps to a table in the underlying database. Instead of writing tedious database interfacing code yourself, an <em>ORM</em> takes care of these issues for you while you can focus on programming the logics of the system.</p><h2>The Old Way of Writing Database Code in Python</h2><p>We&#8217;re going to use the library <em>sqlite3</em> to create a simple database with two tables <code>Person</code> and <code>Address</code> in the following design:</p><p><img alt="SQLAlchemy Person and Address DDL" src="http://pythoncentral.org/wp-content/uploads/2013/04/SQLAlchemyPersonAddress.png?daef55" /></p><p>Note: If you want to checkout how to use SQLite for Python, you might want to have a look at the <a title="Introduction to SQLite in Python" href="http://pythoncentral.org/introduction-to-sqlite-in-python/">SQLite in Python</a> series.</p><p>In this design, we have two tables <code>person</code> and <code>address</code> and <code>address.person_id</code> is a foreign key to the <code>person</code> table. Now we write the corresponding database initialization code in a file <code>sqlite_ex.py</code>.</p><pre class="brush: python; title: ; notranslate">
import sqlite3
conn = sqlite3.connect('example.db')

c = conn.cursor()
c.execute('''
          CREATE TABLE person
          (id INTEGER PRIMARY KEY ASC, name varchar(250) NOT NULL)
          ''')
c.execute('''
          CREATE TABLE address
          (id INTEGER PRIMARY KEY ASC, street_name varchar(250), street_number varchar(250),
           post_code varchar(250) NOT NULL, person_id INTEGER NOT NULL,
           FOREIGN KEY(person_id) REFERENCES person(id))
          ''')

c.execute('''
          INSERT INTO person VALUES(1, 'pythoncentral')
          ''')
c.execute('''
          INSERT INTO address VALUES(1, 'python road', '1', '00000', 1)
          ''')

conn.commit()
conn.close()
</pre><p>Notice that we have inserted one record into each table. Run the following command in your shell.</p><pre class="brush: bash; title: ; notranslate">
$ python sqlite_ex.py
</pre><p>Now we can query the database <code>example.db</code> to fetch the records. Write the following code in a file <code>sqlite_q.py</code>.</p><pre class="brush: python; title: ; notranslate">
import sqlite3
conn = sqlite3.connect('example.db')

c = conn.cursor()
c.execute('SELECT * FROM person')
print c.fetchall()
c.execute('SELECT * FROM address')
print c.fetchall()
conn.close()
</pre><p>And run the following statement in your shell.</p><pre class="brush: bash; title: ; notranslate">
$ python sqlite_q.py
[(1, u'pythoncentral')]
[(1, u'python road', u'1', u'00000', 1)]
</pre><p>In the previous example, we used an sqlite3 connection to commit the changes to the database and a sqlite3 cursor to execute raw SQL statements to <em>CRUD</em> (create, read, update and delete) data in the database. Although the raw SQL certainly gets the job done, it is not easy to maintain these statements. In the next section, we&#8217;re going to use SQLAlchemy&#8217;s <em>declarative</em> to map the <code>Person</code> and <code>Address</code> tables into Python classes.</p><h2>Python&#8217;s SQLAlchemy and Declarative</h2><p>There are three most important components in writing SQLAlchemy code:</p><ul><li>A <code>Table</code> that represents a table in a database.</li><li>A <code>mapper</code> that maps a Python class to a table in a database.</li><li>A class object that defines how a database record maps to a normal Python object.</li></ul><p>Instead of having to write code for <code>Table</code>, <code>mapper</code> and the class object at different places, SQLAlchemy&#8217;s <em>declarative</em> allows a <code>Table</code>, a <code>mapper</code> and a class object to be defined at once in one class definition.</p><p>The following <em>declarative</em> definitions specify the same tables defined in <code>sqlite_ex.py</code>:</p><pre class="brush: python; title: ; notranslate">
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class Person(Base):
    __tablename__ = 'person'
    # Here we define columns for the table person
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

class Address(Base):
    __tablename__ = 'address'
    # Here we define columns for the table address.
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    street_name = Column(String(250))
    street_number = Column(String(250))
    post_code = Column(String(250), nullable=False)
    person_id = Column(Integer, ForeignKey('person.id'))
    person = relationship(Person)

# Create an engine that stores data in the local directory's
# sqlalchemy_example.db file.
engine = create_engine('sqlite:///sqlalchemy_example.db')

# Create all tables in the engine. This is equivalent to &quot;Create Table&quot;
# statements in raw SQL.
Base.metadata.create_all(engine)
</pre><p>Save the previous code into a file <code>sqlalchemy_declarative.py</code> and run the following command in your shell:</p><pre class="brush: bash; title: ; notranslate">
$ python sqlalchemy_declarative.py
</pre><p>Now a new sqlite3 db file called &#8220;sqlalchemy_example.db&#8221; should be created in your current directory. Since the sqlalchemy db is empty right now, let&#8217;s write some code to insert records into the database:</p><pre class="brush: python; title: ; notranslate">
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from sqlalchemy_declarative import Address, Base, Person

engine = create_engine('sqlite:///sqlalchemy_example.db')
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
# A DBSession() instance establishes all conversations with the database
# and represents a &quot;staging zone&quot; for all the objects loaded into the
# database session object. Any change made against the objects in the
# session won't be persisted into the database until you call
# session.commit(). If you're not happy about the changes, you can
# revert all of them back to the last commit by calling
# session.rollback()
session = DBSession()

# Insert a Person in the person table
new_person = Person(name='new person')
session.add(new_person)
session.commit()

# Insert an Address in the address table
new_address = Address(post_code='00000', person=new_person)
session.add(new_address)
session.commit()
</pre><p>Save the previous code into a local file <code>sqlalchemy_insert.py</code> and run the command <code>python sqlalchemy_insert.py</code> in your shell. Now we have one <code>Person</code> object and one <code>Address</code> object stored in the database. Let&#8217;s query the database using the classes defined in <code>sqlalchemy_declarative.py</code>:</p><pre class="brush: bash; title: ; notranslate">
&gt;&gt;&gt; from sqlalchemy_declarative import Person, Base, Address
&gt;&gt;&gt; from sqlalchemy import create_engine
&gt;&gt;&gt; engine = create_engine('sqlite:///sqlalchemy_example.db')
&gt;&gt;&gt; Base.metadata.bind = engine
&gt;&gt;&gt; from sqlalchemy.orm import sessionmaker
&gt;&gt;&gt; DBSession = sessionmaker()
&gt;&gt;&gt; DBSession.bind = engine
&gt;&gt;&gt; session = DBSession()
&gt;&gt;&gt; # Make a query to find all Persons in the database
&gt;&gt;&gt; session.query(Person).all()
[&lt;sqlalchemy_declarative.Person object at 0x2ee3a10&gt;]
&gt;&gt;&gt;
&gt;&gt;&gt; # Return the first Person from all Persons in the database
&gt;&gt;&gt; person = session.query(Person).first()
&gt;&gt;&gt; person.name
u'new person'
&gt;&gt;&gt;
&gt;&gt;&gt; # Find all Address whose person field is pointing to the person object
&gt;&gt;&gt; session.query(Address).filter(Address.person == person).all()
[&lt;sqlalchemy_declarative.Address object at 0x2ee3cd0&gt;]
&gt;&gt;&gt;
&gt;&gt;&gt; # Retrieve one Address whose person field is point to the person object
&gt;&gt;&gt; session.query(Address).filter(Address.person == person).one()
&lt;sqlalchemy_declarative.Address object at 0x2ee3cd0&gt;
&gt;&gt;&gt; address = session.query(Address).filter(Address.person == person).one()
&gt;&gt;&gt; address.post_code
u'00000'
</pre><h2>Summary of Python&#8217;s SQLAlchemy</h2><p>In this article, we learned how to write database code using SQLAlchemy&#8217;s <em>declaratives</em>. Compared to writing the traditional raw SQL statements using <em>sqlite3</em>, SQLAlchemy&#8217;s code is more object-oriented and easier to read and maintain. In addition, we can easily create, read, update and delete SQLAlchemy objects like they&#8217;re normal Python objects.</p><p>You might be wondering that if SQLAlchemy&#8217;s just a thin layer of abstraction above the raw SQL statements, then it&#8217;s not very impressive and you might prefer to writing raw SQL statements instead. In the following articles of this series, we&#8217;re going to investigate various aspects of SQLAlchemy and compare it against raw SQL statements when they&#8217;re both used to implement the same functionalities. I believe at the end of this series, you will be convinced that SQLAlchemy is superior to writing raw SQL statements.</p><p>The post <a href="http://pythoncentral.org/introductory-tutorial-python-sqlalchemy/">Introductory Tutorial of Python&#8217;s SQLAlchemy</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/PythonCentral?a=bYV2--Tw8Io:Cb0xh-OR7J8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=bYV2--Tw8Io:Cb0xh-OR7J8:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=bYV2--Tw8Io:Cb0xh-OR7J8:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/PythonCentral?i=bYV2--Tw8Io:Cb0xh-OR7J8:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/bYV2--Tw8Io" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pythoncentral.org/introductory-tutorial-python-sqlalchemy/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <series:name><![CDATA[SQLAlchemy]]></series:name> <feedburner:origLink>http://pythoncentral.org/introductory-tutorial-python-sqlalchemy/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=introductory-tutorial-python-sqlalchemy</feedburner:origLink></item> <item><title>Writing Simple Views for Your First Python Django Application</title><link>http://feedproxy.google.com/~r/PythonCentral/~3/MpMZQaZjSPI/</link> <comments>http://pythoncentral.org/writing-simple-views-for-your-first-python-django-application/#comments</comments> <pubDate>Tue, 16 Apr 2013 12:16:50 +0000</pubDate> <dc:creator>Xiaonuo Gantan</dc:creator> <category><![CDATA[Django Guide]]></category> <category><![CDATA[Library Guides]]></category> <category><![CDATA[Web Frameworks]]></category> <category><![CDATA[Django]]></category> <category><![CDATA[views]]></category><guid isPermaLink="false">http://pythoncentral.org/?p=2569</guid> <description><![CDATA[<p>In the previous article Activate Admin Application for Your Python Django Website, we learned how to activate the built-in Admin Application from Django in your website. In this article, we are going to write simple views for your website. What is a view? In Django, a view is an endpoint that can be accessed by [...]</p><p>The post <a href="http://pythoncentral.org/writing-simple-views-for-your-first-python-django-application/">Writing Simple Views for Your First Python Django Application</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p>]]></description> <content:encoded><![CDATA[<p>In the previous article <a href="http://pythoncentral.org/activate-admin-application-for-your-python-django-website/" title="Activate Admin Application for Your Python Django Website">Activate Admin Application for Your Python Django Website</a>, we learned how to activate the built-in Admin Application from Django in your website. In this article, we are going to write simple views for your website.</p><h2>What is a view?</h2><p>In Django, a <em>view</em> is an endpoint that can be accessed by any client to retrieve data over the wire. For example, some <em>views</em> serve data rendered with a template to a web server that in turn serves the HTML page to a client. While other <em>views</em> serve JSON data to a web server and these <em>views</em> become part of a <em>RESTful</em> API.</p><p>In Django, <em>views</em> are simple Python functions or methods which return data to a front-end web server. When a <em>request</em> comes in, Django chooses a <em>view</em> by examining the <em>request</em>&#8216;s URL after the domain name. In order to call the correct <em>view</em> when a <em>request</em> is made, you need to insert a list of URL patterns into <code>myblog/urls.py</code>. A URL pattern is a regular expression based string which specifies the generic form of a <em>view</em>&#8216;s URL. For example, <code>r'^posts/(?P\d{4})/$'</code> matches all URLs whose parts after the domain name follow the pattern of a string &#8216;posts&#8217; followed by a four-digits number.</p><h2>Views for Our Django Website</h2><p>In our blog website, we will write the following views:</p><ul><li><code>Post</code> &#8220;index&#8221; view that displays a list of most recent posts or popular posts in the blog, just like the home page of <a href="http://pythoncentral.org" title="pythoncentral.org" target="_blank">Python Central</a></li><li><code>Post</code> &#8220;detail&#8221; view that displays the details of a <code>Post</code>, which is similar to each individual article page on <a href="http://pythoncentral.org" title="pythoncentral.org" target="_blank">Python Central</a></li></ul><p>In the &#8220;index&#8221; view, a user should be able to see a list of latest <code>Posts</code> made by others. In the &#8220;detail&#8221; view, a user should be able to see the content of a <code>Post</code> as well as a list of <code>Comment</code>s made by others.</p><h3>Index View</h3><p>Let&#8217;s write your first <em>view</em> &#8220;index&#8221; that shows a list of most recent <code>Post</code>s. Create a file <code>myblog/views.py</code> with the following content:</p><pre class="brush: python; title: ; notranslate">
from django.http import HttpResponse

def index(request):
    return HttpResponse('This page shows a list of most recent posts.')
</pre><p>And modify the file <code>myblog/urls.py</code>:</p><pre class="brush: python; title: ; notranslate">
from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Add the following line to link the root URL to the function myblog.views.index()
    url(r'^$', 'myblog.views.index', name='index'),
    # url(r'^myblog/', include('myblog.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)
</pre><p>Now you can access <a href="http://127.0.0.1:8000/" title="127.0.0.1:8000" target="_blank">127.0.0.1:8000</a> in your browser to view the content returned by <code>myblog.views.index()</code>:<br /> <img src="http://pythoncentral.org/wp-content/uploads/2013/04/DjangoHomePageHelloWorld.png?daef55" alt="Django Home Page Plain" /></p><p>Since the return value of <code>myblog.views.index</code> is a string &#8220;This page shows a list of most recent posts.&#8221;, it shows up on this page. Next, we are going to modify the function <code>myblog.views.index</code> to return a list of <code>Post</code>s that are posted no earlier than two days ago:</p><pre class="brush: python; title: ; notranslate">
from datetime import datetime, timedelta
from django.http import HttpResponse

from myblog import models as m

def index(request):
    two_days_ago = datetime.utcnow() - timedelta(days=2)
    recent_posts = m.Post.objects.filter(created_at__gt=two_days_ago).all()
    return HttpResponse(recent_posts)
</pre><p>Now you can refresh <a href="http://127.0.0.1:8000/" title="127.0.0.1:8000" target="_blank">127.0.0.1:8000</a> to see that no post is made less than two days ago:<br /> <img src="http://pythoncentral.org/wp-content/uploads/2013/04/DjangoHomePageEmptyListOfPost.png?daef55" alt="Django Home Page Zero Post" /></p><p>Let&#8217;s go ahead and add a <code>Post</code> using the Admin interface at the <a href="http://127.0.0.1:8000/admin" title="Admin Site" target="_blank">Admin Site</a>:</p><p><img src="http://pythoncentral.org/wp-content/uploads/2013/04/DjangoAdminAddAPost.png?daef55" alt="Django Admin Add a Post" /></p><p>Click &#8220;Save&#8221; and the post admin page should show that a new post is added and there&#8217;re three posts total in the database now:</p><p><img src="http://pythoncentral.org/wp-content/uploads/2013/04/DjangoAdminPostListPage.png?daef55" alt="Django Admin Post List Page" /></p><p>Now you can refresh the <a href="http://127.0.0.1:8000/" title="Home Page" target="_blank">Home Page</a> to see that one <code>Post</code> is returned:</p><p><img src="http://pythoncentral.org/wp-content/uploads/2013/04/DjangoHomePageOnePost.png?daef55" alt="Django Home Page with One Post" /></p><h2>Django  Views Templates</h2><p>Obviously, only displaying &#8220;Post object&#8221; is not very helpful to the users and we need a more informative page to show a list of <code>Post</code>s. This is when a <em>template</em> would be helpful to turn an useless page like the current one into a presentable one.</p><p>Create a new file <code>myblog/templates/index.html</code> with the following content:</p><pre class="brush: python; title: ; notranslate">
{% if post_list %}
    &lt;ul&gt;
    {% for post in post_list %}
        &lt;li&gt;
            &lt;a href=&quot;/post/{{ post.id }}/&quot;&gt;{{ post.content }}&lt;/a&gt;
            &lt;span&gt;{{ post.created_at }}&lt;/span&gt;
        &lt;/li&gt;
    {% endfor %}
    &lt;/ul&gt;
{% else %}
    &lt;p&gt;No post is made during the past two days.&lt;/p&gt;
{% endif %}
</pre><p></p><p>And modify the file <code>myblog/views.py</code> to use the Django template system to render the response of <a href="http://127.0.0.1:8000/" title="127.0.0.1:8000" target="_blank">127.0.0.1:8000</a>:</p><pre class="brush: python; title: ; notranslate">
from datetime import datetime, timedelta
from django.http import HttpResponse
from django.template import Context, loader 

from myblog import models as m
    
    
def index(request):
    two_days_ago = datetime.utcnow() - timedelta(days=2)

    # Retrieve a list of posts that are created less than two days ago
    recent_posts = m.Post.objects.filter(created_at__gt=two_days_ago).all()

    # Load the template myblog/templates/index.html
    template = loader.get_template('index.html')

    # Context is a normal Python dictionary whose keys can be accessed in the template index.html
    context = Context({
        'post_list': recent_posts
    })

    return HttpResponse(template.render(context))
</pre><p>Now you can refresh the <a href="http://127.0.0.1:8000/" title="Home Page">Home Page</a> again to see that one <code>Post</code> is rendered using the template in <code>myblog/templates/index.html</code>:</p><p><img src="http://pythoncentral.org/wp-content/uploads/2013/04/DjangoHomePageOnePostWithTemplate.png?daef55" alt="Django Home Page with Template" /></p><p>Although the current code of the <em>view</em> index() works, it&#8217;s a bit longer than necessary. You can shorten the code using a Django shortcut <code>render</code>:</p><pre class="brush: python; title: ; notranslate">
from datetime import datetime, timedelta
from django.http import HttpResponse
from django.shortcuts import render
from django.template import Context
from myblog import models as m

def index(request):
    two_days_ago = datetime.utcnow() - timedelta(days=2)
    recent_posts = m.Post.objects.filter(created_at__gt=two_days_ago).all()
    context = Context({
        'post_list': recent_posts
    })
    # Render accepts three arguments: the request object, the
    # path of the template file and the context
    return render(request, 'index.html', context)
</pre><h2>Django&#8217;s Detail View</h2><p>Similar to the <code>index</code> view, the <code>detail</code> view shows a page that presents detailed information about a <code>Post</code> at URLs like <code>/post/1/detail.html</code>, where <code>1</code> is the id of a <code>Post</code>.</p><p>Similar to the <code>index</code> view, you need to write the URL pattern before writing the <code>detail</code> view. Modify the file <code>myblog/urls.py</code> in the following way:</p><pre class="brush: python; title: ; notranslate">
from django.conf.urls import patterns, include, url                          

# Uncomment the next two lines to enable the admin:                          
from django.contrib import admin
admin.autodiscover()                                                         

urlpatterns = patterns('',                                                   
    url(r'^$', 'myblog.views.index', name='index'),
    # Map the view function myblog.views.post_detail() to an URL pattern
    url(r'^post/(?P&lt;post_id&gt;\d+)/detail.html$',
        'myblog.views.post_detail', name='post_detail'),
    # url(r'^myblog/', include('myblog.foo.urls')),                          
        
    # Uncomment the admin/doc line below to enable admin documentation:      
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),           
                                                                             
    # Uncomment the next line to enable the admin:                           
    url(r'^admin/', include(admin.site.urls)),                               
)
</pre><p>Then you can implement the <em>view</em> function in <code>myblog/views.py</code>:</p><pre class="brush: python; title: ; notranslate">
from datetime import datetime, timedelta
from django.http import Http404, HttpResponse
from django.shortcuts import render
from django.template import Context
from myblog import models as m

    
def index(request):
    two_days_ago = datetime.utcnow() - timedelta(days=2)
    recent_posts = m.Post.objects.filter(created_at__gt=two_days_ago).all()
    context = Context({
        'post_list': recent_posts
    })
    return render(request, 'index.html', context)
                                                                             
    
# post_detail accepts two arguments: the normal request object and an integer
# whose value is mapped by post_id defined in r'^post/(?P&lt;post_id&gt;\d+)/detail.html$'
def post_detail(request, post_id):
    try:
        post = m.Post.objects.get(pk=post_id)
    except m.Post.DoesNotExist:
        # If no Post has id post_id, we raise an HTTP 404 error.
        raise Http404
    return render(request, 'post/detail.html', {'post': post})
</pre><p>Then we need to add a new template file at <code>myblog/templates/post/detail.html</code>:</p><pre class="brush: python; title: ; notranslate">
&lt;div&gt;                                                                        
    &lt;h1&gt;{{ post.content }}&lt;/h1&gt;                                              
    &lt;h2&gt;{{ post.created_at }}&lt;/h2&gt;                                           
&lt;/div&gt;
</pre><p>Now you can access the URL <a href="http://127.0.0.1:8000/post/1/detail.html" title="Post Detail Page" target="_blank">Post Detail</a>:</p><p><img src="http://pythoncentral.org/wp-content/uploads/2013/04/DjangoPostDetailPage1.png?daef55" alt="Django Post Detail Page" /></p><p>If you access a <code>Post</code> whose <code>id</code> is not in the database, our <code>detail</code> <em>view</em> will show a HTTP 404 error page:</p><p><img src="http://pythoncentral.org/wp-content/uploads/2013/04/DjangoPostDetailPage4041.png?daef55" alt="Django Post Detail 404 Error Page" /></p><h2>Summary</h2><p>In this article, we wrote our first two <em>views</em>. The <code>index</code> view shows a list of <code>posts</code> that are created by users less than two days ago and the <code>detail</code> view presents the detailed content of a <code>Post</code>. Generally speaking, the process of writing a <code>view</code> involves:</p><ul><li>Write URL patterns for the view in <code>myblog/urls.py</code></li><li>Write the actual view&#8217;s code in <code>myblog/views.py</code></li><li>Write a template file in the directory <code>myblog/templates/</code></li></ul><p>The post <a href="http://pythoncentral.org/writing-simple-views-for-your-first-python-django-application/">Writing Simple Views for Your First Python Django Application</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/PythonCentral?a=MpMZQaZjSPI:5P0pIF8Ocb0:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=MpMZQaZjSPI:5P0pIF8Ocb0:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=MpMZQaZjSPI:5P0pIF8Ocb0:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/PythonCentral?i=MpMZQaZjSPI:5P0pIF8Ocb0:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/MpMZQaZjSPI" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pythoncentral.org/writing-simple-views-for-your-first-python-django-application/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <series:name><![CDATA[Django Guide]]></series:name> <feedburner:origLink>http://pythoncentral.org/writing-simple-views-for-your-first-python-django-application/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=writing-simple-views-for-your-first-python-django-application</feedburner:origLink></item> <item><title>Advanced SQLite Usage in Python</title><link>http://feedproxy.google.com/~r/PythonCentral/~3/t9HiCnOr9bU/</link> <comments>http://pythoncentral.org/advanced-sqlite-usage-in-python/#comments</comments> <pubDate>Tue, 16 Apr 2013 11:57:56 +0000</pubDate> <dc:creator>Andres Torres</dc:creator> <category><![CDATA[Databases]]></category> <category><![CDATA[Library Guides]]></category> <category><![CDATA[SQLite]]></category> <category><![CDATA[sql]]></category> <category><![CDATA[sqlite]]></category> <category><![CDATA[sqlite3]]></category> <category><![CDATA[sqlite3.create_function]]></category> <category><![CDATA[sqlite3.executescript]]></category><guid isPermaLink="false">http://pythoncentral.org/?p=2069</guid> <description><![CDATA[<p>Following the SQLite3 series, this post is about some advanced topics when we are working with the SQLite3 module. If you missed the first part, you can find it here. Using SQLite&#8217;s date and datetime Types Sometimes we need to insert and retrieve some date and datetime types in our SQLite3 database. When you execute [...]</p><p>The post <a href="http://pythoncentral.org/advanced-sqlite-usage-in-python/">Advanced SQLite Usage in Python</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p>]]></description> <content:encoded><![CDATA[<p>Following the SQLite3 series, this post is about some advanced topics when we are working with the SQLite3 module. If you missed the first part, you can find it <a title="Introduction to SQLite in Python" href="http://pythoncentral.org/introduction-to-sqlite-in-python/">here</a>.</p><h2>Using SQLite&#8217;s date and datetime Types</h2><p>Sometimes we need to insert and retrieve some <code>date</code> and <code>datetime</code> types in our SQLite3 database. When you execute the insert query with a date or datetime object, the <code>sqlite3</code> module calls the default adapter and converts them to an ISO format. When you execute a query in order to retrieve those values, the <code>sqlite3</code> module is going to return a string object:</p><pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import sqlite3
&gt;&gt;&gt; from datetime import date, datetime
&gt;&gt;&gt;
&gt;&gt;&gt; db = sqlite3.connect(':memory:')
&gt;&gt;&gt; c = db.cursor()
&gt;&gt;&gt; c.execute('''CREATE TABLE example(id INTEGER PRIMARY KEY, created_at DATE)''')
&gt;&gt;&gt;
&gt;&gt;&gt; # Insert a date object into the database
&gt;&gt;&gt; today = date.today()
&gt;&gt;&gt; c.execute('''INSERT INTO example(created_at) VALUES(?)''', (today,))
&gt;&gt;&gt; db.commit()
&gt;&gt;&gt;
&gt;&gt;&gt; # Retrieve the inserted object
&gt;&gt;&gt; c.execute('''SELECT created_at FROM example''')
&gt;&gt;&gt; row = c.fetchone()
&gt;&gt;&gt; print('The date is {0} and the datatype is {1}'.format(row[0], type(row[0])))
# The date is 2013-04-14 and the datatype is &lt;class 'str'&gt;
&gt;&gt;&gt; db.close()
</pre><p>The problem is that if you inserted a date object in the database, most of the time you are expecting a date object when you retrieve it, not a string object. This problem can be solved passing <code>PARSE_DECLTYPES</code> and <code>PARSE_COLNAMES</code> to the <code>connect</code> method:</p><pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import sqlite3
&gt;&gt;&gt; from datetime import date, datetime
&gt;&gt;&gt;
&gt;&gt;&gt; db = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
&gt;&gt;&gt; c = db.cursor()
&gt;&gt;&gt; c.execute('''CREATE TABLE example(id INTEGER PRIMARY KEY, created_at DATE)''')
&gt;&gt;&gt; # Insert a date object into the database
&gt;&gt;&gt; today = date.today()
&gt;&gt;&gt; c.execute('''INSERT INTO example(created_at) VALUES(?)''', (today,))
&gt;&gt;&gt; db.commit()
&gt;&gt;&gt;
&gt;&gt;&gt; # Retrieve the inserted object
&gt;&gt;&gt; c.execute('''SELECT created_at FROM example''')
&gt;&gt;&gt; row = c.fetchone()
&gt;&gt;&gt; print('The date is {0} and the datatype is {1}'.format(row[0], type(row[0])))
# The date is 2013-04-14 and the datatype is &lt;class 'datetime.date'&gt;
&gt;&gt;&gt; db.close()
</pre><p>Changing the connect method, the database now is returning a date object. The <code>sqlite3</code> module uses the column&#8217;s type to return the correct type of object. So, if we need to work with a <code>datetime</code> object, we must declare the column in the table as a <code>timestamp</code> type:</p><pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; c.execute('''CREATE TABLE example(id INTEGER PRIMARY KEY, created_at timestamp)''')
&gt;&gt;&gt; # Insert a datetime object
&gt;&gt;&gt; now = datetime.now()
&gt;&gt;&gt; c.execute('''INSERT INTO example(created_at) VALUES(?)''', (now,))
&gt;&gt;&gt; db.commit()
&gt;&gt;&gt;
&gt;&gt;&gt; # Retrieve the inserted object
&gt;&gt;&gt; c.execute('''SELECT created_at FROM example''')
&gt;&gt;&gt; row = c.fetchone()
&gt;&gt;&gt; print('The date is {0} and the datatype is {1}'.format(row[0], type(row[0])))
# The date is 2013-04-14 16:29:11.666274 and the datatype is &lt;class 'datetime.datetime'&gt;
</pre><p>In case you have declared a column type as <code>DATE</code>, but you need to work with a <code>datetime</code> object, it is necessary to modify your query in order to parse the object correctly:</p><pre class="brush: python; title: ; notranslate">
c.execute('''CREATE TABLE example(id INTEGER PRIMARY KEY, created_at DATE)''')
# We are going to insert a datetime object into a DATE column
now = datetime.now()
c.execute('''INSERT INTO example(created_at) VALUES(?)''', (now,))
db.commit()

# Retrieve the inserted object
c.execute('''SELECT created_at as &quot;created_at [timestamp]&quot; FROM example''')
</pre><p>Using <code>as "created_at [timestamp]"</code> in the SQL query will make the adapter to parse the object correctly.</p><h2>Insert Multiple Rows with SQLite&#8217;s executemany</h2><p>Sometimes we need to insert a sequence of objects in the database, the <code>sqlite3</code> module provides the <code>executemany</code> method to execute a SQL query against a sequence.</p><pre class="brush: python; title: ; notranslate">
# Import the SQLite3 module
import sqlite3
db = sqlite3.connect(':memory:')
c = db.cursor()
c.execute('''CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT, phone TEXT)''')
users = [
    ('John', '5557241'), 
    ('Adam', '5547874'), 
    ('Jack', '5484522'), 
    ('Monthy',' 6656565')
]

c.executemany('''INSERT INTO users(name, phone) VALUES(?,?)''', users)
db.commit()

# Print the users
c.execute('''SELECT * FROM users''')
for row in c:
    print(row)

db.close()
</pre><p>Please note that each element of the sequence must be a tuple.</p><h2>Execute SQL File with SQLite&#8217;s executescript</h2><p>The <code>execute</code> method only allows you to execute a single SQL sentence. If you need to execute several different SQL sentences you should use <code>executescript</code> method:</p><pre class="brush: python; title: ; notranslate">
# Import the SQLite3 module
import sqlite3
db = sqlite3.connect(':memory:')
c = db.cursor()
script = '''CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT, phone TEXT);
            CREATE TABLE accounts(id INTEGER PRIMARY KEY, description TEXT);
            
            INSERT INTO users(name, phone) VALUES ('John', '5557241'), 
             ('Adam', '5547874'), ('Jack', '5484522');'''
c.executescript(script)

# Print the results
c.execute('''SELECT * FROM users''')
for row in c:
    print(row)

db.close()
</pre><p>If you need to read the script from a file:</p><pre class="brush: python; title: ; notranslate">
fd = open('myscript.sql', 'r')
script = fd.read()
c.executescript(script)
fd.close()
</pre><p>Please remember that it is a good idea to surround your code with a <code>try/except/else</code> clause in order to catch the exceptions. To learn more about the <code>try/except/else</code> keywords, checkout the <a href="http://pythoncentral.org/catching-python-exceptions-the-try-except-else-keywords/" title="Catching Python Exceptions – The try/except/else keywords">Catching Python Exceptions – The try/except/else keywords</a> article.</p><h2>Defining SQLite SQL Functions</h2><p>Sometimes we need to use our own functions in a statement, specially when we are inserting data in order to accomplish some specific task. A good example of this is when we are storing passwords in the database and we need to encrypt those passwords:</p><pre class="brush: python; title: ; notranslate">
import sqlite3 #Import the SQLite3 module
import hashlib

def encrypt_password(password):
    # Do not use this algorithm in a real environment
    encrypted_pass = hashlib.sha1(password.encode('utf-8')).hexdigest()
    return encrypted_pass

db = sqlite3.connect(':memory:')
# Register the function
db.create_function('encrypt', 1, encrypt_password)
c = db.cursor()
c.execute('''CREATE TABLE users(id INTEGER PRIMARY KEY, email TEXT, password TEXT)''')
user = ('johndoe@example.com', '12345678')
c.execute('''INSERT INTO users(email, password) VALUES (?,encrypt(?))''', user)
</pre><p>The <code>create_function</code> takes 3 parameters: <code>name</code> (the name used to call the function inside the statement), the number of parameters the function expects (1 parameter in this case) and a callable object (the function itself). To use our registered function, we called it using <code>encrypt()</code> in the statement.</p><p>Finally, PLEASE use a true encryption algorithm when you are storing passwords!</p><p>The post <a href="http://pythoncentral.org/advanced-sqlite-usage-in-python/">Advanced SQLite Usage in Python</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/PythonCentral?a=t9HiCnOr9bU:GNKDrAWgC1o:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=t9HiCnOr9bU:GNKDrAWgC1o:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=t9HiCnOr9bU:GNKDrAWgC1o:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/PythonCentral?i=t9HiCnOr9bU:GNKDrAWgC1o:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/t9HiCnOr9bU" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pythoncentral.org/advanced-sqlite-usage-in-python/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <series:name><![CDATA[SQLite]]></series:name> <feedburner:origLink>http://pythoncentral.org/advanced-sqlite-usage-in-python/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=advanced-sqlite-usage-in-python</feedburner:origLink></item> <item><title>Python for Android: Using Webviews (SL4A)</title><link>http://feedproxy.google.com/~r/PythonCentral/~3/AGX4d3_A7hs/</link> <comments>http://pythoncentral.org/python-for-android-using-webviews-sl4a/#comments</comments> <pubDate>Tue, 16 Apr 2013 11:35:39 +0000</pubDate> <dc:creator>Carl Smith</dc:creator> <category><![CDATA[Android Scripting Layer (SL4A)]]></category> <category><![CDATA[Library Guides]]></category> <category><![CDATA[HTML]]></category> <category><![CDATA[javascript]]></category> <category><![CDATA[sl4a]]></category> <category><![CDATA[webviews]]></category><guid isPermaLink="false">http://pythoncentral.org/?p=2410</guid> <description><![CDATA[<p>Webviews make it easy to use web technologies to build graphical user interfaces for native applications. Many people already know some webcraft, and it&#8217;s easy to pick up and well worth knowing, so there&#8217;s a broad appeal in being able to use these technologies for native apps. This also allows developers to tap into the [...]</p><p>The post <a href="http://pythoncentral.org/python-for-android-using-webviews-sl4a/">Python for Android: Using Webviews (SL4A)</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p>]]></description> <content:encoded><![CDATA[<p>Webviews make it easy to use web technologies to build graphical user interfaces for native applications. Many people already know some webcraft, and it&#8217;s easy to pick up and well worth knowing, so there&#8217;s a broad appeal in being able to use these technologies for native apps. This also allows developers to tap into the vast and thriving ecosystem of JavaScript libraries that have gone supernova since HTML5 started rolling out.</p><p>To use webviews, you&#8217;ll obviously need to know some HTML, CSS and JavaScript, so basic familiarity with these languages is assumed in this article.</p><h2>Webviews with SL4A: A Call and Two Hooks</h2><p>When you first use webviews, you&#8217;ll find things work a bit differently than you&#8217;d expect coming from programming native graphical interfaces or programming web applications. Thankfully, things are much easier all round. For example, you don&#8217;t have to manage frame rates or buffers in your event loop as webviews are rendered by an engine, in SL4A&#8217;s case, WebKit, so the Python code doesn&#8217;t need to handle any of that. At the same time, you don&#8217;t have things like AJAX and websockets to manage; you just post simple events to and from the user interface. In many ways, you have the best of both worlds with webviews.</p><p>This is one of those things that&#8217;s easier to explain with some code, so we&#8217;ll just start with a hello-world and keep incrementing.</p><p>To build a webview based app, you need at least one HTML file and one Python script, which implement the view and an app to use it. For simplicity, we&#8217;ll call them <code>index.html</code> and <code>main.py</code>.</p><h3>The Webview Call</h3><p>Below is the content of <code>index.html</code>. The meta tag in the head is just there to tell the device not to try and rescale anything.</p><pre class="brush: xml; title: ; notranslate">
&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
    &lt;head&gt;

        &lt;meta name=&quot;viewport&quot; id=&quot;viewport&quot;
            content=&quot;width=device-width, target-densitydpi=device-dpi,
            initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0&quot;
        /&gt;

    &lt;/head&gt;

    &lt;body&gt;
        Hello World&lt;be&gt;
        with SL4a Webviews
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>This is the content of <code>main.py</code>:</p><pre class="brush: python; title: ; notranslate">
from android import Android
import time

droid = Android()
droid.webViewShow('file:///sdcard/sl4a/scripts/example/index.html')

time.sleep(4)
</pre><p>This script creates an <code>Android</code> object, called <code>droid</code>, which is standard procedure for SL4A apps ~ <code>droid</code> exposes the Scripting Layer API. The script then launches the webview using the droid&#8217;s <code>webViewShow</code> method, passing a local file URL as the only argument. Obviously, you need to edit that URL to point to your HTML file. The script then sleeps for 4 seconds, just so you have time to see the webview on your device before the Python script exits and kills it.</p><p>As you can see, launching a webview just takes a single call. To keep the program running indefinitely, and to manage communication between the Python script and the webview, the script will need an event loop, but there&#8217;s a couple of hooks you need to know about first.</p><h3>The First Hook</h3><p>Once you have your webview running, you need to pass messages to it and handle messages from it. Everything boils down to events.</p><p>Apart from the Android stuff, the following version of <code>index.html</code> is pretty basic. There&#8217;s an explanation of how it all works below.</p><pre class="brush: xml; title: ; notranslate">
&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta name=&quot;viewport&quot; id=&quot;viewport&quot;
            content=&quot;width=device-width, target-densitydpi=device-dpi,
            initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0&quot;
        /&gt;

        &lt;style&gt;
            body { background-color: #EEE }
            #banner { text-align: center }
            #userin {
                font-size: 64px;
                position: absolute;
                left: 10px;
                right: 10px;
            }
        &lt;/style&gt;

        &lt;script&gt;
            var droid = new Android();
            function postInput(input) {
                // Post the content of the text field to the python side if
                // the user has pressed enter (or soft keyboard equivalent)
                if (event.keyCode == 13)
                    droid.eventPost('line', input);
            }
        &lt;/script&gt;
    &lt;/head&gt;

    &lt;body&gt;

        &lt;div id=&quot;banner&quot;&gt;
            &lt;h1&gt;SL4A&lt;/h1&gt;
            &lt;h2&gt;Text to Speech Machine&lt;/h2&gt;
        &lt;/div&gt;
    
        &lt;input id=&quot;userin&quot; type=&quot;text&quot; spellcheck=&quot;false&quot;
            autofocus=&quot;autofocus&quot; onkeyup=&quot;postInput(this.value)&quot;
        /&gt;

    &lt;/body&gt;
&lt;/html&gt;
</pre><p>Now, <code>index.html</code> has a textual banner at the top of the page, with a text field underneath that the user can type into. When the user enters some text, the string in the text field is passed to a function, <code>postInput</code>, which posts the string to the Python script as an event, using the Droid&#8217;s <code>eventPost</code> method. The first argument to <code>eventPost</code>, <code>'line'</code>, is currently irrelevant and could&#8217;ve been anything.</p><p>This was a good point to chuck in some simple CSS too, else the text field would have been really small and ugly.</p><p>Below is a new version of <code>main.py</code>. This version will launch the webview, then block and wait for an event. When it gets the event, it grabs the data, the string the user entered in the text field, and uses the Android Text to Speech Facade to read out the user input. It exits immediately afterwards, so it will only handle one event.</p><pre class="brush: python; title: ; notranslate">
from android import Android
droid = Android()

droid.webViewShow('file:///sdcard/sl4a/scripts/example/index.html')

# Wait for an event from webview
event = droid.eventWait().result

# Get the data, the user's input
data = event['data']

# Do text to speech on the input
droid.ttsSpeak(data)
</pre><p>It&#8217;s easy to put the last three lines in a loop to handle multiple events, but it&#8217;s worth looking at the code a bit more first.</p><p><img src="http://pythoncentral.org/wp-content/uploads/2013/04/Screenshot_2013-04-12-01-12-34.png?daef55" alt="SL4A Webview Example Screenshot: Simple Echo Version" width="240" height="400" class="alignright wp-image-2617" /></p><p>Line 6 assigns <code>droid.eventWait().result</code> to a variable, <code>event</code>. The <code>eventWait</code> method is blocking, it just waits for any event to be posted, then returns a <code>dict</code> that contains information about the event.</p><p>Note that all calls to the the Scripting Layer are RPC calls and communication is in JSON. It&#8217;s the incoming JSON that&#8217;s always returned, as a <code>dict</code>, by any call to the SL4A API. This is covered in detail elsewhere, but, in short, it&#8217;s the <code>result</code> that&#8217;s often all you care about, hence it&#8217;s commonplace to see API calls written like the one on Line 6.</p><p>Anyway, <code>droid.eventWait().result</code>, and therefore <code>event</code> in the script above, is a <code>dict</code> containing information about the event.</p><p>If the last three lines of <code>main.py</code> were inside a loop, it could handle multiple events, but then there&#8217;d be no way for the user to exit the app cleanly.</p><p>The following version of <code>main.py</code> can handle two types of event, <code>line</code> and <code>kill</code> events. The <code>line</code> events will be handled as before; the script just reads a line of user input out loud, but this time, this will happen inside a loop, iterating until a <code>kill</code> event occurs. A <code>kill</code> event will cause the script to exit, taking the webview with it.</p><p>The webview itself doesn&#8217;t currently have any way to post <code>kill</code> events, but that&#8217;s easily resolved later.</p><pre class="brush: python; title: ; notranslate">
import sys

from android import Android
droid = Android()

droid.webViewShow('file:///sdcard/sl4a/scripts/example/index.html')

# Complete one iteration for each event
while True: 
    event = droid.eventWait().result
    
    if event['name'] == 'kill':
        sys.exit()
    elif event['name'] == 'line':
        droid.ttsSpeak(event['data'])
</pre><p>Note that the script references <code>event['name']</code> and <code>event['data']</code>. The following JavaScript snippet just illustrates how events are posted from the front end. The call takes two arguments, both strings. The first is an event name, the second is some event data.</p><pre class="brush: python; title: ; notranslate">
var droid = new Android();
droid.eventPost('name', 'data');
</pre><p>The arguments are passed into <code>main.py</code> as a <code>dict</code>, which it assigns to <code>event</code>. The first argument is available as <code>event['name']</code>, the second as <code>event['data']</code>.</p><p>The following version of <code>index.html</code> includes a little more HTML and CSS, adding a button that will post a <code>kill</code> event when it is pressed.</p><pre class="brush: xml; title: ; notranslate">
&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
    &lt;head&gt;

        &lt;meta name=&quot;viewport&quot; id=&quot;viewport&quot;
            content=&quot;width=device-width, target-densitydpi=device-dpi,
            initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0&quot;
        /&gt;

        &lt;style&gt;
            body { background-color: #EEE }
            #banner { text-align: center }
            #userin {
                font-size: 64px;
                position: absolute; right:10px; left:10px;
            }
            #killer {
                font-size: 32px; padding: 16px;
                position: absolute; bottom:10px; right:10px; left:10px;
            }
        &lt;/style&gt;

        &lt;script&gt;
            var droid = new Android();
            function postInput(input) {
                if (event.keyCode == 13)
                    droid.eventPost('line', input)
            }
        &lt;/script&gt;

    &lt;/head&gt;

    &lt;body&gt;
        &lt;div id=&quot;banner&quot;&gt;
            &lt;h1&gt;SL4A&lt;/h1&gt;
        &lt;h2&gt;Text to Speech Machine 2&lt;/h2&gt;
        &lt;/div&gt;
    
        &lt;input id=&quot;userin&quot; type=&quot;text&quot; spellcheck=&quot;false&quot;
            autofocus=&quot;autofocus&quot; onkeyup=&quot;postInput(this.value)&quot;
        /&gt;

        &lt;button id=&quot;killer&quot; type=&quot;button&quot;
                onclick=&quot;droid.eventPost('kill', '')&quot;
        &gt;KILL BUTTON&lt;/button&gt;

    &lt;/body&gt;
&lt;/html&gt;
</pre><p>The app now has a webview that can post multiple types of event, distinguished by name, that carry data about the event to handler code in the Python event loop. Now that you understand how to post events &#8216;inward&#8217;, from JavaScript to Python, you just need to know how to post events &#8216;outward&#8217;, from Python to JavaScript. Then you have all the bits you need to do graphical user interfaces with webviews in SL4A.</p><h3>The Second Hook</h3><p>Posting an event from Python is really easy, especially if you know how it&#8217;s done in JavaScript. Basically, you just use the same API in the same way, with <code>droid.eventPost('name', 'data')</code>. Handling events in JavaScript is a little different though. JavaScript is event oriented, so the event loop is implicit. To handle events in JavaScript, you need to register callbacks. In this case, you register functions to handle events by name, using <code>droid.registerCallback('name' some_function)</code>.</p><p>The following JavaScript snippet registers a simple callback, using a <code>lambda</code>, for handling <code>spam</code> events.</p><pre class="brush: jscript; title: ; notranslate">
droid.registerCallback('spam', function(e) {
    alert(e.data)
});
</pre><p>Note that the function receives one argument, <code>e</code>, which is the event. It has all the properties you should now expect from an event object.</p><h2>SL4A Webview: Complete Example</h2><p>This final version of the example code implements a crude Python evaluator. It simply evaluates any Python expression the user enters and prints the result in the webview.</p><p>Doing this only requires a few small changes to <code>index.html</code>: In the body, there&#8217;s an empty <code>div</code> with an <code>id</code> named <code>output</code>, which is where the output of the evaluation will appear, and, in the style sheet, there&#8217;s a few simple tweaks for this output <code>div</code>. The only other change is to the JavaScript, where a callback is registered that will handle <code>stdout</code> events. The function just prints the event data to the output div, overwriting whatever might have been there before.</p><pre class="brush: xml; title: ; notranslate">
&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
	&lt;head&gt;
	    &lt;meta name=&quot;viewport&quot; id=&quot;viewport&quot;
	        content=&quot;width=device-width, target-densitydpi=device-dpi,
	        initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0&quot;
	    /&gt;
	
	    &lt;style&gt;
	        body { background-color: #EEE }
	        #banner { text-align: center }
	        #userin {
	            font-size: 64px;
	            position: absolute;
	            right: 10px;
	            left: 10px;
	        }
	        #output {
	            font-size: 32px;
	            font-family: monospace;
	            padding: 20px;
	            position: absolute;
	            top: 250px;
	            }
	        #killer {
	            font-size: 32px;
	            padding: 16px;
	            position: absolute; bottom: 10px;
	            right: 10px;
	            left: 10px;
	        }
	    &lt;/style&gt;
	
	    &lt;script&gt;
	        var droid = new Android();
	        
	        function postInput(input) {
	            if (event.keyCode == 13)
	                droid.eventPost('line', input)
	            
	            droid.registerCallback('stdout', function(e) {
	                document.getElementById('output').innerHTML = e.data;
	            });
	        }
	    &lt;/script&gt;
	
	&lt;/head&gt;

    &lt;body&gt;
	    &lt;div id=&quot;banner&quot;&gt;
	        &lt;h1&gt;SL4A Webviews&lt;/h1&gt;
	        &lt;h2&gt;Example: Python Evaluator&lt;/h2&gt;
	    &lt;/div&gt;
	    
	    &lt;input id=&quot;userin&quot; type=&quot;text&quot; spellcheck=&quot;false&quot;
	           autofocus=&quot;autofocus&quot; onkeyup=&quot;postInput(this.value)&quot;
	    /&gt;
	    
	    &lt;div id=&quot;output&quot;&gt;&lt;/div&gt;
	    
	    &lt;button id=&quot;killer&quot; type=&quot;button&quot;
	            onclick=&quot;droid.eventPost('kill', '')&quot;
	    &gt;KILL BUTTON&lt;/button&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>On the Python side, the only change is in how <code>line</code> events are handled. Now, a function called <code>line_handler</code> takes the line, evaluates it, converts the result to a string and then passes the string to the webview as the data for a <code>sdtout</code> event.</p><pre class="brush: python; title: ; notranslate">
import sys

from android import Android
droid = Android()

def line_handler(line):
    ''' Evaluate user input and print the result into a webview.
    This function takes a line of user input and calls eval on
    it, posting the result to the webview as a stdout event.
    '''
    
    output = str(eval(line))
    droid.eventPost('stdout', output)


droid.webViewShow('file:///sdcard/sl4a/scripts/example/index.html')

while True:
    event = droid.eventWait().result
    
    if event['name'] == 'kill':
        sys.exit()
    elif event['name'] == 'line':
        line_handler(event['data'])
</pre><p>Admittedly, this isn&#8217;t the most exciting or polished app in the world, but it does illustrate how the Events API can be used with webviews to create graphical user interfaces. You could use the <code>code</code> module to turn this example app into a Python interactive interpreter without too much work, or use ACE to build a code editor that&#8217;s better than the crappy SL4A built in one, or just replace the SL4A interface entirely.</p><p><img src="http://pythoncentral.org/wp-content/uploads/2013/04/Screenshot_2013-04-08-21-58-40-180x300.png?daef55" alt="SL4A Webview Example Screenshot" width="240" height="400" class="alignright wp-image-2608" /></p><p>There&#8217;s a ton of good JavaScript libraries available now days for building front-ends. With Python on Android underneath, you can get really creative.</p><p>Obviously, it&#8217;s all a bit of a hack, but it&#8217;s a nice one. For a dev who just needs to modify some phones, or a hobbyist wanting to put out a tablet RPG, really for anyone who just wants an nice easy way to do a graphical app on an Android device, webviews are ideal.</p><p><em>Note:</em> The Events API is a little richer and a lot more powerful than this example demonstrates, but the call to <code>webViewShow</code> and the two hooks, posting events from JavaScript to the Python event loop and from Python to JavaScript callbacks, are all you need to build a webview based user interface.</p><p><em>Note:</em> Remember, you&#8217;re still building a regular SL4A application, so you can use all the native Android UI components, like dialogues, toasts, notifications and so on, alongside webviews, giving you a nice and simple tool set for building rich Android applications with Python and HTML5.</p><p>The post <a href="http://pythoncentral.org/python-for-android-using-webviews-sl4a/">Python for Android: Using Webviews (SL4A)</a> appeared first on <a href="http://pythoncentral.org">Python Central</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/PythonCentral?a=AGX4d3_A7hs:Wgc4FayigSI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=AGX4d3_A7hs:Wgc4FayigSI:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/PythonCentral?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/PythonCentral?a=AGX4d3_A7hs:Wgc4FayigSI:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/PythonCentral?i=AGX4d3_A7hs:Wgc4FayigSI:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/AGX4d3_A7hs" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pythoncentral.org/python-for-android-using-webviews-sl4a/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <series:name><![CDATA[Python for Android]]></series:name> <feedburner:origLink>http://pythoncentral.org/python-for-android-using-webviews-sl4a/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=python-for-android-using-webviews-sl4a</feedburner:origLink></item> </channel> </rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using apc
Database Caching 12/49 queries in 0.045 seconds using apc
Object Caching 3032/3290 objects using apc

 Served from: pythoncentral.org @ 2013-05-21 05:43:17 by W3 Total Cache -->
