What is the difference between parenthesis and brackets in Python

Tuples and lists

Both are arrays, but tuples are immutable. This means that once you define a tuple, you cannot add elements, pop, append, remove an element, etc. You need to create a new tuple out of the old one every time you make a change.

  • Tuples (1,2,3,4,5,6) are great for static definition. They are hashable, lean and unequivocal.
  • Lists [1,2,3,4,5,6] are great for computation. They are mutable and queueable.

Both are addressed with integers in brackets.

Whether it is a list or a tuple, addressing one element is the same.

create a tuple with y = (“a”,”b”,”c”) and do this;

y = ("a","b","c")
print (y[0])
for i in y:
    print (i)

For lists and tuples, know this too;

for i in range(0,len(y)):
    print (i,y,y[i])

Now redefine y as a list and try it again. Same results?

shortest Python timezones example

assuming we import datetime and pytz, just for a little bit of brevity ….

print datetime.datetime.utcnow().replace(tzinfo=pytz.utc).\
   astimezone(pytz.timezone("US/Eastern")).strftime("%Y-%m-%d %H:%M")

Whoa Nelly, Break it down bro! Below is an example of getting a ‘Naive’ time. I.E. it will be the time of the computer you are using, but have no associated timezone designation. This example also will get an error if you can’t import datetime.

import datetime
nowVariable = datetime.datetime.now()
print nowVariable

But a naive time object is unaware of the timezone, and the pytz object library is a great addition to datetime, but again, the next example will make your time object timezone aware, but first it will test that your computer can import the pytz object library.

import datetime, pytz
nowVariable = datetime.datetime.now()
laTimeVariable = nowVariable.replace(tzinfo=pytz.timezone("US/Pacific"))
print laTimeVariable

Other timezones could be US/Mountain, US/Central, Europe/Rome, Australia/Perth, Asia/Hong_Kong, etc.

Now, if we want to print the ‘aware’ date object in a pretty format, we can say;

print laTimeVariable.strftime("%Y-%m-%d %H:%M %Z")

This is great to populate the display variable when the date and time are sent to the screen. But with many different timezones and everything happening on the world wide dub dub dub all over the world at all hours, internally to my python code, I might want to always store and calculate the time in one single standard timezone, only converting as the last step to display it to a local user.

To get the current universal time, naive and aware;

utcNaiveVariable = datetime.datetime.utcnow()
utcAwareVariable = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)

Curling, just not Canadian Style Python 2.6.6 and the urllib2 library

In bash, getting a web page

curl http://web-atlanta.com/ >html.html

The bash curl command has nothing to do with Canadian Curling, which is like shuffleboard on ice amidst the tension garnered tolerating a joke about the Queen or the national health care system from a surfboard riding processed cheese eating upper Mexican from south of the barbarian line. In bash, curl is short for client url, a simple http request of a web address.

In Python

x = urllib2.urlopen("http://web-atlanta.com")
w = x.read()

And as a part of a class init

  def __init__(self,TableName,filename,url):
    self.sqhandle=sqlite3.connect(filename) # empty if noexist
    self.sq1cursor = self.sqhandle.cursor()
    self.filename = filename
    try:
      self.sq1cursor.execute('''CREATE TABLE '''
         +TableName+''' (somenum real, somestring text)''')
      self.sqhandle.commit()
    except:
      print TableName,"table already exists"
    self.samples = 0
    x = urllib2.urlopen(url)
    self.pagedata = x.read()

So if we instantiate a class we now have the html as classname.pagedata and sqlite3 handle and cursor as classname.sqhandle and sq1cursor

We need to do some things with sql like

    command = 'INSERT INTO '+table+' VALUES (' + x +', "'+ y +'")'
    try:
      classname.sq1cursor.execute(command)
      classname.sqhandle.commit()
    except:
      print command

sqlite3 insert a row

  def sqlinsert(sqhandle,sq1cursor,table,x,y):
    command = 'INSERT INTO '+table+' VALUES (' + x +', "'+ y +'")'
    try:
      sq1cursor.execute(command)
      sqhandle.commit()
    except:
      print "failed to ", command

Boto Python Amazon EC2

