Stupid Python Tricks
Stupid Python Tricks
Background
What is it?
“Python is a clear and powerful object-oriented programming
language, comparable to Perl, Ruby, Scheme, or Java.”
- Python Wiki
●
Elegant syntax
●
Easy to use
●
Easy to extend
●
Embeddable
●
Powerful
●
Popular
Why Else?
●
Simple, straightforward language
●
People know it!
– used heavily in the industry
– taught in Academia
Raspberry Pi
Raspberry Pi
https://www.raspberrypi.org/blog/pioneers-summer-camp-2017/rasberry-pi-pioneers-at-go
ogle-kings-cross-28717-8/
© 2016-2018 IBM Corporation
Cognitive Systems
Icon Explanation
Icon Explanation
smtp = smtplib.SMTP('smtp.example.com')
smtp.send_message(msg)
smtp.quit()
smtp = smtplib.SMTP('smtp.example.com')
msg = MIMEMultipart()
msg['From'] = 'sysadmin@example.com'
msg['To'] = 'bugwriter@example.com'
msg['Subject'] = 'Application Crashed. Fix now!'
msg.attach(MimeText('See attached logs.'))
msg.attach(part)
smtp.send_message(msg)
smtp.quit()
DIY cPYtoimpf
●
Built in support for csv reading/parsing & writing
– Multiple pre-defined output formats
– Extensible – generate your own format
●
Documentation: https://docs.python.org/3/library/csv.html
DIY cPYtoimpf
from csv import writer, QUOTE_NONNUMERIC
import ibm_db_dbi as db2
conn = db2.connect()
cur = conn.cursor()
cur.execute("select cusnum, lstnam, init, cdtlmt
from qiws.qcustcdt where cdtlmt > 100")
DIY cPYtoimpf
938472,"Henning ","G K",5000
839283,"Jones ","B D",400
392859,"Vine ","S S",700
938485,"Johnson ","J A",9999
397267,"Tyron ","W E",1000
389572,"Stevens ","K L",400
846283,"Alison ","J S",5000
475938,"Doe ","J W",700
693829,"Thomas ","A N",9999
593029,"Williams","E D",200
192837,"Lee ","F L",700
583990,"Abraham ","M T",9999
DIY cPYtoimpf
from csv import writer, QUOTE_NONNUMERIC
# <snip>
def trim_col(s):
return s.rstrip() if hasattr(s, 'rstrip') else s
DIY cPYtoimpf
938472,"Henning","G K",5000
839283,"Jones","B D",400
392859,"Vine","S S",700
938485,"Johnson","J A",9999
397267,"Tyron","W E",1000
389572,"Stevens","K L",400
846283,"Alison","J S",5000
475938,"Doe","J W",700
693829,"Thomas","A N",9999
593029,"Williams","E D",200
192837,"Lee","F L",700
583990,"Abraham","M T",9999
parser.add_argument('--action', required=True, \
choices=('start', 'stop', 'restart'), \
help='Server Action')
parser.add_argument('--server', default='*ALL', \
help='Server to act on')
args = parser.parse_args()
if args.action == 'restart':
cl += ' RESTART(*HTTP)'
system('system "{}"'.format(cl))
HTTP Admin
optional arguments:
-h, --help show this help message and exit
--action {start,stop,restart}
Server Action
--server SERVER Server to act on
Parsing JSON
●
Encode and decode JSON
●
Load from file object or string
●
Documentation:
– https://docs.python.org/3/library/json.html
Reading JSON
import ibm_db_dbi as db2
import json
Reading JSON
Henning : 5000
Jones : 400
Vine : 700
Johnson : 9999
Tyron : 1000
Stevens : 400
Alison : 5000
Doe : 700
Thomas : 9999
Williams: 200
Lee : 700
Abraham : 9999
Using SQLite
●
Access the lightweight database from Python
●
Useful for applications that support SQLite but not Db2
●
Documentation:
– https://docs.python.org/3/library/sqlite3.html
conn = sqlite3.connect('my.db')
# name, #parms, func
conn.create_function('btc', 1, usd_to_btc)
cur = conn.cursor()
Package Management
●
Python has a package manager: pip (pip3)
●
Use pip to install packages from the internet
– Automatically determines dependencies needed
– Downloads needed packages from the Python Package Index
(pypi.python.org)
– Installs the packages
●
upgrade and uninstall packages as well
●
pip can also install local packages (wheels)
●
No internet access from IBM i? No problem! Check out devpi
https://devpi.net/docs/devpi/devpi/stable/%2Bd/index.html
x.add_column("Area", \
[1295, 5905, 112, 1357, 2058])
x.add_column("Annual Rainfall", \
[600.5, 1146.4, 1714.7, 619.5, 1214.8])
print(x)
print(x)
conn = db2.connect()
cur = conn.cursor()
cur.execute("select cusnum, lstnam, cdtlmt,
baldue, cdtdue from qiws.qcustcdt")
print(from_db_cursor(cur))
ws.insert_chart('C1', chart)
cur = db2.connect().cursor()
cur.execute("select cusnum, lstnam, cdtlmt,
baldue, cdtdue from qiws.qcustcdt")
ws = workbook.add_worksheet()
ws.set_column(0, len(headers)-1, 16)
Using Bottle
●
Lightweight framework for building web applications
– Includes a templating engine
– Self-hosting web server included
– Or use with flipflop (also included in OPS) in FastCGI mode
●
Need PTF SI60566 or superseding
●
See https://ibm.biz/installpythonpackages for more info to
install
●
https://pypi.python.org/pypi/bottle
views/index.html
<!DOCTYPE HTML>
<html lang="en-US">
<head><title>IBM i Bottle Sample</title></head>
<body>
<form action="query" method="post">
<h1><label for="sql">SQL Query</label></h1>
<textarea rows="4" cols="60" name="sql" />
</textarea>
<br /><br />
<input type="submit" value="Execute" />
</form>
</body>
</html>
© 2016-2018 IBM Corporation
Cognitive Systems
views/query.html
% from prettytable import from_db_cursor
% table = from_db_cursor(rows)
<!DOCTYPE HTML>
<html lang="en-US">
<head><title>IBM i Bottle Query</title><head>
<body>
{{! table.get_html_string() }}
</body>
</html>
@get('/')
def root():
return bottle.template('index')
@post('/query')
@view('query')
def query():
cur = db2.connect().cursor()
cur.execute(request.forms.get('sql'))
return {'rows': cur}
run(host='0.0.0.0', port=9000)
© 2016-2018 IBM Corporation
Cognitive Systems
Website Example
Website Example
https://commons.wikimedia.org/wiki/File:4-Week-Old_Netherlands_Dwarf_Rabbit.J
PG
© 2016-2018 IBM Corporation
Cognitive Systems
Making Thumbnails
from PIL import Image
img = Image.open('rabbit_full.jpg')
small_size = [ dim//2 for dim in img.size ]
small_img = img.resize(small_size)
small_img.save('rabbit.jpg')
# or better yet
max_size = (534, 534)
small_img = img.thumbnail(max_size)
small_img.save('rabbit.jpg')
Cropping Pictures
from PIL import Image
img = Image.open('rabbit.jpg')
# upper left x,y; lower right x,y
box = (0, 160, 356, 460)
small_img = img.crop(box)
small_img.save('rabbit_crop.jpg')
Watermarking
from PIL import Image
img = Image.open('rabbit.jpg')
logo = Image.open('ibmi.png')
position = ( \
(img.width – logo.width - 5), \
(img.height – logo.height - 5))
Using Twitter
import tweepy
from os import environ
KEY = environ["CONSUMER_KEY"]
SECRET = environ["CONSUMER_SECRET"]
ACCESS_TOKEN = environ["ACCESS_TOKEN"]
ACCESS_SECRET = environ["ACCESS_TOKEN_SECRET"]
Using Twitter
@theGonif
@kadler_ibm @OCEANUserGroup Is it not enough that
there's no snow? �
@kadler_ibm
Excited to talk about #Python on #IBMi at today's
@OCEANUserGroup kickoff, but where's my
California sunrise? https://t.co/oAXcAqDHdO
@freschesolution
Join us TOMORROW with @OCEANUserGroup to kick off
another great year with #IBM star guests
@Steve_Will_IBMi &… https://t.co/iowktrR2rl
© 2016-2018 IBM Corporation
Cognitive Systems
Shipping Packages
●
Python API for goshippo.com
– Supports FedEx, UPS, USPS, and more
– Price Estimation
– Shipment creation
– Tracking
– Customs declaration
●
Installation
– pip3 install shippo
●
Documentation
– https://pypi.python.org/pypi/shippo
– https://github.com/goshippo/shippo-python-client
– https://goshippo.com/docs
●
License: MIT
shipment = shippo.Shipment.create(
address_from=from,
address_to=to,
parcels=[parcel], async=False
)
Shippo Output
USPS Priority Mail Express: $29.02
USPS Priority Mail: $6.47
USPS Parcel Select: $6.83
key = pyotp.random_base32()
print(key) # XK3I4RJ3OY7M7DAY
totp = pyotp.TOTP(key)
print(totp.now()) # 923442
time.sleep(60)
print(totp.now()) # 593490
Generating QR Codes
●
Generate QR Codes in Python
●
Uses PIL/Pillow under the covers
●
Installation
– pip3 install qrcode
●
Documentation
– https://pypi.python.org/pypi/qrcode
– https://github.com/lincolnloop/python-qrcode
●
License: BSD
Generating QR Codes
import qrcode
qr = qrcode.make(url)
qr.save('qr.png')
Generating QR Codes
from bottle import request, response, get, run
import qrcode
import pyotp
import io
@get('/')
def root():
key = request.query.get('key', 'XK3I4RJ3OY7M7DAY')
totp = pyotp.TOTP(key)
qr = qrcode.make(totp.provisioning_uri('pyqrcode'))
imgbuf = io.BytesIO()
qr.save(imgbuf, format='PNG')
response.content_type ='image/png'
return imgbuf.getvalue()
© 2016-2018 IBM Corporation
Cognitive Systems
Generating QR Codes
url =
'http://ibmsystemsmag.com/CMSTemplates/IBMSystemsMag/F
eeds/Open-Your-i.aspx'
feed = feedparser.parse(url)
u = 'http://imdb.com/title/tt0071853/fullcredits'
resp = urlopen(u)
if __name__ == '__main__':
import plac; plac.call(main)
© 2016-2018 IBM Corporation
Cognitive Systems
optional arguments:
-h, --help show this help message and exit
-port PORT Local port
Questions?
Python 3 Programs
●
Programs are added to /QOpenSys/usr/bin
– SSH is recommended, QP2TERM or QSH as last resort
●
Programs:
– python3 – main runtime/interpreter
– pip3 – package manager: Installs local wheels, downloads
wheels and dependencies from the Python Package Index (PyPI)
– pydoc3 – documentation tool, can be used to show
documentation for keywords, topics, functions, modules,
packages, and more
– 2to3 – converts Python 2 source code to Python 3
https://facebook.com/IBMPowerSystems
https://twitter.com/IBMPowerSystems
https://www.linkedin.com/company/ibm-power-systems
http://www.youtube.com/c/ibmpowersystems
https://www.ibm.com/blogs/systems/topics/servers/power-systems/
More to Follow:
Blogs Twitter #Hashtags
IBM Systems Magazine You and i (Steve Will) @IBMSystems #PowerSystems
IBM Systems Magazine i-Can (Dawn May) @COMMONug #IBMi
IBM Systems Magazine: iDevelop (Jon Paris and Susan Gantner) @IBMChampions #IBMAIX
@IBMSystemsISVs
IBM Systems Magazine: iTalk with Tuohy #POWER8
@LinuxIBMMag
IBM Systems Magazine: Open your i (Jesse Gorzinski) #LinuxonPower
@OpenPOWERorg
Trevor Perry Blog @AIXMag #OpenPOWER
IBM DB2 for i (Mike Cain) @IBMiMag #HANAonPower
IBM DB2 Web Query for i (Doug Mack) @ITJungleNews #ITinfrastructure
Modern-i-zation (Tim Rowe) @SAPonIBMi #OpenSource
@SiDforIBMi #HybridCloud
@IBMAIXeSupp
#BigData
@IBMAIXdoc
#IBMiOSS
Special notices
This document was developed for IBM offerings in the United States as of the date of publication. IBM may not make these offerings available in other countries, and the information is subject to
change without notice. Consult your local IBM business contact for information on the IBM offerings available in your area.
Information in this document concerning non-IBM products was obtained from the suppliers of these products or other public sources. Questions on the capabilities of non-IBM products should be
addressed to the suppliers of those products.
IBM may have patents or pending patent applications covering subject matter in this document. The furnishing of this document does not give you any license to these patents. Send license inquires,
in writing, to IBM Director of Licensing, IBM Corporation, New Castle Drive, Armonk, NY 10504-1785 USA.
All statements regarding IBM future direction and intent are subject to change or withdrawal without notice, and represent goals and objectives only.
The information contained in this document has not been submitted to any formal IBM test and is provided "AS IS" with no warranties or guarantees either expressed or implied.
All examples cited or described in this document are presented as illustrations of the manner in which some IBM products can be used and the results that may be achieved. Actual environmental
costs and performance characteristics will vary depending on individual client configurations and conditions.
IBM Global Financing offerings are provided through IBM Credit Corporation in the United States and other IBM subsidiaries and divisions worldwide to qualified commercial and government clients.
Rates are based on a client's credit rating, financing terms, offering type, equipment type and options, and may vary by country. Other restrictions may apply. Rates and offerings are subject to
change, extension or withdrawal without notice.
IBM is not responsible for printing errors in this document that result in pricing or information inaccuracies.
All prices shown are IBM's United States suggested list prices and are subject to change without notice; reseller prices may vary.
IBM hardware products are manufactured from new parts, or new and serviceable used parts. Regardless, our warranty terms apply.
Any performance data contained in this document was determined in a controlled environment. Actual results may vary significantly and are dependent on many factors including system hardware
configuration and software design and configuration. Some measurements quoted in this document may have been made on development-level systems. There is no guarantee these measurements
will be the same on generally-available systems. Some measurements quoted in this document may have been estimated through extrapolation. Users of this document should verify the applicable
data for their specific environment.