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

What is ERP

Enterprise Resource Planning

Accounting and Operations

Bookkeeping, but more comprehensive

 

ERP = Enterprise Resource Planning. A comprehensive suite of applications to manage planning and operational functions requiring massive information processing in the business environment

MSInc fills a broad set of IS and IT needs from network support for small businesses with Quickbooks™, Peachtree™, or MS200/500™ accounting modules, as well as customized solutions. We provide network planning, tuning, and connectivity as well as email, web design, PC repair, PC support, and custom MySQL customer service databases. We also provide our own ERP Solution using Thoroughbred™, PVX™, and Basis BBX™ BB8 based accounting and operations systems. Our solutions support a full ERP backbone for manufacturing clients with up to 500 employees. For SaaS or “Software as a Service”, see our new Vehicle Dispatch system, available in lease and purchase license forms. Our lease model leads the way in SOA, or Service Oriented Architecture. Also available for standardized and custom ERP, MRP, CRM, and Financials models in fully normalized designs. Because of our breadth of services, from highly secure financial information, to password accessible customer service portals, through to highly visible and optimized web-sites, we are highly skilled at managing the various security requirements of your company.

Outsourcing, Eastern metro Atlanta. Small and Medium Sized Business.

Drupal, Joomla and WordPress

blogging and more powerful user definable website software, php and apache based cms

 

Drupal addin features, links at the end of each blurb will take you to the drupal project page

FileField helps with CMS applications requiring a great deal of files and robust file management. FileField also has a file manager API. filefield

WYSIWYG – improved ‘What you see is what you get’ editor

Drupal allows text and html editing, probably with the tinyMCE library, but WYSIWYG allows you to integrate your preferred editor, e.g. TinyMCE, YUI, CKEditor, FCKeditor, jWysiwyg, markItUp, NicEdit, openWYSIWYG, Whizzywig, or WYMeditor. wysiwyg

Webform – contact form, survey, poll, etc.

Webform allows you to quickly create a form, and can save the submission in a database table. webform

Google Analytics

If you have not installed Google Analytics on a website, you have been missing out on a robust and simple tracking tool that shows charts, emails reports, even analyses keywords used to find nodes on the drupal site. A simple plugin would only need the UA code for basic functionality. google_analytics

Ubercart – shopping cart, ecommerce

For Drupal, Ubercart was developed for usability, and can handle shippable real goods, music downloads, software downloads, memberships or subscriptions. The extension purports to offer integrated order processing including payment and shipping processes. wow! ubercart

Drupal is a CMS, or Content Management System, is open source, runs on LAMP and offers newbies the ability to quickly post their content on the internet without the constraint and boredom of wordpress.

Purchase Price Variance

Standard costing techniques in ERP

 

In absorption accounting, the measurement of the inflation or deflation of prices on raw material is measured with purchase price variance. A unit of raw material is assigned a standard cost for the year and the variation in landed cost for deliveries is tracked not with a complicated scheme of tracking on a lifo or fifo basis where each molecule of raw material can be allocated to a product that reaches the consumer, but a standard periodic cost is assigned to a unit of purchased goods. For example, if we choose to fix the cost of a #8-32 1/2″ Stainless round slotted head machine screw at $.15 for the year, the portion of the final cost of a product that uses this purchased item need not change just because the landed price for one million screws that week was $.149900 each.

We freeze the standard cost for the screw at $.15 and book a purchase price variance, favorable, of a hundred bucks. The mechanics require an accounting discipline and business logic in the purchasing and accounts payable departments of recording the landed price vs the standard. When an invoice is received from a vendor on the raw material account, the first thing we want to ascertain is that the material was received and that our vendor deserves to be paid for goods that were delivered and accepted for inventory. This means that a given purchase order receipt, which was a debit to inventory on hand for a given part number should be matched up with the invoice. This receipt is marked then as paid and the accounts payable can be processed with no shoe leather put to waste by either the purchasing or accounting departments.

A register of vouchers accepted for a given day then can be generated with the landed cost put against the standard cost to determine the favorable or unfavorable purchase price variance for raw material acquisition.

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