Amazon web services API for python, Boto 2.6.0, 2.9.5 and 2.9.6 for Python 2.7

 First, a sample boto python 2.7 script tested on Dreamhost with their installed boto 2.6 as well as boto 2.9.5 and 2.9.6 on Heroku. The Amazon keys are imported from our custom made cred2 module, which you will make yourself for your keys.

#!/usr/bin/python

import boto.ec2
import cred2

conn = boto.ec2.connect_to_region("us-east-1", \
    aws_access_key_id=cred2.awsaki(), aws_secret_access_key=cred2.awssak() )

# conn.start_instances('i-59999x2x')

reservations = conn.get_all_instances()
print reservations
for res in reservations:
  for isx in res.instances:
    print isx

 

substitute what the python 2.7 functions return with your keys

Your amazon keys can be found in your Amazon Web Services account

#!/usr/bin/python

def awsaki():
  return 'AKXXXXXXXXXXXXXXXXXX'

def awssak():
  return 'vvv999ccc888xxx777zzz666lll555kkk444z/'

We used awsaki which means Amazon Web Services Access Key ID or A.W.S.A.K.I. which is the best terminology to use in search engines to find information on digging this out of your account

Google this

Amazon Web Services Access Key ID

We used awssak which means Amazon Web Services Secret Access Key or A.W.S.S.A.K. which is good terminology to use in search engines to find information on digging this out of your account

Google this

Amazon Web Services Secret Access Key

 

Python 2.7 script to start an AWS instance that is stopped

#!/usr/bin/python

import boto.ec2
import cred2

conn = boto.ec2.connect_to_region("us-east-1", \
    aws_access_key_id=cred2.awsaki(), aws_secret_access_key=cred2.awssak() )

reservations = conn.get_all_instances()
rsx = reservations[0]
hsx = rsx.instances[0].start()

This works great if you have an AWS account with one instance, which is the one you want to start. So we aren’t creating an instance here, we are just starting an instance that has been stopped.

 

Now a minimal example in flask to pass boto results to the jinja template rendering modules

@app.route('/aws')
def awshm():
 x = zzcode.botoclass(); cvx = x.botofunc()
 return render_template('aws.html',navigation=navfunc(), contentVar=cvx )

 

Here we use boto in the class

class botoclass:
 def botofunc(self):
  import boto.ec2
  import credec2
  conn = boto.ec2.connect_to_region("us-east-1", \
    aws_access_key_id=credec2.awsaki(), aws_secret_access_key=credec2.awssak())
  reservations = conn.get_all_instances()
  cvx = list()
  for rsx in reservations:
   for isx in rsx.instances:
    cvx.append({'reservation': str(isx), 'status': str(isx.state), \
              'dns': str(isx.public_dns_name), 'ip': str(isx.ip_address) })
  return cvx

 

In the midst of a template in the templates directory named aws.html is this table

<TABLE>
<TR><TH>Reservation </TH><TH>Status </TH><TH>Domain </TH><TH>ip </TH></TR>
{% for item in contentVar %}
<TR>
 <TD>{{ item.reservation }}</TD>
 <TD>{{ item.status    }}</TD>
 <TD>{{ item.dns      }}</TD>
 <TD>{{ item.ip       }}</TD>
</TR>
{% endfor %}
              </TABLE>

 

Perl MySql Example

Perl with DBI, Perl Database access

 

#!/usr/bin/perl -w
#
#script to add up some table data

use DBI;
use CGI::Carp qw(fatalsToBrowser);

print “Content-type: text/html\n\n”;
my $dbh = DBI->connect(’dbi:mysql:database=DATABASE_NAME;host=localhost’, ‘USERNAME’, ‘PASSWORD’)
or die “Couldn’t connect to database: ” . DBI->errstr;

my ( $k, $id, $book_date, $svc_type, $cust_id, $time_pref, $a_sched,$a_eight);
my $t_date=”20080115″;

$sqlquery = qq( SELECT id, book_date, svc_type, cust_id, time_pref, FROM `orders` WHERE  `move_date` = $t_date );
$sth = $dbh->prepare ( $sqlquery );
$sth->execute() || die “Couldn’t execute query: ” . DBI->errstr;

$k = 0;
$sth->bind_columns( \$id, \$book_date, \$svc_type, \$cust_id, \$move_date, \$time_pref, \$est_men, \$est_trks );
while ( $sth->fetch() ) {
$a_sched  += 1;
if ( $time_pref eq “8-9A.M.” ) { $a_eight  +=1; }
}

#Now $a_sched contains the number of records $a_eight contains the number of 8-9A.M. record for that date.

atlanta custom database design   vehicle dispatch ERP

Windows Idle Python – two confusing screens

Using the two screens in python idle for windows and ubuntu

When using the Python Idle editor and run environment, users are sometimes confused with two completely separate windows, or get one window which interprets Python but does not allow them to save their work.

Python Shell Window

The primary Python screen is the Python shell. If that is your only window, you should select File->New Window.

Untitled (maybe)

This window is a seperate editor task. This is where you edit entire programs.

The Rhythm

For short little things, you can execute them in the shell. Try these and see if you get the same output.

x="123456"
print x

123456

print x.find('12'),x.find('23'),x.find('asdf')

0 1 -1

if x.find('23')>-1:
  print x.index('23')

1

Sprox form with Genshi

Make sure we have these;

pip install sprox
pip install genshi
pip install tw.forms

And we will be able to write a script to produce a form without getting too long.

from sqlalchemy import Column, Integer, String, create_engine, Date, Float, Text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sprox.formbase import AddRecordForm, FormBase
from sprox.fillerbase import TableFiller
from sprox.tablebase import TableBase

# coding: utf-8

Base = declarative_base()
metadata = Base.metadata


class Customer(Base):
    __tablename__ = 'customer'

    id = Column(Integer, primary_key=True)
    customer = Column(String(6), nullable=False, unique=True)
    name = Column(String(40), nullable=False)
    zip = Column(String(255), nullable=False)
    phone1 = Column(String(31), nullable=False)

class newCustomerForm(FormBase):
    __model__ = Customer

class DBSession1():
    def __init__(self):
        dbhost = "x"
        dbuser = "x"
        dbpass = "x"
        dbdbas = "x"
        self.engine1= create_engine('mysql://' + dbuser + ":" + dbpass + "@" + dbhost + "/" + dbdbas)
        self.Base1 = declarative_base()
        self.Session1 = sessionmaker(bind=self.engine1)
        return None


if __name__ == "__main__":
    w = DBSession1()
    x = newCustomerForm(w.Session1)
    print x()

This should produce html to enter fields that can be the centerpiece of a template or fetched with javascript and placed in a div. We still have not populated the form with data for updating, but this will do for a create. We also have explicitly defined the model, and we really want to do that on the fly.

What is Genshi and why did it pop up?

This might actually be a weakness of the Sprox packages, but Sprox really likes Genshi to make that final push from a Python data structure to HTML code. I call it a weakness, but this final transition is the realm of a template architecture. Popular Python templating specifications include Jinja2, Chameleon(Zope), Mako, etc. The weakness here is that it really likes Genshi, and it is not obvious how to use, for example, Mako instead.

Python SQLAlchemy MySql Columns

Lets switch to SqlAlchemy to get columns

#!/bin/python27

from sqlalchemy import create_engine, Table
from sqlalchemy.orm import scoped_session,sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import sqlite3

class DBSession1():
    def __init__(self):
        dbhost = "x"
        dbuser = "x"
        dbpass = "x"
        dbdbas = "x"
        self.engine1= create_engine('mysql://' + dbuser + ":" + dbpass + "@" + dbhost + "/" + dbdbas)
        self.Base1 = declarative_base()
        return None

if __name__=="__main__":

    x = DBSession1()
    customers = Table('customer', x.Base1.metadata, autoload=True, autoload_with=x.engine1)
    print customers.columns

Once again, we get a list of columns.You will need to put your MySql database credential in for this to work, often times the host is localhost.

Here is a loop to look at even more information on the database columns. You can tack this onto the end of the code segment above.

    for col in customers.columns:
        print col.name,col.type,col.nullable,col.primary_key,col.foreign_keys