code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponse, Http404
from django.contrib.auth.models import User
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from django.shortcuts import render_to_response
from forfood.restaurant.models import *
from forfood.menu.models import *
from forfood.helpers.user_helper import *
from forfood.order.models import *
from forfood.menu.models import MenuItem
from time import time
def create_order(request):
# if 'menu_item_num' in request.GET and 'menu_item_id' not in request.GET:
# return HttpResponse('The item does not exist!')
# elif 'menu_item_num' not in request.GET and 'menu_item_id' in request.GET:
# return HttpResponse('The menu item num does not exist!')
# elif 'menu_item_num' not in request.GET and 'menu_item_id' not in request.GET:
# return HttpResponse('The menu item and menu item num do not exist!')
# else:
# return HttpResponse('The item does not exist!')
if request.method == 'POST':
customer = find_customer(request.user)
if not customer:
raise Http404
restaurant = find_restaurant_by_id(request.POST['restaurant_id'])
if not restaurant:
raise Http404
d = request.POST
if len(d.keys()) <= 2:
print "xxx"
raise Http404
order = Order.objects.create(customer=customer, restaurant=restaurant)
count = 0
total = 0
for k in d.keys():
try:
k_int = int(k)
except:
continue
menu_item = MenuItem.objects.get(id=k_int)
order_item = OrderItem.objects.create(order=order, item=menu_item, count=d[k])
count = count + 1
total = total + menu_item.price
#order.orderitem_set.add(order_item)
#order.save()
return HttpResponseRedirect('/order/%d/'%order.id)
else:
raise Http404
def orders_page(request):
customer = find_customer(request.user)
if not customer:
raise Http404
return render_to_response('order/all.html', RequestContext(request,locals()))
def order_page(request, oid):
try:
order = Order.objects.get(id = oid)
except:
raise Http404
customer = find_customer(request.user)
if not customer:
raise Http404
if order.customer != customer:
raise Http404
if request.method == 'POST':
order.status = 1
order.c_confirm_time = int(time())
order.save()
pass
return render_to_response('order/main.html', RequestContext(request,locals()))
def change_order_status(request, oid):
try:
order = Order.objects.get(id = oid)
except:
raise Http404
restaurant = find_restaurant(request.user)
if order.restaurant != restaurant:
raise Http404
if order.status > 3:
raise Http404
order.status = order.status + 1
order.save()
order.set_time_by_status()
return HttpResponse("success")
def undo_change_order_status(request, oid):
try:
order = Order.objects.get(id = oid)
except:
raise Http404
restaurant = find_restaurant(request.user)
if order.restaurant != restaurant:
raise Http404
if order.status < 2:
raise Http404
order.status = order.status - 1
order.save()
return HttpResponse("success") | Python |
#!/usr/bin/python
import random
import time
import os
import yaml
class RandomVerse:
menu_options = ["",'Verse', "Add Verse", "Delete Verse"]
verse_list = {}
def __init__(self):
print ""
print ""
print "Welcome to a random verse generator!"
time.sleep(1)
def LoadVerses():
try:
with open("verse_list.yml", "r") as f:
self.verse_list = yaml.load(f.read())
print "Your verses have been loaded!"
except:
self.verse_list = {'John':{'3':{'16':"For God so loved the world,\
that he gave his only Son, that whoever believes in him\
should not perish but have eternal life.", 'notes':""}}}
def SaveVerses():
with open("verse_list.yml", "w") as f:
yaml.dump(self.verse_list, f)
f.close()
print "Your verses have been saved!"
print " See you 'round!"
def OpeningMenu():
"""The opening menu for the program, providing options for the user to choose
to use features."""
print ""
print "What would you like to see?"
for idx,option in enumerate(self.menu_options):
if idx == 0:
pass
else:
print str(idx)+": "+option
option = raw_input("> ")
if option == "1" or option == 'Verse':
print "Which book would you like to open?"
book = raw_input(": ").lower
print "Which chapter is this verse in?"
chapter = raw_input(": ").lower
print "What verse would you like displayed?"
print "(If you would like every verse for this chapter, press enter.)"
verse = raw_input(": ").lower
VerseLookup(book, chapter, verse)
def VerseLookup(book, chapter, verse):
book_list = []
chapter_list = []
verse_list = []
for passage in self.verse_list.keys():
print passage
book_list.append(passage)
if book not in book_list:
print "That book has no entries!"
OpeningMenu()
time.sleep(1)
else:
for passage in self.verse_list[book].keys():
chapter_list.append(passage)
if chapter not in chapter_list:
print "That chapter has no entries!"
time.sleep(1)
OpeningMenu()
else:
for passage in self.verse_list[book][chapter].keys():
verse_list.append(passage)
if verse not in verse_list:
print "That verse does not seem to have been entered."
time.sleep(1)
OpeningMenu()
else:
print self.verse_list[book][chapter][verse]
LoadVerses()
OpeningMenu()
SaveVerses()
if __name__ == "__main__":
RandomVerse()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of FORTAX Calculator;
# (c) 2009 Andrew Shephard; andrubuntu@gmail.com
#
# FORTAX Calculator is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
# FORTAX Calculator is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
# You should have received a copy of the GNU General Public License along
# with FORTAX Calculator. If not, see <http://www.gnu.org/licenses/>.
import sys
import os
import csv
import string
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from returnbudcon import *
#UIgrid is user interface produced with QtDesigner, myTable defines a table class
from UIgrid import *
from myTable import *
#resources file
import resources
class myMainWindow(QMainWindow):
""" modify the mainwindow class so it emits a signal when resized
"""
def resizeEvent(self,event):
self.emit(SIGNAL("signalResize()"))
class StartQT4(myMainWindow): #QMainWindow
def __init__(self, *args):
myMainWindow.__init__(self, *args)
#main interface setup
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
#icon
icon = QIcon(':/icons/icon.png')
self.setWindowIcon(icon)
#initialize some variables
self.numkids = 0
self.numsys = 0
self.doHours = True
self.headersKinks=["Hours", "Earnings", "Income", "Rate"]
self.dir = os.path.dirname(sys.executable)
self.dir = os.getcwd()
self.resdir = os.path.join(self.dir,'resources')
self.sysDir = os.path.join(self.resdir,'systems')
self.savdir = self.dir
if os.path.isdir(self.sysDir):
self.ui.lineSysDir.setText(self.sysDir)
self.sysList()
self.ui.gridLayout_2.removeWidget(self.ui.tabKinks)
self.ui.tabKinks.setParent(None)
del self.ui.tabKinks
self.ui.tabKinks = QTabWidget(self.ui.centralwidget)
self.ui.tabKinks.setObjectName("tabKinks")
self.ui.gridLayout_2.addWidget(self.ui.tabKinks, 0, 1, 2, 1)
thispage=QWidget()
gridLayout = QVBoxLayout()
tableKinks = myTableKinks(self.ui.tabKinks)
figButton = QPushButton(self.ui.tabKinks)
copyButton = QPushButton(self.ui.tabKinks)
saveButton = QPushButton(self.ui.tabKinks)
figButton.setText("Figure")
copyButton.setText("Copy")
saveButton.setText("Save")
tableKinks.setObjectName('tableKinks0')
tableKinks.horizontalHeader().setVisible(True)
tableKinks.verticalHeader().setVisible(False)
tableKinks.setHorizontalHeaderLabels(self.headersKinks)
gridLayout.addWidget(tableKinks)
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(figButton)
hbox.addWidget(copyButton)
hbox.addWidget(saveButton)
gridLayout.addLayout(hbox)
thispage.setLayout(gridLayout)
self.ui.tabKinks.addTab(thispage,'System')
self.ui.pushHideShowIncomes.setText("Show incomes")
self.ui.pushHideShowKinks.setText("Show kinks")
self.ui.pushHideShowSettings.setText("Show settings")
showHidewidth = 0
showHidewidth = max(showHidewidth,self.ui.pushHideShowIncomes.width())
showHidewidth = max(showHidewidth,self.ui.pushHideShowKinks.width())
showHidewidth = max(showHidewidth,self.ui.pushHideShowSettings.width())
self.ui.pushHideShowIncomes.setText("Hide incomes")
self.ui.pushHideShowKinks.setText("Hide kinks")
self.ui.pushHideShowSettings.setText("Hide settings")
showHidewidth = max(showHidewidth,self.ui.pushHideShowIncomes.width())
showHidewidth = max(showHidewidth,self.ui.pushHideShowKinks.width())
showHidewidth = max(showHidewidth,self.ui.pushHideShowSettings.width())
self.ui.pushHideShowIncomes.setMinimumWidth(showHidewidth)
self.ui.pushHideShowKinks.setMinimumWidth(showHidewidth)
self.ui.pushHideShowSettings.setMinimumWidth(showHidewidth)
self.ui.tabIncome.setTabEnabled(2,False)
self.ui.tableIncomes = myTable(self.ui.tabIncomesFamily)
self.ui.tabKinks.setEnabled(False)
self.ui.gridLayoutIncomes.addWidget(self.ui.tableIncomes)
self.ui.tableIncomes.setObjectName("tableIncomes")
self.ui.tableIncomes.horizontalHeader().setVisible(False)
self.ui.tableIncomeAd1 = myTable(self.ui.tabIncomesAd1)
self.ui.gridLayoutIncomeAd1.addWidget(self.ui.tableIncomeAd1)
self.ui.tableIncomeAd1.setObjectName("tableIncomeAd1")
self.ui.tableIncomeAd1.horizontalHeader().setVisible(False)
self.ui.tableIncomeAd2 = myTable(self.ui.tabIncomesAd2)
self.ui.gridLayoutIncomeAd2.addWidget(self.ui.tableIncomeAd2)
self.ui.tableIncomeAd2.setObjectName("tableIncomeAd2")
self.ui.tableIncomeAd2.horizontalHeader().setVisible(False)
#define some actions
self.connect(self.ui.addKid, SIGNAL('clicked()'), self.addKidAction)
self.connect(self.ui.removeKid, SIGNAL('clicked()'), self.removeKidAction)
self.connect(self.ui.checkCouple,SIGNAL('clicked()'), self.coupleAction)
self.connect(self.ui.toolSysBrowse,SIGNAL('clicked()'), self.sysBrowse)
self.connect(self.ui.lineSysDir,SIGNAL('returnPressed()'), self.sysList)
self.connect(self.ui.lineSysDir,SIGNAL('editingFinished()'), self.sysList)
self.connect(self.ui.pushFortax,SIGNAL('clicked()'), self.calc)
self.connect(self.ui.pushCopyIncomes,SIGNAL('clicked()'), self.ui.tableIncomes.copyTable)
self.connect(self.ui.pushSaveIncomes,SIGNAL('clicked()'), self.ui.tableIncomes.saveTable)
self.connect(self.ui.pushCopyIncomeAd1,SIGNAL('clicked()'), self.ui.tableIncomeAd1.copyTable)
self.connect(self.ui.pushSaveIncomeAd1,SIGNAL('clicked()'), self.ui.tableIncomeAd1.saveTable)
self.connect(self.ui.pushCopyIncomeAd2,SIGNAL('clicked()'), self.ui.tableIncomeAd2.copyTable)
self.connect(self.ui.pushSaveIncomeAd2,SIGNAL('clicked()'), self.ui.tableIncomeAd2.saveTable)
self.connect(self.ui.checkPriceDate,SIGNAL('clicked()'), self.checkDateAction)
self.connect(self.ui.radioHoursBc,SIGNAL('clicked()'), self.bcModeAction)
self.connect(self.ui.radioEarnBc,SIGNAL('clicked()'), self.bcModeAction)
self.connect(self.ui.pushHideShowSettings,SIGNAL('clicked()'), self.hideShowSettings)
self.connect(self.ui.pushHideShowKinks,SIGNAL('clicked()'), self.hideShowKinks)
self.connect(self.ui.pushHideShowIncomes,SIGNAL('clicked()'), self.hideShowIncomes)
self.connect(self,SIGNAL('signalResize()'), self.adjustAllColumns)
self.connect(self.ui.tabKinks,SIGNAL('currentChanged(QWidget *)'), self.adjustAllColumns)
self.connect(self.ui.pushFigures,SIGNAL('clicked()'), self.allFigures)
#define shortcut keys
shortcutCalc = QShortcut(self)
shortcutCalc.setKey("Ctrl+Return")
self.connect(shortcutCalc,SIGNAL('activated()'), self.calc)
shortcutSettingsPanel = QShortcut(self)
shortcutSettingsPanel.setKey("Ctrl+1")
self.connect(shortcutSettingsPanel,SIGNAL('activated()'), self.hideShowSettings)
shortcutKinksPanel = QShortcut(self)
shortcutKinksPanel.setKey("Ctrl+2")
self.connect(shortcutKinksPanel,SIGNAL('activated()'), self.hideShowKinks)
shortcutIncomesPanel = QShortcut(self)
shortcutIncomesPanel.setKey("Ctrl+3")
self.connect(shortcutIncomesPanel,SIGNAL('activated()'), self.hideShowIncomes)
self.taxFile = os.path.join(self.resdir,'taxlist.csv')
if not os.path.isfile(self.taxFile):
self.ui.comboTaxOut.setEnabled(False)
else:
reader = csv.reader(open(self.taxFile, "rb"))
self.taxLongName = []
self.taxLongNameAd = []
self.taxShortName = []
self.taxLevel = []
for row in reader:
self.taxLongName.append(row[0])
self.taxShortName.append(row[1])
self.taxLevel.append(row[2])
if row[2]=='ad1':
self.taxLongNameAd.append('Adult 1: '+row[0])
elif row[2]=='ad2':
self.taxLongNameAd.append('Adult 2: '+row[0])
else:
self.taxLongNameAd.append(row[0])
self.taxNum = len(self.taxLevel)
self.ui.comboTaxOut.clear()
self.ui.comboTaxOut.addItems(self.taxLongNameAd)
ind = self.ui.comboTaxOut.findText("Disposable Income")
if ind>=0:
self.ui.comboTaxOut.setCurrentIndex(ind)
self.rpiFile = os.path.join(self.resdir,'rpi.csv')
if not os.path.isfile(self.rpiFile):
self.ui.checkPriceDate.setEnabled(False)
else:
reader = csv.reader(open(self.rpiFile, "rb"), delimiter=',', quoting=csv.QUOTE_NONE)
reader.next() #skip header
self.priceDate = []
self.priceIndex = []
for row in reader:
self.priceDate.append(int(row[0]))
self.priceIndex.append(float(row[1]))
self.priceNum = len(self.priceDate)
date = QDate.fromString(QString(str(self.priceDate[0])),"yyyyMMdd")
self.ui.datePriceDate.setMinimumDate(date)
date = QDate.fromString(QString(str(self.priceDate[self.priceNum-1])),"yyyyMMdd")
self.ui.datePriceDate.setMaximumDate(date)
self.ui.datePriceDate.setDate(date)
self.bcModeAction()
self.coupleAction()
def allFigures(self):
""" plot budget constraints for all active systems
"""
if self.doHours:
columnX = 0; columnY = 2
pound = u"\u00A3" #pound
labelX = 'Hours per week'
labelY = self.incomeComponent
titleString = 'Budget constraint, fixed ' + pound + string.strip(format(self.wageOrHours,"7.2f")) + ' hourly wage'
else:
columnX = 1; columnY = 2
labelX = 'Earnings, pounds per week'
labelY = self.incomeComponent
titleString = 'Budget constraint, fixed at ' + string.strip(format(self.wageOrHours,"7.0f")) + ' hours'
dataX = []
dataY = []
leg = []
for s in range(self.numsys):
objname = QString("tableKinks"+str(s))
tableKinks = self.ui.tabKinks.findChild(myTableKinks,objname)
if tableKinks:
dataX.append(array(tableKinks.tableData[:,columnX]))
dataY.append(array(tableKinks.tableData[:,columnY]))
leg.append(tableKinks.tableName)
aw = figureWindow(dataX=dataX,dataY=dataY,
labelLegend=leg,labelX=labelX,labelY=labelY,
labelTitle=titleString,sourceNote=self.source)
aw.exec_()
def adjustAllColumns(self):
""" if adjust all column sizes
"""
if self.ui.tabKinks.isVisible():
for s in range(self.numsys):
objname = QString("tableKinks"+str(s))
tableKinks = self.ui.tabKinks.findChild(myTableKinks,objname)
if tableKinks:
tableKinks.adjustColumnSizes()
if self.ui.tableIncomes.isVisible():
self.ui.tableIncomes.adjustColumnSizes()
if self.ui.tableIncomeAd1.isVisible():
self.ui.tableIncomeAd1.adjustColumnSizes()
if self.ui.tableIncomeAd2.isVisible():
self.ui.tableIncomeAd2.adjustColumnSizes()
def hideShowIncomes(self):
""" hide/show incomes panel
"""
if (not self.ui.tabSettings.isVisible()) and (not self.ui.tabKinks.isVisible()):
return
if self.ui.tabIncome.isVisible():
self.ui.tabIncome.setVisible(False)
self.ui.pushHideShowIncomes.setText("Show incomes")
if not self.ui.tabKinks.isVisible():
self.ui.pushHideShowSettings.setEnabled(False)
if not self.ui.tabSettings.isVisible():
self.ui.pushHideShowKinks.setEnabled(False)
else:
self.ui.tabIncome.setVisible(True)
self.ui.pushHideShowIncomes.setText("Hide incomes")
self.ui.pushHideShowIncomes.setMinimumWidth(100)
self.ui.pushHideShowIncomes.setEnabled(True)
self.ui.pushHideShowKinks.setEnabled(True)
self.ui.pushHideShowSettings.setEnabled(True)
self.adjustAllColumns()
def hideShowSettings(self):
""" hide/show settings panel
"""
if (not self.ui.tabIncome.isVisible()) and (not self.ui.tabKinks.isVisible()):
return
if self.ui.tabSettings.isVisible():
self.ui.tabSettings.setVisible(False)
self.ui.pushHideShowSettings.setText("Show settings")
if not self.ui.tabKinks.isVisible():
self.ui.pushHideShowIncomes.setEnabled(False)
if not self.ui.tabIncome.isVisible():
self.ui.pushHideShowKinks.setEnabled(False)
else:
self.ui.tabSettings.setVisible(True)
self.ui.pushHideShowSettings.setText("Hide settings")
self.ui.pushHideShowIncomes.setEnabled(True)
self.ui.pushHideShowKinks.setEnabled(True)
self.ui.pushHideShowSettings.setEnabled(True)
self.adjustAllColumns()
def hideShowKinks(self):
""" hide/show kinks panel
"""
if (not self.ui.tabSettings.isVisible()) and (not self.ui.tabIncome.isVisible()):
return
if self.ui.tabKinks.isVisible():
self.ui.tabKinks.setVisible(False)
self.ui.pushHideShowKinks.setText("Show kinks")
if not self.ui.tabSettings.isVisible():
self.ui.pushHideShowIncomes.setEnabled(False)
if not self.ui.tabIncome.isVisible():
self.ui.pushHideShowSettings.setEnabled(False)
else:
self.ui.tabKinks.setVisible(True)
self.ui.pushHideShowKinks.setText("Hide kinks")
self.ui.pushHideShowIncomes.setEnabled(True)
self.ui.pushHideShowKinks.setEnabled(True)
self.ui.pushHideShowSettings.setEnabled(True)
self.adjustAllColumns()
def bcModeAction(self):
""" change visibility depending on whether earnings/hours kinks
"""
if self.ui.radioHoursBc.isChecked():
self.ui.labelEarnHours.setEnabled(False)
self.ui.doubleSpinEarnHours.setEnabled(False)
self.ui.labelEarnStart.setEnabled(False)
self.ui.doubleSpinEarnStart.setEnabled(False)
self.ui.labelEarnEnd.setEnabled(False)
self.ui.doubleSpinEarnEnd.setEnabled(False)
self.ui.labelWage.setEnabled(True)
self.ui.doubleSpinWage.setEnabled(True)
self.ui.labelHoursStart.setEnabled(True)
self.ui.doubleSpinHoursStart.setEnabled(True)
self.ui.labelHoursEnd.setEnabled(True)
self.ui.doubleSpinHoursEnd.setEnabled(True)
else:
self.ui.labelEarnHours.setEnabled(True)
self.ui.doubleSpinEarnHours.setEnabled(True)
self.ui.labelEarnStart.setEnabled(True)
self.ui.doubleSpinEarnStart.setEnabled(True)
self.ui.labelEarnEnd.setEnabled(True)
self.ui.doubleSpinEarnEnd.setEnabled(True)
self.ui.labelWage.setEnabled(False)
self.ui.doubleSpinWage.setEnabled(False)
self.ui.labelHoursStart.setEnabled(False)
self.ui.doubleSpinHoursStart.setEnabled(False)
self.ui.labelHoursEnd.setEnabled(False)
self.ui.doubleSpinHoursEnd.setEnabled(False)
def checkDateAction(self):
""" if using uprating date change cal visibility
"""
if self.ui.checkPriceDate.isChecked():
self.ui.labelPriceDate.setEnabled(True)
self.ui.datePriceDate.setEnabled(True)
else:
self.ui.labelPriceDate.setEnabled(False)
self.ui.datePriceDate.setEnabled(False)
def calc(self):
""" performs calculations, calls FORTAX
"""
nosys = False
#is system okay?
if self.ui.listSysFiles.currentRow()<0:
nosys = True
else:
selsys = self.ui.listSysFiles.selectedItems()
self.numsys = 0
sysname = []
sysnameNoExt = []
for thissys in selsys:
sysname.append(str(thissys.text()))
sysnameNoExt.append(os.path.splitext(str(thissys.text()))[0])
self.numsys+=1
if nosys:
reply = QMessageBox.warning(self, 'FORTAX: Error',
"No system is selected", QMessageBox.Ok)
return
#check ranges of hours/earnings
if self.ui.radioHoursBc.isChecked():
self.wageOrHours = self.ui.doubleSpinWage.value()
range0 = self.ui.doubleSpinHoursStart.value()
range1 = self.ui.doubleSpinHoursEnd.value()
if range0>range1:
reply = QMessageBox.warning(self, 'FORTAX: Error',
"End hours must be larger than start hours", QMessageBox.Ok)
return
else:
self.wageOrHours = self.ui.doubleSpinEarnHours.value()
range0 = self.ui.doubleSpinEarnStart.value()
range1 = self.ui.doubleSpinEarnEnd.value()
if range0>range1:
reply = QMessageBox.warning(self, 'FORTAX: Error',
"End earn must be larger than start earn", QMessageBox.Ok)
return
#hours or earnings kinks?
if self.ui.radioHoursBc.isChecked():
self.doHours = True
else:
self.doHours = False
adult = self.ui.comboAdult.currentIndex()+1
couple = self.ui.checkCouple.isChecked()
married = self.ui.checkMarried.isChecked()
age1 = self.ui.spinAge1.value()
age2 = self.ui.spinAge2.value()
wage1 = self.ui.doubleSpinWage1.value()
wage2 = self.ui.doubleSpinWage2.value()
hours1 = self.ui.doubleSpinHrs1.value()
hours2 = self.ui.doubleSpinHrs2.value()
selfemp1 = self.ui.checkSelfEmp1.isChecked()
selfemp2 = self.ui.checkSelfEmp2.isChecked()
tenure = self.ui.comboTenure.currentIndex()+1
rent = self.ui.doubleSpinRent.value()
ctband = self.ui.comboCouncilTax.currentIndex()+1
banddratio = self.ui.doubleSpinBandD.value()
childcare = self.ui.doubleSpinChildcare.value()
maintenance = self.ui.doubleSpinMaintenance.value()
self.ui.pushFigures.setEnabled(True)
if couple:
self.ui.tabIncome.setTabEnabled(2,True)
else:
self.ui.tabIncome.setTabEnabled(2,False)
setprice = self.ui.checkPriceDate.isChecked()
if (setprice):
pricetarget = int(QDate.toString(self.ui.datePriceDate.date(),"yyyyMMdd"))
self.source = "Source: User calculation using FORTAX. Incomes expressed in" + QDate.toString(self.ui.datePriceDate.date()," MMMM yyyy ") + "prices."
else:
pricetarget = 0
self.source = "Source: User calculation using FORTAX. Incomes expressed in nominal prices."
kids = zeros(max(self.numkids,1),int)
if self.numkids>0:
kids[0] = self.ui.kid1.value()
if self.numkids>1:
kids[1] = self.ui.kid2.value()
if self.numkids>2:
kids[2] = self.ui.kid3.value()
if self.numkids>3:
kids[3] = self.ui.kid4.value()
if self.numkids>4:
kids[4] = self.ui.kid5.value()
if self.numkids>5:
kids[5] = self.ui.kid6.value()
if self.numkids>6:
kids[6] = self.ui.kid7.value()
if self.numkids>7:
kids[7] = self.ui.kid8.value()
if self.numkids>8:
kids[8] = self.ui.kid9.value()
if self.numkids>9:
kids[9] = self.ui.kid10.value()
taxout = self.taxShortName[self.ui.comboTaxOut.currentIndex()]
taxlevel = self.taxLevel[self.ui.comboTaxOut.currentIndex()]
self.incomeComponent = self.taxLongName[self.ui.comboTaxOut.currentIndex()]
#convert system list to csv
sysnamecsv = ','.join([str(i) for i in sysname])
#call fortax to calculate incomes and budget constraints
ret = returnbudcon(self.wageOrHours,range0,range1,self.doHours,self.sysDir,self.numsys,sysnamecsv,
taxout,taxlevel,adult,couple,married,
age1,wage1,hours1,selfemp1,age2,wage2,hours2,selfemp2,
self.numkids,kids,tenure,rent,ctband,banddratio,childcare,maintenance,
setprice,pricetarget,self.priceDate,self.priceIndex,self.priceNum)
#detailed incomes
headers0=[]; headers1=[]; headers2=[]
m0=0; m1=0; m2=0
list0=[]; list1=[]; list2=[]
#ret 0, kinks_hrs
#ret 1, kinks_earn
#ret 2, kinks_net
#ret 3, kinks_mtr
#ret 4, kinks_num
#ret 5, netoutLevel
#ret 6, netoutName
#ret 7, netoutAmt
#ret 8 netoutNum
data0 = zeros((ret[8],self.numsys),float)
data1 = zeros((ret[8],self.numsys),float)
data2 = zeros((ret[8],self.numsys),float)
#note: only amt differs by system
for item in range(ret[8]):
if any(ret[7][item])<>0:
shortName = string.strip(ndarray.tostring(ret[6][item]))
taxLevel = string.strip(ndarray.tostring(ret[5][item]))
nameIndex = -1
for name in range(self.taxNum):
if self.taxLevel[name]==taxLevel and self.taxShortName[name]==shortName:
nameIndex = name
break
if taxLevel=='tu':
if nameIndex>=0:
headers0.append(self.taxLongName[nameIndex])
data0[m0]=ret[7][item]
m0+=1
elif taxLevel=='ad1':
if nameIndex>=0:
headers1.append(self.taxLongName[nameIndex])
data1[m1]=ret[7][item]
m1+=1
elif taxLevel=='ad2':
if nameIndex>=0:
headers2.append(self.taxLongName[nameIndex])
data2[m2]=ret[7][item]
m2+=1
if m0>0:
self.ui.tableIncomes.setData(data0[0:m0],cellFormat="7.2f",readOnly=True)
self.ui.tableIncomes.setHorizontalHeaderLabels(sysnameNoExt)
self.ui.tableIncomes.horizontalHeader().setVisible(True)
self.ui.tableIncomes.setVerticalHeaderLabels(headers0)
self.ui.tableIncomes.adjustColumnSizes()
self.ui.pushCopyIncomes.setEnabled(True)
self.ui.pushSaveIncomes.setEnabled(True)
else:
self.ui.tableIncomes.reset()
self.ui.pushCopyIncomes.setEnabled(False)
self.ui.pushSaveIncomes.setEnabled(False)
if m1>0:
self.ui.labelAd1NotWorking.setVisible(False)
self.ui.tableIncomeAd1.setData(data1[0:m1],cellFormat="7.2f",readOnly=True)
self.ui.tableIncomeAd1.setHorizontalHeaderLabels(sysnameNoExt)
self.ui.tableIncomeAd1.horizontalHeader().setVisible(True)
self.ui.tableIncomeAd1.setVerticalHeaderLabels(headers1)
self.ui.tableIncomeAd1.adjustColumnSizes()
self.ui.pushCopyIncomeAd1.setEnabled(True)
self.ui.pushSaveIncomeAd1.setEnabled(True)
else:
self.ui.tableIncomeAd1.reset()
self.ui.labelAd1NotWorking.setVisible(True)
self.ui.pushCopyIncomeAd1.setEnabled(False)
self.ui.pushSaveIncomeAd1.setEnabled(False)
if m2>0:
self.ui.labelAd2NotWorking.setVisible(False)
self.ui.tableIncomeAd2.setData(data2[0:m2],cellFormat="7.2f",readOnly=True)
self.ui.tableIncomeAd2.setHorizontalHeaderLabels(sysnameNoExt)
self.ui.tableIncomeAd2.horizontalHeader().setVisible(True)
self.ui.tableIncomeAd2.setVerticalHeaderLabels(headers2)
self.ui.tableIncomeAd2.adjustColumnSizes()
self.ui.pushCopyIncomeAd2.setEnabled(True)
self.ui.pushSaveIncomeAd2.setEnabled(True)
else:
self.ui.labelAd2NotWorking.setVisible(True)
self.ui.tableIncomeAd2.reset()
self.ui.pushCopyIncomeAd2.setEnabled(False)
self.ui.pushSaveIncomeAd2.setEnabled(False)
#destroy kinks tab
self.ui.gridLayout_2.removeWidget(self.ui.tabKinks)
self.ui.tabKinks.setParent(None)
del self.ui.tabKinks
#create new kinks tab
self.ui.tabKinks = QTabWidget(self.ui.centralwidget)
self.ui.tabKinks.setObjectName("tabKinks")
self.ui.gridLayout_2.addWidget(self.ui.tabKinks, 0, 1, 2, 1)
self.ui.tabKinks.setEnabled(True)
#create blank page (will delete later)
thispage=QWidget()
self.ui.tabKinks.addTab(thispage,'blank')
for s in range(self.numsys):
numKinks = ret[4][s]
my_array = zeros([numKinks,4],float)
for i in range(numKinks):
my_array[i,0] = ret[0][i][s]
my_array[i,1] = ret[1][i][s]
my_array[i,2] = ret[2][i][s]
my_array[i,3] = ret[3][i][s]
thispage=QWidget()
gridLayout = QVBoxLayout()
tableKinks = myTableKinks(self.ui.tabKinks)
figButton = QPushButton(self.ui.tabKinks)
figButton.setText("Figure")
copyButton = QPushButton(self.ui.tabKinks)
copyButton.setText("Copy")
saveButton = QPushButton(self.ui.tabKinks)
saveButton.setText("Save")
figButton.setToolTip(QApplication.translate("MainWindow", "Show figure under "+sysnameNoExt[s]+" system",
None, QApplication.UnicodeUTF8))
copyButton.setToolTip(QApplication.translate("MainWindow", "Copy budget constraint under "+sysnameNoExt[s]+" system to clipboard",
None, QApplication.UnicodeUTF8))
saveButton.setToolTip(QApplication.translate("MainWindow", "Save budget constraint under "+sysnameNoExt[s]+" system as .csv file",
None, QApplication.UnicodeUTF8))
tableKinks.setObjectName('tableKinks'+str(s))
tableKinks.setData(my_array,cellFormat="7.2f",readOnly=True)
tableKinks.horizontalHeader().setVisible(True)
tableKinks.verticalHeader().setVisible(False)
tableKinks.setHorizontalHeaderLabels(self.headersKinks)
#extra stuff if used for plotting
tableKinks.setTableName(sysnameNoExt[s])
if self.doHours:
pound = u"\u00A3"
tableKinks.setFigureLabelY(self.incomeComponent)
tableKinks.setFigureLabelX('Hours per week')
titleString = 'Budget constraint, fixed ' + pound + string.strip(format(self.wageOrHours,"7.2f")) + ' hourly wage'
tableKinks.setFigureLabelTitle(titleString)
tableKinks.setFigureColumnX(0)
tableKinks.setFigureColumnY(2)
tableKinks.setSourceNote(self.source)
else:
tableKinks.setFigureLabelY(self.incomeComponent)
tableKinks.setFigureLabelX('Earnings, pounds per week')
titleString = 'Budget constraint, fixed at ' + string.strip(format(self.wageOrHours,"7.0f")) + ' hours'
tableKinks.setFigureLabelTitle(titleString)
tableKinks.setFigureColumnX(1)
tableKinks.setFigureColumnY(2)
tableKinks.setSourceNote(self.source)
gridLayout.addWidget(tableKinks)
#add buttons
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(figButton)
hbox.addWidget(copyButton)
hbox.addWidget(saveButton)
gridLayout.addLayout(hbox)
thispage.setLayout(gridLayout)
self.connect(figButton,SIGNAL('clicked()'), tableKinks.drawKinks)
self.connect(copyButton,SIGNAL('clicked()'), tableKinks.copyTable)
self.connect(saveButton,SIGNAL('clicked()'), tableKinks.saveTable)
self.ui.tabKinks.addTab(thispage,sysnameNoExt[s])
tableKinks.adjustColumnSizes()
self.ui.tabKinks.removeTab(0)
def toggleAdult2(self):
""" if adult added, change visibilty and update count
"""
if self.ui.checkCouple.isChecked():
self.ui.labelAdult2.setEnabled(True)
self.ui.age2lab.setEnabled(True)
self.ui.wage2lab.setEnabled(True)
self.ui.hrs2lab.setEnabled(True)
self.ui.spinAge2.setEnabled(True)
self.ui.doubleSpinWage2.setEnabled(True)
self.ui.doubleSpinHrs2.setEnabled(True)
self.ui.checkSelfEmp2.setEnabled(True)
else:
self.ui.labelAdult2.setEnabled(False)
self.ui.age2lab.setEnabled(False)
self.ui.wage2lab.setEnabled(False)
self.ui.hrs2lab.setEnabled(False)
self.ui.spinAge2.setEnabled(False)
self.ui.doubleSpinWage2.setEnabled(False)
self.ui.doubleSpinHrs2.setEnabled(False)
self.ui.checkSelfEmp2.setEnabled(False)
def addKidAction(self):
""" if child added, change visibilty and update count
"""
self.numkids = min(self.numkids+1,10)
if self.numkids==1:
self.ui.kid1.setEnabled(True)
self.ui.kid1lab.setEnabled(True)
elif self.numkids==2:
self.ui.kid2.setEnabled(True)
self.ui.kid2lab.setEnabled(True)
elif self.numkids==3:
self.ui.kid3.setEnabled(True)
self.ui.kid3lab.setEnabled(True)
elif self.numkids==4:
self.ui.kid4.setEnabled(True)
self.ui.kid4lab.setEnabled(True)
elif self.numkids==5:
self.ui.kid5.setEnabled(True)
self.ui.kid5lab.setEnabled(True)
elif self.numkids==6:
self.ui.kid6.setEnabled(True)
self.ui.kid6lab.setEnabled(True)
elif self.numkids==7:
self.ui.kid7.setEnabled(True)
self.ui.kid7lab.setEnabled(True)
elif self.numkids==8:
self.ui.kid8.setEnabled(True)
self.ui.kid8lab.setEnabled(True)
elif self.numkids==9:
self.ui.kid9.setEnabled(True)
self.ui.kid9lab.setEnabled(True)
elif self.numkids==10:
self.ui.kid10.setEnabled(True)
self.ui.kid10lab.setEnabled(True)
def removeKidAction(self):
""" if child removed, change visibilty and update count
"""
if self.numkids==1:
self.ui.kid1.setEnabled(False)
self.ui.kid1lab.setEnabled(False)
elif self.numkids==2:
self.ui.kid2.setEnabled(False)
self.ui.kid2lab.setEnabled(False)
elif self.numkids==3:
self.ui.kid3.setEnabled(False)
self.ui.kid3lab.setEnabled(False)
elif self.numkids==4:
self.ui.kid4.setEnabled(False)
self.ui.kid4lab.setEnabled(False)
elif self.numkids==5:
self.ui.kid5.setEnabled(False)
self.ui.kid5lab.setEnabled(False)
elif self.numkids==6:
self.ui.kid6.setEnabled(False)
self.ui.kid6lab.setEnabled(False)
elif self.numkids==7:
self.ui.kid7.setEnabled(False)
self.ui.kid7lab.setEnabled(False)
elif self.numkids==8:
self.ui.kid8.setEnabled(False)
self.ui.kid8lab.setEnabled(False)
elif self.numkids==9:
self.ui.kid9.setEnabled(False)
self.ui.kid9lab.setEnabled(False)
elif self.numkids==10:
self.ui.kid10.setEnabled(False)
self.ui.kid10lab.setEnabled(False)
self.numkids = max(self.numkids-1,0)
def coupleAction(self):
""" change visibility if a couple is selected
"""
self.ui.comboAdult.setCurrentIndex(0)
if self.ui.checkCouple.isChecked():
self.ui.comboAdult.setEnabled(True)
self.ui.checkMarried.setEnabled(True)
self.toggleAdult2()
else:
self.ui.comboAdult.setEnabled(False)
self.ui.checkMarried.setEnabled(False)
self.toggleAdult2()
def sysBrowse(self):
""" browse for system file
"""
filename = QFileDialog.getExistingDirectory(self, 'Open directory',self.sysDir)
if filename<>"":
self.ui.lineSysDir.setText(filename)
self.sysList()
self.sysDir = filename #os.path.dirname(str(filename))
def sysList(self):
""" list tax systems
"""
#filelist = []
self.ui.listSysFiles.clear()
filepath = self.ui.lineSysDir.text()
if os.path.isdir(filepath):
files = os.listdir(filepath)
for p in files:
filep = os.path.join(str(filepath),p)
if os.path.isfile(filep):
f = open(filep, 'r')
head=f.read(21)
if head=='<?xml version="1.0"?>':
f.readline() #nextline
head2 =f.read(8)
if head2=='<fortax>':
self.ui.listSysFiles.addItem(p)
#filelist.append(p)
f.close()
#print filelist
#filelist2 = []
#for filename in filelist:
#filelist2.append(os.path.splitext(filename)[0])
#print filelist2
if self.ui.listSysFiles.count()>0:
self.ui.listSysFiles.sortItems()
self.ui.listSysFiles.setCurrentRow(0)
if __name__ == "__main__":
app = QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
sys.exit(app.exec_())
| Python |
# -*- coding: utf-8 -*-
# This file is part of FORTAX Calculator;
# (c) 2009 Andrew Shephard; andrubuntu@gmail.com
#
# FORTAX Calculator is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
# FORTAX Calculator is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
# You should have received a copy of the GNU General Public License along
# with FORTAX Calculator. If not, see <http://www.gnu.org/licenses/>.
import os
import csv
from PyQt4.QtCore import *
from PyQt4.QtGui import *
#from numpy import *
from numpy import ndarray, zeros, array
#import matplotlib for figure plotting
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import resources
class figureWindow(QDialog):
""" budget constraont figure class
"""
def __init__(self,dataX,dataY,labelLegend="",labelX="",labelY="",labelTitle="",labelFigure="Figure",sourceNote=""):
QDialog.__init__(self)
self.setAttribute(Qt.WA_DeleteOnClose)
self.setWindowTitle(labelFigure)
l = QVBoxLayout(self)
sc = MyMplCanvas(self, width=5, height=4, dpi=100)
datanum = 0
for data in dataX:
datanum+=1
for data in range(datanum):
sc.axes.plot(dataX[data],dataY[data],label=labelLegend[data],linewidth=1)
sc.axes.set_xlabel(labelX,size='x-small')
sc.axes.set_ylabel(labelY,size='x-small')
sc.axes.set_title(labelTitle,size='small')
sc.axes.grid(True)
labels = sc.axes.get_xticklabels() + sc.axes.get_yticklabels()
for label in labels:
label.set_size('x-small')
leg = sc.axes.legend(loc='best')
for t in leg.get_texts():
t.set_fontsize('x-small')
l.addWidget(sc)
if sourceNote<>"":
source = QLabel(sourceNote)
l.addWidget(source)
self.setFocus()
class MyMplCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
#hold to allow multiple plots
self.axes.hold(True)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
class myTable(QTableWidget):
def __init__(self, parent):
QTableWidget.__init__(self, parent)
font = QFont()
font.setPointSize(8)
self.setFont(font)
self.tableName = ''
self.tableData = []
#self.removeAction()
self.__initActions__()
self.__initContextMenus__()
savdir = '/home/andrew/'
def setSavdir(self,savdir):
myTable.savdir = savdir
def getSavdir(self):
return myTable.savdir
def setTableName(self,name):
self.tableName = name
def getTableName(self):
return tableName
def adjustColumnSizes(self):
self.hide()
self.show()
if self.columnCount()>0:
available = self.width()-self.verticalHeader().width()-2
for col in range(self.columnCount()):
available-=self.columnWidth(col)
perColumn = available/self.columnCount()
for col in range(self.columnCount()):
self.setColumnWidth(col,max(self.columnWidth(col)+perColumn,70))
def reset(self):
self.setColumnCount(0)
self.setRowCount(0)
def setData(self,data,cellFormat="",readOnly=False):
dataSize = data.shape
self.setColumnCount(dataSize[1])
self.setRowCount(dataSize[0])
self.tableData = data
m = 0
for row in data:
n = 0
for item in row:
newitem = QTableWidgetItem(format(item,cellFormat))
if readOnly:
newitem.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
self.setItem(m, n, newitem)
n+=1
m+=1
def getData(self,getHeader=False):
if getHeader:
horizontalHeader = self.existHorizontalHeaders()
verticalHeader = self.existVerticalHeaders()
else:
horizontalHeader = False
verticalHeader = False
data = []
if horizontalHeader:
header = self.getHorizontalHeaders()
if verticalHeader:
header.insert(0,"")
data.append(header)
header = self.getVerticalHeaders()
for row in range(self.rowCount()):
thisrow = []
if verticalHeader:
thisrow.append(header[row])
for col in range(self.columnCount()):
cell = self.item(row, col)
if cell:
thisrow.append(str(cell.text()))
else:
thisrow.append("")
data.append(thisrow)
return data
def copyTable(self,getHeader=True):
if getHeader:
horizontalHeader = self.existHorizontalHeaders()
verticalHeader = self.existVerticalHeaders()
else:
horizontalHeader = False
verticalHeader = False
clipStr = QString()
#horizontalHeader
if horizontalHeader:
header = self.getHorizontalHeaders()
if verticalHeader:
header.insert(0,"")
for head in header:
clipStr.append(head)
clipStr.append("\t")
clipStr.chop(1)
clipStr.append("\n")
#verticalHeader
header = self.getVerticalHeaders()
for row in range(self.rowCount()):
if verticalHeader:
clipStr.append(header[row])
clipStr.append(QString("\t"))
for col in range(self.columnCount()):
cell = self.item(row, col)
if cell:
clipStr.append(cell.text())
else:
clipStr.append(QString(""))
clipStr.append(QString("\t"))
clipStr.chop(1)
clipStr.append(QString("\n"))
cb = QApplication.clipboard()
cb.setText(clipStr)
def saveTable(self,filename=""):
data = self.getData(True)
noFilename = False
if filename=="":
filename = QFileDialog.getSaveFileName(self, 'Save file',myTable.savdir,'*.csv')
noFilename = True
if filename<>"":
writer = csv.writer(open(filename, 'w'))
writer.writerows(data)
if noFilename:
myTable.savdir = os.path.dirname(str(filename))
def existHorizontalHeaders(self):
exist = False
for col in range(self.columnCount()):
cell = self.horizontalHeaderItem(col)
if cell:
exist = True
break
return exist
def existVerticalHeaders(self):
exist = False
for row in range(self.rowCount()):
cell = self.verticalHeaderItem(row)
if cell:
exist = True
break
return exist
def getHorizontalHeaders(self):
headers = []
for col in range(self.columnCount()):
cell = self.horizontalHeaderItem(col)
if cell:
headers.append(str(cell.text()))
else:
headers.append("")
return headers
def getVerticalHeaders(self):
headers = []
for row in range(self.rowCount()):
cell = self.verticalHeaderItem(row)
if cell:
headers.append(str(cell.text()))
else:
headers.append("")
return headers
def __initActions__(self):
icon = QIcon(':/icons/copy.png')
self.copyAction = QAction("&Copy selection",self)
self.copyAction.setIcon(icon)
#QIconSet(QPixmap(editcut)),
self.copyAction.setShortcut("Ctrl+C")
self.copyAction.setShortcutContext(Qt.WidgetShortcut)
self.addAction(self.copyAction)
self.connect(self.copyAction, SIGNAL("triggered()"), self.copyCells)
def __initContextMenus__(self):
#icon = QPixmap(':/icons/copy.png')
#self.setPixMap(icon)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.connect(self, SIGNAL("customContextMenuRequested(QPoint)"), self.tableWidgetContext)
def tableWidgetContext(self, point):
tw_menu = QMenu("Menu", self)
tw_menu.addAction(self.copyAction)
tw_menu.exec_(self.mapToGlobal(point))
def copyCells(self):
rowSel = [False]*self.rowCount()
colSel = [False]*self.columnCount()
horizontalHeader = self.existHorizontalHeaders()
verticalHeader = self.existVerticalHeaders()
#loop to determine if any cells in each row or column are selected
for row in range(self.rowCount()):
for col in range(self.columnCount()):
cell = self.item(row, col)
if self.isItemSelected(cell):
rowSel[row] = True
colSel[col] = True
clipStr = QString()
if horizontalHeader:
header = self.getHorizontalHeaders()
if verticalHeader:
clipStr.append("\t")
for col in range(self.columnCount()):
if colSel[col]:
clipStr.append(header[col])
clipStr.append("\t")
clipStr.chop(1)
clipStr.append("\n")
if verticalHeader:
header = self.getVerticalHeaders()
for row in range(self.rowCount()):
if rowSel[row]:
if verticalHeader:
clipStr.append(header[row])
clipStr.append(QString("\t"))
for col in range(self.columnCount()):
if colSel[col]:
cell = self.item(row, col)
if self.isItemSelected(cell):
clipStr.append(cell.text())
clipStr.append(QString("\t"))
else:
clipStr.append(QString("\t"))
#clipStr.append(QString("\t"))
clipStr.chop(1)
clipStr.append(QString("\n"))
cb = QApplication.clipboard()
cb.setText(clipStr)
return
class myTableKinks(myTable):
""" modify myTable class to containt information for plotting kinks
"""
def __init__(self, parent):
myTable.__init__(self,parent)
self.labelX = ""
self.labelY = "Net income"
self.labelTitle = "Budget constraint"
self.columnX = 0
self.columnY = 1
self.sourceNote = ""
def setSourceNote(self,source):
self.sourceNote = source
def getSourceNote(self,source):
return self.sourceNote
def setFigureColumnX(self,col):
self.columnX = col
def setFigureColumnY(self,col):
self.columnY = col
def setFigureLabelY(self,label):
self.labelY = label
def setFigureLabelX(self,label):
self.labelX = label
def setFigureLabelY(self,label):
self.labelY = label
def setFigureLabelTitle(self,label):
self.labelTitle = label
def getFigureLabelX(self):
return self.labelX
def getFigureLabelY(self):
return self.labelY
def getFigureLabelTitle(self):
return self.labelTitle
def drawKinks(self):
data = array(self.tableData)
aw = figureWindow(dataX=[data[:,self.columnX]],dataY=[data[:,self.columnY]],
labelLegend=[self.tableName],
labelX=self.labelX,labelY=self.labelY,
labelTitle=self.labelTitle,sourceNote=self.sourceNote)
aw.exec_()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of FORTAX Calculator;
# (c) 2009 Andrew Shephard; andrubuntu@gmail.com
#
# FORTAX Calculator is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
# FORTAX Calculator is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
# You should have received a copy of the GNU General Public License along
# with FORTAX Calculator. If not, see <http://www.gnu.org/licenses/>.
import sys
import os
import csv
import string
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from returnbudcon import *
#UIgrid is user interface produced with QtDesigner, myTable defines a table class
from UIgrid import *
from myTable import *
#resources file
import resources
class myMainWindow(QMainWindow):
""" modify the mainwindow class so it emits a signal when resized
"""
def resizeEvent(self,event):
self.emit(SIGNAL("signalResize()"))
class StartQT4(myMainWindow): #QMainWindow
def __init__(self, *args):
myMainWindow.__init__(self, *args)
#main interface setup
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
#icon
icon = QIcon(':/icons/icon.png')
self.setWindowIcon(icon)
#initialize some variables
self.numkids = 0
self.numsys = 0
self.doHours = True
self.headersKinks=["Hours", "Earnings", "Income", "Rate"]
self.dir = os.path.dirname(sys.executable)
self.dir = os.getcwd()
self.resdir = os.path.join(self.dir,'resources')
self.sysDir = os.path.join(self.resdir,'systems')
self.savdir = self.dir
if os.path.isdir(self.sysDir):
self.ui.lineSysDir.setText(self.sysDir)
self.sysList()
self.ui.gridLayout_2.removeWidget(self.ui.tabKinks)
self.ui.tabKinks.setParent(None)
del self.ui.tabKinks
self.ui.tabKinks = QTabWidget(self.ui.centralwidget)
self.ui.tabKinks.setObjectName("tabKinks")
self.ui.gridLayout_2.addWidget(self.ui.tabKinks, 0, 1, 2, 1)
thispage=QWidget()
gridLayout = QVBoxLayout()
tableKinks = myTableKinks(self.ui.tabKinks)
figButton = QPushButton(self.ui.tabKinks)
copyButton = QPushButton(self.ui.tabKinks)
saveButton = QPushButton(self.ui.tabKinks)
figButton.setText("Figure")
copyButton.setText("Copy")
saveButton.setText("Save")
tableKinks.setObjectName('tableKinks0')
tableKinks.horizontalHeader().setVisible(True)
tableKinks.verticalHeader().setVisible(False)
tableKinks.setHorizontalHeaderLabels(self.headersKinks)
gridLayout.addWidget(tableKinks)
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(figButton)
hbox.addWidget(copyButton)
hbox.addWidget(saveButton)
gridLayout.addLayout(hbox)
thispage.setLayout(gridLayout)
self.ui.tabKinks.addTab(thispage,'System')
self.ui.pushHideShowIncomes.setText("Show incomes")
self.ui.pushHideShowKinks.setText("Show kinks")
self.ui.pushHideShowSettings.setText("Show settings")
showHidewidth = 0
showHidewidth = max(showHidewidth,self.ui.pushHideShowIncomes.width())
showHidewidth = max(showHidewidth,self.ui.pushHideShowKinks.width())
showHidewidth = max(showHidewidth,self.ui.pushHideShowSettings.width())
self.ui.pushHideShowIncomes.setText("Hide incomes")
self.ui.pushHideShowKinks.setText("Hide kinks")
self.ui.pushHideShowSettings.setText("Hide settings")
showHidewidth = max(showHidewidth,self.ui.pushHideShowIncomes.width())
showHidewidth = max(showHidewidth,self.ui.pushHideShowKinks.width())
showHidewidth = max(showHidewidth,self.ui.pushHideShowSettings.width())
self.ui.pushHideShowIncomes.setMinimumWidth(showHidewidth)
self.ui.pushHideShowKinks.setMinimumWidth(showHidewidth)
self.ui.pushHideShowSettings.setMinimumWidth(showHidewidth)
self.ui.tabIncome.setTabEnabled(2,False)
self.ui.tableIncomes = myTable(self.ui.tabIncomesFamily)
self.ui.tabKinks.setEnabled(False)
self.ui.gridLayoutIncomes.addWidget(self.ui.tableIncomes)
self.ui.tableIncomes.setObjectName("tableIncomes")
self.ui.tableIncomes.horizontalHeader().setVisible(False)
self.ui.tableIncomeAd1 = myTable(self.ui.tabIncomesAd1)
self.ui.gridLayoutIncomeAd1.addWidget(self.ui.tableIncomeAd1)
self.ui.tableIncomeAd1.setObjectName("tableIncomeAd1")
self.ui.tableIncomeAd1.horizontalHeader().setVisible(False)
self.ui.tableIncomeAd2 = myTable(self.ui.tabIncomesAd2)
self.ui.gridLayoutIncomeAd2.addWidget(self.ui.tableIncomeAd2)
self.ui.tableIncomeAd2.setObjectName("tableIncomeAd2")
self.ui.tableIncomeAd2.horizontalHeader().setVisible(False)
#define some actions
self.connect(self.ui.addKid, SIGNAL('clicked()'), self.addKidAction)
self.connect(self.ui.removeKid, SIGNAL('clicked()'), self.removeKidAction)
self.connect(self.ui.checkCouple,SIGNAL('clicked()'), self.coupleAction)
self.connect(self.ui.toolSysBrowse,SIGNAL('clicked()'), self.sysBrowse)
self.connect(self.ui.lineSysDir,SIGNAL('returnPressed()'), self.sysList)
self.connect(self.ui.lineSysDir,SIGNAL('editingFinished()'), self.sysList)
self.connect(self.ui.pushFortax,SIGNAL('clicked()'), self.calc)
self.connect(self.ui.pushCopyIncomes,SIGNAL('clicked()'), self.ui.tableIncomes.copyTable)
self.connect(self.ui.pushSaveIncomes,SIGNAL('clicked()'), self.ui.tableIncomes.saveTable)
self.connect(self.ui.pushCopyIncomeAd1,SIGNAL('clicked()'), self.ui.tableIncomeAd1.copyTable)
self.connect(self.ui.pushSaveIncomeAd1,SIGNAL('clicked()'), self.ui.tableIncomeAd1.saveTable)
self.connect(self.ui.pushCopyIncomeAd2,SIGNAL('clicked()'), self.ui.tableIncomeAd2.copyTable)
self.connect(self.ui.pushSaveIncomeAd2,SIGNAL('clicked()'), self.ui.tableIncomeAd2.saveTable)
self.connect(self.ui.checkPriceDate,SIGNAL('clicked()'), self.checkDateAction)
self.connect(self.ui.radioHoursBc,SIGNAL('clicked()'), self.bcModeAction)
self.connect(self.ui.radioEarnBc,SIGNAL('clicked()'), self.bcModeAction)
self.connect(self.ui.pushHideShowSettings,SIGNAL('clicked()'), self.hideShowSettings)
self.connect(self.ui.pushHideShowKinks,SIGNAL('clicked()'), self.hideShowKinks)
self.connect(self.ui.pushHideShowIncomes,SIGNAL('clicked()'), self.hideShowIncomes)
self.connect(self,SIGNAL('signalResize()'), self.adjustAllColumns)
self.connect(self.ui.tabKinks,SIGNAL('currentChanged(QWidget *)'), self.adjustAllColumns)
self.connect(self.ui.pushFigures,SIGNAL('clicked()'), self.allFigures)
#define shortcut keys
shortcutCalc = QShortcut(self)
shortcutCalc.setKey("Ctrl+Return")
self.connect(shortcutCalc,SIGNAL('activated()'), self.calc)
shortcutSettingsPanel = QShortcut(self)
shortcutSettingsPanel.setKey("Ctrl+1")
self.connect(shortcutSettingsPanel,SIGNAL('activated()'), self.hideShowSettings)
shortcutKinksPanel = QShortcut(self)
shortcutKinksPanel.setKey("Ctrl+2")
self.connect(shortcutKinksPanel,SIGNAL('activated()'), self.hideShowKinks)
shortcutIncomesPanel = QShortcut(self)
shortcutIncomesPanel.setKey("Ctrl+3")
self.connect(shortcutIncomesPanel,SIGNAL('activated()'), self.hideShowIncomes)
self.taxFile = os.path.join(self.resdir,'taxlist.csv')
if not os.path.isfile(self.taxFile):
self.ui.comboTaxOut.setEnabled(False)
else:
reader = csv.reader(open(self.taxFile, "rb"))
self.taxLongName = []
self.taxLongNameAd = []
self.taxShortName = []
self.taxLevel = []
for row in reader:
self.taxLongName.append(row[0])
self.taxShortName.append(row[1])
self.taxLevel.append(row[2])
if row[2]=='ad1':
self.taxLongNameAd.append('Adult 1: '+row[0])
elif row[2]=='ad2':
self.taxLongNameAd.append('Adult 2: '+row[0])
else:
self.taxLongNameAd.append(row[0])
self.taxNum = len(self.taxLevel)
self.ui.comboTaxOut.clear()
self.ui.comboTaxOut.addItems(self.taxLongNameAd)
ind = self.ui.comboTaxOut.findText("Disposable Income")
if ind>=0:
self.ui.comboTaxOut.setCurrentIndex(ind)
self.rpiFile = os.path.join(self.resdir,'rpi.csv')
if not os.path.isfile(self.rpiFile):
self.ui.checkPriceDate.setEnabled(False)
else:
reader = csv.reader(open(self.rpiFile, "rb"), delimiter=',', quoting=csv.QUOTE_NONE)
reader.next() #skip header
self.priceDate = []
self.priceIndex = []
for row in reader:
self.priceDate.append(int(row[0]))
self.priceIndex.append(float(row[1]))
self.priceNum = len(self.priceDate)
date = QDate.fromString(QString(str(self.priceDate[0])),"yyyyMMdd")
self.ui.datePriceDate.setMinimumDate(date)
date = QDate.fromString(QString(str(self.priceDate[self.priceNum-1])),"yyyyMMdd")
self.ui.datePriceDate.setMaximumDate(date)
self.ui.datePriceDate.setDate(date)
self.bcModeAction()
self.coupleAction()
def allFigures(self):
""" plot budget constraints for all active systems
"""
if self.doHours:
columnX = 0; columnY = 2
pound = u"\u00A3" #pound
labelX = 'Hours per week'
labelY = self.incomeComponent
titleString = 'Budget constraint, fixed ' + pound + string.strip(format(self.wageOrHours,"7.2f")) + ' hourly wage'
else:
columnX = 1; columnY = 2
labelX = 'Earnings, pounds per week'
labelY = self.incomeComponent
titleString = 'Budget constraint, fixed at ' + string.strip(format(self.wageOrHours,"7.0f")) + ' hours'
dataX = []
dataY = []
leg = []
for s in range(self.numsys):
objname = QString("tableKinks"+str(s))
tableKinks = self.ui.tabKinks.findChild(myTableKinks,objname)
if tableKinks:
dataX.append(array(tableKinks.tableData[:,columnX]))
dataY.append(array(tableKinks.tableData[:,columnY]))
leg.append(tableKinks.tableName)
aw = figureWindow(dataX=dataX,dataY=dataY,
labelLegend=leg,labelX=labelX,labelY=labelY,
labelTitle=titleString,sourceNote=self.source)
aw.exec_()
def adjustAllColumns(self):
""" if adjust all column sizes
"""
if self.ui.tabKinks.isVisible():
for s in range(self.numsys):
objname = QString("tableKinks"+str(s))
tableKinks = self.ui.tabKinks.findChild(myTableKinks,objname)
if tableKinks:
tableKinks.adjustColumnSizes()
if self.ui.tableIncomes.isVisible():
self.ui.tableIncomes.adjustColumnSizes()
if self.ui.tableIncomeAd1.isVisible():
self.ui.tableIncomeAd1.adjustColumnSizes()
if self.ui.tableIncomeAd2.isVisible():
self.ui.tableIncomeAd2.adjustColumnSizes()
def hideShowIncomes(self):
""" hide/show incomes panel
"""
if (not self.ui.tabSettings.isVisible()) and (not self.ui.tabKinks.isVisible()):
return
if self.ui.tabIncome.isVisible():
self.ui.tabIncome.setVisible(False)
self.ui.pushHideShowIncomes.setText("Show incomes")
if not self.ui.tabKinks.isVisible():
self.ui.pushHideShowSettings.setEnabled(False)
if not self.ui.tabSettings.isVisible():
self.ui.pushHideShowKinks.setEnabled(False)
else:
self.ui.tabIncome.setVisible(True)
self.ui.pushHideShowIncomes.setText("Hide incomes")
self.ui.pushHideShowIncomes.setMinimumWidth(100)
self.ui.pushHideShowIncomes.setEnabled(True)
self.ui.pushHideShowKinks.setEnabled(True)
self.ui.pushHideShowSettings.setEnabled(True)
self.adjustAllColumns()
def hideShowSettings(self):
""" hide/show settings panel
"""
if (not self.ui.tabIncome.isVisible()) and (not self.ui.tabKinks.isVisible()):
return
if self.ui.tabSettings.isVisible():
self.ui.tabSettings.setVisible(False)
self.ui.pushHideShowSettings.setText("Show settings")
if not self.ui.tabKinks.isVisible():
self.ui.pushHideShowIncomes.setEnabled(False)
if not self.ui.tabIncome.isVisible():
self.ui.pushHideShowKinks.setEnabled(False)
else:
self.ui.tabSettings.setVisible(True)
self.ui.pushHideShowSettings.setText("Hide settings")
self.ui.pushHideShowIncomes.setEnabled(True)
self.ui.pushHideShowKinks.setEnabled(True)
self.ui.pushHideShowSettings.setEnabled(True)
self.adjustAllColumns()
def hideShowKinks(self):
""" hide/show kinks panel
"""
if (not self.ui.tabSettings.isVisible()) and (not self.ui.tabIncome.isVisible()):
return
if self.ui.tabKinks.isVisible():
self.ui.tabKinks.setVisible(False)
self.ui.pushHideShowKinks.setText("Show kinks")
if not self.ui.tabSettings.isVisible():
self.ui.pushHideShowIncomes.setEnabled(False)
if not self.ui.tabIncome.isVisible():
self.ui.pushHideShowSettings.setEnabled(False)
else:
self.ui.tabKinks.setVisible(True)
self.ui.pushHideShowKinks.setText("Hide kinks")
self.ui.pushHideShowIncomes.setEnabled(True)
self.ui.pushHideShowKinks.setEnabled(True)
self.ui.pushHideShowSettings.setEnabled(True)
self.adjustAllColumns()
def bcModeAction(self):
""" change visibility depending on whether earnings/hours kinks
"""
if self.ui.radioHoursBc.isChecked():
self.ui.labelEarnHours.setEnabled(False)
self.ui.doubleSpinEarnHours.setEnabled(False)
self.ui.labelEarnStart.setEnabled(False)
self.ui.doubleSpinEarnStart.setEnabled(False)
self.ui.labelEarnEnd.setEnabled(False)
self.ui.doubleSpinEarnEnd.setEnabled(False)
self.ui.labelWage.setEnabled(True)
self.ui.doubleSpinWage.setEnabled(True)
self.ui.labelHoursStart.setEnabled(True)
self.ui.doubleSpinHoursStart.setEnabled(True)
self.ui.labelHoursEnd.setEnabled(True)
self.ui.doubleSpinHoursEnd.setEnabled(True)
else:
self.ui.labelEarnHours.setEnabled(True)
self.ui.doubleSpinEarnHours.setEnabled(True)
self.ui.labelEarnStart.setEnabled(True)
self.ui.doubleSpinEarnStart.setEnabled(True)
self.ui.labelEarnEnd.setEnabled(True)
self.ui.doubleSpinEarnEnd.setEnabled(True)
self.ui.labelWage.setEnabled(False)
self.ui.doubleSpinWage.setEnabled(False)
self.ui.labelHoursStart.setEnabled(False)
self.ui.doubleSpinHoursStart.setEnabled(False)
self.ui.labelHoursEnd.setEnabled(False)
self.ui.doubleSpinHoursEnd.setEnabled(False)
def checkDateAction(self):
""" if using uprating date change cal visibility
"""
if self.ui.checkPriceDate.isChecked():
self.ui.labelPriceDate.setEnabled(True)
self.ui.datePriceDate.setEnabled(True)
else:
self.ui.labelPriceDate.setEnabled(False)
self.ui.datePriceDate.setEnabled(False)
def calc(self):
""" performs calculations, calls FORTAX
"""
nosys = False
#is system okay?
if self.ui.listSysFiles.currentRow()<0:
nosys = True
else:
selsys = self.ui.listSysFiles.selectedItems()
self.numsys = 0
sysname = []
sysnameNoExt = []
for thissys in selsys:
sysname.append(str(thissys.text()))
sysnameNoExt.append(os.path.splitext(str(thissys.text()))[0])
self.numsys+=1
if nosys:
reply = QMessageBox.warning(self, 'FORTAX: Error',
"No system is selected", QMessageBox.Ok)
return
#check ranges of hours/earnings
if self.ui.radioHoursBc.isChecked():
self.wageOrHours = self.ui.doubleSpinWage.value()
range0 = self.ui.doubleSpinHoursStart.value()
range1 = self.ui.doubleSpinHoursEnd.value()
if range0>range1:
reply = QMessageBox.warning(self, 'FORTAX: Error',
"End hours must be larger than start hours", QMessageBox.Ok)
return
else:
self.wageOrHours = self.ui.doubleSpinEarnHours.value()
range0 = self.ui.doubleSpinEarnStart.value()
range1 = self.ui.doubleSpinEarnEnd.value()
if range0>range1:
reply = QMessageBox.warning(self, 'FORTAX: Error',
"End earn must be larger than start earn", QMessageBox.Ok)
return
#hours or earnings kinks?
if self.ui.radioHoursBc.isChecked():
self.doHours = True
else:
self.doHours = False
adult = self.ui.comboAdult.currentIndex()+1
couple = self.ui.checkCouple.isChecked()
married = self.ui.checkMarried.isChecked()
age1 = self.ui.spinAge1.value()
age2 = self.ui.spinAge2.value()
wage1 = self.ui.doubleSpinWage1.value()
wage2 = self.ui.doubleSpinWage2.value()
hours1 = self.ui.doubleSpinHrs1.value()
hours2 = self.ui.doubleSpinHrs2.value()
selfemp1 = self.ui.checkSelfEmp1.isChecked()
selfemp2 = self.ui.checkSelfEmp2.isChecked()
tenure = self.ui.comboTenure.currentIndex()+1
rent = self.ui.doubleSpinRent.value()
ctband = self.ui.comboCouncilTax.currentIndex()+1
banddratio = self.ui.doubleSpinBandD.value()
childcare = self.ui.doubleSpinChildcare.value()
maintenance = self.ui.doubleSpinMaintenance.value()
self.ui.pushFigures.setEnabled(True)
if couple:
self.ui.tabIncome.setTabEnabled(2,True)
else:
self.ui.tabIncome.setTabEnabled(2,False)
setprice = self.ui.checkPriceDate.isChecked()
if (setprice):
pricetarget = int(QDate.toString(self.ui.datePriceDate.date(),"yyyyMMdd"))
self.source = "Source: User calculation using FORTAX. Incomes expressed in" + QDate.toString(self.ui.datePriceDate.date()," MMMM yyyy ") + "prices."
else:
pricetarget = 0
self.source = "Source: User calculation using FORTAX. Incomes expressed in nominal prices."
kids = zeros(max(self.numkids,1),int)
if self.numkids>0:
kids[0] = self.ui.kid1.value()
if self.numkids>1:
kids[1] = self.ui.kid2.value()
if self.numkids>2:
kids[2] = self.ui.kid3.value()
if self.numkids>3:
kids[3] = self.ui.kid4.value()
if self.numkids>4:
kids[4] = self.ui.kid5.value()
if self.numkids>5:
kids[5] = self.ui.kid6.value()
if self.numkids>6:
kids[6] = self.ui.kid7.value()
if self.numkids>7:
kids[7] = self.ui.kid8.value()
if self.numkids>8:
kids[8] = self.ui.kid9.value()
if self.numkids>9:
kids[9] = self.ui.kid10.value()
taxout = self.taxShortName[self.ui.comboTaxOut.currentIndex()]
taxlevel = self.taxLevel[self.ui.comboTaxOut.currentIndex()]
self.incomeComponent = self.taxLongName[self.ui.comboTaxOut.currentIndex()]
#convert system list to csv
sysnamecsv = ','.join([str(i) for i in sysname])
#call fortax to calculate incomes and budget constraints
ret = returnbudcon(self.wageOrHours,range0,range1,self.doHours,self.sysDir,self.numsys,sysnamecsv,
taxout,taxlevel,adult,couple,married,
age1,wage1,hours1,selfemp1,age2,wage2,hours2,selfemp2,
self.numkids,kids,tenure,rent,ctband,banddratio,childcare,maintenance,
setprice,pricetarget,self.priceDate,self.priceIndex,self.priceNum)
#detailed incomes
headers0=[]; headers1=[]; headers2=[]
m0=0; m1=0; m2=0
list0=[]; list1=[]; list2=[]
#ret 0, kinks_hrs
#ret 1, kinks_earn
#ret 2, kinks_net
#ret 3, kinks_mtr
#ret 4, kinks_num
#ret 5, netoutLevel
#ret 6, netoutName
#ret 7, netoutAmt
#ret 8 netoutNum
data0 = zeros((ret[8],self.numsys),float)
data1 = zeros((ret[8],self.numsys),float)
data2 = zeros((ret[8],self.numsys),float)
#note: only amt differs by system
for item in range(ret[8]):
if any(ret[7][item])<>0:
shortName = string.strip(ndarray.tostring(ret[6][item]))
taxLevel = string.strip(ndarray.tostring(ret[5][item]))
nameIndex = -1
for name in range(self.taxNum):
if self.taxLevel[name]==taxLevel and self.taxShortName[name]==shortName:
nameIndex = name
break
if taxLevel=='tu':
if nameIndex>=0:
headers0.append(self.taxLongName[nameIndex])
data0[m0]=ret[7][item]
m0+=1
elif taxLevel=='ad1':
if nameIndex>=0:
headers1.append(self.taxLongName[nameIndex])
data1[m1]=ret[7][item]
m1+=1
elif taxLevel=='ad2':
if nameIndex>=0:
headers2.append(self.taxLongName[nameIndex])
data2[m2]=ret[7][item]
m2+=1
if m0>0:
self.ui.tableIncomes.setData(data0[0:m0],cellFormat="7.2f",readOnly=True)
self.ui.tableIncomes.setHorizontalHeaderLabels(sysnameNoExt)
self.ui.tableIncomes.horizontalHeader().setVisible(True)
self.ui.tableIncomes.setVerticalHeaderLabels(headers0)
self.ui.tableIncomes.adjustColumnSizes()
self.ui.pushCopyIncomes.setEnabled(True)
self.ui.pushSaveIncomes.setEnabled(True)
else:
self.ui.tableIncomes.reset()
self.ui.pushCopyIncomes.setEnabled(False)
self.ui.pushSaveIncomes.setEnabled(False)
if m1>0:
self.ui.labelAd1NotWorking.setVisible(False)
self.ui.tableIncomeAd1.setData(data1[0:m1],cellFormat="7.2f",readOnly=True)
self.ui.tableIncomeAd1.setHorizontalHeaderLabels(sysnameNoExt)
self.ui.tableIncomeAd1.horizontalHeader().setVisible(True)
self.ui.tableIncomeAd1.setVerticalHeaderLabels(headers1)
self.ui.tableIncomeAd1.adjustColumnSizes()
self.ui.pushCopyIncomeAd1.setEnabled(True)
self.ui.pushSaveIncomeAd1.setEnabled(True)
else:
self.ui.tableIncomeAd1.reset()
self.ui.labelAd1NotWorking.setVisible(True)
self.ui.pushCopyIncomeAd1.setEnabled(False)
self.ui.pushSaveIncomeAd1.setEnabled(False)
if m2>0:
self.ui.labelAd2NotWorking.setVisible(False)
self.ui.tableIncomeAd2.setData(data2[0:m2],cellFormat="7.2f",readOnly=True)
self.ui.tableIncomeAd2.setHorizontalHeaderLabels(sysnameNoExt)
self.ui.tableIncomeAd2.horizontalHeader().setVisible(True)
self.ui.tableIncomeAd2.setVerticalHeaderLabels(headers2)
self.ui.tableIncomeAd2.adjustColumnSizes()
self.ui.pushCopyIncomeAd2.setEnabled(True)
self.ui.pushSaveIncomeAd2.setEnabled(True)
else:
self.ui.labelAd2NotWorking.setVisible(True)
self.ui.tableIncomeAd2.reset()
self.ui.pushCopyIncomeAd2.setEnabled(False)
self.ui.pushSaveIncomeAd2.setEnabled(False)
#destroy kinks tab
self.ui.gridLayout_2.removeWidget(self.ui.tabKinks)
self.ui.tabKinks.setParent(None)
del self.ui.tabKinks
#create new kinks tab
self.ui.tabKinks = QTabWidget(self.ui.centralwidget)
self.ui.tabKinks.setObjectName("tabKinks")
self.ui.gridLayout_2.addWidget(self.ui.tabKinks, 0, 1, 2, 1)
self.ui.tabKinks.setEnabled(True)
#create blank page (will delete later)
thispage=QWidget()
self.ui.tabKinks.addTab(thispage,'blank')
for s in range(self.numsys):
numKinks = ret[4][s]
my_array = zeros([numKinks,4],float)
for i in range(numKinks):
my_array[i,0] = ret[0][i][s]
my_array[i,1] = ret[1][i][s]
my_array[i,2] = ret[2][i][s]
my_array[i,3] = ret[3][i][s]
thispage=QWidget()
gridLayout = QVBoxLayout()
tableKinks = myTableKinks(self.ui.tabKinks)
figButton = QPushButton(self.ui.tabKinks)
figButton.setText("Figure")
copyButton = QPushButton(self.ui.tabKinks)
copyButton.setText("Copy")
saveButton = QPushButton(self.ui.tabKinks)
saveButton.setText("Save")
figButton.setToolTip(QApplication.translate("MainWindow", "Show figure under "+sysnameNoExt[s]+" system",
None, QApplication.UnicodeUTF8))
copyButton.setToolTip(QApplication.translate("MainWindow", "Copy budget constraint under "+sysnameNoExt[s]+" system to clipboard",
None, QApplication.UnicodeUTF8))
saveButton.setToolTip(QApplication.translate("MainWindow", "Save budget constraint under "+sysnameNoExt[s]+" system as .csv file",
None, QApplication.UnicodeUTF8))
tableKinks.setObjectName('tableKinks'+str(s))
tableKinks.setData(my_array,cellFormat="7.2f",readOnly=True)
tableKinks.horizontalHeader().setVisible(True)
tableKinks.verticalHeader().setVisible(False)
tableKinks.setHorizontalHeaderLabels(self.headersKinks)
#extra stuff if used for plotting
tableKinks.setTableName(sysnameNoExt[s])
if self.doHours:
pound = u"\u00A3"
tableKinks.setFigureLabelY(self.incomeComponent)
tableKinks.setFigureLabelX('Hours per week')
titleString = 'Budget constraint, fixed ' + pound + string.strip(format(self.wageOrHours,"7.2f")) + ' hourly wage'
tableKinks.setFigureLabelTitle(titleString)
tableKinks.setFigureColumnX(0)
tableKinks.setFigureColumnY(2)
tableKinks.setSourceNote(self.source)
else:
tableKinks.setFigureLabelY(self.incomeComponent)
tableKinks.setFigureLabelX('Earnings, pounds per week')
titleString = 'Budget constraint, fixed at ' + string.strip(format(self.wageOrHours,"7.0f")) + ' hours'
tableKinks.setFigureLabelTitle(titleString)
tableKinks.setFigureColumnX(1)
tableKinks.setFigureColumnY(2)
tableKinks.setSourceNote(self.source)
gridLayout.addWidget(tableKinks)
#add buttons
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(figButton)
hbox.addWidget(copyButton)
hbox.addWidget(saveButton)
gridLayout.addLayout(hbox)
thispage.setLayout(gridLayout)
self.connect(figButton,SIGNAL('clicked()'), tableKinks.drawKinks)
self.connect(copyButton,SIGNAL('clicked()'), tableKinks.copyTable)
self.connect(saveButton,SIGNAL('clicked()'), tableKinks.saveTable)
self.ui.tabKinks.addTab(thispage,sysnameNoExt[s])
tableKinks.adjustColumnSizes()
self.ui.tabKinks.removeTab(0)
def toggleAdult2(self):
""" if adult added, change visibilty and update count
"""
if self.ui.checkCouple.isChecked():
self.ui.labelAdult2.setEnabled(True)
self.ui.age2lab.setEnabled(True)
self.ui.wage2lab.setEnabled(True)
self.ui.hrs2lab.setEnabled(True)
self.ui.spinAge2.setEnabled(True)
self.ui.doubleSpinWage2.setEnabled(True)
self.ui.doubleSpinHrs2.setEnabled(True)
self.ui.checkSelfEmp2.setEnabled(True)
else:
self.ui.labelAdult2.setEnabled(False)
self.ui.age2lab.setEnabled(False)
self.ui.wage2lab.setEnabled(False)
self.ui.hrs2lab.setEnabled(False)
self.ui.spinAge2.setEnabled(False)
self.ui.doubleSpinWage2.setEnabled(False)
self.ui.doubleSpinHrs2.setEnabled(False)
self.ui.checkSelfEmp2.setEnabled(False)
def addKidAction(self):
""" if child added, change visibilty and update count
"""
self.numkids = min(self.numkids+1,10)
if self.numkids==1:
self.ui.kid1.setEnabled(True)
self.ui.kid1lab.setEnabled(True)
elif self.numkids==2:
self.ui.kid2.setEnabled(True)
self.ui.kid2lab.setEnabled(True)
elif self.numkids==3:
self.ui.kid3.setEnabled(True)
self.ui.kid3lab.setEnabled(True)
elif self.numkids==4:
self.ui.kid4.setEnabled(True)
self.ui.kid4lab.setEnabled(True)
elif self.numkids==5:
self.ui.kid5.setEnabled(True)
self.ui.kid5lab.setEnabled(True)
elif self.numkids==6:
self.ui.kid6.setEnabled(True)
self.ui.kid6lab.setEnabled(True)
elif self.numkids==7:
self.ui.kid7.setEnabled(True)
self.ui.kid7lab.setEnabled(True)
elif self.numkids==8:
self.ui.kid8.setEnabled(True)
self.ui.kid8lab.setEnabled(True)
elif self.numkids==9:
self.ui.kid9.setEnabled(True)
self.ui.kid9lab.setEnabled(True)
elif self.numkids==10:
self.ui.kid10.setEnabled(True)
self.ui.kid10lab.setEnabled(True)
def removeKidAction(self):
""" if child removed, change visibilty and update count
"""
if self.numkids==1:
self.ui.kid1.setEnabled(False)
self.ui.kid1lab.setEnabled(False)
elif self.numkids==2:
self.ui.kid2.setEnabled(False)
self.ui.kid2lab.setEnabled(False)
elif self.numkids==3:
self.ui.kid3.setEnabled(False)
self.ui.kid3lab.setEnabled(False)
elif self.numkids==4:
self.ui.kid4.setEnabled(False)
self.ui.kid4lab.setEnabled(False)
elif self.numkids==5:
self.ui.kid5.setEnabled(False)
self.ui.kid5lab.setEnabled(False)
elif self.numkids==6:
self.ui.kid6.setEnabled(False)
self.ui.kid6lab.setEnabled(False)
elif self.numkids==7:
self.ui.kid7.setEnabled(False)
self.ui.kid7lab.setEnabled(False)
elif self.numkids==8:
self.ui.kid8.setEnabled(False)
self.ui.kid8lab.setEnabled(False)
elif self.numkids==9:
self.ui.kid9.setEnabled(False)
self.ui.kid9lab.setEnabled(False)
elif self.numkids==10:
self.ui.kid10.setEnabled(False)
self.ui.kid10lab.setEnabled(False)
self.numkids = max(self.numkids-1,0)
def coupleAction(self):
""" change visibility if a couple is selected
"""
self.ui.comboAdult.setCurrentIndex(0)
if self.ui.checkCouple.isChecked():
self.ui.comboAdult.setEnabled(True)
self.ui.checkMarried.setEnabled(True)
self.toggleAdult2()
else:
self.ui.comboAdult.setEnabled(False)
self.ui.checkMarried.setEnabled(False)
self.toggleAdult2()
def sysBrowse(self):
""" browse for system file
"""
filename = QFileDialog.getExistingDirectory(self, 'Open directory',self.sysDir)
if filename<>"":
self.ui.lineSysDir.setText(filename)
self.sysList()
self.sysDir = filename #os.path.dirname(str(filename))
def sysList(self):
""" list tax systems
"""
#filelist = []
self.ui.listSysFiles.clear()
filepath = self.ui.lineSysDir.text()
if os.path.isdir(filepath):
files = os.listdir(filepath)
for p in files:
filep = os.path.join(str(filepath),p)
if os.path.isfile(filep):
f = open(filep, 'r')
head=f.read(21)
if head=='<?xml version="1.0"?>':
f.readline() #nextline
head2 =f.read(8)
if head2=='<fortax>':
self.ui.listSysFiles.addItem(p)
#filelist.append(p)
f.close()
#print filelist
#filelist2 = []
#for filename in filelist:
#filelist2.append(os.path.splitext(filename)[0])
#print filelist2
if self.ui.listSysFiles.count()>0:
self.ui.listSysFiles.sortItems()
self.ui.listSysFiles.setCurrentRow(0)
if __name__ == "__main__":
app = QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
sys.exit(app.exec_())
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of FORTAX Systems;
# (c) 2010 Andrew Shephard; andrubuntu@gmail.com
#
# FORTAX Systems is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
# FORTAX Systems is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
# You should have received a copy of the GNU General Public License along
# with FORTAX Systems. If not, see <http://www.gnu.org/licenses/>.
import optparse
import csv
import fortaxdb
import os.path
def main():
parser = optparse.OptionParser(version='%prog version 0.01a')
parser.add_option(
'-i', '--includes',
help='generate FORTAX include files',
dest='include',
default=False,
action='store_true'
)
parser.add_option(
'-d', '--date',
help='system date YYYYMMDD',
dest='date',
action='store_true'
)
parser.add_option(
'-l', '--label',
help='system label',
dest='label',
default='historic',
action='store_true'
)
(opts, args) = parser.parse_args()
print args
print opts
sysComponents = []
sysNames = []
#open the csv file that lists the system components
if not(os.path.isfile('syslist.csv')):
print 'file syslist.csv does not exist'
sys.exit()
sysList = csv.reader(open('syslist.csv'), delimiter=',', quotechar='"')
if opts.include:
f = open("syslist.inc", "w")
f.write('#undef _$typelist\n')
for row in sysList:
sysComponents.append(row[0])
sysNames.append(row[1])
if opts.include:
f.write('#define _$typelist '+row[0]+'\n')
f.write('#include "'+row[0]+'.inc"'+'\n\n')
f.write('#undef _$typelist\n')
f.write('')
if opts.include:
f.close()
#construct internal system database
fdb = []
for index, fname in enumerate(sysNames):
fdb.append(fortaxdb.fortaxVar(fname,sysComponents[index],opts,args))
#obtain file links from database
fdb_files = fortaxdb.fortaxFileLinks(fdb)
#construct database from linked files
fdb_links = []
for fname in fdb_files:
fdb_links.append(fortaxdb.fortaxVar(fname.strip('"'),fname,opts,args))
#verify whether nested linking
if fortaxdb.recursiveLinking(fdb_links):
print 'error: a linked file may not link to another file'
#check whether file exists
# if not(os.path.isfile(sysname)):
# print 'file '+sysname+' does not exist'
# sys.exit()
# sysfile = csv.reader(open(sysname), delimiter=',', quotechar='"')
fortaxdb.writeXml(fdb,fdb_links,'20021231')
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of FORTAX Systems;
# (c) 2010 Andrew Shephard; andrubuntu@gmail.com
#
# FORTAX Systems is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
# FORTAX Systems is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
# You should have received a copy of the GNU General Public License along
# with FORTAX Systems. If not, see <http://www.gnu.org/licenses/>.
import csv
import sys
import os.path
import datetime
from operator import itemgetter
class varClass(object):
"""Class docstring."""
def __init__(self, varindex, varname, vartype, vararray, vardata, varperiod, varlabel):
"""Method docstring."""
self.varindex = varindex
self.varname = varname
self.vartype = vartype
self.vararray = vararray
self.period = varperiod
self.label = varlabel
self.data = vardata
self.fileLink = [False for ixD in range(len(self.data))]
for ixD in range(len(self.data)):
if self.data[ixD][0:2]=='@>':
self.fileLink[ixD] = True
class fortaxVar():
def find(self, prefix, varname, header):
for h, hstr in enumerate(header):
if hstr[0:len(prefix)]==prefix:
if hstr[len(prefix):]==varname:
return h
return -1
def __init__(self,fname,sysname,opts,args):
#check whether file exists
if not(os.path.isfile(fname)):
print 'file '+fname+' does not exist'
sys.exit()
#open file
sysfile = csv.reader(open(fname), delimiter=',', quotechar='"')
#initialize
self.sysname = sysname #system name
db = [] #data in file fname
existHeader = False #if a file header exists
self.existLabel = False #if labels exist for variable
self.existPeriod = False #if period exist for variable
self.indexFile = False #if file is index file
#read sysfile line by line
for row in sysfile:
row2 = [x.strip() for x in row]
if row2[0]=='@#': #data line
db.append(row2)
elif row2[0]=='@^': #header line
if existHeader:
print 'error: multiple header records detected in '+fname
sys.exit()
self.header = row2
existHeader = True
elif row2[0]=='@!': #header line of index file
if existHeader:
print 'error: multiple header records detected in '+fname
sys.exit()
self.header = row2
existHeader = True
self.indexFile = True
elif row2[0]=='@?': #label line
if self.existLabel:
print 'error: multiple label records detected in '+fname
sys.exit()
self.label = row2
self.existLabel = True
elif row2[0]=='@.': #period line
if self.existPeriod:
print 'error: multiple period records detected in '+fname
sys.exit()
self.period = row2
self.existPeriod = True
#check header exists
if not existHeader:
print 'error: no header record exists in '+fname
sys.exit()
#column with date information
try:
dateInd = self.header.index('date')
except:
print 'error: no date column in '+fname
sys.exit()
#column with label information
try:
labelInd = self.header.index('label')
except:
print 'error: no label column'
sys.exit()
if self.indexFile:
try:
indexInd = self.header.index('index')
except:
print 'error: index file but no index column'
sys.exit()
#sort data by label, date, index
if self.indexFile:
db = sorted(db, key=itemgetter(indexInd))
db = sorted(db, key=itemgetter(dateInd))
db = sorted(db, key=itemgetter(labelInd))
#number of entries in db
self.numRec = len(db)
#for each line in db, create lists with date and label information
#dates will be stored as integers
#self.idDate = [int(0) for ixD in range(self.numRec)]
#self.idLabel = ['' for ixD in range(self.numRec)]
self.idDate = []
self.idLabel = []
self.idDate2 = []
self.idLabel2 = []
#if self.indexFile:
# self.idIndex = [int(0) for ixD in range(self.numRec)]
#check whether the date is valid
for ixD in range(self.numRec):
if not checkDate(db[ixD][dateInd]):
print 'error: invalid YYYYMMDD date format in '+fname
sys.exit()
else:
self.idDate.append(int(db[ixD][dateInd]))
self.idLabel.append(db[ixD][labelInd])
for ixD in range(self.numRec):
if (ixD==0) or (db[ixD][labelInd]!=db[ixD-1][labelInd]) or (db[ixD][dateInd]!=db[ixD-1][dateInd]):
self.idDate2.append(int(db[ixD][dateInd]))
self.idLabel2.append(db[ixD][labelInd])
#extract information from the database db
self.getFortaxVar(db)
#self.missingFortaxVar()
#self.checkFortaxVar()
#clean up junk
del self.header
#del self.idDate
if self.existPeriod:
del self.period
if self.existLabel:
del self.label
del self.existLabel
del self.existPeriod
del self.idLabel
def missingFortaxVar(self):
for var in self.varlist:
for ixD in range(self.numRec):
if var.data[ixD]=='':
if var.vartype=='range':
var.data[ixD] = '0'
if var.vartype in ('amount','minamount','rate'):
var.data[ixD] = '0.0'
if var.vartype in ('bool'):
var.data[ixD] = '0'
def getFortaxVar(self,db):
#varlist will contain the list of components in this system part
self.varlist = []
for h, hstr in enumerate(self.header):
if hstr[0:2]=='@_':
thisvar=hstr[2:].split('.')
#check whether we have a valid fortax variable construct
valid, varName, varType, varArray = self.validVarConstruct(thisvar)
if not valid:
print 'error: ' + hstr + ' is not a valid fortax variable construct'
sys.exit()
varData = []
#if an index file, the data will be a list. note that index is ORDINAL
if self.indexFile:
newObs = True
for ixD in range(self.numRec):
if newObs:
this = []
newObs = False
this.append(db[ixD][h])
if ixD<self.numRec-1:
if (self.idLabel[ixD]!=self.idLabel[ixD+1]) or (self.idDate[ixD]!=self.idDate[ixD+1]):
varData.append(this)
newObs = True
varData.append(this)
else:
for ixD in range(self.numRec):
varData.append(db[ixD][h])
#read label if it exists, otherwise set equal to variable name
if self.existLabel:
varLabel = self.label[h]
else:
varLabel = varName
#read period if it exists. this needs to be strictly positive,
#otherwise set equal to -1
if self.existPeriod:
varPeriod = self.period[h]
else:
varPeriod = -1
#append to varlist
self.varlist.append(varClass(h,varName,varType,varArray,varData,varPeriod,varLabel))
def validVarConstruct(self,thisvar):
"""Check whether we have a valid fortax variable construct."""
validLength = self.validVarConstructLength(thisvar)
if not validLength:
return False, '', '', False
validName, varName = self.validVarConstructName(thisvar[0])
if not validName:
return False, '', '', False
validType, varType, varArray = self.validVarConstructType(thisvar[1])
if not validType:
return False, '', '', False
return True, varName, varType, varArray
def validVarConstructLength(self,varlen):
"""Return True if length 3, False otherwise."""
if len(varlen)!=2:
print 'variable must specify name and type'
return False
else:
return True
def validVarConstructName(self,varname):
"""Return True if legal Fortan variable name, False otherwise."""
if (len(varname[0])>32):
return False, ''
if not(varname[0][0].isalpha()):
return False, ''
for ch in varname[0][1:]:
if not(ch.isalpha() or ch.isdigit() or ch=='_'):
return False, ''
return True, varname
def validVarConstructType(self,vartype):
"""Return True if valid Fortax type, False otherwise."""
indArray = vartype.find('[]')
if indArray>0:
thisType = vartype[0:indArray]
isArray = True
else:
thisType = vartype
isArray = False
if thisType in ('rng','range'):
type = 'range'
elif thisType in ('rate'):
type = 'rate'
elif thisType in ('amt','amount'):
type = 'amount'
elif thisType in ('minamt','minamount'):
type = 'minamount'
elif thisType in ('bool'):
type = 'bool'
else:
print 'variable type must be range, rate, amount, minamount, bool (or abbreviated forms)'
return False, ''
return True, type, isArray
def validVarConstructStorage(self,varStorage):
"""Return True if valid Fortax storage, False otherwise."""
if varStorage in fortaxStorageName.integer:
storage = fortaxStorage.integer
elif varStorage in fortaxStorageName.logical:
storage = fortaxStorage.logical
elif varStorage in fortaxStorageName.double:
storage = fortaxStorage.double
elif varStorage in fortaxStorageName.integerarray:
storage = fortaxStorage.integerarray
elif varStorage in fortaxStorageName.logicalarray:
storage = fortaxStorage.logicalarray
elif varStorage in fortaxStorageName.doublearray:
storage = fortaxStorage.doublearray
else:
print 'storage must be integer, integerarray, logical, logicalarray, double, doublearray (or abbreviated forms)'
return False
return True, storage
def validName(varname):
"""Return True is legal Fortan variable name, False otherwise."""
if (len(varname[0])>32):
return False
if not(varname[0][0].isalpha()):
return False
for ch in varname[0][1:]:
if not(ch.isalpha() or ch.isdigit() or ch=='_'):
return False
return True
def validPeriod(period):
"""Determine whether period is valid."""
try:
i = float(period)
except ValueError:
return False
else:
if i>0:
return True
else:
return False
def checkDate(datestr):
"""Return True if a valid date, False otherwise."""
try:
year = int(datestr[0:4])
except:
return False
try:
month = int(datestr[4:6])
except:
return False
try:
day = int(datestr[6:8])
except:
return False
try:
datetime.date(year, month, day)
except ValueError:
return False
return True
def getFortaxSysIndex(db,date):
if not checkDate(date):
print 'error: invalid date'
sys.exit()
else:
intDate = int(date)
if db.indexFile:
if date<db.idDate2[0]:
print 'error: requested date is out-of-range'
sys.exit()
if intDate>=db.idDate2[-1]:
dateIndex = db.numRec-1
else:
for ixD in range(len(db.idDate2)):
if intDate>=db.idDate2[ixD] and intDate<db.idDate2[ixD+1]:
dateIndex = ixD
else:
if date<db.idDate[0]:
print 'error: requested date is out-of-range'
sys.exit()
if intDate>=db.idDate[-1]:
dateIndex = db.numRec-1
else:
for ixD in range(db.numRec-1):
if intDate>=db.idDate[ixD] and intDate<db.idDate[ixD+1]:
dateIndex = ixD
return dateIndex
def fortaxFileLinks(db):
fileLinks = []
for thisDb in db:
for var in thisDb.varlist:
for ixD in range(thisDb.numRec):
if var.data[ixD][0:2]=='@>':
thisLink = var.data[ixD][2:]
try:
fileLinks.index(thisLink)
except:
fileLinks.append(thisLink)
return fileLinks
def recursiveLinking(db):
for thisDb in db:
for var in thisDb.varlist:
for ixD in range(len(var.data)): #range(thisDb.numRec):
if isinstance(var.data[ixD],list):
for a in var.data[ixD]:
if a[0:2]=='@>':
return True
else:
if var.data[ixD][0:2]=='@>':
return True
return False
def getLinkValue(db_name,db_link,var_name,date):
for thisDb in db_link:
if thisDb.sysname==db_name:
dateIndex = getFortaxSysIndex(thisDb,date)
for var in thisDb.varlist:
if var.varname==var_name:
return var.data[dateIndex]
return None
def writeXml(db,db_link,date):
print '<?xml version="1.0"?>'
print '<fortax>'
for thisDb in db:
#get date index
dateIndex = getFortaxSysIndex(thisDb,date)
print '<system basename="'+thisDb.sysname+'">'
for var in thisDb.varlist:
xmlStr = ' <'
if var.vartype=='range':
xmlStr = xmlStr+'finteger'
elif var.vartype in ('amount','minamount','rate'):
xmlStr = xmlStr+'fdouble'
elif var.vartype in ('bool'):
xmlStr = xmlStr+'flogical'
if var.vararray:
xmlStr = xmlStr+'array'
if var.fileLink[dateIndex]:
linkVal2 = getLinkValue(var.data[dateIndex][2:],db_link,var.varname,date)
linkVal = linkVal2[0]
for val in linkVal2[1:]:
linkVal = linkVal + ','+val
else:
linkVal = var.data[dateIndex]
xmlStr = xmlStr + ' name="'+var.varname+'" value="'
xmlStr = xmlStr + linkVal
xmlStr = xmlStr + '">'
print xmlStr
print '</system>'
print '</fortax>'
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of FORTAX Systems;
# (c) 2010 Andrew Shephard; andrubuntu@gmail.com
#
# FORTAX Systems is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
# FORTAX Systems is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
# You should have received a copy of the GNU General Public License along
# with FORTAX Systems. If not, see <http://www.gnu.org/licenses/>.
import optparse
import csv
import fortaxdb
import os.path
def main():
parser = optparse.OptionParser(version='%prog version 0.01a')
parser.add_option(
'-i', '--includes',
help='generate FORTAX include files',
dest='include',
default=False,
action='store_true'
)
parser.add_option(
'-d', '--date',
help='system date YYYYMMDD',
dest='date',
action='store_true'
)
parser.add_option(
'-l', '--label',
help='system label',
dest='label',
default='historic',
action='store_true'
)
(opts, args) = parser.parse_args()
print args
print opts
sysComponents = []
sysNames = []
#open the csv file that lists the system components
if not(os.path.isfile('syslist.csv')):
print 'file syslist.csv does not exist'
sys.exit()
sysList = csv.reader(open('syslist.csv'), delimiter=',', quotechar='"')
if opts.include:
f = open("syslist.inc", "w")
f.write('#undef _$typelist\n')
for row in sysList:
sysComponents.append(row[0])
sysNames.append(row[1])
if opts.include:
f.write('#define _$typelist '+row[0]+'\n')
f.write('#include "'+row[0]+'.inc"'+'\n\n')
f.write('#undef _$typelist\n')
f.write('')
if opts.include:
f.close()
#construct internal system database
fdb = []
for index, fname in enumerate(sysNames):
fdb.append(fortaxdb.fortaxVar(fname,sysComponents[index],opts,args))
#obtain file links from database
fdb_files = fortaxdb.fortaxFileLinks(fdb)
#construct database from linked files
fdb_links = []
for fname in fdb_files:
fdb_links.append(fortaxdb.fortaxVar(fname.strip('"'),fname,opts,args))
#verify whether nested linking
if fortaxdb.recursiveLinking(fdb_links):
print 'error: a linked file may not link to another file'
#check whether file exists
# if not(os.path.isfile(sysname)):
# print 'file '+sysname+' does not exist'
# sys.exit()
# sysfile = csv.reader(open(sysname), delimiter=',', quotechar='"')
fortaxdb.writeXml(fdb,fdb_links,'20021231')
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of FORTAX Systems;
# (c) 2010 Andrew Shephard; andrubuntu@gmail.com
#
# FORTAX Systems is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
# FORTAX Systems is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
# You should have received a copy of the GNU General Public License along
# with FORTAX Systems. If not, see <http://www.gnu.org/licenses/>.
import csv
import sys
import os.path
import datetime
from operator import itemgetter
class varClass(object):
"""Class docstring."""
def __init__(self, varindex, varname, vartype, vararray, vardata, varperiod, varlabel):
"""Method docstring."""
self.varindex = varindex
self.varname = varname
self.vartype = vartype
self.vararray = vararray
self.period = varperiod
self.label = varlabel
self.data = vardata
self.fileLink = [False for ixD in range(len(self.data))]
for ixD in range(len(self.data)):
if self.data[ixD][0:2]=='@>':
self.fileLink[ixD] = True
class fortaxVar():
def find(self, prefix, varname, header):
for h, hstr in enumerate(header):
if hstr[0:len(prefix)]==prefix:
if hstr[len(prefix):]==varname:
return h
return -1
def __init__(self,fname,sysname,opts,args):
#check whether file exists
if not(os.path.isfile(fname)):
print 'file '+fname+' does not exist'
sys.exit()
#open file
sysfile = csv.reader(open(fname), delimiter=',', quotechar='"')
#initialize
self.sysname = sysname #system name
db = [] #data in file fname
existHeader = False #if a file header exists
self.existLabel = False #if labels exist for variable
self.existPeriod = False #if period exist for variable
self.indexFile = False #if file is index file
#read sysfile line by line
for row in sysfile:
row2 = [x.strip() for x in row]
if row2[0]=='@#': #data line
db.append(row2)
elif row2[0]=='@^': #header line
if existHeader:
print 'error: multiple header records detected in '+fname
sys.exit()
self.header = row2
existHeader = True
elif row2[0]=='@!': #header line of index file
if existHeader:
print 'error: multiple header records detected in '+fname
sys.exit()
self.header = row2
existHeader = True
self.indexFile = True
elif row2[0]=='@?': #label line
if self.existLabel:
print 'error: multiple label records detected in '+fname
sys.exit()
self.label = row2
self.existLabel = True
elif row2[0]=='@.': #period line
if self.existPeriod:
print 'error: multiple period records detected in '+fname
sys.exit()
self.period = row2
self.existPeriod = True
#check header exists
if not existHeader:
print 'error: no header record exists in '+fname
sys.exit()
#column with date information
try:
dateInd = self.header.index('date')
except:
print 'error: no date column in '+fname
sys.exit()
#column with label information
try:
labelInd = self.header.index('label')
except:
print 'error: no label column'
sys.exit()
if self.indexFile:
try:
indexInd = self.header.index('index')
except:
print 'error: index file but no index column'
sys.exit()
#sort data by label, date, index
if self.indexFile:
db = sorted(db, key=itemgetter(indexInd))
db = sorted(db, key=itemgetter(dateInd))
db = sorted(db, key=itemgetter(labelInd))
#number of entries in db
self.numRec = len(db)
#for each line in db, create lists with date and label information
#dates will be stored as integers
#self.idDate = [int(0) for ixD in range(self.numRec)]
#self.idLabel = ['' for ixD in range(self.numRec)]
self.idDate = []
self.idLabel = []
self.idDate2 = []
self.idLabel2 = []
#if self.indexFile:
# self.idIndex = [int(0) for ixD in range(self.numRec)]
#check whether the date is valid
for ixD in range(self.numRec):
if not checkDate(db[ixD][dateInd]):
print 'error: invalid YYYYMMDD date format in '+fname
sys.exit()
else:
self.idDate.append(int(db[ixD][dateInd]))
self.idLabel.append(db[ixD][labelInd])
for ixD in range(self.numRec):
if (ixD==0) or (db[ixD][labelInd]!=db[ixD-1][labelInd]) or (db[ixD][dateInd]!=db[ixD-1][dateInd]):
self.idDate2.append(int(db[ixD][dateInd]))
self.idLabel2.append(db[ixD][labelInd])
#extract information from the database db
self.getFortaxVar(db)
#self.missingFortaxVar()
#self.checkFortaxVar()
#clean up junk
del self.header
#del self.idDate
if self.existPeriod:
del self.period
if self.existLabel:
del self.label
del self.existLabel
del self.existPeriod
del self.idLabel
def missingFortaxVar(self):
for var in self.varlist:
for ixD in range(self.numRec):
if var.data[ixD]=='':
if var.vartype=='range':
var.data[ixD] = '0'
if var.vartype in ('amount','minamount','rate'):
var.data[ixD] = '0.0'
if var.vartype in ('bool'):
var.data[ixD] = '0'
def getFortaxVar(self,db):
#varlist will contain the list of components in this system part
self.varlist = []
for h, hstr in enumerate(self.header):
if hstr[0:2]=='@_':
thisvar=hstr[2:].split('.')
#check whether we have a valid fortax variable construct
valid, varName, varType, varArray = self.validVarConstruct(thisvar)
if not valid:
print 'error: ' + hstr + ' is not a valid fortax variable construct'
sys.exit()
varData = []
#if an index file, the data will be a list. note that index is ORDINAL
if self.indexFile:
newObs = True
for ixD in range(self.numRec):
if newObs:
this = []
newObs = False
this.append(db[ixD][h])
if ixD<self.numRec-1:
if (self.idLabel[ixD]!=self.idLabel[ixD+1]) or (self.idDate[ixD]!=self.idDate[ixD+1]):
varData.append(this)
newObs = True
varData.append(this)
else:
for ixD in range(self.numRec):
varData.append(db[ixD][h])
#read label if it exists, otherwise set equal to variable name
if self.existLabel:
varLabel = self.label[h]
else:
varLabel = varName
#read period if it exists. this needs to be strictly positive,
#otherwise set equal to -1
if self.existPeriod:
varPeriod = self.period[h]
else:
varPeriod = -1
#append to varlist
self.varlist.append(varClass(h,varName,varType,varArray,varData,varPeriod,varLabel))
def validVarConstruct(self,thisvar):
"""Check whether we have a valid fortax variable construct."""
validLength = self.validVarConstructLength(thisvar)
if not validLength:
return False, '', '', False
validName, varName = self.validVarConstructName(thisvar[0])
if not validName:
return False, '', '', False
validType, varType, varArray = self.validVarConstructType(thisvar[1])
if not validType:
return False, '', '', False
return True, varName, varType, varArray
def validVarConstructLength(self,varlen):
"""Return True if length 3, False otherwise."""
if len(varlen)!=2:
print 'variable must specify name and type'
return False
else:
return True
def validVarConstructName(self,varname):
"""Return True if legal Fortan variable name, False otherwise."""
if (len(varname[0])>32):
return False, ''
if not(varname[0][0].isalpha()):
return False, ''
for ch in varname[0][1:]:
if not(ch.isalpha() or ch.isdigit() or ch=='_'):
return False, ''
return True, varname
def validVarConstructType(self,vartype):
"""Return True if valid Fortax type, False otherwise."""
indArray = vartype.find('[]')
if indArray>0:
thisType = vartype[0:indArray]
isArray = True
else:
thisType = vartype
isArray = False
if thisType in ('rng','range'):
type = 'range'
elif thisType in ('rate'):
type = 'rate'
elif thisType in ('amt','amount'):
type = 'amount'
elif thisType in ('minamt','minamount'):
type = 'minamount'
elif thisType in ('bool'):
type = 'bool'
else:
print 'variable type must be range, rate, amount, minamount, bool (or abbreviated forms)'
return False, ''
return True, type, isArray
def validVarConstructStorage(self,varStorage):
"""Return True if valid Fortax storage, False otherwise."""
if varStorage in fortaxStorageName.integer:
storage = fortaxStorage.integer
elif varStorage in fortaxStorageName.logical:
storage = fortaxStorage.logical
elif varStorage in fortaxStorageName.double:
storage = fortaxStorage.double
elif varStorage in fortaxStorageName.integerarray:
storage = fortaxStorage.integerarray
elif varStorage in fortaxStorageName.logicalarray:
storage = fortaxStorage.logicalarray
elif varStorage in fortaxStorageName.doublearray:
storage = fortaxStorage.doublearray
else:
print 'storage must be integer, integerarray, logical, logicalarray, double, doublearray (or abbreviated forms)'
return False
return True, storage
def validName(varname):
"""Return True is legal Fortan variable name, False otherwise."""
if (len(varname[0])>32):
return False
if not(varname[0][0].isalpha()):
return False
for ch in varname[0][1:]:
if not(ch.isalpha() or ch.isdigit() or ch=='_'):
return False
return True
def validPeriod(period):
"""Determine whether period is valid."""
try:
i = float(period)
except ValueError:
return False
else:
if i>0:
return True
else:
return False
def checkDate(datestr):
"""Return True if a valid date, False otherwise."""
try:
year = int(datestr[0:4])
except:
return False
try:
month = int(datestr[4:6])
except:
return False
try:
day = int(datestr[6:8])
except:
return False
try:
datetime.date(year, month, day)
except ValueError:
return False
return True
def getFortaxSysIndex(db,date):
if not checkDate(date):
print 'error: invalid date'
sys.exit()
else:
intDate = int(date)
if db.indexFile:
if date<db.idDate2[0]:
print 'error: requested date is out-of-range'
sys.exit()
if intDate>=db.idDate2[-1]:
dateIndex = db.numRec-1
else:
for ixD in range(len(db.idDate2)):
if intDate>=db.idDate2[ixD] and intDate<db.idDate2[ixD+1]:
dateIndex = ixD
else:
if date<db.idDate[0]:
print 'error: requested date is out-of-range'
sys.exit()
if intDate>=db.idDate[-1]:
dateIndex = db.numRec-1
else:
for ixD in range(db.numRec-1):
if intDate>=db.idDate[ixD] and intDate<db.idDate[ixD+1]:
dateIndex = ixD
return dateIndex
def fortaxFileLinks(db):
fileLinks = []
for thisDb in db:
for var in thisDb.varlist:
for ixD in range(thisDb.numRec):
if var.data[ixD][0:2]=='@>':
thisLink = var.data[ixD][2:]
try:
fileLinks.index(thisLink)
except:
fileLinks.append(thisLink)
return fileLinks
def recursiveLinking(db):
for thisDb in db:
for var in thisDb.varlist:
for ixD in range(len(var.data)): #range(thisDb.numRec):
if isinstance(var.data[ixD],list):
for a in var.data[ixD]:
if a[0:2]=='@>':
return True
else:
if var.data[ixD][0:2]=='@>':
return True
return False
def getLinkValue(db_name,db_link,var_name,date):
for thisDb in db_link:
if thisDb.sysname==db_name:
dateIndex = getFortaxSysIndex(thisDb,date)
for var in thisDb.varlist:
if var.varname==var_name:
return var.data[dateIndex]
return None
def writeXml(db,db_link,date):
print '<?xml version="1.0"?>'
print '<fortax>'
for thisDb in db:
#get date index
dateIndex = getFortaxSysIndex(thisDb,date)
print '<system basename="'+thisDb.sysname+'">'
for var in thisDb.varlist:
xmlStr = ' <'
if var.vartype=='range':
xmlStr = xmlStr+'finteger'
elif var.vartype in ('amount','minamount','rate'):
xmlStr = xmlStr+'fdouble'
elif var.vartype in ('bool'):
xmlStr = xmlStr+'flogical'
if var.vararray:
xmlStr = xmlStr+'array'
if var.fileLink[dateIndex]:
linkVal2 = getLinkValue(var.data[dateIndex][2:],db_link,var.varname,date)
linkVal = linkVal2[0]
for val in linkVal2[1:]:
linkVal = linkVal + ','+val
else:
linkVal = var.data[dateIndex]
xmlStr = xmlStr + ' name="'+var.varname+'" value="'
xmlStr = xmlStr + linkVal
xmlStr = xmlStr + '">'
print xmlStr
print '</system>'
print '</fortax>'
| Python |
#!/usr/bin/python
#
# Copyright (C) 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'afshar@google.com (Ali Afshar)'
# Add the library location to the path
import sys
sys.path.insert(0, 'lib')
import os
import httplib2
import sessions
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from apiclient.discovery import build
from apiclient.http import MediaUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from oauth2client.client import AccessTokenRefreshError
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.appengine import simplejson as json
ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file '
'https://www.googleapis.com/auth/userinfo.email '
'https://www.googleapis.com/auth/userinfo.profile')
def SibPath(name):
"""Generate a path that is a sibling of this file.
Args:
name: Name of sibling file.
Returns:
Path to sibling file.
"""
return os.path.join(os.path.dirname(__file__), name)
# Load the secret that is used for client side sessions
# Create one of these for yourself with, for example:
# python -c "import os; print os.urandom(64)" > session-secret
SESSION_SECRET = open(SibPath('session.secret')).read()
INDEX_HTML = open(SibPath('index.html')).read()
class Credentials(db.Model):
"""Datastore entity for storing OAuth2.0 credentials.
The CredentialsProperty is provided by the Google API Python Client, and is
used by the Storage classes to store OAuth 2.0 credentials in the data store."""
credentials = CredentialsProperty()
def CreateService(service, version, creds):
"""Create a Google API service.
Load an API service from a discovery document and authorize it with the
provided credentials.
Args:
service: Service name (e.g 'drive', 'oauth2').
version: Service version (e.g 'v1').
creds: Credentials used to authorize service.
Returns:
Authorized Google API service.
"""
# Instantiate an Http instance
http = httplib2.Http()
# Authorize the Http instance with the passed credentials
creds.authorize(http)
# Build a service from the passed discovery document path
return build(service, version, http=http)
class DriveState(object):
"""Store state provided by Drive."""
def __init__(self, state):
"""Create a new instance of drive state.
Parse and load the JSON state parameter.
Args:
state: State query parameter as a string.
"""
if state:
state_data = json.loads(state)
self.action = state_data['action']
self.ids = map(str, state_data.get('ids', []))
else:
self.action = 'create'
self.ids = []
@classmethod
def FromRequest(cls, request):
"""Create a Drive State instance from an HTTP request.
Args:
cls: Type this class method is called against.
request: HTTP request.
"""
return DriveState(request.get('state'))
class BaseDriveHandler(webapp.RequestHandler):
"""Base request handler for drive applications.
Adds Authorization support for Drive.
"""
def CreateOAuthFlow(self):
"""Create OAuth2.0 flow controller
This controller can be used to perform all parts of the OAuth 2.0 dance
including exchanging an Authorization code.
Args:
request: HTTP request to create OAuth2.0 flow for
Returns:
OAuth2.0 Flow instance suitable for performing OAuth2.0.
"""
flow = flow_from_clientsecrets('client_secrets.json', scope='')
# Dynamically set the redirect_uri based on the request URL. This is extremely
# convenient for debugging to an alternative host without manually setting the
# redirect URI.
flow.redirect_uri = self.request.url.split('?', 1)[0].rsplit('/', 1)[0]
return flow
def GetCodeCredentials(self):
"""Create OAuth 2.0 credentials by extracting a code and performing OAuth2.0.
The authorization code is extracted form the URI parameters. If it is absent,
None is returned immediately. Otherwise, if it is present, it is used to
perform step 2 of the OAuth 2.0 web server flow.
Once a token is received, the user information is fetched from the userinfo
service and stored in the session. The token is saved in the datastore against
the user ID received from the userinfo service.
Args:
request: HTTP request used for extracting an authorization code and the
session information.
Returns:
OAuth2.0 credentials suitable for authorizing clients or None if
Authorization could not take place.
"""
# Other frameworks use different API to get a query parameter.
code = self.request.get('code')
if not code:
# returns None to indicate that no code was passed from Google Drive.
return None
# Auth flow is a controller that is loaded with the client information,
# including client_id, client_secret, redirect_uri etc
oauth_flow = self.CreateOAuthFlow()
# Perform the exchange of the code. If there is a failure with exchanging
# the code, return None.
try:
creds = oauth_flow.step2_exchange(code)
except FlowExchangeError:
return None
# Create an API service that can use the userinfo API. Authorize it with our
# credentials that we gained from the code exchange.
users_service = CreateService('oauth2', 'v2', creds)
# Make a call against the userinfo service to retrieve the user's information.
# In this case we are interested in the user's "id" field.
userid = users_service.userinfo().get().execute().get('id')
# Store the user id in the user's cookie-based session.
session = sessions.LilCookies(self, SESSION_SECRET)
session.set_secure_cookie(name='userid', value=userid)
# Store the credentials in the data store using the userid as the key.
StorageByKeyName(Credentials, userid, 'credentials').put(creds)
return creds
def GetSessionCredentials(self):
"""Get OAuth 2.0 credentials for an HTTP session.
If the user has a user id stored in their cookie session, extract that value
and use it to load that user's credentials from the data store.
Args:
request: HTTP request to use session from.
Returns:
OAuth2.0 credentials suitable for authorizing clients.
"""
# Try to load the user id from the session
session = sessions.LilCookies(self, SESSION_SECRET)
userid = session.get_secure_cookie(name='userid')
if not userid:
# return None to indicate that no credentials could be loaded from the
# session.
return None
# Load the credentials from the data store, using the userid as a key.
creds = StorageByKeyName(Credentials, userid, 'credentials').get()
# if the credentials are invalid, return None to indicate that the credentials
# cannot be used.
if creds and creds.invalid:
return None
return creds
def RedirectAuth(self):
"""Redirect a handler to an authorization page.
Used when a handler fails to fetch credentials suitable for making Drive API
requests. The request is redirected to an OAuth 2.0 authorization approval
page and on approval, are returned to application.
Args:
handler: webapp.RequestHandler to redirect.
"""
flow = self.CreateOAuthFlow()
# Manually add the required scopes. Since this redirect does not originate
# from the Google Drive UI, which authomatically sets the scopes that are
# listed in the API Console.
flow.scope = ALL_SCOPES
# Create the redirect URI by performing step 1 of the OAuth 2.0 web server
# flow.
uri = flow.step1_get_authorize_url(flow.redirect_uri)
# Perform the redirect.
self.redirect(uri)
def RespondJSON(self, data):
"""Generate a JSON response and return it to the client.
Args:
data: The data that will be converted to JSON to return.
"""
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(data))
def CreateAuthorizedService(self, service, version):
"""Create an authorize service instance.
The service can only ever retrieve the credentials from the session.
Args:
service: Service name (e.g 'drive', 'oauth2').
version: Service version (e.g 'v1').
Returns:
Authorized service or redirect to authorization flow if no credentials.
"""
# For the service, the session holds the credentials
creds = self.GetSessionCredentials()
if creds:
# If the session contains credentials, use them to create a Drive service
# instance.
return CreateService(service, version, creds)
else:
# If no credentials could be loaded from the session, redirect the user to
# the authorization page.
self.RedirectAuth()
def CreateDrive(self):
"""Create a drive client instance."""
return self.CreateAuthorizedService('drive', 'v2')
def CreateUserInfo(self):
"""Create a user info client instance."""
return self.CreateAuthorizedService('oauth2', 'v2')
class MainPage(BaseDriveHandler):
"""Web handler for the main page.
Handles requests and returns the user interface for Open With and Create
cases. Responsible for parsing the state provided from the Drive UI and acting
appropriately.
"""
def get(self):
"""Handle GET for Create New and Open With.
This creates an authorized client, and checks whether a resource id has
been passed or not. If a resource ID has been passed, this is the Open
With use-case, otherwise it is the Create New use-case.
"""
# Generate a state instance for the request, this includes the action, and
# the file id(s) that have been sent from the Drive user interface.
drive_state = DriveState.FromRequest(self.request)
if drive_state.action == 'open' and len(drive_state.ids) > 0:
code = self.request.get('code')
if code:
code = '?code=%s' % code
self.redirect('/#edit/%s%s' % (drive_state.ids[0], code))
return
# Fetch the credentials by extracting an OAuth 2.0 authorization code from
# the request URL. If the code is not present, redirect to the OAuth 2.0
# authorization URL.
creds = self.GetCodeCredentials()
if not creds:
return self.RedirectAuth()
# Extract the numerical portion of the client_id from the stored value in
# the OAuth flow. You could also store this value as a separate variable
# somewhere.
client_id = self.CreateOAuthFlow().client_id.split('.')[0].split('-')[0]
self.RenderTemplate()
def RenderTemplate(self):
"""Render a named template in a context."""
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write(INDEX_HTML)
class ServiceHandler(BaseDriveHandler):
"""Web handler for the service to read and write to Drive."""
def post(self):
"""Called when HTTP POST requests are received by the web application.
The POST body is JSON which is deserialized and used as values to create a
new file in Drive. The authorization access token for this action is
retreived from the data store.
"""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
# Load the data that has been posted as JSON
data = self.RequestJSON()
# Create a new file data structure.
resource = {
'title': data['title'],
'description': data['description'],
'mimeType': data['mimeType'],
}
try:
# Make an insert request to create a new file. A MediaInMemoryUpload
# instance is used to upload the file body.
resource = service.files().insert(
body=resource,
media_body=MediaInMemoryUpload(
data.get('content', ''),
data['mimeType'],
resumable=True)
).execute()
# Respond with the new file id as JSON.
self.RespondJSON(resource['id'])
except AccessTokenRefreshError:
# In cases where the access token has expired and cannot be refreshed
# (e.g. manual token revoking) redirect the user to the authorization page
# to authorize.
self.RedirectAuth()
def get(self):
"""Called when HTTP GET requests are received by the web application.
Use the query parameter file_id to fetch the required file's metadata then
content and return it as a JSON object.
Since DrEdit deals with text files, it is safe to dump the content directly
into JSON, but this is not the case with binary files, where something like
Base64 encoding is more appropriate.
"""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
try:
# Requests are expected to pass the file_id query parameter.
file_id = self.request.get('file_id')
if file_id:
# Fetch the file metadata by making the service.files().get method of
# the Drive API.
f = service.files().get(fileId=file_id).execute()
downloadUrl = f.get('downloadUrl')
# If a download URL is provided in the file metadata, use it to make an
# authorized request to fetch the file ontent. Set this content in the
# data to return as the 'content' field. If there is no downloadUrl,
# just set empty content.
if downloadUrl:
resp, f['content'] = service._http.request(downloadUrl)
else:
f['content'] = ''
else:
f = None
# Generate a JSON response with the file data and return to the client.
self.RespondJSON(f)
except AccessTokenRefreshError:
# Catch AccessTokenRefreshError which occurs when the API client library
# fails to refresh a token. This occurs, for example, when a refresh token
# is revoked. When this happens the user is redirected to the
# Authorization URL.
self.RedirectAuth()
def put(self):
"""Called when HTTP PUT requests are received by the web application.
The PUT body is JSON which is deserialized and used as values to update
a file in Drive. The authorization access token for this action is
retreived from the data store.
"""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
# Load the data that has been posted as JSON
data = self.RequestJSON()
try:
# Create a new file data structure.
content = data.get('content')
if 'content' in data:
data.pop('content')
if content is not None:
# Make an update request to update the file. A MediaInMemoryUpload
# instance is used to upload the file body. Because of a limitation, this
# request must be made in two parts, the first to update the metadata, and
# the second to update the body.
resource = service.files().update(
fileId=data['resource_id'],
newRevision=self.request.get('newRevision', False),
body=data,
media_body=MediaInMemoryUpload(
content, data['mimeType'], resumable=True)
).execute()
else:
# Only update the metadata, a patch request is prefered but not yet
# supported on Google App Engine; see
# http://code.google.com/p/googleappengine/issues/detail?id=6316.
resource = service.files().update(
fileId=data['resource_id'],
newRevision=self.request.get('newRevision', False),
body=data).execute()
# Respond with the new file id as JSON.
self.RespondJSON(resource['id'])
except AccessTokenRefreshError:
# In cases where the access token has expired and cannot be refreshed
# (e.g. manual token revoking) redirect the user to the authorization page
# to authorize.
self.RedirectAuth()
def RequestJSON(self):
"""Load the request body as JSON.
Returns:
Request body loaded as JSON or None if there is no request body.
"""
if self.request.body:
return json.loads(self.request.body)
class UserHandler(BaseDriveHandler):
"""Web handler for the service to read user information."""
def get(self):
"""Called when HTTP GET requests are received by the web application."""
# Create a Drive service
service = self.CreateUserInfo()
if service is None:
return
try:
result = service.userinfo().get().execute()
# Generate a JSON response with the file data and return to the client.
self.RespondJSON(result)
except AccessTokenRefreshError:
# Catch AccessTokenRefreshError which occurs when the API client library
# fails to refresh a token. This occurs, for example, when a refresh token
# is revoked. When this happens the user is redirected to the
# Authorization URL.
self.RedirectAuth()
class AboutHandler(BaseDriveHandler):
"""Web handler for the service to read user information."""
def get(self):
"""Called when HTTP GET requests are received by the web application."""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
try:
result = service.about().get().execute()
# Generate a JSON response with the file data and return to the client.
self.RespondJSON(result)
except AccessTokenRefreshError:
# Catch AccessTokenRefreshError which occurs when the API client library
# fails to refresh a token. This occurs, for example, when a refresh token
# is revoked. When this happens the user is redirected to the
# Authorization URL.
self.RedirectAuth()
class MediaInMemoryUpload(MediaUpload):
"""MediaUpload for a chunk of bytes.
Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed plain text:
"""
def __init__(self, body, mimetype='application/octet-stream',
chunksize=256*1024, resumable=False):
"""Create a new MediaBytesUpload.
Args:
body: string, Bytes of body content.
mimetype: string, Mime-type of the file or default of
'application/octet-stream'.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._body = body
self._mimetype = mimetype
self._resumable = resumable
self._chunksize = chunksize
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body.
"""
return len(self._body)
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
return self._body[begin:begin + length]
# Create an WSGI application suitable for running on App Engine
application = webapp.WSGIApplication(
[('/', MainPage), ('/svc', ServiceHandler), ('/about', AboutHandler),
('/user', UserHandler)],
# XXX Set to False in production.
debug=True
)
def main():
"""Main entry point for executing a request with this handler."""
run_wsgi_app(application)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'afshar@google.com (Ali Afshar)'
import os
import httplib2
import sessions
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from apiclient.discovery import build_from_document
from apiclient.http import MediaUpload
from oauth2client import client
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.appengine import simplejson as json
APIS_BASE = 'https://www.googleapis.com'
ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file '
'https://www.googleapis.com/auth/userinfo.email '
'https://www.googleapis.com/auth/userinfo.profile')
CODE_PARAMETER = 'code'
STATE_PARAMETER = 'state'
SESSION_SECRET = open('session.secret').read()
DRIVE_DISCOVERY_DOC = open('drive.json').read()
USERS_DISCOVERY_DOC = open('users.json').read()
class Credentials(db.Model):
"""Datastore entity for storing OAuth2.0 credentials."""
credentials = CredentialsProperty()
def CreateOAuthFlow(request):
"""Create OAuth2.0 flow controller
Args:
request: HTTP request to create OAuth2.0 flow for
Returns:
OAuth2.0 Flow instance suitable for performing OAuth2.0.
"""
flow = client.flow_from_clientsecrets('client-debug.json', scope='')
flow.redirect_uri = request.url.split('?', 1)[0].rstrip('/')
return flow
def GetCodeCredentials(request):
"""Create OAuth2.0 credentials by extracting a code and performing OAuth2.0.
Args:
request: HTTP request used for extracting an authorization code.
Returns:
OAuth2.0 credentials suitable for authorizing clients.
"""
code = request.get(CODE_PARAMETER)
if code:
oauth_flow = CreateOAuthFlow(request)
creds = oauth_flow.step2_exchange(code)
users_service = CreateService(USERS_DISCOVERY_DOC, creds)
userid = users_service.userinfo().get().execute().get('id')
request.session.set_secure_cookie(name='userid', value=userid)
StorageByKeyName(Credentials, userid, 'credentials').put(creds)
return creds
def GetSessionCredentials(request):
"""Get OAuth2.0 credentials for an HTTP session.
Args:
request: HTTP request to use session from.
Returns:
OAuth2.0 credentials suitable for authorizing clients.
"""
userid = request.session.get_secure_cookie(name='userid')
if userid:
creds = StorageByKeyName(Credentials, userid, 'credentials').get()
if creds and not creds.invalid:
return creds
def CreateService(discovery_doc, creds):
"""Create a Google API service.
Args:
discovery_doc: Discovery doc used to configure service.
creds: Credentials used to authorize service.
Returns:
Authorized Google API service.
"""
http = httplib2.Http()
creds.authorize(http)
return build_from_document(discovery_doc, APIS_BASE, http=http)
def RedirectAuth(handler):
"""Redirect a handler to an authorization page.
Args:
handler: webapp.RequestHandler to redirect.
"""
flow = CreateOAuthFlow(handler.request)
flow.scope = ALL_SCOPES
uri = flow.step1_get_authorize_url(flow.redirect_uri)
handler.redirect(uri)
def CreateDrive(handler):
"""Create a fully authorized drive service for this handler.
Args:
handler: RequestHandler from which drive service is generated.
Returns:
Authorized drive service, generated from the handler request.
"""
request = handler.request
request.session = sessions.LilCookies(handler, SESSION_SECRET)
creds = GetCodeCredentials(request) or GetSessionCredentials(request)
if creds:
return CreateService(DRIVE_DISCOVERY_DOC, creds)
else:
RedirectAuth(handler)
def ServiceEnabled(view):
"""Decorator to inject an authorized service into an HTTP handler.
Args:
view: HTTP request handler method.
Returns:
Decorated handler which accepts the service as a parameter.
"""
def ServiceDecoratedView(handler, view=view):
service = CreateDrive(handler)
response_data = view(handler, service)
handler.response.headers['Content-Type'] = 'text/html'
handler.response.out.write(response_data)
return ServiceDecoratedView
def ServiceEnabledJson(view):
"""Decorator to inject an authorized service into a JSON HTTP handler.
Args:
view: HTTP request handler method.
Returns:
Decorated handler which accepts the service as a parameter.
"""
def ServiceDecoratedView(handler, view=view):
service = CreateDrive(handler)
if handler.request.body:
data = json.loads(handler.request.body)
else:
data = None
response_data = json.dumps(view(handler, service, data))
handler.response.headers['Content-Type'] = 'application/json'
handler.response.out.write(response_data)
return ServiceDecoratedView
class DriveState(object):
"""Store state provided by Drive."""
def __init__(self, state):
self.ParseState(state)
@classmethod
def FromRequest(cls, request):
"""Create a Drive State instance from an HTTP request.
Args:
cls: Type this class method is called against.
request: HTTP request.
"""
return DriveState(request.get(STATE_PARAMETER))
def ParseState(self, state):
"""Parse a state parameter and set internal values.
Args:
state: State parameter to parse.
"""
if state.startswith('{'):
self.ParseJsonState(state)
else:
self.ParsePlainState(state)
def ParseJsonState(self, state):
"""Parse a state parameter that is JSON.
Args:
state: State parameter to parse
"""
state_data = json.loads(state)
self.action = state_data['action']
self.ids = map(str, state_data.get('ids', []))
def ParsePlainState(self, state):
"""Parse a state parameter that is a plain resource id or missing.
Args:
state: State parameter to parse
"""
if state:
self.action = 'open'
self.ids = [state]
else:
self.action = 'create'
self.ids = []
class MediaInMemoryUpload(MediaUpload):
"""MediaUpload for a chunk of bytes.
Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed plain text:
"""
def __init__(self, body, mimetype='application/octet-stream',
chunksize=256*1024, resumable=False):
"""Create a new MediaBytesUpload.
Args:
body: string, Bytes of body content.
mimetype: string, Mime-type of the file or default of
'application/octet-stream'.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._body = body
self._mimetype = mimetype
self._resumable = resumable
self._chunksize = chunksize
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body.
"""
return len(self._body)
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
return self._body[begin:begin + length]
def RenderTemplate(name, **context):
"""Render a named template in a context.
Args:
name: Template name.
context: Keyword arguments to render as template variables.
"""
return template.render(name, context)
| Python |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import base64
import urllib
import time
import random
import urlparse
import hmac
import binascii
import httplib2
try:
from urlparse import parse_qs
parse_qs # placate pyflakes
except ImportError:
# fall back for Python 2.5
from cgi import parse_qs
try:
from hashlib import sha1
sha = sha1
except ImportError:
# hashlib was added in Python 2.5
import sha
import _version
__version__ = _version.__version__
OAUTH_VERSION = '1.0' # Hi Blaine!
HTTP_METHOD = 'GET'
SIGNATURE_METHOD = 'PLAINTEXT'
class Error(RuntimeError):
"""Generic exception class."""
def __init__(self, message='OAuth error occurred.'):
self._message = message
@property
def message(self):
"""A hack to get around the deprecation errors in 2.6."""
return self._message
def __str__(self):
return self._message
class MissingSignature(Error):
pass
def build_authenticate_header(realm=''):
"""Optional WWW-Authenticate header (401 error)"""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def build_xoauth_string(url, consumer, token=None):
"""Build an XOAUTH string for use in SMTP/IMPA authentication."""
request = Request.from_consumer_and_token(consumer, token,
"GET", url)
signing_method = SignatureMethod_HMAC_SHA1()
request.sign_request(signing_method, consumer, token)
params = []
for k, v in sorted(request.iteritems()):
if v is not None:
params.append('%s="%s"' % (k, escape(v)))
return "%s %s %s" % ("GET", url, ','.join(params))
def to_unicode(s):
""" Convert to unicode, raise exception with instructive error
message if s is not unicode, ascii, or utf-8. """
if not isinstance(s, unicode):
if not isinstance(s, str):
raise TypeError('You are required to pass either unicode or string here, not: %r (%s)' % (type(s), s))
try:
s = s.decode('utf-8')
except UnicodeDecodeError, le:
raise TypeError('You are required to pass either a unicode object or a utf-8 string here. You passed a Python string object which contained non-utf-8: %r. The UnicodeDecodeError that resulted from attempting to interpret it as utf-8 was: %s' % (s, le,))
return s
def to_utf8(s):
return to_unicode(s).encode('utf-8')
def to_unicode_if_string(s):
if isinstance(s, basestring):
return to_unicode(s)
else:
return s
def to_utf8_if_string(s):
if isinstance(s, basestring):
return to_utf8(s)
else:
return s
def to_unicode_optional_iterator(x):
"""
Raise TypeError if x is a str containing non-utf8 bytes or if x is
an iterable which contains such a str.
"""
if isinstance(x, basestring):
return to_unicode(x)
try:
l = list(x)
except TypeError, e:
assert 'is not iterable' in str(e)
return x
else:
return [ to_unicode(e) for e in l ]
def to_utf8_optional_iterator(x):
"""
Raise TypeError if x is a str or if x is an iterable which
contains a str.
"""
if isinstance(x, basestring):
return to_utf8(x)
try:
l = list(x)
except TypeError, e:
assert 'is not iterable' in str(e)
return x
else:
return [ to_utf8_if_string(e) for e in l ]
def escape(s):
"""Escape a URL including any /."""
return urllib.quote(s.encode('utf-8'), safe='~')
def generate_timestamp():
"""Get seconds since epoch (UTC)."""
return int(time.time())
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
class Consumer(object):
"""A consumer of OAuth-protected services.
The OAuth consumer is a "third-party" service that wants to access
protected resources from an OAuth service provider on behalf of an end
user. It's kind of the OAuth client.
Usually a consumer must be registered with the service provider by the
developer of the consumer software. As part of that process, the service
provider gives the consumer a *key* and a *secret* with which the consumer
software can identify itself to the service. The consumer will include its
key in each request to identify itself, but will use its secret only when
signing requests, to prove that the request is from that particular
registered consumer.
Once registered, the consumer can then use its consumer credentials to ask
the service provider for a request token, kicking off the OAuth
authorization process.
"""
key = None
secret = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
if self.key is None or self.secret is None:
raise ValueError("Key and secret must be set.")
def __str__(self):
data = {'oauth_consumer_key': self.key,
'oauth_consumer_secret': self.secret}
return urllib.urlencode(data)
class Token(object):
"""An OAuth credential used to request authorization or a protected
resource.
Tokens in OAuth comprise a *key* and a *secret*. The key is included in
requests to identify the token being used, but the secret is used only in
the signature, to prove that the requester is who the server gave the
token to.
When first negotiating the authorization, the consumer asks for a *request
token* that the live user authorizes with the service provider. The
consumer then exchanges the request token for an *access token* that can
be used to access protected resources.
"""
key = None
secret = None
callback = None
callback_confirmed = None
verifier = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
if self.key is None or self.secret is None:
raise ValueError("Key and secret must be set.")
def set_callback(self, callback):
self.callback = callback
self.callback_confirmed = 'true'
def set_verifier(self, verifier=None):
if verifier is not None:
self.verifier = verifier
else:
self.verifier = generate_verifier()
def get_callback_url(self):
if self.callback and self.verifier:
# Append the oauth_verifier.
parts = urlparse.urlparse(self.callback)
scheme, netloc, path, params, query, fragment = parts[:6]
if query:
query = '%s&oauth_verifier=%s' % (query, self.verifier)
else:
query = 'oauth_verifier=%s' % self.verifier
return urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
return self.callback
def to_string(self):
"""Returns this token as a plain string, suitable for storage.
The resulting string includes the token's secret, so you should never
send or store this string where a third party can read it.
"""
data = {
'oauth_token': self.key,
'oauth_token_secret': self.secret,
}
if self.callback_confirmed is not None:
data['oauth_callback_confirmed'] = self.callback_confirmed
return urllib.urlencode(data)
@staticmethod
def from_string(s):
"""Deserializes a token from a string like one returned by
`to_string()`."""
if not len(s):
raise ValueError("Invalid parameter string.")
params = parse_qs(s, keep_blank_values=False)
if not len(params):
raise ValueError("Invalid parameter string.")
try:
key = params['oauth_token'][0]
except Exception:
raise ValueError("'oauth_token' not found in OAuth request.")
try:
secret = params['oauth_token_secret'][0]
except Exception:
raise ValueError("'oauth_token_secret' not found in "
"OAuth request.")
token = Token(key, secret)
try:
token.callback_confirmed = params['oauth_callback_confirmed'][0]
except KeyError:
pass # 1.0, no callback confirmed.
return token
def __str__(self):
return self.to_string()
def setter(attr):
name = attr.__name__
def getter(self):
try:
return self.__dict__[name]
except KeyError:
raise AttributeError(name)
def deleter(self):
del self.__dict__[name]
return property(getter, attr, deleter)
class Request(dict):
"""The parameters and information for an HTTP request, suitable for
authorizing with OAuth credentials.
When a consumer wants to access a service's protected resources, it does
so using a signed HTTP request identifying itself (the consumer) with its
key, and providing an access token authorized by the end user to access
those resources.
"""
version = OAUTH_VERSION
def __init__(self, method=HTTP_METHOD, url=None, parameters=None,
body='', is_form_encoded=False):
if url is not None:
self.url = to_unicode(url)
self.method = method
if parameters is not None:
for k, v in parameters.iteritems():
k = to_unicode(k)
v = to_unicode_optional_iterator(v)
self[k] = v
self.body = body
self.is_form_encoded = is_form_encoded
@setter
def url(self, value):
self.__dict__['url'] = value
if value is not None:
scheme, netloc, path, params, query, fragment = urlparse.urlparse(value)
# Exclude default port numbers.
if scheme == 'http' and netloc[-3:] == ':80':
netloc = netloc[:-3]
elif scheme == 'https' and netloc[-4:] == ':443':
netloc = netloc[:-4]
if scheme not in ('http', 'https'):
raise ValueError("Unsupported URL %s (%s)." % (value, scheme))
# Normalized URL excludes params, query, and fragment.
self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None))
else:
self.normalized_url = None
self.__dict__['url'] = None
@setter
def method(self, value):
self.__dict__['method'] = value.upper()
def _get_timestamp_nonce(self):
return self['oauth_timestamp'], self['oauth_nonce']
def get_nonoauth_parameters(self):
"""Get any non-OAuth parameters."""
return dict([(k, v) for k, v in self.iteritems()
if not k.startswith('oauth_')])
def to_header(self, realm=''):
"""Serialize as a header for an HTTPAuth request."""
oauth_params = ((k, v) for k, v in self.items()
if k.startswith('oauth_'))
stringy_params = ((k, escape(str(v))) for k, v in oauth_params)
header_params = ('%s="%s"' % (k, v) for k, v in stringy_params)
params_header = ', '.join(header_params)
auth_header = 'OAuth realm="%s"' % realm
if params_header:
auth_header = "%s, %s" % (auth_header, params_header)
return {'Authorization': auth_header}
def to_postdata(self):
"""Serialize as post data for a POST request."""
d = {}
for k, v in self.iteritems():
d[k.encode('utf-8')] = to_utf8_optional_iterator(v)
# tell urlencode to deal with sequence values and map them correctly
# to resulting querystring. for example self["k"] = ["v1", "v2"] will
# result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D
return urllib.urlencode(d, True).replace('+', '%20')
def to_url(self):
"""Serialize as a URL for a GET request."""
base_url = urlparse.urlparse(self.url)
try:
query = base_url.query
except AttributeError:
# must be python <2.5
query = base_url[4]
query = parse_qs(query)
for k, v in self.items():
query.setdefault(k, []).append(v)
try:
scheme = base_url.scheme
netloc = base_url.netloc
path = base_url.path
params = base_url.params
fragment = base_url.fragment
except AttributeError:
# must be python <2.5
scheme = base_url[0]
netloc = base_url[1]
path = base_url[2]
params = base_url[3]
fragment = base_url[5]
url = (scheme, netloc, path, params,
urllib.urlencode(query, True), fragment)
return urlparse.urlunparse(url)
def get_parameter(self, parameter):
ret = self.get(parameter)
if ret is None:
raise Error('Parameter not found: %s' % parameter)
return ret
def get_normalized_parameters(self):
"""Return a string that contains the parameters that must be signed."""
items = []
for key, value in self.iteritems():
if key == 'oauth_signature':
continue
# 1.0a/9.1.1 states that kvp must be sorted by key, then by value,
# so we unpack sequence values into multiple items for sorting.
if isinstance(value, basestring):
items.append((to_utf8_if_string(key), to_utf8(value)))
else:
try:
value = list(value)
except TypeError, e:
assert 'is not iterable' in str(e)
items.append((to_utf8_if_string(key), to_utf8_if_string(value)))
else:
items.extend((to_utf8_if_string(key), to_utf8_if_string(item)) for item in value)
# Include any query string parameters from the provided URL
query = urlparse.urlparse(self.url)[4]
url_items = self._split_url_string(query).items()
url_items = [(to_utf8(k), to_utf8(v)) for k, v in url_items if k != 'oauth_signature' ]
items.extend(url_items)
items.sort()
encoded_str = urllib.urlencode(items)
# Encode signature parameters per Oauth Core 1.0 protocol
# spec draft 7, section 3.6
# (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6)
# Spaces must be encoded with "%20" instead of "+"
return encoded_str.replace('+', '%20').replace('%7E', '~')
def sign_request(self, signature_method, consumer, token):
"""Set the signature parameter to the result of sign."""
if not self.is_form_encoded:
# according to
# http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html
# section 4.1.1 "OAuth Consumers MUST NOT include an
# oauth_body_hash parameter on requests with form-encoded
# request bodies."
self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest())
if 'oauth_consumer_key' not in self:
self['oauth_consumer_key'] = consumer.key
if token and 'oauth_token' not in self:
self['oauth_token'] = token.key
self['oauth_signature_method'] = signature_method.name
self['oauth_signature'] = signature_method.sign(self, consumer, token)
@classmethod
def make_timestamp(cls):
"""Get seconds since epoch (UTC)."""
return str(int(time.time()))
@classmethod
def make_nonce(cls):
"""Generate pseudorandom number."""
return str(random.randint(0, 100000000))
@classmethod
def from_request(cls, http_method, http_url, headers=None, parameters=None,
query_string=None):
"""Combines multiple parameter sources."""
if parameters is None:
parameters = {}
# Headers
if headers and 'Authorization' in headers:
auth_header = headers['Authorization']
# Check that the authorization header is OAuth.
if auth_header[:6] == 'OAuth ':
auth_header = auth_header[6:]
try:
# Get the parameters from the header.
header_params = cls._split_header(auth_header)
parameters.update(header_params)
except:
raise Error('Unable to parse OAuth parameters from '
'Authorization header.')
# GET or POST query string.
if query_string:
query_params = cls._split_url_string(query_string)
parameters.update(query_params)
# URL parameters.
param_str = urlparse.urlparse(http_url)[4] # query
url_params = cls._split_url_string(param_str)
parameters.update(url_params)
if parameters:
return cls(http_method, http_url, parameters)
return None
@classmethod
def from_consumer_and_token(cls, consumer, token=None,
http_method=HTTP_METHOD, http_url=None, parameters=None,
body='', is_form_encoded=False):
if not parameters:
parameters = {}
defaults = {
'oauth_consumer_key': consumer.key,
'oauth_timestamp': cls.make_timestamp(),
'oauth_nonce': cls.make_nonce(),
'oauth_version': cls.version,
}
defaults.update(parameters)
parameters = defaults
if token:
parameters['oauth_token'] = token.key
if token.verifier:
parameters['oauth_verifier'] = token.verifier
return Request(http_method, http_url, parameters, body=body,
is_form_encoded=is_form_encoded)
@classmethod
def from_token_and_callback(cls, token, callback=None,
http_method=HTTP_METHOD, http_url=None, parameters=None):
if not parameters:
parameters = {}
parameters['oauth_token'] = token.key
if callback:
parameters['oauth_callback'] = callback
return cls(http_method, http_url, parameters)
@staticmethod
def _split_header(header):
"""Turn Authorization: header into parameters."""
params = {}
parts = header.split(',')
for param in parts:
# Ignore realm parameter.
if param.find('realm') > -1:
continue
# Remove whitespace.
param = param.strip()
# Split key-value.
param_parts = param.split('=', 1)
# Remove quotes and unescape the value.
params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"'))
return params
@staticmethod
def _split_url_string(param_str):
"""Turn URL string into parameters."""
parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True)
for k, v in parameters.iteritems():
parameters[k] = urllib.unquote(v[0])
return parameters
class Client(httplib2.Http):
"""OAuthClient is a worker to attempt to execute a request."""
def __init__(self, consumer, token=None, cache=None, timeout=None,
proxy_info=None):
if consumer is not None and not isinstance(consumer, Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, Token):
raise ValueError("Invalid token.")
self.consumer = consumer
self.token = token
self.method = SignatureMethod_HMAC_SHA1()
httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info)
def set_signature_method(self, method):
if not isinstance(method, SignatureMethod):
raise ValueError("Invalid signature method.")
self.method = method
def request(self, uri, method="GET", body='', headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
DEFAULT_POST_CONTENT_TYPE = 'application/x-www-form-urlencoded'
if not isinstance(headers, dict):
headers = {}
if method == "POST":
headers['Content-Type'] = headers.get('Content-Type',
DEFAULT_POST_CONTENT_TYPE)
is_form_encoded = \
headers.get('Content-Type') == 'application/x-www-form-urlencoded'
if is_form_encoded and body:
parameters = parse_qs(body)
else:
parameters = None
req = Request.from_consumer_and_token(self.consumer,
token=self.token, http_method=method, http_url=uri,
parameters=parameters, body=body, is_form_encoded=is_form_encoded)
req.sign_request(self.method, self.consumer, self.token)
schema, rest = urllib.splittype(uri)
if rest.startswith('//'):
hierpart = '//'
else:
hierpart = ''
host, rest = urllib.splithost(rest)
realm = schema + ':' + hierpart + host
if is_form_encoded:
body = req.to_postdata()
elif method == "GET":
uri = req.to_url()
else:
headers.update(req.to_header(realm=realm))
return httplib2.Http.request(self, uri, method=method, body=body,
headers=headers, redirections=redirections,
connection_type=connection_type)
class Server(object):
"""A skeletal implementation of a service provider, providing protected
resources to requests from authorized consumers.
This class implements the logic to check requests for authorization. You
can use it with your web server or web framework to protect certain
resources with OAuth.
"""
timestamp_threshold = 300 # In seconds, five minutes.
version = OAUTH_VERSION
signature_methods = None
def __init__(self, signature_methods=None):
self.signature_methods = signature_methods or {}
def add_signature_method(self, signature_method):
self.signature_methods[signature_method.name] = signature_method
return self.signature_methods
def verify_request(self, request, consumer, token):
"""Verifies an api call and checks all the parameters."""
self._check_version(request)
self._check_signature(request, consumer, token)
parameters = request.get_nonoauth_parameters()
return parameters
def build_authenticate_header(self, realm=''):
"""Optional support for the authenticate header."""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def _check_version(self, request):
"""Verify the correct version of the request for this server."""
version = self._get_version(request)
if version and version != self.version:
raise Error('OAuth version %s not supported.' % str(version))
def _get_version(self, request):
"""Return the version of the request for this server."""
try:
version = request.get_parameter('oauth_version')
except:
version = OAUTH_VERSION
return version
def _get_signature_method(self, request):
"""Figure out the signature with some defaults."""
try:
signature_method = request.get_parameter('oauth_signature_method')
except:
signature_method = SIGNATURE_METHOD
try:
# Get the signature method object.
signature_method = self.signature_methods[signature_method]
except:
signature_method_names = ', '.join(self.signature_methods.keys())
raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names))
return signature_method
def _get_verifier(self, request):
return request.get_parameter('oauth_verifier')
def _check_signature(self, request, consumer, token):
timestamp, nonce = request._get_timestamp_nonce()
self._check_timestamp(timestamp)
signature_method = self._get_signature_method(request)
try:
signature = request.get_parameter('oauth_signature')
except:
raise MissingSignature('Missing oauth_signature.')
# Validate the signature.
valid = signature_method.check(request, consumer, token, signature)
if not valid:
key, base = signature_method.signing_base(request, consumer, token)
raise Error('Invalid signature. Expected signature base '
'string: %s' % base)
def _check_timestamp(self, timestamp):
"""Verify that timestamp is recentish."""
timestamp = int(timestamp)
now = int(time.time())
lapsed = now - timestamp
if lapsed > self.timestamp_threshold:
raise Error('Expired timestamp: given %d and now %s has a '
'greater difference than threshold %d' % (timestamp, now,
self.timestamp_threshold))
class SignatureMethod(object):
"""A way of signing requests.
The OAuth protocol lets consumers and service providers pick a way to sign
requests. This interface shows the methods expected by the other `oauth`
modules for signing requests. Subclass it and implement its methods to
provide a new way to sign requests.
"""
def signing_base(self, request, consumer, token):
"""Calculates the string that needs to be signed.
This method returns a 2-tuple containing the starting key for the
signing and the message to be signed. The latter may be used in error
messages to help clients debug their software.
"""
raise NotImplementedError
def sign(self, request, consumer, token):
"""Returns the signature for the given request, based on the consumer
and token also provided.
You should use your implementation of `signing_base()` to build the
message to sign. Otherwise it may be less useful for debugging.
"""
raise NotImplementedError
def check(self, request, consumer, token, signature):
"""Returns whether the given signature is the correct signature for
the given consumer and token signing the given request."""
built = self.sign(request, consumer, token)
return built == signature
class SignatureMethod_HMAC_SHA1(SignatureMethod):
name = 'HMAC-SHA1'
def signing_base(self, request, consumer, token):
if not hasattr(request, 'normalized_url') or request.normalized_url is None:
raise ValueError("Base URL for request is not set.")
sig = (
escape(request.method),
escape(request.normalized_url),
escape(request.get_normalized_parameters()),
)
key = '%s&' % escape(consumer.secret)
if token:
key += escape(token.secret)
raw = '&'.join(sig)
return key, raw
def sign(self, request, consumer, token):
"""Builds the base signature string."""
key, raw = self.signing_base(request, consumer, token)
hashed = hmac.new(key, raw, sha)
# Calculate the digest base 64.
return binascii.b2a_base64(hashed.digest())[:-1]
class SignatureMethod_PLAINTEXT(SignatureMethod):
name = 'PLAINTEXT'
def signing_base(self, request, consumer, token):
"""Concatenates the consumer key and secret with the token's
secret."""
sig = '%s&' % escape(consumer.secret)
if token:
sig = sig + escape(token.secret)
return sig, sig
def sign(self, request, consumer, token):
key, raw = self.signing_base(request, consumer, token)
return raw
| Python |
# This is the version of this source code.
manual_verstr = "1.5"
auto_build_num = "211"
verstr = manual_verstr + "." + auto_build_num
try:
from pyutil.version_class import Version as pyutil_Version
__version__ = pyutil_Version(verstr)
except (ImportError, ValueError):
# Maybe there is no pyutil installed.
from distutils.version import LooseVersion as distutils_Version
__version__ = distutils_Version(verstr)
| Python |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import oauth2
import imaplib
class IMAP4_SSL(imaplib.IMAP4_SSL):
"""IMAP wrapper for imaplib.IMAP4_SSL that implements XOAUTH."""
def authenticate(self, url, consumer, token):
if consumer is not None and not isinstance(consumer, oauth2.Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, oauth2.Token):
raise ValueError("Invalid token.")
imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH',
lambda x: oauth2.build_xoauth_string(url, consumer, token))
| Python |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import oauth2
import smtplib
import base64
class SMTP(smtplib.SMTP):
"""SMTP wrapper for smtplib.SMTP that implements XOAUTH."""
def authenticate(self, url, consumer, token):
if consumer is not None and not isinstance(consumer, oauth2.Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, oauth2.Token):
raise ValueError("Invalid token.")
self.docmd('AUTH', 'XOAUTH %s' % \
base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command-line tools for authenticating via OAuth 2.0
Do the OAuth 2.0 Web Server dance for a command line application. Stores the
generated credentials in a common file that is used by other example apps in
the same directory.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
__all__ = ['run']
import BaseHTTPServer
import gflags
import socket
import sys
import webbrowser
from client import FlowExchangeError
from client import OOB_CALLBACK_URN
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('auth_local_webserver', True,
('Run a local web server to handle redirects during '
'OAuth authorization.'))
gflags.DEFINE_string('auth_host_name', 'localhost',
('Host name to use when running a local web server to '
'handle redirects during OAuth authorization.'))
gflags.DEFINE_multi_int('auth_host_port', [8080, 8090],
('Port to use when running a local web server to '
'handle redirects during OAuth authorization.'))
class ClientRedirectServer(BaseHTTPServer.HTTPServer):
"""A server to handle OAuth 2.0 redirects back to localhost.
Waits for a single request and parses the query parameters
into query_params and then stops serving.
"""
query_params = {}
class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""A handler for OAuth 2.0 redirects back to localhost.
Waits for a single request and parses the query parameters
into the servers query_params and then stops serving.
"""
def do_GET(s):
"""Handle a GET request.
Parses the query parameters and prints a message
if the flow has completed. Note that we can't detect
if an error occurred.
"""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
query = s.path.split('?', 1)[-1]
query = dict(parse_qsl(query))
s.server.query_params = query
s.wfile.write("<html><head><title>Authentication Status</title></head>")
s.wfile.write("<body><p>The authentication flow has completed.</p>")
s.wfile.write("</body></html>")
def log_message(self, format, *args):
"""Do not log messages to stdout while running as command line program."""
pass
def run(flow, storage, http=None):
"""Core code for a command-line application.
Args:
flow: Flow, an OAuth 2.0 Flow to step through.
storage: Storage, a Storage to store the credential in.
http: An instance of httplib2.Http.request
or something that acts like it.
Returns:
Credentials, the obtained credential.
"""
if FLAGS.auth_local_webserver:
success = False
port_number = 0
for port in FLAGS.auth_host_port:
port_number = port
try:
httpd = ClientRedirectServer((FLAGS.auth_host_name, port),
ClientRedirectHandler)
except socket.error, e:
pass
else:
success = True
break
FLAGS.auth_local_webserver = success
if not success:
print 'Failed to start a local webserver listening on either port 8080'
print 'or port 9090. Please check your firewall settings and locally'
print 'running programs that may be blocking or using those ports.'
print
print 'Falling back to --noauth_local_webserver and continuing with',
print 'authorization.'
print
if FLAGS.auth_local_webserver:
oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number)
else:
oauth_callback = OOB_CALLBACK_URN
authorize_url = flow.step1_get_authorize_url(oauth_callback)
if FLAGS.auth_local_webserver:
webbrowser.open(authorize_url, new=1, autoraise=True)
print 'Your browser has been opened to visit:'
print
print ' ' + authorize_url
print
print 'If your browser is on a different machine then exit and re-run this'
print 'application with the command-line parameter '
print
print ' --noauth_local_webserver'
print
else:
print 'Go to the following link in your browser:'
print
print ' ' + authorize_url
print
code = None
if FLAGS.auth_local_webserver:
httpd.handle_request()
if 'error' in httpd.query_params:
sys.exit('Authentication request was rejected.')
if 'code' in httpd.query_params:
code = httpd.query_params['code']
else:
print 'Failed to find "code" in the query parameters of the redirect.'
sys.exit('Try running with --noauth_local_webserver.')
else:
code = raw_input('Enter verification code: ').strip()
try:
credential = flow.step2_exchange(code, http)
except FlowExchangeError, e:
sys.exit('Authentication has failed: %s' % e)
storage.put(credential)
credential.set_store(storage)
print 'Authentication successful.'
return credential
| Python |
# Copyright 2011 Google Inc. All Rights Reserved.
"""Multi-credential file store with lock support.
This module implements a JSON credential store where multiple
credentials can be stored in one file. That file supports locking
both in a single process and across processes.
The credential themselves are keyed off of:
* client_id
* user_agent
* scope
The format of the stored data is like so:
{
'file_version': 1,
'data': [
{
'key': {
'clientId': '<client id>',
'userAgent': '<user agent>',
'scope': '<scope>'
},
'credential': {
# JSON serialized Credentials.
}
}
]
}
"""
__author__ = 'jbeda@google.com (Joe Beda)'
import base64
import errno
import logging
import os
import threading
from anyjson import simplejson
from client import Storage as BaseStorage
from client import Credentials
from locked_file import LockedFile
logger = logging.getLogger(__name__)
# A dict from 'filename'->_MultiStore instances
_multistores = {}
_multistores_lock = threading.Lock()
class Error(Exception):
"""Base error for this module."""
pass
class NewerCredentialStoreError(Error):
"""The credential store is a newer version that supported."""
pass
def get_credential_storage(filename, client_id, user_agent, scope,
warn_on_readonly=True):
"""Get a Storage instance for a credential.
Args:
filename: The JSON file storing a set of credentials
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: string or list of strings, Scope(s) being requested
warn_on_readonly: if True, log a warning if the store is readonly
Returns:
An object derived from client.Storage for getting/setting the
credential.
"""
filename = os.path.realpath(os.path.expanduser(filename))
_multistores_lock.acquire()
try:
multistore = _multistores.setdefault(
filename, _MultiStore(filename, warn_on_readonly))
finally:
_multistores_lock.release()
if type(scope) is list:
scope = ' '.join(scope)
return multistore._get_storage(client_id, user_agent, scope)
class _MultiStore(object):
"""A file backed store for multiple credentials."""
def __init__(self, filename, warn_on_readonly=True):
"""Initialize the class.
This will create the file if necessary.
"""
self._file = LockedFile(filename, 'r+b', 'rb')
self._thread_lock = threading.Lock()
self._read_only = False
self._warn_on_readonly = warn_on_readonly
self._create_file_if_needed()
# Cache of deserialized store. This is only valid after the
# _MultiStore is locked or _refresh_data_cache is called. This is
# of the form of:
#
# (client_id, user_agent, scope) -> OAuth2Credential
#
# If this is None, then the store hasn't been read yet.
self._data = None
class _Storage(BaseStorage):
"""A Storage object that knows how to read/write a single credential."""
def __init__(self, multistore, client_id, user_agent, scope):
self._multistore = multistore
self._client_id = client_id
self._user_agent = user_agent
self._scope = scope
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant.
"""
self._multistore._lock()
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
self._multistore._unlock()
def locked_get(self):
"""Retrieve credential.
The Storage lock must be held when this is called.
Returns:
oauth2client.client.Credentials
"""
credential = self._multistore._get_credential(
self._client_id, self._user_agent, self._scope)
if credential:
credential.set_store(self)
return credential
def locked_put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
self._multistore._update_credential(credentials, self._scope)
def locked_delete(self):
"""Delete a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
self._multistore._delete_credential(self._client_id, self._user_agent,
self._scope)
def _create_file_if_needed(self):
"""Create an empty file if necessary.
This method will not initialize the file. Instead it implements a
simple version of "touch" to ensure the file has been created.
"""
if not os.path.exists(self._file.filename()):
old_umask = os.umask(0177)
try:
open(self._file.filename(), 'a+b').close()
finally:
os.umask(old_umask)
def _lock(self):
"""Lock the entire multistore."""
self._thread_lock.acquire()
self._file.open_and_lock()
if not self._file.is_locked():
self._read_only = True
if self._warn_on_readonly:
logger.warn('The credentials file (%s) is not writable. Opening in '
'read-only mode. Any refreshed credentials will only be '
'valid for this run.' % self._file.filename())
if os.path.getsize(self._file.filename()) == 0:
logger.debug('Initializing empty multistore file')
# The multistore is empty so write out an empty file.
self._data = {}
self._write()
elif not self._read_only or self._data is None:
# Only refresh the data if we are read/write or we haven't
# cached the data yet. If we are readonly, we assume is isn't
# changing out from under us and that we only have to read it
# once. This prevents us from whacking any new access keys that
# we have cached in memory but were unable to write out.
self._refresh_data_cache()
def _unlock(self):
"""Release the lock on the multistore."""
self._file.unlock_and_close()
self._thread_lock.release()
def _locked_json_read(self):
"""Get the raw content of the multistore file.
The multistore must be locked when this is called.
Returns:
The contents of the multistore decoded as JSON.
"""
assert self._thread_lock.locked()
self._file.file_handle().seek(0)
return simplejson.load(self._file.file_handle())
def _locked_json_write(self, data):
"""Write a JSON serializable data structure to the multistore.
The multistore must be locked when this is called.
Args:
data: The data to be serialized and written.
"""
assert self._thread_lock.locked()
if self._read_only:
return
self._file.file_handle().seek(0)
simplejson.dump(data, self._file.file_handle(), sort_keys=True, indent=2)
self._file.file_handle().truncate()
def _refresh_data_cache(self):
"""Refresh the contents of the multistore.
The multistore must be locked when this is called.
Raises:
NewerCredentialStoreError: Raised when a newer client has written the
store.
"""
self._data = {}
try:
raw_data = self._locked_json_read()
except Exception:
logger.warn('Credential data store could not be loaded. '
'Will ignore and overwrite.')
return
version = 0
try:
version = raw_data['file_version']
except Exception:
logger.warn('Missing version for credential data store. It may be '
'corrupt or an old version. Overwriting.')
if version > 1:
raise NewerCredentialStoreError(
'Credential file has file_version of %d. '
'Only file_version of 1 is supported.' % version)
credentials = []
try:
credentials = raw_data['data']
except (TypeError, KeyError):
pass
for cred_entry in credentials:
try:
(key, credential) = self._decode_credential_from_json(cred_entry)
self._data[key] = credential
except:
# If something goes wrong loading a credential, just ignore it
logger.info('Error decoding credential, skipping', exc_info=True)
def _decode_credential_from_json(self, cred_entry):
"""Load a credential from our JSON serialization.
Args:
cred_entry: A dict entry from the data member of our format
Returns:
(key, cred) where the key is the key tuple and the cred is the
OAuth2Credential object.
"""
raw_key = cred_entry['key']
client_id = raw_key['clientId']
user_agent = raw_key['userAgent']
scope = raw_key['scope']
key = (client_id, user_agent, scope)
credential = None
credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential']))
return (key, credential)
def _write(self):
"""Write the cached data back out.
The multistore must be locked.
"""
raw_data = {'file_version': 1}
raw_creds = []
raw_data['data'] = raw_creds
for (cred_key, cred) in self._data.items():
raw_key = {
'clientId': cred_key[0],
'userAgent': cred_key[1],
'scope': cred_key[2]
}
raw_cred = simplejson.loads(cred.to_json())
raw_creds.append({'key': raw_key, 'credential': raw_cred})
self._locked_json_write(raw_data)
def _get_credential(self, client_id, user_agent, scope):
"""Get a credential from the multistore.
The multistore must be locked.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: A string for the scope(s) being requested
Returns:
The credential specified or None if not present
"""
key = (client_id, user_agent, scope)
return self._data.get(key, None)
def _update_credential(self, cred, scope):
"""Update a credential and write the multistore.
This must be called when the multistore is locked.
Args:
cred: The OAuth2Credential to update/set
scope: The scope(s) that this credential covers
"""
key = (cred.client_id, cred.user_agent, scope)
self._data[key] = cred
self._write()
def _delete_credential(self, client_id, user_agent, scope):
"""Delete a credential and write the multistore.
This must be called when the multistore is locked.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: The scope(s) that this credential covers
"""
key = (client_id, user_agent, scope)
try:
del self._data[key]
except KeyError:
pass
self._write()
def _get_storage(self, client_id, user_agent, scope):
"""Get a Storage object to get/set a credential.
This Storage is a 'view' into the multistore.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: A string for the scope(s) being requested
Returns:
A Storage object that can be used to get/set this cred
"""
return self._Storage(self, client_id, user_agent, scope)
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""An OAuth 2.0 client.
Tools for interacting with OAuth 2.0 protected resources.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import base64
import clientsecrets
import copy
import datetime
import httplib2
import logging
import os
import sys
import time
import urllib
import urlparse
from anyjson import simplejson
HAS_OPENSSL = False
try:
from oauth2client.crypt import Signer
from oauth2client.crypt import make_signed_jwt
from oauth2client.crypt import verify_signed_jwt_with_certs
HAS_OPENSSL = True
except ImportError:
pass
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
logger = logging.getLogger(__name__)
# Expiry is stored in RFC3339 UTC format
EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
# Which certs to use to validate id_tokens received.
ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth2/v1/certs'
# Constant to use for the out of band OAuth 2.0 flow.
OOB_CALLBACK_URN = 'urn:ietf:wg:oauth:2.0:oob'
class Error(Exception):
"""Base error for this module."""
pass
class FlowExchangeError(Error):
"""Error trying to exchange an authorization grant for an access token."""
pass
class AccessTokenRefreshError(Error):
"""Error trying to refresh an expired access token."""
pass
class UnknownClientSecretsFlowError(Error):
"""The client secrets file called for an unknown type of OAuth 2.0 flow. """
pass
class AccessTokenCredentialsError(Error):
"""Having only the access_token means no refresh is possible."""
pass
class VerifyJwtTokenError(Error):
"""Could on retrieve certificates for validation."""
pass
def _abstract():
raise NotImplementedError('You need to override this function')
class MemoryCache(object):
"""httplib2 Cache implementation which only caches locally."""
def __init__(self):
self.cache = {}
def get(self, key):
return self.cache.get(key)
def set(self, key, value):
self.cache[key] = value
def delete(self, key):
self.cache.pop(key, None)
class Credentials(object):
"""Base class for all Credentials objects.
Subclasses must define an authorize() method that applies the credentials to
an HTTP transport.
Subclasses must also specify a classmethod named 'from_json' that takes a JSON
string as input and returns an instaniated Credentials object.
"""
NON_SERIALIZED_MEMBERS = ['store']
def authorize(self, http):
"""Take an httplib2.Http instance (or equivalent) and
authorizes it for the set of credentials, usually by
replacing http.request() with a method that adds in
the appropriate headers and then delegates to the original
Http.request() method.
"""
_abstract()
def refresh(self, http):
"""Forces a refresh of the access_token.
Args:
http: httplib2.Http, an http object to be used to make the refresh
request.
"""
_abstract()
def apply(self, headers):
"""Add the authorization to the headers.
Args:
headers: dict, the headers to add the Authorization header to.
"""
_abstract()
def _to_json(self, strip):
"""Utility function for creating a JSON representation of an instance of Credentials.
Args:
strip: array, An array of names of members to not include in the JSON.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
t = type(self)
d = copy.copy(self.__dict__)
for member in strip:
if member in d:
del d[member]
if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime):
d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT)
# Add in information we will need later to reconsistitue this instance.
d['_class'] = t.__name__
d['_module'] = t.__module__
return simplejson.dumps(d)
def to_json(self):
"""Creating a JSON representation of an instance of Credentials.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
return self._to_json(Credentials.NON_SERIALIZED_MEMBERS)
@classmethod
def new_from_json(cls, s):
"""Utility class method to instantiate a Credentials subclass from a JSON
representation produced by to_json().
Args:
s: string, JSON from to_json().
Returns:
An instance of the subclass of Credentials that was serialized with
to_json().
"""
data = simplejson.loads(s)
# Find and call the right classmethod from_json() to restore the object.
module = data['_module']
try:
m = __import__(module)
except ImportError:
# In case there's an object from the old package structure, update it
module = module.replace('.apiclient', '')
m = __import__(module)
m = __import__(module, fromlist=module.split('.')[:-1])
kls = getattr(m, data['_class'])
from_json = getattr(kls, 'from_json')
return from_json(s)
@classmethod
def from_json(cls, s):
"""Instantiate a Credentials object from a JSON description of it.
The JSON should have been produced by calling .to_json() on the object.
Args:
data: dict, A deserialized JSON object.
Returns:
An instance of a Credentials subclass.
"""
return Credentials()
class Flow(object):
"""Base class for all Flow objects."""
pass
class Storage(object):
"""Base class for all Storage objects.
Store and retrieve a single credential. This class supports locking
such that multiple processes and threads can operate on a single
store.
"""
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant.
"""
pass
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
pass
def locked_get(self):
"""Retrieve credential.
The Storage lock must be held when this is called.
Returns:
oauth2client.client.Credentials
"""
_abstract()
def locked_put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
_abstract()
def locked_delete(self):
"""Delete a credential.
The Storage lock must be held when this is called.
"""
_abstract()
def get(self):
"""Retrieve credential.
The Storage lock must *not* be held when this is called.
Returns:
oauth2client.client.Credentials
"""
self.acquire_lock()
try:
return self.locked_get()
finally:
self.release_lock()
def put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
self.acquire_lock()
try:
self.locked_put(credentials)
finally:
self.release_lock()
def delete(self):
"""Delete credential.
Frees any resources associated with storing the credential.
The Storage lock must *not* be held when this is called.
Returns:
None
"""
self.acquire_lock()
try:
return self.locked_delete()
finally:
self.release_lock()
class OAuth2Credentials(Credentials):
"""Credentials object for OAuth 2.0.
Credentials can be applied to an httplib2.Http object using the authorize()
method, which then adds the OAuth 2.0 access token to each request.
OAuth2Credentials objects may be safely pickled and unpickled.
"""
def __init__(self, access_token, client_id, client_secret, refresh_token,
token_expiry, token_uri, user_agent, id_token=None):
"""Create an instance of OAuth2Credentials.
This constructor is not usually called by the user, instead
OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow.
Args:
access_token: string, access token.
client_id: string, client identifier.
client_secret: string, client secret.
refresh_token: string, refresh token.
token_expiry: datetime, when the access_token expires.
token_uri: string, URI of token endpoint.
user_agent: string, The HTTP User-Agent to provide for this application.
id_token: object, The identity of the resource owner.
Notes:
store: callable, A callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has expired and been refreshed.
"""
self.access_token = access_token
self.client_id = client_id
self.client_secret = client_secret
self.refresh_token = refresh_token
self.store = None
self.token_expiry = token_expiry
self.token_uri = token_uri
self.user_agent = user_agent
self.id_token = id_token
# True if the credentials have been revoked or expired and can't be
# refreshed.
self.invalid = False
def authorize(self, http):
"""Authorize an httplib2.Http instance with these credentials.
The modified http.request method will add authentication headers to each
request and will refresh access_tokens when a 401 is received on a
request. In addition the http.request method has a credentials property,
http.request.credentials, which is the Credentials object that authorized
it.
Args:
http: An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can't create a new OAuth subclass of httplib2.Authenication
because it never gets passed the absolute URI, which is needed for
signing. So instead we have to overload 'request' with a closure
that adds in the Authorization header and then calls the original
version of 'request()'.
"""
request_orig = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
if not self.access_token:
logger.info('Attempting refresh to obtain initial access_token')
self._refresh(request_orig)
# Modify the request headers to add the appropriate
# Authorization header.
if headers is None:
headers = {}
self.apply(headers)
if self.user_agent is not None:
if 'user-agent' in headers:
headers['user-agent'] = self.user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = self.user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
if resp.status == 401:
logger.info('Refreshing due to a 401')
self._refresh(request_orig)
self.apply(headers)
return request_orig(uri, method, body, headers,
redirections, connection_type)
else:
return (resp, content)
# Replace the request method with our own closure.
http.request = new_request
# Set credentials as a property of the request method.
setattr(http.request, 'credentials', self)
return http
def refresh(self, http):
"""Forces a refresh of the access_token.
Args:
http: httplib2.Http, an http object to be used to make the refresh
request.
"""
self._refresh(http.request)
def apply(self, headers):
"""Add the authorization to the headers.
Args:
headers: dict, the headers to add the Authorization header to.
"""
headers['Authorization'] = 'Bearer ' + self.access_token
def to_json(self):
return self._to_json(Credentials.NON_SERIALIZED_MEMBERS)
@classmethod
def from_json(cls, s):
"""Instantiate a Credentials object from a JSON description of it. The JSON
should have been produced by calling .to_json() on the object.
Args:
data: dict, A deserialized JSON object.
Returns:
An instance of a Credentials subclass.
"""
data = simplejson.loads(s)
if 'token_expiry' in data and not isinstance(data['token_expiry'],
datetime.datetime):
try:
data['token_expiry'] = datetime.datetime.strptime(
data['token_expiry'], EXPIRY_FORMAT)
except:
data['token_expiry'] = None
retval = OAuth2Credentials(
data['access_token'],
data['client_id'],
data['client_secret'],
data['refresh_token'],
data['token_expiry'],
data['token_uri'],
data['user_agent'],
data.get('id_token', None))
retval.invalid = data['invalid']
return retval
@property
def access_token_expired(self):
"""True if the credential is expired or invalid.
If the token_expiry isn't set, we assume the token doesn't expire.
"""
if self.invalid:
return True
if not self.token_expiry:
return False
now = datetime.datetime.utcnow()
if now >= self.token_expiry:
logger.info('access_token is expired. Now: %s, token_expiry: %s',
now, self.token_expiry)
return True
return False
def set_store(self, store):
"""Set the Storage for the credential.
Args:
store: Storage, an implementation of Stroage object.
This is needed to store the latest access_token if it
has expired and been refreshed. This implementation uses
locking to check for updates before updating the
access_token.
"""
self.store = store
def _updateFromCredential(self, other):
"""Update this Credential from another instance."""
self.__dict__.update(other.__getstate__())
def __getstate__(self):
"""Trim the state down to something that can be pickled."""
d = copy.copy(self.__dict__)
del d['store']
return d
def __setstate__(self, state):
"""Reconstitute the state of the object from being pickled."""
self.__dict__.update(state)
self.store = None
def _generate_refresh_request_body(self):
"""Generate the body that will be used in the refresh request."""
body = urllib.urlencode({
'grant_type': 'refresh_token',
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token,
})
return body
def _generate_refresh_request_headers(self):
"""Generate the headers that will be used in the refresh request."""
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
if self.user_agent is not None:
headers['user-agent'] = self.user_agent
return headers
def _refresh(self, http_request):
"""Refreshes the access_token.
This method first checks by reading the Storage object if available.
If a refresh is still needed, it holds the Storage lock until the
refresh is completed.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
if not self.store:
self._do_refresh_request(http_request)
else:
self.store.acquire_lock()
try:
new_cred = self.store.locked_get()
if (new_cred and not new_cred.invalid and
new_cred.access_token != self.access_token):
logger.info('Updated access_token read from Storage')
self._updateFromCredential(new_cred)
else:
self._do_refresh_request(http_request)
finally:
self.store.release_lock()
def _do_refresh_request(self, http_request):
"""Refresh the access_token using the refresh_token.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
body = self._generate_refresh_request_body()
headers = self._generate_refresh_request_headers()
logger.info('Refreshing access_token')
resp, content = http_request(
self.token_uri, method='POST', body=body, headers=headers)
if resp.status == 200:
# TODO(jcgregorio) Raise an error if loads fails?
d = simplejson.loads(content)
self.access_token = d['access_token']
self.refresh_token = d.get('refresh_token', self.refresh_token)
if 'expires_in' in d:
self.token_expiry = datetime.timedelta(
seconds=int(d['expires_in'])) + datetime.datetime.utcnow()
else:
self.token_expiry = None
if self.store:
self.store.locked_put(self)
else:
# An {'error':...} response body means the token is expired or revoked,
# so we flag the credentials as such.
logger.info('Failed to retrieve access token: %s' % content)
error_msg = 'Invalid response %s.' % resp['status']
try:
d = simplejson.loads(content)
if 'error' in d:
error_msg = d['error']
self.invalid = True
if self.store:
self.store.locked_put(self)
except:
pass
raise AccessTokenRefreshError(error_msg)
class AccessTokenCredentials(OAuth2Credentials):
"""Credentials object for OAuth 2.0.
Credentials can be applied to an httplib2.Http object using the
authorize() method, which then signs each request from that object
with the OAuth 2.0 access token. This set of credentials is for the
use case where you have acquired an OAuth 2.0 access_token from
another place such as a JavaScript client or another web
application, and wish to use it from Python. Because only the
access_token is present it can not be refreshed and will in time
expire.
AccessTokenCredentials objects may be safely pickled and unpickled.
Usage:
credentials = AccessTokenCredentials('<an access token>',
'my-user-agent/1.0')
http = httplib2.Http()
http = credentials.authorize(http)
Exceptions:
AccessTokenCredentialsExpired: raised when the access_token expires or is
revoked.
"""
def __init__(self, access_token, user_agent):
"""Create an instance of OAuth2Credentials
This is one of the few types if Credentials that you should contrust,
Credentials objects are usually instantiated by a Flow.
Args:
access_token: string, access token.
user_agent: string, The HTTP User-Agent to provide for this application.
Notes:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
"""
super(AccessTokenCredentials, self).__init__(
access_token,
None,
None,
None,
None,
None,
user_agent)
@classmethod
def from_json(cls, s):
data = simplejson.loads(s)
retval = AccessTokenCredentials(
data['access_token'],
data['user_agent'])
return retval
def _refresh(self, http_request):
raise AccessTokenCredentialsError(
"The access_token is expired or invalid and can't be refreshed.")
class AssertionCredentials(OAuth2Credentials):
"""Abstract Credentials object used for OAuth 2.0 assertion grants.
This credential does not require a flow to instantiate because it
represents a two legged flow, and therefore has all of the required
information to generate and refresh its own access tokens. It must
be subclassed to generate the appropriate assertion string.
AssertionCredentials objects may be safely pickled and unpickled.
"""
def __init__(self, assertion_type, user_agent,
token_uri='https://accounts.google.com/o/oauth2/token',
**unused_kwargs):
"""Constructor for AssertionFlowCredentials.
Args:
assertion_type: string, assertion type that will be declared to the auth
server
user_agent: string, The HTTP User-Agent to provide for this application.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
"""
super(AssertionCredentials, self).__init__(
None,
None,
None,
None,
None,
token_uri,
user_agent)
self.assertion_type = assertion_type
def _generate_refresh_request_body(self):
assertion = self._generate_assertion()
body = urllib.urlencode({
'assertion_type': self.assertion_type,
'assertion': assertion,
'grant_type': 'assertion',
})
return body
def _generate_assertion(self):
"""Generate the assertion string that will be used in the access token
request.
"""
_abstract()
if HAS_OPENSSL:
# PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then
# don't create the SignedJwtAssertionCredentials or the verify_id_token()
# method.
class SignedJwtAssertionCredentials(AssertionCredentials):
"""Credentials object used for OAuth 2.0 Signed JWT assertion grants.
This credential does not require a flow to instantiate because it
represents a two legged flow, and therefore has all of the required
information to generate and refresh its own access tokens.
"""
MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
def __init__(self,
service_account_name,
private_key,
scope,
private_key_password='notasecret',
user_agent=None,
token_uri='https://accounts.google.com/o/oauth2/token',
**kwargs):
"""Constructor for SignedJwtAssertionCredentials.
Args:
service_account_name: string, id for account, usually an email address.
private_key: string, private key in P12 format.
scope: string or list of strings, scope(s) of the credentials being
requested.
private_key_password: string, password for private_key.
user_agent: string, HTTP User-Agent to provide for this application.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
kwargs: kwargs, Additional parameters to add to the JWT token, for
example prn=joe@xample.org."""
super(SignedJwtAssertionCredentials, self).__init__(
'http://oauth.net/grant_type/jwt/1.0/bearer',
user_agent,
token_uri=token_uri,
)
if type(scope) is list:
scope = ' '.join(scope)
self.scope = scope
self.private_key = private_key
self.private_key_password = private_key_password
self.service_account_name = service_account_name
self.kwargs = kwargs
@classmethod
def from_json(cls, s):
data = simplejson.loads(s)
retval = SignedJwtAssertionCredentials(
data['service_account_name'],
data['private_key'],
data['private_key_password'],
data['scope'],
data['user_agent'],
data['token_uri'],
data['kwargs']
)
retval.invalid = data['invalid']
return retval
def _generate_assertion(self):
"""Generate the assertion that will be used in the request."""
now = long(time.time())
payload = {
'aud': self.token_uri,
'scope': self.scope,
'iat': now,
'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS,
'iss': self.service_account_name
}
payload.update(self.kwargs)
logger.debug(str(payload))
return make_signed_jwt(
Signer.from_string(self.private_key, self.private_key_password),
payload)
# Only used in verify_id_token(), which is always calling to the same URI
# for the certs.
_cached_http = httplib2.Http(MemoryCache())
def verify_id_token(id_token, audience, http=None,
cert_uri=ID_TOKEN_VERIFICATON_CERTS):
"""Verifies a signed JWT id_token.
Args:
id_token: string, A Signed JWT.
audience: string, The audience 'aud' that the token should be for.
http: httplib2.Http, instance to use to make the HTTP request. Callers
should supply an instance that has caching enabled.
cert_uri: string, URI of the certificates in JSON format to
verify the JWT against.
Returns:
The deserialized JSON in the JWT.
Raises:
oauth2client.crypt.AppIdentityError if the JWT fails to verify.
"""
if http is None:
http = _cached_http
resp, content = http.request(cert_uri)
if resp.status == 200:
certs = simplejson.loads(content)
return verify_signed_jwt_with_certs(id_token, certs, audience)
else:
raise VerifyJwtTokenError('Status code: %d' % resp.status)
def _urlsafe_b64decode(b64string):
# Guard against unicode strings, which base64 can't handle.
b64string = b64string.encode('ascii')
padded = b64string + '=' * (4 - len(b64string) % 4)
return base64.urlsafe_b64decode(padded)
def _extract_id_token(id_token):
"""Extract the JSON payload from a JWT.
Does the extraction w/o checking the signature.
Args:
id_token: string, OAuth 2.0 id_token.
Returns:
object, The deserialized JSON payload.
"""
segments = id_token.split('.')
if (len(segments) != 3):
raise VerifyJwtTokenError(
'Wrong number of segments in token: %s' % id_token)
return simplejson.loads(_urlsafe_b64decode(segments[1]))
def credentials_from_code(client_id, client_secret, scope, code,
redirect_uri = 'postmessage',
http=None, user_agent=None,
token_uri='https://accounts.google.com/o/oauth2/token'):
"""Exchanges an authorization code for an OAuth2Credentials object.
Args:
client_id: string, client identifier.
client_secret: string, client secret.
scope: string or list of strings, scope(s) to request.
code: string, An authroization code, most likely passed down from
the client
redirect_uri: string, this is generally set to 'postmessage' to match the
redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
Returns:
An OAuth2Credentials object.
Raises:
FlowExchangeError if the authorization code cannot be exchanged for an
access token
"""
flow = OAuth2WebServerFlow(client_id, client_secret, scope, user_agent,
'https://accounts.google.com/o/oauth2/auth',
token_uri)
# We primarily make this call to set up the redirect_uri in the flow object
uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri)
credentials = flow.step2_exchange(code, http)
return credentials
def credentials_from_clientsecrets_and_code(filename, scope, code,
message = None,
redirect_uri = 'postmessage',
http=None):
"""Returns OAuth2Credentials from a clientsecrets file and an auth code.
Will create the right kind of Flow based on the contents of the clientsecrets
file or will raise InvalidClientSecretsError for unknown types of Flows.
Args:
filename: string, File name of clientsecrets.
scope: string or list of strings, scope(s) to request.
code: string, An authroization code, most likely passed down from
the client
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. If message is provided then
sys.exit will be called in the case of an error. If message in not
provided then clientsecrets.InvalidClientSecretsError will be raised.
redirect_uri: string, this is generally set to 'postmessage' to match the
redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
Returns:
An OAuth2Credentials object.
Raises:
FlowExchangeError if the authorization code cannot be exchanged for an
access token
UnknownClientSecretsFlowError if the file describes an unknown kind of Flow.
clientsecrets.InvalidClientSecretsError if the clientsecrets file is
invalid.
"""
flow = flow_from_clientsecrets(filename, scope, message)
# We primarily make this call to set up the redirect_uri in the flow object
uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri)
credentials = flow.step2_exchange(code, http)
return credentials
class OAuth2WebServerFlow(Flow):
"""Does the Web Server Flow for OAuth 2.0.
OAuth2Credentials objects may be safely pickled and unpickled.
"""
def __init__(self, client_id, client_secret, scope, user_agent=None,
auth_uri='https://accounts.google.com/o/oauth2/auth',
token_uri='https://accounts.google.com/o/oauth2/token',
**kwargs):
"""Constructor for OAuth2WebServerFlow.
Args:
client_id: string, client identifier.
client_secret: string client secret.
scope: string or list of strings, scope(s) of the credentials being
requested.
user_agent: string, HTTP User-Agent to provide for this application.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
**kwargs: dict, The keyword arguments are all optional and required
parameters for the OAuth calls.
"""
self.client_id = client_id
self.client_secret = client_secret
if type(scope) is list:
scope = ' '.join(scope)
self.scope = scope
self.user_agent = user_agent
self.auth_uri = auth_uri
self.token_uri = token_uri
self.params = {
'access_type': 'offline',
}
self.params.update(kwargs)
self.redirect_uri = None
def step1_get_authorize_url(self, redirect_uri=OOB_CALLBACK_URN):
"""Returns a URI to redirect to the provider.
Args:
redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for
a non-web-based application, or a URI that handles the callback from
the authorization server.
If redirect_uri is 'urn:ietf:wg:oauth:2.0:oob' then pass in the
generated verification code to step2_exchange,
otherwise pass in the query parameters received
at the callback uri to step2_exchange.
"""
self.redirect_uri = redirect_uri
query = {
'response_type': 'code',
'client_id': self.client_id,
'redirect_uri': redirect_uri,
'scope': self.scope,
}
query.update(self.params)
parts = list(urlparse.urlparse(self.auth_uri))
query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part
parts[4] = urllib.urlencode(query)
return urlparse.urlunparse(parts)
def step2_exchange(self, code, http=None):
"""Exhanges a code for OAuth2Credentials.
Args:
code: string or dict, either the code as a string, or a dictionary
of the query parameters to the redirect_uri, which contains
the code.
http: httplib2.Http, optional http instance to use to do the fetch
Returns:
An OAuth2Credentials object that can be used to authorize requests.
Raises:
FlowExchangeError if a problem occured exchanging the code for a
refresh_token.
"""
if not (isinstance(code, str) or isinstance(code, unicode)):
if 'code' not in code:
if 'error' in code:
error_msg = code['error']
else:
error_msg = 'No code was supplied in the query parameters.'
raise FlowExchangeError(error_msg)
else:
code = code['code']
body = urllib.urlencode({
'grant_type': 'authorization_code',
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': code,
'redirect_uri': self.redirect_uri,
'scope': self.scope,
})
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
if self.user_agent is not None:
headers['user-agent'] = self.user_agent
if http is None:
http = httplib2.Http()
resp, content = http.request(self.token_uri, method='POST', body=body,
headers=headers)
if resp.status == 200:
# TODO(jcgregorio) Raise an error if simplejson.loads fails?
d = simplejson.loads(content)
access_token = d['access_token']
refresh_token = d.get('refresh_token', None)
token_expiry = None
if 'expires_in' in d:
token_expiry = datetime.datetime.utcnow() + datetime.timedelta(
seconds=int(d['expires_in']))
if 'id_token' in d:
d['id_token'] = _extract_id_token(d['id_token'])
logger.info('Successfully retrieved access token: %s' % content)
return OAuth2Credentials(access_token, self.client_id,
self.client_secret, refresh_token, token_expiry,
self.token_uri, self.user_agent,
id_token=d.get('id_token', None))
else:
logger.info('Failed to retrieve access token: %s' % content)
error_msg = 'Invalid response %s.' % resp['status']
try:
d = simplejson.loads(content)
if 'error' in d:
error_msg = d['error']
except:
pass
raise FlowExchangeError(error_msg)
def flow_from_clientsecrets(filename, scope, message=None):
"""Create a Flow from a clientsecrets file.
Will create the right kind of Flow based on the contents of the clientsecrets
file or will raise InvalidClientSecretsError for unknown types of Flows.
Args:
filename: string, File name of client secrets.
scope: string or list of strings, scope(s) to request.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. If message is provided then
sys.exit will be called in the case of an error. If message in not
provided then clientsecrets.InvalidClientSecretsError will be raised.
Returns:
A Flow object.
Raises:
UnknownClientSecretsFlowError if the file describes an unknown kind of Flow.
clientsecrets.InvalidClientSecretsError if the clientsecrets file is
invalid.
"""
try:
client_type, client_info = clientsecrets.loadfile(filename)
if client_type in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]:
return OAuth2WebServerFlow(
client_info['client_id'],
client_info['client_secret'],
scope,
None, # user_agent
client_info['auth_uri'],
client_info['token_uri'])
except clientsecrets.InvalidClientSecretsError:
if message:
sys.exit(message)
else:
raise
else:
raise UnknownClientSecretsFlowError(
'This OAuth 2.0 flow is unsupported: "%s"' * client_type)
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth 2.0
credentials.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import os
import stat
import threading
from anyjson import simplejson
from client import Storage as BaseStorage
from client import Credentials
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from a file."""
def __init__(self, filename):
self._filename = filename
self._lock = threading.Lock()
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant."""
self._lock.acquire()
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
self._lock.release()
def locked_get(self):
"""Retrieve Credential from file.
Returns:
oauth2client.client.Credentials
"""
credentials = None
try:
f = open(self._filename, 'rb')
content = f.read()
f.close()
except IOError:
return credentials
try:
credentials = Credentials.new_from_json(content)
credentials.set_store(self)
except ValueError:
pass
return credentials
def _create_file_if_needed(self):
"""Create an empty file if necessary.
This method will not initialize the file. Instead it implements a
simple version of "touch" to ensure the file has been created.
"""
if not os.path.exists(self._filename):
old_umask = os.umask(0177)
try:
open(self._filename, 'a+b').close()
finally:
os.umask(old_umask)
def locked_put(self, credentials):
"""Write Credentials to file.
Args:
credentials: Credentials, the credentials to store.
"""
self._create_file_if_needed()
f = open(self._filename, 'wb')
f.write(credentials.to_json())
f.close()
def locked_delete(self):
"""Delete Credentials file.
Args:
credentials: Credentials, the credentials to store.
"""
os.unlink(self._filename)
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""OAuth 2.0 utilities for Django.
Utilities for using OAuth 2.0 in conjunction with
the Django datastore.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import oauth2client
import base64
import pickle
from django.db import models
from oauth2client.client import Storage as BaseStorage
class CredentialsField(models.Field):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return "TextField"
def to_python(self, value):
if value is None:
return None
if isinstance(value, oauth2client.client.Credentials):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value, connection, prepared=False):
if value is None:
return None
return base64.b64encode(pickle.dumps(value))
class FlowField(models.Field):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return "TextField"
def to_python(self, value):
if value is None:
return None
if isinstance(value, oauth2client.client.Flow):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value, connection, prepared=False):
if value is None:
return None
return base64.b64encode(pickle.dumps(value))
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from
the datastore.
This Storage helper presumes the Credentials
have been stored as a CredenialsField
on a db model class.
"""
def __init__(self, model_class, key_name, key_value, property_name):
"""Constructor for Storage.
Args:
model: db.Model, model class
key_name: string, key name for the entity that has the credentials
key_value: string, key value for the entity that has the credentials
property_name: string, name of the property that is an CredentialsProperty
"""
self.model_class = model_class
self.key_name = key_name
self.key_value = key_value
self.property_name = property_name
def locked_get(self):
"""Retrieve Credential from datastore.
Returns:
oauth2client.Credentials
"""
credential = None
query = {self.key_name: self.key_value}
entities = self.model_class.objects.filter(**query)
if len(entities) > 0:
credential = getattr(entities[0], self.property_name)
if credential and hasattr(credential, 'set_store'):
credential.set_store(self)
return credential
def locked_put(self, credentials):
"""Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.
"""
args = {self.key_name: self.key_value}
entity = self.model_class(**args)
setattr(entity, self.property_name, credentials)
entity.save()
def locked_delete(self):
"""Delete Credentials from the datastore."""
query = {self.key_name: self.key_value}
entities = self.model_class.objects.filter(**query).delete()
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for Google App Engine
Utilities for making it easier to use OAuth 2.0 on Google App Engine.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import base64
import httplib2
import logging
import pickle
import time
import clientsecrets
from anyjson import simplejson
from client import AccessTokenRefreshError
from client import AssertionCredentials
from client import Credentials
from client import Flow
from client import OAuth2WebServerFlow
from client import Storage
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.api import app_identity
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns'
class InvalidClientSecretsError(Exception):
"""The client_secrets.json file is malformed or missing required fields."""
pass
class AppAssertionCredentials(AssertionCredentials):
"""Credentials object for App Engine Assertion Grants
This object will allow an App Engine application to identify itself to Google
and other OAuth 2.0 servers that can verify assertions. It can be used for
the purpose of accessing data stored under an account assigned to the App
Engine application itself.
This credential does not require a flow to instantiate because it represents
a two legged flow, and therefore has all of the required information to
generate and refresh its own access tokens.
"""
def __init__(self, scope, **kwargs):
"""Constructor for AppAssertionCredentials
Args:
scope: string or list of strings, scope(s) of the credentials being requested.
"""
if type(scope) is list:
scope = ' '.join(scope)
self.scope = scope
super(AppAssertionCredentials, self).__init__(
None,
None,
None)
@classmethod
def from_json(cls, json):
data = simplejson.loads(json)
return AppAssertionCredentials(data['scope'])
def _refresh(self, http_request):
"""Refreshes the access_token.
Since the underlying App Engine app_identity implementation does its own
caching we can skip all the storage hoops and just to a refresh using the
API.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
try:
(token, _) = app_identity.get_access_token(self.scope)
except app_identity.Error, e:
raise AccessTokenRefreshError(str(e))
self.access_token = token
class FlowProperty(db.Property):
"""App Engine datastore Property for Flow.
Utility property that allows easy storage and retreival of an
oauth2client.Flow"""
# Tell what the user type is.
data_type = Flow
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
flow = super(FlowProperty,
self).get_value_for_datastore(model_instance)
return db.Blob(pickle.dumps(flow))
# For reading from datastore.
def make_value_from_datastore(self, value):
if value is None:
return None
return pickle.loads(value)
def validate(self, value):
if value is not None and not isinstance(value, Flow):
raise db.BadValueError('Property %s must be convertible '
'to a FlowThreeLegged instance (%s)' %
(self.name, value))
return super(FlowProperty, self).validate(value)
def empty(self, value):
return not value
class CredentialsProperty(db.Property):
"""App Engine datastore Property for Credentials.
Utility property that allows easy storage and retrieval of
oath2client.Credentials
"""
# Tell what the user type is.
data_type = Credentials
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
logging.info("get: Got type " + str(type(model_instance)))
cred = super(CredentialsProperty,
self).get_value_for_datastore(model_instance)
if cred is None:
cred = ''
else:
cred = cred.to_json()
return db.Blob(cred)
# For reading from datastore.
def make_value_from_datastore(self, value):
logging.info("make: Got type " + str(type(value)))
if value is None:
return None
if len(value) == 0:
return None
try:
credentials = Credentials.new_from_json(value)
except ValueError:
credentials = None
return credentials
def validate(self, value):
value = super(CredentialsProperty, self).validate(value)
logging.info("validate: Got type " + str(type(value)))
if value is not None and not isinstance(value, Credentials):
raise db.BadValueError('Property %s must be convertible '
'to a Credentials instance (%s)' %
(self.name, value))
#if value is not None and not isinstance(value, Credentials):
# return None
return value
class StorageByKeyName(Storage):
"""Store and retrieve a single credential to and from
the App Engine datastore.
This Storage helper presumes the Credentials
have been stored as a CredenialsProperty
on a datastore model class, and that entities
are stored by key_name.
"""
def __init__(self, model, key_name, property_name, cache=None):
"""Constructor for Storage.
Args:
model: db.Model, model class
key_name: string, key name for the entity that has the credentials
property_name: string, name of the property that is a CredentialsProperty
cache: memcache, a write-through cache to put in front of the datastore
"""
self._model = model
self._key_name = key_name
self._property_name = property_name
self._cache = cache
def locked_get(self):
"""Retrieve Credential from datastore.
Returns:
oauth2client.Credentials
"""
if self._cache:
json = self._cache.get(self._key_name)
if json:
return Credentials.new_from_json(json)
credential = None
entity = self._model.get_by_key_name(self._key_name)
if entity is not None:
credential = getattr(entity, self._property_name)
if credential and hasattr(credential, 'set_store'):
credential.set_store(self)
if self._cache:
self._cache.set(self._key_name, credential.to_json())
return credential
def locked_put(self, credentials):
"""Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.
"""
entity = self._model.get_or_insert(self._key_name)
setattr(entity, self._property_name, credentials)
entity.put()
if self._cache:
self._cache.set(self._key_name, credentials.to_json())
def locked_delete(self):
"""Delete Credential from datastore."""
if self._cache:
self._cache.delete(self._key_name)
entity = self._model.get_by_key_name(self._key_name)
if entity is not None:
entity.delete()
class CredentialsModel(db.Model):
"""Storage for OAuth 2.0 Credentials
Storage of the model is keyed by the user.user_id().
"""
credentials = CredentialsProperty()
class OAuth2Decorator(object):
"""Utility for making OAuth 2.0 easier.
Instantiate and then use with oauth_required or oauth_aware
as decorators on webapp.RequestHandler methods.
Example:
decorator = OAuth2Decorator(
client_id='837...ent.com',
client_secret='Qh...wwI',
scope='https://www.googleapis.com/auth/plus')
class MainHandler(webapp.RequestHandler):
@decorator.oauth_required
def get(self):
http = decorator.http()
# http is authorized with the user's Credentials and can be used
# in API calls
"""
def __init__(self, client_id, client_secret, scope,
auth_uri='https://accounts.google.com/o/oauth2/auth',
token_uri='https://accounts.google.com/o/oauth2/token',
user_agent=None,
message=None, **kwargs):
"""Constructor for OAuth2Decorator
Args:
client_id: string, client identifier.
client_secret: string client secret.
scope: string or list of strings, scope(s) of the credentials being
requested.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
user_agent: string, User agent of your application, default to None.
message: Message to display if there are problems with the OAuth 2.0
configuration. The message may contain HTML and will be presented on the
web interface for any method that uses the decorator.
**kwargs: dict, Keyword arguments are be passed along as kwargs to the
OAuth2WebServerFlow constructor.
"""
self.flow = OAuth2WebServerFlow(client_id, client_secret, scope, user_agent,
auth_uri, token_uri, **kwargs)
self.credentials = None
self._request_handler = None
self._message = message
self._in_error = False
def _display_error_message(self, request_handler):
request_handler.response.out.write('<html><body>')
request_handler.response.out.write(self._message)
request_handler.response.out.write('</body></html>')
def oauth_required(self, method):
"""Decorator that starts the OAuth 2.0 dance.
Starts the OAuth dance for the logged in user if they haven't already
granted access for this application.
Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.
"""
def check_oauth(request_handler, *args, **kwargs):
if self._in_error:
self._display_error_message(request_handler)
return
user = users.get_current_user()
# Don't use @login_decorator as this could be used in a POST request.
if not user:
request_handler.redirect(users.create_login_url(
request_handler.request.uri))
return
# Store the request URI in 'state' so we can use it later
self.flow.params['state'] = request_handler.request.url
self._request_handler = request_handler
self.credentials = StorageByKeyName(
CredentialsModel, user.user_id(), 'credentials').get()
if not self.has_credentials():
return request_handler.redirect(self.authorize_url())
try:
method(request_handler, *args, **kwargs)
except AccessTokenRefreshError:
return request_handler.redirect(self.authorize_url())
return check_oauth
def oauth_aware(self, method):
"""Decorator that sets up for OAuth 2.0 dance, but doesn't do it.
Does all the setup for the OAuth dance, but doesn't initiate it.
This decorator is useful if you want to create a page that knows
whether or not the user has granted access to this application.
From within a method decorated with @oauth_aware the has_credentials()
and authorize_url() methods can be called.
Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.
"""
def setup_oauth(request_handler, *args, **kwargs):
if self._in_error:
self._display_error_message(request_handler)
return
user = users.get_current_user()
# Don't use @login_decorator as this could be used in a POST request.
if not user:
request_handler.redirect(users.create_login_url(
request_handler.request.uri))
return
self.flow.params['state'] = request_handler.request.url
self._request_handler = request_handler
self.credentials = StorageByKeyName(
CredentialsModel, user.user_id(), 'credentials').get()
method(request_handler, *args, **kwargs)
return setup_oauth
def has_credentials(self):
"""True if for the logged in user there are valid access Credentials.
Must only be called from with a webapp.RequestHandler subclassed method
that had been decorated with either @oauth_required or @oauth_aware.
"""
return self.credentials is not None and not self.credentials.invalid
def authorize_url(self):
"""Returns the URL to start the OAuth dance.
Must only be called from with a webapp.RequestHandler subclassed method
that had been decorated with either @oauth_required or @oauth_aware.
"""
callback = self._request_handler.request.relative_url('/oauth2callback')
url = self.flow.step1_get_authorize_url(callback)
user = users.get_current_user()
memcache.set(user.user_id(), pickle.dumps(self.flow),
namespace=OAUTH2CLIENT_NAMESPACE)
return str(url)
def http(self):
"""Returns an authorized http instance.
Must only be called from within an @oauth_required decorated method, or
from within an @oauth_aware decorated method where has_credentials()
returns True.
"""
return self.credentials.authorize(httplib2.Http())
class OAuth2DecoratorFromClientSecrets(OAuth2Decorator):
"""An OAuth2Decorator that builds from a clientsecrets file.
Uses a clientsecrets file as the source for all the information when
constructing an OAuth2Decorator.
Example:
decorator = OAuth2DecoratorFromClientSecrets(
os.path.join(os.path.dirname(__file__), 'client_secrets.json')
scope='https://www.googleapis.com/auth/plus')
class MainHandler(webapp.RequestHandler):
@decorator.oauth_required
def get(self):
http = decorator.http()
# http is authorized with the user's Credentials and can be used
# in API calls
"""
def __init__(self, filename, scope, message=None):
"""Constructor
Args:
filename: string, File name of client secrets.
scope: string or list of strings, scope(s) of the credentials being
requested.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. The message may contain HTML and
will be presented on the web interface for any method that uses the
decorator.
"""
try:
client_type, client_info = clientsecrets.loadfile(filename)
if client_type not in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]:
raise InvalidClientSecretsError('OAuth2Decorator doesn\'t support this OAuth 2.0 flow.')
super(OAuth2DecoratorFromClientSecrets,
self).__init__(
client_info['client_id'],
client_info['client_secret'],
scope,
client_info['auth_uri'],
client_info['token_uri'],
message)
except clientsecrets.InvalidClientSecretsError:
self._in_error = True
if message is not None:
self._message = message
else:
self._message = "Please configure your application for OAuth 2.0"
def oauth2decorator_from_clientsecrets(filename, scope, message=None):
"""Creates an OAuth2Decorator populated from a clientsecrets file.
Args:
filename: string, File name of client secrets.
scope: string or list of strings, scope(s) of the credentials being
requested.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. The message may contain HTML and
will be presented on the web interface for any method that uses the
decorator.
Returns: An OAuth2Decorator
"""
return OAuth2DecoratorFromClientSecrets(filename, scope, message)
class OAuth2Handler(webapp.RequestHandler):
"""Handler for the redirect_uri of the OAuth 2.0 dance."""
@login_required
def get(self):
error = self.request.get('error')
if error:
errormsg = self.request.get('error_description', error)
self.response.out.write(
'The authorization request failed: %s' % errormsg)
else:
user = users.get_current_user()
flow = pickle.loads(memcache.get(user.user_id(),
namespace=OAUTH2CLIENT_NAMESPACE))
# This code should be ammended with application specific error
# handling. The following cases should be considered:
# 1. What if the flow doesn't exist in memcache? Or is corrupt?
# 2. What if the step2_exchange fails?
if flow:
credentials = flow.step2_exchange(self.request.params)
StorageByKeyName(
CredentialsModel, user.user_id(), 'credentials').put(credentials)
self.redirect(str(self.request.get('state')))
else:
# TODO Add error handling here.
pass
application = webapp.WSGIApplication([('/oauth2callback', OAuth2Handler)])
def main():
run_wsgi_app(application)
| Python |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import hashlib
import logging
import time
from OpenSSL import crypto
from anyjson import simplejson
CLOCK_SKEW_SECS = 300 # 5 minutes in seconds
AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds
MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds
class AppIdentityError(Exception):
pass
class Verifier(object):
"""Verifies the signature on a message."""
def __init__(self, pubkey):
"""Constructor.
Args:
pubkey, OpenSSL.crypto.PKey, The public key to verify with.
"""
self._pubkey = pubkey
def verify(self, message, signature):
"""Verifies a message against a signature.
Args:
message: string, The message to verify.
signature: string, The signature on the message.
Returns:
True if message was singed by the private key associated with the public
key that this object was constructed with.
"""
try:
crypto.verify(self._pubkey, signature, message, 'sha256')
return True
except:
return False
@staticmethod
def from_string(key_pem, is_x509_cert):
"""Construct a Verified instance from a string.
Args:
key_pem: string, public key in PEM format.
is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is
expected to be an RSA key in PEM format.
Returns:
Verifier instance.
Raises:
OpenSSL.crypto.Error if the key_pem can't be parsed.
"""
if is_x509_cert:
pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
else:
pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
return Verifier(pubkey)
class Signer(object):
"""Signs messages with a private key."""
def __init__(self, pkey):
"""Constructor.
Args:
pkey, OpenSSL.crypto.PKey, The private key to sign with.
"""
self._key = pkey
def sign(self, message):
"""Signs a message.
Args:
message: string, Message to be signed.
Returns:
string, The signature of the message for the given key.
"""
return crypto.sign(self._key, message, 'sha256')
@staticmethod
def from_string(key, password='notasecret'):
"""Construct a Signer instance from a string.
Args:
key: string, private key in P12 format.
password: string, password for the private key file.
Returns:
Signer instance.
Raises:
OpenSSL.crypto.Error if the key can't be parsed.
"""
pkey = crypto.load_pkcs12(key, password).get_privatekey()
return Signer(pkey)
def _urlsafe_b64encode(raw_bytes):
return base64.urlsafe_b64encode(raw_bytes).rstrip('=')
def _urlsafe_b64decode(b64string):
# Guard against unicode strings, which base64 can't handle.
b64string = b64string.encode('ascii')
padded = b64string + '=' * (4 - len(b64string) % 4)
return base64.urlsafe_b64decode(padded)
def _json_encode(data):
return simplejson.dumps(data, separators = (',', ':'))
def make_signed_jwt(signer, payload):
"""Make a signed JWT.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
Args:
signer: crypt.Signer, Cryptographic signer.
payload: dict, Dictionary of data to convert to JSON and then sign.
Returns:
string, The JWT for the payload.
"""
header = {'typ': 'JWT', 'alg': 'RS256'}
segments = [
_urlsafe_b64encode(_json_encode(header)),
_urlsafe_b64encode(_json_encode(payload)),
]
signing_input = '.'.join(segments)
signature = signer.sign(signing_input)
segments.append(_urlsafe_b64encode(signature))
logging.debug(str(segments))
return '.'.join(segments)
def verify_signed_jwt_with_certs(jwt, certs, audience):
"""Verify a JWT against public certs.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
Args:
jwt: string, A JWT.
certs: dict, Dictionary where values of public keys in PEM format.
audience: string, The audience, 'aud', that this JWT should contain. If
None then the JWT's 'aud' parameter is not verified.
Returns:
dict, The deserialized JSON payload in the JWT.
Raises:
AppIdentityError if any checks are failed.
"""
segments = jwt.split('.')
if (len(segments) != 3):
raise AppIdentityError(
'Wrong number of segments in token: %s' % jwt)
signed = '%s.%s' % (segments[0], segments[1])
signature = _urlsafe_b64decode(segments[2])
# Parse token.
json_body = _urlsafe_b64decode(segments[1])
try:
parsed = simplejson.loads(json_body)
except:
raise AppIdentityError('Can\'t parse token: %s' % json_body)
# Check signature.
verified = False
for (keyname, pem) in certs.items():
verifier = Verifier.from_string(pem, True)
if (verifier.verify(signed, signature)):
verified = True
break
if not verified:
raise AppIdentityError('Invalid token signature: %s' % jwt)
# Check creation timestamp.
iat = parsed.get('iat')
if iat is None:
raise AppIdentityError('No iat field in token: %s' % json_body)
earliest = iat - CLOCK_SKEW_SECS
# Check expiration timestamp.
now = long(time.time())
exp = parsed.get('exp')
if exp is None:
raise AppIdentityError('No exp field in token: %s' % json_body)
if exp >= now + MAX_TOKEN_LIFETIME_SECS:
raise AppIdentityError(
'exp field too far in future: %s' % json_body)
latest = exp + CLOCK_SKEW_SECS
if now < earliest:
raise AppIdentityError('Token used too early, %d < %d: %s' %
(now, earliest, json_body))
if now > latest:
raise AppIdentityError('Token used too late, %d > %d: %s' %
(now, latest, json_body))
# Check audience.
if audience is not None:
aud = parsed.get('aud')
if aud is None:
raise AppIdentityError('No aud field in token: %s' % json_body)
if aud != audience:
raise AppIdentityError('Wrong recipient, %s != %s: %s' %
(aud, audience, json_body))
return parsed
| Python |
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for reading OAuth 2.0 client secret files.
A client_secrets.json file contains all the information needed to interact with
an OAuth 2.0 protected service.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from anyjson import simplejson
# Properties that make a client_secrets.json file valid.
TYPE_WEB = 'web'
TYPE_INSTALLED = 'installed'
VALID_CLIENT = {
TYPE_WEB: {
'required': [
'client_id',
'client_secret',
'redirect_uris',
'auth_uri',
'token_uri'],
'string': [
'client_id',
'client_secret'
]
},
TYPE_INSTALLED: {
'required': [
'client_id',
'client_secret',
'redirect_uris',
'auth_uri',
'token_uri'],
'string': [
'client_id',
'client_secret'
]
}
}
class Error(Exception):
"""Base error for this module."""
pass
class InvalidClientSecretsError(Error):
"""Format of ClientSecrets file is invalid."""
pass
def _validate_clientsecrets(obj):
if obj is None or len(obj) != 1:
raise InvalidClientSecretsError('Invalid file format.')
client_type = obj.keys()[0]
if client_type not in VALID_CLIENT.keys():
raise InvalidClientSecretsError('Unknown client type: %s.' % client_type)
client_info = obj[client_type]
for prop_name in VALID_CLIENT[client_type]['required']:
if prop_name not in client_info:
raise InvalidClientSecretsError(
'Missing property "%s" in a client type of "%s".' % (prop_name,
client_type))
for prop_name in VALID_CLIENT[client_type]['string']:
if client_info[prop_name].startswith('[['):
raise InvalidClientSecretsError(
'Property "%s" is not configured.' % prop_name)
return client_type, client_info
def load(fp):
obj = simplejson.load(fp)
return _validate_clientsecrets(obj)
def loads(s):
obj = simplejson.loads(s)
return _validate_clientsecrets(obj)
def loadfile(filename):
try:
fp = file(filename, 'r')
try:
obj = simplejson.load(fp)
finally:
fp.close()
except IOError:
raise InvalidClientSecretsError('File not found: "%s"' % filename)
return _validate_clientsecrets(obj)
| Python |
# Copyright 2011 Google Inc. All Rights Reserved.
"""Locked file interface that should work on Unix and Windows pythons.
This module first tries to use fcntl locking to ensure serialized access
to a file, then falls back on a lock file if that is unavialable.
Usage:
f = LockedFile('filename', 'r+b', 'rb')
f.open_and_lock()
if f.is_locked():
print 'Acquired filename with r+b mode'
f.file_handle().write('locked data')
else:
print 'Aquired filename with rb mode'
f.unlock_and_close()
"""
__author__ = 'cache@google.com (David T McWherter)'
import errno
import logging
import os
import time
logger = logging.getLogger(__name__)
class AlreadyLockedException(Exception):
"""Trying to lock a file that has already been locked by the LockedFile."""
pass
class _Opener(object):
"""Base class for different locking primitives."""
def __init__(self, filename, mode, fallback_mode):
"""Create an Opener.
Args:
filename: string, The pathname of the file.
mode: string, The preferred mode to access the file with.
fallback_mode: string, The mode to use if locking fails.
"""
self._locked = False
self._filename = filename
self._mode = mode
self._fallback_mode = fallback_mode
self._fh = None
def is_locked(self):
"""Was the file locked."""
return self._locked
def file_handle(self):
"""The file handle to the file. Valid only after opened."""
return self._fh
def filename(self):
"""The filename that is being locked."""
return self._filename
def open_and_lock(self, timeout, delay):
"""Open the file and lock it.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries.
"""
pass
def unlock_and_close(self):
"""Unlock and close the file."""
pass
class _PosixOpener(_Opener):
"""Lock files using Posix advisory lock files."""
def open_and_lock(self, timeout, delay):
"""Open the file and lock it.
Tries to create a .lock file next to the file we're trying to open.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries.
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
self._locked = False
try:
self._fh = open(self._filename, self._mode)
except IOError, e:
# If we can't access with _mode, try _fallback_mode and don't lock.
if e.errno == errno.EACCES:
self._fh = open(self._filename, self._fallback_mode)
return
lock_filename = self._posix_lockfile(self._filename)
start_time = time.time()
while True:
try:
self._lock_fd = os.open(lock_filename,
os.O_CREAT|os.O_EXCL|os.O_RDWR)
self._locked = True
break
except OSError, e:
if e.errno != errno.EEXIST:
raise
if (time.time() - start_time) >= timeout:
logger.warn('Could not acquire lock %s in %s seconds' % (
lock_filename, timeout))
# Close the file and open in fallback_mode.
if self._fh:
self._fh.close()
self._fh = open(self._filename, self._fallback_mode)
return
time.sleep(delay)
def unlock_and_close(self):
"""Unlock a file by removing the .lock file, and close the handle."""
if self._locked:
lock_filename = self._posix_lockfile(self._filename)
os.unlink(lock_filename)
os.close(self._lock_fd)
self._locked = False
self._lock_fd = None
if self._fh:
self._fh.close()
def _posix_lockfile(self, filename):
"""The name of the lock file to use for posix locking."""
return '%s.lock' % filename
try:
import fcntl
class _FcntlOpener(_Opener):
"""Open, lock, and unlock a file using fcntl.lockf."""
def open_and_lock(self, timeout, delay):
"""Open the file and lock it.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
start_time = time.time()
try:
self._fh = open(self._filename, self._mode)
except IOError, e:
# If we can't access with _mode, try _fallback_mode and don't lock.
if e.errno == errno.EACCES:
self._fh = open(self._filename, self._fallback_mode)
return
# We opened in _mode, try to lock the file.
while True:
try:
fcntl.lockf(self._fh.fileno(), fcntl.LOCK_EX)
self._locked = True
return
except IOError, e:
# If not retrying, then just pass on the error.
if timeout == 0:
raise e
if e.errno != errno.EACCES:
raise e
# We could not acquire the lock. Try again.
if (time.time() - start_time) >= timeout:
logger.warn('Could not lock %s in %s seconds' % (
self._filename, timeout))
if self._fh:
self._fh.close()
self._fh = open(self._filename, self._fallback_mode)
return
time.sleep(delay)
def unlock_and_close(self):
"""Close and unlock the file using the fcntl.lockf primitive."""
if self._locked:
fcntl.lockf(self._fh.fileno(), fcntl.LOCK_UN)
self._locked = False
if self._fh:
self._fh.close()
except ImportError:
_FcntlOpener = None
try:
import pywintypes
import win32con
import win32file
class _Win32Opener(_Opener):
"""Open, lock, and unlock a file using windows primitives."""
# Error #33:
# 'The process cannot access the file because another process'
FILE_IN_USE_ERROR = 33
# Error #158:
# 'The segment is already unlocked.'
FILE_ALREADY_UNLOCKED_ERROR = 158
def open_and_lock(self, timeout, delay):
"""Open the file and lock it.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
start_time = time.time()
try:
self._fh = open(self._filename, self._mode)
except IOError, e:
# If we can't access with _mode, try _fallback_mode and don't lock.
if e.errno == errno.EACCES:
self._fh = open(self._filename, self._fallback_mode)
return
# We opened in _mode, try to lock the file.
while True:
try:
hfile = win32file._get_osfhandle(self._fh.fileno())
win32file.LockFileEx(
hfile,
(win32con.LOCKFILE_FAIL_IMMEDIATELY|
win32con.LOCKFILE_EXCLUSIVE_LOCK), 0, -0x10000,
pywintypes.OVERLAPPED())
self._locked = True
return
except pywintypes.error, e:
if timeout == 0:
raise e
# If the error is not that the file is already in use, raise.
if e[0] != _Win32Opener.FILE_IN_USE_ERROR:
raise
# We could not acquire the lock. Try again.
if (time.time() - start_time) >= timeout:
logger.warn('Could not lock %s in %s seconds' % (
self._filename, timeout))
if self._fh:
self._fh.close()
self._fh = open(self._filename, self._fallback_mode)
return
time.sleep(delay)
def unlock_and_close(self):
"""Close and unlock the file using the win32 primitive."""
if self._locked:
try:
hfile = win32file._get_osfhandle(self._fh.fileno())
win32file.UnlockFileEx(hfile, 0, -0x10000, pywintypes.OVERLAPPED())
except pywintypes.error, e:
if e[0] != _Win32Opener.FILE_ALREADY_UNLOCKED_ERROR:
raise
self._locked = False
if self._fh:
self._fh.close()
except ImportError:
_Win32Opener = None
class LockedFile(object):
"""Represent a file that has exclusive access."""
def __init__(self, filename, mode, fallback_mode, use_native_locking=True):
"""Construct a LockedFile.
Args:
filename: string, The path of the file to open.
mode: string, The mode to try to open the file with.
fallback_mode: string, The mode to use if locking fails.
use_native_locking: bool, Whether or not fcntl/win32 locking is used.
"""
opener = None
if not opener and use_native_locking:
if _Win32Opener:
opener = _Win32Opener(filename, mode, fallback_mode)
if _FcntlOpener:
opener = _FcntlOpener(filename, mode, fallback_mode)
if not opener:
opener = _PosixOpener(filename, mode, fallback_mode)
self._opener = opener
def filename(self):
"""Return the filename we were constructed with."""
return self._opener._filename
def file_handle(self):
"""Return the file_handle to the opened file."""
return self._opener.file_handle()
def is_locked(self):
"""Return whether we successfully locked the file."""
return self._opener.is_locked()
def open_and_lock(self, timeout=0, delay=0.05):
"""Open the file, trying to lock it.
Args:
timeout: float, The number of seconds to try to acquire the lock.
delay: float, The number of seconds to wait between retry attempts.
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.
"""
self._opener.open_and_lock(timeout, delay)
def unlock_and_close(self):
"""Unlock and close a file."""
self._opener.unlock_and_close()
| Python |
__version__ = "1.0c2"
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility module to import a JSON module
Hides all the messy details of exactly where
we get a simplejson module from.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
try: # pragma: no cover
# Should work for Python2.6 and higher.
import json as simplejson
except ImportError: # pragma: no cover
try:
import simplejson
except ImportError:
# Try to import from django, should work on App Engine
from django.utils import simplejson
| Python |
import Cookie
import datetime
import time
import email.utils
import calendar
import base64
import hashlib
import hmac
import re
import logging
# Ripped from the Tornado Framework's web.py
# http://github.com/facebook/tornado/commit/39ac6d169a36a54bb1f6b9bf1fdebb5c9da96e09
#
# Tornado is licensed under the Apache Licence, Version 2.0
# (http://www.apache.org/licenses/LICENSE-2.0.html).
#
# Example:
# from vendor.prayls.lilcookies import LilCookies
# cookieutil = LilCookies(self, application_settings['cookie_secret'])
# cookieutil.set_secure_cookie(name = 'mykey', value = 'myvalue', expires_days= 365*100)
# cookieutil.get_secure_cookie(name = 'mykey')
class LilCookies:
@staticmethod
def _utf8(s):
if isinstance(s, unicode):
return s.encode("utf-8")
assert isinstance(s, str)
return s
@staticmethod
def _time_independent_equals(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
@staticmethod
def _signature_from_secret(cookie_secret, *parts):
""" Takes a secret salt value to create a signature for values in the `parts` param."""
hash = hmac.new(cookie_secret, digestmod=hashlib.sha1)
for part in parts: hash.update(part)
return hash.hexdigest()
@staticmethod
def _signed_cookie_value(cookie_secret, name, value):
""" Returns a signed value for use in a cookie.
This is helpful to have in its own method if you need to re-use this function for other needs. """
timestamp = str(int(time.time()))
value = base64.b64encode(value)
signature = LilCookies._signature_from_secret(cookie_secret, name, value, timestamp)
return "|".join([value, timestamp, signature])
@staticmethod
def _verified_cookie_value(cookie_secret, name, signed_value):
"""Returns the un-encrypted value given the signed value if it validates, or None."""
value = signed_value
if not value: return None
parts = value.split("|")
if len(parts) != 3: return None
signature = LilCookies._signature_from_secret(cookie_secret, name, parts[0], parts[1])
if not LilCookies._time_independent_equals(parts[2], signature):
logging.warning("Invalid cookie signature %r", value)
return None
timestamp = int(parts[1])
if timestamp < time.time() - 31 * 86400:
logging.warning("Expired cookie %r", value)
return None
try:
return base64.b64decode(parts[0])
except:
return None
def __init__(self, handler, cookie_secret):
"""You must specify the cookie_secret to use any of the secure methods.
It should be a long, random sequence of bytes to be used as the HMAC
secret for the signature.
"""
if len(cookie_secret) < 45:
raise ValueError("LilCookies cookie_secret should at least be 45 characters long, but got `%s`" % cookie_secret)
self.handler = handler
self.request = handler.request
self.response = handler.response
self.cookie_secret = cookie_secret
def cookies(self):
"""A dictionary of Cookie.Morsel objects."""
if not hasattr(self, "_cookies"):
self._cookies = Cookie.BaseCookie()
if "Cookie" in self.request.headers:
try:
self._cookies.load(self.request.headers["Cookie"])
except:
self.clear_all_cookies()
return self._cookies
def get_cookie(self, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
if name in self.cookies():
return self._cookies[name].value
return default
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cookie.html#morsel-objects
for available attributes.
"""
name = LilCookies._utf8(name)
value = LilCookies._utf8(value)
if re.search(r"[\x00-\x20]", name + value):
# Don't let us accidentally inject bad stuff
raise ValueError("Invalid cookie %r: %r" % (name, value))
if not hasattr(self, "_new_cookies"):
self._new_cookies = []
new_cookie = Cookie.BaseCookie()
self._new_cookies.append(new_cookie)
new_cookie[name] = value
if domain:
new_cookie[name]["domain"] = domain
if expires_days is not None and not expires:
expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days)
if expires:
timestamp = calendar.timegm(expires.utctimetuple())
new_cookie[name]["expires"] = email.utils.formatdate(
timestamp, localtime=False, usegmt=True)
if path:
new_cookie[name]["path"] = path
for k, v in kwargs.iteritems():
new_cookie[name][k] = v
# The 2 lines below were not in Tornado. Instead, they output all their cookies to the headers at once before a response flush.
for vals in new_cookie.values():
self.response.headers._headers.append(('Set-Cookie', vals.OutputString(None)))
def clear_cookie(self, name, path="/", domain=None):
"""Deletes the cookie with the given name."""
expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
self.set_cookie(name, value="", path=path, expires=expires,
domain=domain)
def clear_all_cookies(self):
"""Deletes all the cookies the user sent with this request."""
for name in self.cookies().iterkeys():
self.clear_cookie(name)
def set_secure_cookie(self, name, value, expires_days=30, **kwargs):
"""Signs and timestamps a cookie so it cannot be forged.
To read a cookie set with this method, use get_secure_cookie().
"""
value = LilCookies._signed_cookie_value(self.cookie_secret, name, value)
self.set_cookie(name, value, expires_days=expires_days, **kwargs)
def get_secure_cookie(self, name, value=None):
"""Returns the given signed cookie if it validates, or None."""
if value is None: value = self.get_cookie(name)
return LilCookies._verified_cookie_value(self.cookie_secret, name, value)
def _cookie_signature(self, *parts):
return LilCookies._signature_from_secret(self.cookie_secret)
| Python |
# Copyright (C) 2007 Joe Gregorio
#
# Licensed under the MIT License
"""MIME-Type Parser
This module provides basic functions for handling mime-types. It can handle
matching mime-types against a list of media-ranges. See section 14.1 of the
HTTP specification [RFC 2616] for a complete explanation.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
Contents:
- parse_mime_type(): Parses a mime-type into its component parts.
- parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q'
quality parameter.
- quality(): Determines the quality ('q') of a mime-type when
compared against a list of media-ranges.
- quality_parsed(): Just like quality() except the second parameter must be
pre-parsed.
- best_match(): Choose the mime-type with the highest quality ('q')
from a list of candidates.
"""
__version__ = '0.1.3'
__author__ = 'Joe Gregorio'
__email__ = 'joe@bitworking.org'
__license__ = 'MIT License'
__credits__ = ''
def parse_mime_type(mime_type):
"""Parses a mime-type into its component parts.
Carves up a mime-type and returns a tuple of the (type, subtype, params)
where 'params' is a dictionary of all the parameters for the media range.
For example, the media range 'application/xhtml;q=0.5' would get parsed
into:
('application', 'xhtml', {'q', '0.5'})
"""
parts = mime_type.split(';')
params = dict([tuple([s.strip() for s in param.split('=', 1)])\
for param in parts[1:]
])
full_type = parts[0].strip()
# Java URLConnection class sends an Accept header that includes a
# single '*'. Turn it into a legal wildcard.
if full_type == '*':
full_type = '*/*'
(type, subtype) = full_type.split('/')
return (type.strip(), subtype.strip(), params)
def parse_media_range(range):
"""Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
into:
('application', '*', {'q', '0.5'})
In addition this function also guarantees that there is a value for 'q'
in the params dictionary, filling it in with a proper default if
necessary.
"""
(type, subtype, params) = parse_mime_type(range)
if not params.has_key('q') or not params['q'] or \
not float(params['q']) or float(params['q']) > 1\
or float(params['q']) < 0:
params['q'] = '1'
return (type, subtype, params)
def fitness_and_quality_parsed(mime_type, parsed_ranges):
"""Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality parameter of the best
match, or (-1, 0) if no match was found. Just as for quality_parsed(),
'parsed_ranges' must be a list of parsed media ranges.
"""
best_fitness = -1
best_fit_q = 0
(target_type, target_subtype, target_params) =\
parse_media_range(mime_type)
for (type, subtype, params) in parsed_ranges:
type_match = (type == target_type or\
type == '*' or\
target_type == '*')
subtype_match = (subtype == target_subtype or\
subtype == '*' or\
target_subtype == '*')
if type_match and subtype_match:
param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \
target_params.iteritems() if key != 'q' and \
params.has_key(key) and value == params[key]], 0)
fitness = (type == target_type) and 100 or 0
fitness += (subtype == target_subtype) and 10 or 0
fitness += param_matches
if fitness > best_fitness:
best_fitness = fitness
best_fit_q = params['q']
return best_fitness, float(best_fit_q)
def quality_parsed(mime_type, parsed_ranges):
"""Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns the 'q'
quality parameter of the best match, 0 if no match was found. This function
bahaves the same as quality() except that 'parsed_ranges' must be a list of
parsed media ranges.
"""
return fitness_and_quality_parsed(mime_type, parsed_ranges)[1]
def quality(mime_type, ranges):
"""Return the quality ('q') of a mime-type against a list of media-ranges.
Returns the quality 'q' of a mime-type when compared against the
media-ranges in ranges. For example:
>>> quality('text/html','text/*;q=0.3, text/html;q=0.7,
text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5')
0.7
"""
parsed_ranges = [parse_media_range(r) for r in ranges.split(',')]
return quality_parsed(mime_type, parsed_ranges)
def best_match(supported, header):
"""Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: header. The value of 'supported'
is a list of mime-types. The list of supported mime-types should be sorted
in order of increasing desirability, in case of a situation where there is
a tie.
>>> best_match(['application/xbel+xml', 'text/xml'],
'text/*;q=0.5,*/*; q=0.1')
'text/xml'
"""
split_header = _filter_blank(header.split(','))
parsed_header = [parse_media_range(r) for r in split_header]
weighted_matches = []
pos = 0
for mime_type in supported:
weighted_matches.append((fitness_and_quality_parsed(mime_type,
parsed_header), pos, mime_type))
pos += 1
weighted_matches.sort()
return weighted_matches[-1][0][1] and weighted_matches[-1][2] or ''
def _filter_blank(i):
for s in i:
if s.strip():
yield s
| Python |
# Copyright (C) 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes to encapsulate a single HTTP request.
The classes implement a command pattern, with every
object supporting an execute() method that does the
actuall HTTP request.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import StringIO
import base64
import copy
import gzip
import httplib2
import mimeparse
import mimetypes
import os
import urllib
import urlparse
import uuid
from email.generator import Generator
from email.mime.multipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart
from email.parser import FeedParser
from errors import BatchError
from errors import HttpError
from errors import ResumableUploadError
from errors import UnexpectedBodyError
from errors import UnexpectedMethodError
from model import JsonModel
from oauth2client.anyjson import simplejson
DEFAULT_CHUNK_SIZE = 512*1024
class MediaUploadProgress(object):
"""Status of a resumable upload."""
def __init__(self, resumable_progress, total_size):
"""Constructor.
Args:
resumable_progress: int, bytes sent so far.
total_size: int, total bytes in complete upload, or None if the total
upload size isn't known ahead of time.
"""
self.resumable_progress = resumable_progress
self.total_size = total_size
def progress(self):
"""Percent of upload completed, as a float.
Returns:
the percentage complete as a float, returning 0.0 if the total size of
the upload is unknown.
"""
if self.total_size is not None:
return float(self.resumable_progress) / float(self.total_size)
else:
return 0.0
class MediaDownloadProgress(object):
"""Status of a resumable download."""
def __init__(self, resumable_progress, total_size):
"""Constructor.
Args:
resumable_progress: int, bytes received so far.
total_size: int, total bytes in complete download.
"""
self.resumable_progress = resumable_progress
self.total_size = total_size
def progress(self):
"""Percent of download completed, as a float.
Returns:
the percentage complete as a float, returning 0.0 if the total size of
the download is unknown.
"""
if self.total_size is not None:
return float(self.resumable_progress) / float(self.total_size)
else:
return 0.0
class MediaUpload(object):
"""Describes a media object to upload.
Base class that defines the interface of MediaUpload subclasses.
Note that subclasses of MediaUpload may allow you to control the chunksize
when upload a media object. It is important to keep the size of the chunk as
large as possible to keep the upload efficient. Other factors may influence
the size of the chunk you use, particularly if you are working in an
environment where individual HTTP requests may have a hardcoded time limit,
such as under certain classes of requests under Google App Engine.
"""
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
raise NotImplementedError()
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return 'application/octet-stream'
def size(self):
"""Size of upload.
Returns:
Size of the body, or None of the size is unknown.
"""
return None
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return False
def getbytes(self, begin, end):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
raise NotImplementedError()
def _to_json(self, strip=None):
"""Utility function for creating a JSON representation of a MediaUpload.
Args:
strip: array, An array of names of members to not include in the JSON.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
t = type(self)
d = copy.copy(self.__dict__)
if strip is not None:
for member in strip:
del d[member]
d['_class'] = t.__name__
d['_module'] = t.__module__
return simplejson.dumps(d)
def to_json(self):
"""Create a JSON representation of an instance of MediaUpload.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
return self._to_json()
@classmethod
def new_from_json(cls, s):
"""Utility class method to instantiate a MediaUpload subclass from a JSON
representation produced by to_json().
Args:
s: string, JSON from to_json().
Returns:
An instance of the subclass of MediaUpload that was serialized with
to_json().
"""
data = simplejson.loads(s)
# Find and call the right classmethod from_json() to restore the object.
module = data['_module']
m = __import__(module, fromlist=module.split('.')[:-1])
kls = getattr(m, data['_class'])
from_json = getattr(kls, 'from_json')
return from_json(s)
class MediaFileUpload(MediaUpload):
"""A MediaUpload for a file.
Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed uploading images:
media = MediaFileUpload('cow.png', mimetype='image/png',
chunksize=1024*1024, resumable=True)
farm.animals()..insert(
id='cow',
name='cow.png',
media_body=media).execute()
"""
def __init__(self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, resumable=False):
"""Constructor.
Args:
filename: string, Name of the file.
mimetype: string, Mime-type of the file. If None then a mime-type will be
guessed from the file extension.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._filename = filename
self._size = os.path.getsize(filename)
self._fd = None
if mimetype is None:
(mimetype, encoding) = mimetypes.guess_type(filename)
self._mimetype = mimetype
self._chunksize = chunksize
self._resumable = resumable
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body, or None of the size is unknown.
"""
return self._size
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorted than length if EOF was reached
first.
"""
if self._fd is None:
self._fd = open(self._filename, 'rb')
self._fd.seek(begin)
return self._fd.read(length)
def to_json(self):
"""Creating a JSON representation of an instance of MediaFileUpload.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
return self._to_json(['_fd'])
@staticmethod
def from_json(s):
d = simplejson.loads(s)
return MediaFileUpload(
d['_filename'], d['_mimetype'], d['_chunksize'], d['_resumable'])
class MediaIoBaseUpload(MediaUpload):
"""A MediaUpload for a io.Base objects.
Note that the Python file object is compatible with io.Base and can be used
with this class also.
fh = io.BytesIO('...Some data to upload...')
media = MediaIoBaseUpload(fh, mimetype='image/png',
chunksize=1024*1024, resumable=True)
farm.animals().insert(
id='cow',
name='cow.png',
media_body=media).execute()
"""
def __init__(self, fh, mimetype, chunksize=DEFAULT_CHUNK_SIZE,
resumable=False):
"""Constructor.
Args:
fh: io.Base or file object, The source of the bytes to upload. MUST be
opened in blocking mode, do not use streams opened in non-blocking mode.
mimetype: string, Mime-type of the file. If None then a mime-type will be
guessed from the file extension.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._fh = fh
self._mimetype = mimetype
self._chunksize = chunksize
self._resumable = resumable
self._size = None
try:
if hasattr(self._fh, 'fileno'):
fileno = self._fh.fileno()
# Pipes and such show up as 0 length files.
size = os.fstat(fileno).st_size
if size:
self._size = os.fstat(fileno).st_size
except IOError:
pass
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body, or None of the size is unknown.
"""
return self._size
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorted than length if EOF was reached
first.
"""
self._fh.seek(begin)
return self._fh.read(length)
def to_json(self):
"""This upload type is not serializable."""
raise NotImplementedError('MediaIoBaseUpload is not serializable.')
class MediaInMemoryUpload(MediaUpload):
"""MediaUpload for a chunk of bytes.
Construct a MediaFileUpload and pass as the media_body parameter of the
method.
"""
def __init__(self, body, mimetype='application/octet-stream',
chunksize=DEFAULT_CHUNK_SIZE, resumable=False):
"""Create a new MediaBytesUpload.
Args:
body: string, Bytes of body content.
mimetype: string, Mime-type of the file or default of
'application/octet-stream'.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._body = body
self._mimetype = mimetype
self._resumable = resumable
self._chunksize = chunksize
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body, or None of the size is unknown.
"""
return len(self._body)
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
return self._body[begin:begin + length]
def to_json(self):
"""Create a JSON representation of a MediaInMemoryUpload.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
t = type(self)
d = copy.copy(self.__dict__)
del d['_body']
d['_class'] = t.__name__
d['_module'] = t.__module__
d['_b64body'] = base64.b64encode(self._body)
return simplejson.dumps(d)
@staticmethod
def from_json(s):
d = simplejson.loads(s)
return MediaInMemoryUpload(base64.b64decode(d['_b64body']),
d['_mimetype'], d['_chunksize'],
d['_resumable'])
class MediaIoBaseDownload(object):
""""Download media resources.
Note that the Python file object is compatible with io.Base and can be used
with this class also.
Example:
request = farms.animals().get_media(id='cow')
fh = io.FileIO('cow.png', mode='wb')
downloader = MediaIoBaseDownload(fh, request, chunksize=1024*1024)
done = False
while done is False:
status, done = downloader.next_chunk()
if status:
print "Download %d%%." % int(status.progress() * 100)
print "Download Complete!"
"""
def __init__(self, fh, request, chunksize=DEFAULT_CHUNK_SIZE):
"""Constructor.
Args:
fh: io.Base or file object, The stream in which to write the downloaded
bytes.
request: apiclient.http.HttpRequest, the media request to perform in
chunks.
chunksize: int, File will be downloaded in chunks of this many bytes.
"""
self.fh_ = fh
self.request_ = request
self.uri_ = request.uri
self.chunksize_ = chunksize
self.progress_ = 0
self.total_size_ = None
self.done_ = False
def next_chunk(self):
"""Get the next chunk of the download.
Returns:
(status, done): (MediaDownloadStatus, boolean)
The value of 'done' will be True when the media has been fully
downloaded.
Raises:
apiclient.errors.HttpError if the response was not a 2xx.
httplib2.Error if a transport error has occured.
"""
headers = {
'range': 'bytes=%d-%d' % (
self.progress_, self.progress_ + self.chunksize_)
}
http = self.request_.http
http.follow_redirects = False
resp, content = http.request(self.uri_, headers=headers)
if resp.status in [301, 302, 303, 307, 308] and 'location' in resp:
self.uri_ = resp['location']
resp, content = http.request(self.uri_, headers=headers)
if resp.status in [200, 206]:
self.progress_ += len(content)
self.fh_.write(content)
if 'content-range' in resp:
content_range = resp['content-range']
length = content_range.rsplit('/', 1)[1]
self.total_size_ = int(length)
if self.progress_ == self.total_size_:
self.done_ = True
return MediaDownloadProgress(self.progress_, self.total_size_), self.done_
else:
raise HttpError(resp, content, self.uri_)
class HttpRequest(object):
"""Encapsulates a single HTTP request."""
def __init__(self, http, postproc, uri,
method='GET',
body=None,
headers=None,
methodId=None,
resumable=None):
"""Constructor for an HttpRequest.
Args:
http: httplib2.Http, the transport object to use to make a request
postproc: callable, called on the HTTP response and content to transform
it into a data object before returning, or raising an exception
on an error.
uri: string, the absolute URI to send the request to
method: string, the HTTP method to use
body: string, the request body of the HTTP request,
headers: dict, the HTTP request headers
methodId: string, a unique identifier for the API method being called.
resumable: MediaUpload, None if this is not a resumbale request.
"""
self.uri = uri
self.method = method
self.body = body
self.headers = headers or {}
self.methodId = methodId
self.http = http
self.postproc = postproc
self.resumable = resumable
self._in_error_state = False
# Pull the multipart boundary out of the content-type header.
major, minor, params = mimeparse.parse_mime_type(
headers.get('content-type', 'application/json'))
# The size of the non-media part of the request.
self.body_size = len(self.body or '')
# The resumable URI to send chunks to.
self.resumable_uri = None
# The bytes that have been uploaded.
self.resumable_progress = 0
def execute(self, http=None):
"""Execute the request.
Args:
http: httplib2.Http, an http object to be used in place of the
one the HttpRequest request object was constructed with.
Returns:
A deserialized object model of the response body as determined
by the postproc.
Raises:
apiclient.errors.HttpError if the response was not a 2xx.
httplib2.Error if a transport error has occured.
"""
if http is None:
http = self.http
if self.resumable:
body = None
while body is None:
_, body = self.next_chunk(http)
return body
else:
if 'content-length' not in self.headers:
self.headers['content-length'] = str(self.body_size)
resp, content = http.request(self.uri, self.method,
body=self.body,
headers=self.headers)
if resp.status >= 300:
raise HttpError(resp, content, self.uri)
return self.postproc(resp, content)
def next_chunk(self, http=None):
"""Execute the next step of a resumable upload.
Can only be used if the method being executed supports media uploads and
the MediaUpload object passed in was flagged as using resumable upload.
Example:
media = MediaFileUpload('cow.png', mimetype='image/png',
chunksize=1000, resumable=True)
request = farm.animals().insert(
id='cow',
name='cow.png',
media_body=media)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print "Upload %d%% complete." % int(status.progress() * 100)
Returns:
(status, body): (ResumableMediaStatus, object)
The body will be None until the resumable media is fully uploaded.
Raises:
apiclient.errors.HttpError if the response was not a 2xx.
httplib2.Error if a transport error has occured.
"""
if http is None:
http = self.http
if self.resumable.size() is None:
size = '*'
else:
size = str(self.resumable.size())
if self.resumable_uri is None:
start_headers = copy.copy(self.headers)
start_headers['X-Upload-Content-Type'] = self.resumable.mimetype()
if size != '*':
start_headers['X-Upload-Content-Length'] = size
start_headers['content-length'] = str(self.body_size)
resp, content = http.request(self.uri, self.method,
body=self.body,
headers=start_headers)
if resp.status == 200 and 'location' in resp:
self.resumable_uri = resp['location']
else:
raise ResumableUploadError("Failed to retrieve starting URI.")
elif self._in_error_state:
# If we are in an error state then query the server for current state of
# the upload by sending an empty PUT and reading the 'range' header in
# the response.
headers = {
'Content-Range': 'bytes */%s' % size,
'content-length': '0'
}
resp, content = http.request(self.resumable_uri, 'PUT',
headers=headers)
status, body = self._process_response(resp, content)
if body:
# The upload was complete.
return (status, body)
data = self.resumable.getbytes(
self.resumable_progress, self.resumable.chunksize())
# A short read implies that we are at EOF, so finish the upload.
if len(data) < self.resumable.chunksize():
size = str(self.resumable_progress + len(data))
headers = {
'Content-Range': 'bytes %d-%d/%s' % (
self.resumable_progress, self.resumable_progress + len(data) - 1,
size)
}
try:
resp, content = http.request(self.resumable_uri, 'PUT',
body=data,
headers=headers)
except:
self._in_error_state = True
raise
return self._process_response(resp, content)
def _process_response(self, resp, content):
"""Process the response from a single chunk upload.
Args:
resp: httplib2.Response, the response object.
content: string, the content of the response.
Returns:
(status, body): (ResumableMediaStatus, object)
The body will be None until the resumable media is fully uploaded.
Raises:
apiclient.errors.HttpError if the response was not a 2xx or a 308.
"""
if resp.status in [200, 201]:
self._in_error_state = False
return None, self.postproc(resp, content)
elif resp.status == 308:
self._in_error_state = False
# A "308 Resume Incomplete" indicates we are not done.
self.resumable_progress = int(resp['range'].split('-')[1]) + 1
if 'location' in resp:
self.resumable_uri = resp['location']
else:
self._in_error_state = True
raise HttpError(resp, content, self.uri)
return (MediaUploadProgress(self.resumable_progress, self.resumable.size()),
None)
def to_json(self):
"""Returns a JSON representation of the HttpRequest."""
d = copy.copy(self.__dict__)
if d['resumable'] is not None:
d['resumable'] = self.resumable.to_json()
del d['http']
del d['postproc']
return simplejson.dumps(d)
@staticmethod
def from_json(s, http, postproc):
"""Returns an HttpRequest populated with info from a JSON object."""
d = simplejson.loads(s)
if d['resumable'] is not None:
d['resumable'] = MediaUpload.new_from_json(d['resumable'])
return HttpRequest(
http,
postproc,
uri=d['uri'],
method=d['method'],
body=d['body'],
headers=d['headers'],
methodId=d['methodId'],
resumable=d['resumable'])
class BatchHttpRequest(object):
"""Batches multiple HttpRequest objects into a single HTTP request.
Example:
from apiclient.http import BatchHttpRequest
def list_animals(request_id, response):
\"\"\"Do something with the animals list response.\"\"\"
pass
def list_farmers(request_id, response):
\"\"\"Do something with the farmers list response.\"\"\"
pass
service = build('farm', 'v2')
batch = BatchHttpRequest()
batch.add(service.animals().list(), list_animals)
batch.add(service.farmers().list(), list_farmers)
batch.execute(http)
"""
def __init__(self, callback=None, batch_uri=None):
"""Constructor for a BatchHttpRequest.
Args:
callback: callable, A callback to be called for each response, of the
form callback(id, response). The first parameter is the request id, and
the second is the deserialized response object.
batch_uri: string, URI to send batch requests to.
"""
if batch_uri is None:
batch_uri = 'https://www.googleapis.com/batch'
self._batch_uri = batch_uri
# Global callback to be called for each individual response in the batch.
self._callback = callback
# A map from id to request.
self._requests = {}
# A map from id to callback.
self._callbacks = {}
# List of request ids, in the order in which they were added.
self._order = []
# The last auto generated id.
self._last_auto_id = 0
# Unique ID on which to base the Content-ID headers.
self._base_id = None
# A map from request id to (headers, content) response pairs
self._responses = {}
# A map of id(Credentials) that have been refreshed.
self._refreshed_credentials = {}
def _refresh_and_apply_credentials(self, request, http):
"""Refresh the credentials and apply to the request.
Args:
request: HttpRequest, the request.
http: httplib2.Http, the global http object for the batch.
"""
# For the credentials to refresh, but only once per refresh_token
# If there is no http per the request then refresh the http passed in
# via execute()
creds = None
if request.http is not None and hasattr(request.http.request,
'credentials'):
creds = request.http.request.credentials
elif http is not None and hasattr(http.request, 'credentials'):
creds = http.request.credentials
if creds is not None:
if id(creds) not in self._refreshed_credentials:
creds.refresh(http)
self._refreshed_credentials[id(creds)] = 1
# Only apply the credentials if we are using the http object passed in,
# otherwise apply() will get called during _serialize_request().
if request.http is None or not hasattr(request.http.request,
'credentials'):
creds.apply(request.headers)
def _id_to_header(self, id_):
"""Convert an id to a Content-ID header value.
Args:
id_: string, identifier of individual request.
Returns:
A Content-ID header with the id_ encoded into it. A UUID is prepended to
the value because Content-ID headers are supposed to be universally
unique.
"""
if self._base_id is None:
self._base_id = uuid.uuid4()
return '<%s+%s>' % (self._base_id, urllib.quote(id_))
def _header_to_id(self, header):
"""Convert a Content-ID header value to an id.
Presumes the Content-ID header conforms to the format that _id_to_header()
returns.
Args:
header: string, Content-ID header value.
Returns:
The extracted id value.
Raises:
BatchError if the header is not in the expected format.
"""
if header[0] != '<' or header[-1] != '>':
raise BatchError("Invalid value for Content-ID: %s" % header)
if '+' not in header:
raise BatchError("Invalid value for Content-ID: %s" % header)
base, id_ = header[1:-1].rsplit('+', 1)
return urllib.unquote(id_)
def _serialize_request(self, request):
"""Convert an HttpRequest object into a string.
Args:
request: HttpRequest, the request to serialize.
Returns:
The request as a string in application/http format.
"""
# Construct status line
parsed = urlparse.urlparse(request.uri)
request_line = urlparse.urlunparse(
(None, None, parsed.path, parsed.params, parsed.query, None)
)
status_line = request.method + ' ' + request_line + ' HTTP/1.1\n'
major, minor = request.headers.get('content-type', 'application/json').split('/')
msg = MIMENonMultipart(major, minor)
headers = request.headers.copy()
if request.http is not None and hasattr(request.http.request,
'credentials'):
request.http.request.credentials.apply(headers)
# MIMENonMultipart adds its own Content-Type header.
if 'content-type' in headers:
del headers['content-type']
for key, value in headers.iteritems():
msg[key] = value
msg['Host'] = parsed.netloc
msg.set_unixfrom(None)
if request.body is not None:
msg.set_payload(request.body)
msg['content-length'] = str(len(request.body))
# Serialize the mime message.
fp = StringIO.StringIO()
# maxheaderlen=0 means don't line wrap headers.
g = Generator(fp, maxheaderlen=0)
g.flatten(msg, unixfrom=False)
body = fp.getvalue()
# Strip off the \n\n that the MIME lib tacks onto the end of the payload.
if request.body is None:
body = body[:-2]
return status_line.encode('utf-8') + body
def _deserialize_response(self, payload):
"""Convert string into httplib2 response and content.
Args:
payload: string, headers and body as a string.
Returns:
A pair (resp, content) like would be returned from httplib2.request.
"""
# Strip off the status line
status_line, payload = payload.split('\n', 1)
protocol, status, reason = status_line.split(' ', 2)
# Parse the rest of the response
parser = FeedParser()
parser.feed(payload)
msg = parser.close()
msg['status'] = status
# Create httplib2.Response from the parsed headers.
resp = httplib2.Response(msg)
resp.reason = reason
resp.version = int(protocol.split('/', 1)[1].replace('.', ''))
content = payload.split('\r\n\r\n', 1)[1]
return resp, content
def _new_id(self):
"""Create a new id.
Auto incrementing number that avoids conflicts with ids already used.
Returns:
string, a new unique id.
"""
self._last_auto_id += 1
while str(self._last_auto_id) in self._requests:
self._last_auto_id += 1
return str(self._last_auto_id)
def add(self, request, callback=None, request_id=None):
"""Add a new request.
Every callback added will be paired with a unique id, the request_id. That
unique id will be passed back to the callback when the response comes back
from the server. The default behavior is to have the library generate it's
own unique id. If the caller passes in a request_id then they must ensure
uniqueness for each request_id, and if they are not an exception is
raised. Callers should either supply all request_ids or nevery supply a
request id, to avoid such an error.
Args:
request: HttpRequest, Request to add to the batch.
callback: callable, A callback to be called for this response, of the
form callback(id, response). The first parameter is the request id, and
the second is the deserialized response object.
request_id: string, A unique id for the request. The id will be passed to
the callback with the response.
Returns:
None
Raises:
BatchError if a media request is added to a batch.
KeyError is the request_id is not unique.
"""
if request_id is None:
request_id = self._new_id()
if request.resumable is not None:
raise BatchError("Media requests cannot be used in a batch request.")
if request_id in self._requests:
raise KeyError("A request with this ID already exists: %s" % request_id)
self._requests[request_id] = request
self._callbacks[request_id] = callback
self._order.append(request_id)
def _execute(self, http, order, requests):
"""Serialize batch request, send to server, process response.
Args:
http: httplib2.Http, an http object to be used to make the request with.
order: list, list of request ids in the order they were added to the
batch.
request: list, list of request objects to send.
Raises:
httplib2.Error if a transport error has occured.
apiclient.errors.BatchError if the response is the wrong format.
"""
message = MIMEMultipart('mixed')
# Message should not write out it's own headers.
setattr(message, '_write_headers', lambda self: None)
# Add all the individual requests.
for request_id in order:
request = requests[request_id]
msg = MIMENonMultipart('application', 'http')
msg['Content-Transfer-Encoding'] = 'binary'
msg['Content-ID'] = self._id_to_header(request_id)
body = self._serialize_request(request)
msg.set_payload(body)
message.attach(msg)
body = message.as_string()
headers = {}
headers['content-type'] = ('multipart/mixed; '
'boundary="%s"') % message.get_boundary()
resp, content = http.request(self._batch_uri, 'POST', body=body,
headers=headers)
if resp.status >= 300:
raise HttpError(resp, content, self._batch_uri)
# Now break out the individual responses and store each one.
boundary, _ = content.split(None, 1)
# Prepend with a content-type header so FeedParser can handle it.
header = 'content-type: %s\r\n\r\n' % resp['content-type']
for_parser = header + content
parser = FeedParser()
parser.feed(for_parser)
mime_response = parser.close()
if not mime_response.is_multipart():
raise BatchError("Response not in multipart/mixed format.", resp,
content)
for part in mime_response.get_payload():
request_id = self._header_to_id(part['Content-ID'])
headers, content = self._deserialize_response(part.get_payload())
self._responses[request_id] = (headers, content)
def execute(self, http=None):
"""Execute all the requests as a single batched HTTP request.
Args:
http: httplib2.Http, an http object to be used in place of the one the
HttpRequest request object was constructed with. If one isn't supplied
then use a http object from the requests in this batch.
Returns:
None
Raises:
httplib2.Error if a transport error has occured.
apiclient.errors.BatchError if the response is the wrong format.
"""
# If http is not supplied use the first valid one given in the requests.
if http is None:
for request_id in self._order:
request = self._requests[request_id]
if request is not None:
http = request.http
break
if http is None:
raise ValueError("Missing a valid http object.")
self._execute(http, self._order, self._requests)
# Loop over all the requests and check for 401s. For each 401 request the
# credentials should be refreshed and then sent again in a separate batch.
redo_requests = {}
redo_order = []
for request_id in self._order:
headers, content = self._responses[request_id]
if headers['status'] == '401':
redo_order.append(request_id)
request = self._requests[request_id]
self._refresh_and_apply_credentials(request, http)
redo_requests[request_id] = request
if redo_requests:
self._execute(http, redo_order, redo_requests)
# Now process all callbacks that are erroring, and raise an exception for
# ones that return a non-2xx response? Or add extra parameter to callback
# that contains an HttpError?
for request_id in self._order:
headers, content = self._responses[request_id]
request = self._requests[request_id]
callback = self._callbacks[request_id]
response = None
exception = None
try:
r = httplib2.Response(headers)
response = request.postproc(r, content)
except HttpError, e:
exception = e
if callback is not None:
callback(request_id, response, exception)
if self._callback is not None:
self._callback(request_id, response, exception)
class HttpRequestMock(object):
"""Mock of HttpRequest.
Do not construct directly, instead use RequestMockBuilder.
"""
def __init__(self, resp, content, postproc):
"""Constructor for HttpRequestMock
Args:
resp: httplib2.Response, the response to emulate coming from the request
content: string, the response body
postproc: callable, the post processing function usually supplied by
the model class. See model.JsonModel.response() as an example.
"""
self.resp = resp
self.content = content
self.postproc = postproc
if resp is None:
self.resp = httplib2.Response({'status': 200, 'reason': 'OK'})
if 'reason' in self.resp:
self.resp.reason = self.resp['reason']
def execute(self, http=None):
"""Execute the request.
Same behavior as HttpRequest.execute(), but the response is
mocked and not really from an HTTP request/response.
"""
return self.postproc(self.resp, self.content)
class RequestMockBuilder(object):
"""A simple mock of HttpRequest
Pass in a dictionary to the constructor that maps request methodIds to
tuples of (httplib2.Response, content, opt_expected_body) that should be
returned when that method is called. None may also be passed in for the
httplib2.Response, in which case a 200 OK response will be generated.
If an opt_expected_body (str or dict) is provided, it will be compared to
the body and UnexpectedBodyError will be raised on inequality.
Example:
response = '{"data": {"id": "tag:google.c...'
requestBuilder = RequestMockBuilder(
{
'plus.activities.get': (None, response),
}
)
apiclient.discovery.build("plus", "v1", requestBuilder=requestBuilder)
Methods that you do not supply a response for will return a
200 OK with an empty string as the response content or raise an excpetion
if check_unexpected is set to True. The methodId is taken from the rpcName
in the discovery document.
For more details see the project wiki.
"""
def __init__(self, responses, check_unexpected=False):
"""Constructor for RequestMockBuilder
The constructed object should be a callable object
that can replace the class HttpResponse.
responses - A dictionary that maps methodIds into tuples
of (httplib2.Response, content). The methodId
comes from the 'rpcName' field in the discovery
document.
check_unexpected - A boolean setting whether or not UnexpectedMethodError
should be raised on unsupplied method.
"""
self.responses = responses
self.check_unexpected = check_unexpected
def __call__(self, http, postproc, uri, method='GET', body=None,
headers=None, methodId=None, resumable=None):
"""Implements the callable interface that discovery.build() expects
of requestBuilder, which is to build an object compatible with
HttpRequest.execute(). See that method for the description of the
parameters and the expected response.
"""
if methodId in self.responses:
response = self.responses[methodId]
resp, content = response[:2]
if len(response) > 2:
# Test the body against the supplied expected_body.
expected_body = response[2]
if bool(expected_body) != bool(body):
# Not expecting a body and provided one
# or expecting a body and not provided one.
raise UnexpectedBodyError(expected_body, body)
if isinstance(expected_body, str):
expected_body = simplejson.loads(expected_body)
body = simplejson.loads(body)
if body != expected_body:
raise UnexpectedBodyError(expected_body, body)
return HttpRequestMock(resp, content, postproc)
elif self.check_unexpected:
raise UnexpectedMethodError(methodId)
else:
model = JsonModel(False)
return HttpRequestMock(None, '{}', model.response)
class HttpMock(object):
"""Mock of httplib2.Http"""
def __init__(self, filename, headers=None):
"""
Args:
filename: string, absolute filename to read response from
headers: dict, header to return with response
"""
if headers is None:
headers = {'status': '200 OK'}
f = file(filename, 'r')
self.data = f.read()
f.close()
self.headers = headers
def request(self, uri,
method='GET',
body=None,
headers=None,
redirections=1,
connection_type=None):
return httplib2.Response(self.headers), self.data
class HttpMockSequence(object):
"""Mock of httplib2.Http
Mocks a sequence of calls to request returning different responses for each
call. Create an instance initialized with the desired response headers
and content and then use as if an httplib2.Http instance.
http = HttpMockSequence([
({'status': '401'}, ''),
({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
({'status': '200'}, 'echo_request_headers'),
])
resp, content = http.request("http://examples.com")
There are special values you can pass in for content to trigger
behavours that are helpful in testing.
'echo_request_headers' means return the request headers in the response body
'echo_request_headers_as_json' means return the request headers in
the response body
'echo_request_body' means return the request body in the response body
'echo_request_uri' means return the request uri in the response body
"""
def __init__(self, iterable):
"""
Args:
iterable: iterable, a sequence of pairs of (headers, body)
"""
self._iterable = iterable
self.follow_redirects = True
def request(self, uri,
method='GET',
body=None,
headers=None,
redirections=1,
connection_type=None):
resp, content = self._iterable.pop(0)
if content == 'echo_request_headers':
content = headers
elif content == 'echo_request_headers_as_json':
content = simplejson.dumps(headers)
elif content == 'echo_request_body':
content = body
elif content == 'echo_request_uri':
content = uri
return httplib2.Response(resp), content
def set_user_agent(http, user_agent):
"""Set the user-agent on every request.
Args:
http - An instance of httplib2.Http
or something that acts like it.
user_agent: string, the value for the user-agent header.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = set_user_agent(h, "my-app-name/6.0")
Most of the time the user-agent will be set doing auth, this is for the rare
cases where you are accessing an unauthenticated endpoint.
"""
request_orig = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the user-agent."""
if headers is None:
headers = {}
if 'user-agent' in headers:
headers['user-agent'] = user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
return resp, content
http.request = new_request
return http
def tunnel_patch(http):
"""Tunnel PATCH requests over POST.
Args:
http - An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = tunnel_patch(h, "my-app-name/6.0")
Useful if you are running on a platform that doesn't support PATCH.
Apply this last if you are using OAuth 1.0, as changing the method
will result in a different signature.
"""
request_orig = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the user-agent."""
if headers is None:
headers = {}
if method == 'PATCH':
if 'oauth_token' in headers.get('authorization', ''):
logging.warning(
'OAuth 1.0 request made with Credentials after tunnel_patch.')
headers['x-http-method-override'] = "PATCH"
method = 'POST'
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
return resp, content
http.request = new_request
return http
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import copy
import httplib2
import logging
import oauth2 as oauth
import urllib
import urlparse
from anyjson import simplejson
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
class Error(Exception):
"""Base error for this module."""
pass
class RequestError(Error):
"""Error occurred during request."""
pass
class MissingParameter(Error):
pass
class CredentialsInvalidError(Error):
pass
def _abstract():
raise NotImplementedError('You need to override this function')
def _oauth_uri(name, discovery, params):
"""Look up the OAuth URI from the discovery
document and add query parameters based on
params.
name - The name of the OAuth URI to lookup, one
of 'request', 'access', or 'authorize'.
discovery - Portion of discovery document the describes
the OAuth endpoints.
params - Dictionary that is used to form the query parameters
for the specified URI.
"""
if name not in ['request', 'access', 'authorize']:
raise KeyError(name)
keys = discovery[name]['parameters'].keys()
query = {}
for key in keys:
if key in params:
query[key] = params[key]
return discovery[name]['url'] + '?' + urllib.urlencode(query)
class Credentials(object):
"""Base class for all Credentials objects.
Subclasses must define an authorize() method
that applies the credentials to an HTTP transport.
"""
def authorize(self, http):
"""Take an httplib2.Http instance (or equivalent) and
authorizes it for the set of credentials, usually by
replacing http.request() with a method that adds in
the appropriate headers and then delegates to the original
Http.request() method.
"""
_abstract()
class Flow(object):
"""Base class for all Flow objects."""
pass
class Storage(object):
"""Base class for all Storage objects.
Store and retrieve a single credential.
"""
def get(self):
"""Retrieve credential.
Returns:
apiclient.oauth.Credentials
"""
_abstract()
def put(self, credentials):
"""Write a credential.
Args:
credentials: Credentials, the credentials to store.
"""
_abstract()
class OAuthCredentials(Credentials):
"""Credentials object for OAuth 1.0a
"""
def __init__(self, consumer, token, user_agent):
"""
consumer - An instance of oauth.Consumer.
token - An instance of oauth.Token constructed with
the access token and secret.
user_agent - The HTTP User-Agent to provide for this application.
"""
self.consumer = consumer
self.token = token
self.user_agent = user_agent
self.store = None
# True if the credentials have been revoked
self._invalid = False
@property
def invalid(self):
"""True if the credentials are invalid, such as being revoked."""
return getattr(self, "_invalid", False)
def set_store(self, store):
"""Set the storage for the credential.
Args:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has been revoked.
"""
self.store = store
def __getstate__(self):
"""Trim the state down to something that can be pickled."""
d = copy.copy(self.__dict__)
del d['store']
return d
def __setstate__(self, state):
"""Reconstitute the state of the object from being pickled."""
self.__dict__.update(state)
self.store = None
def authorize(self, http):
"""Authorize an httplib2.Http instance with these Credentials
Args:
http - An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can't create a new OAuth
subclass of httplib2.Authenication because
it never gets passed the absolute URI, which is
needed for signing. So instead we have to overload
'request' with a closure that adds in the
Authorization header and then calls the original version
of 'request()'.
"""
request_orig = http.request
signer = oauth.SignatureMethod_HMAC_SHA1()
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the appropriate
Authorization header."""
response_code = 302
http.follow_redirects = False
while response_code in [301, 302]:
req = oauth.Request.from_consumer_and_token(
self.consumer, self.token, http_method=method, http_url=uri)
req.sign_request(signer, self.consumer, self.token)
if headers is None:
headers = {}
headers.update(req.to_header())
if 'user-agent' in headers:
headers['user-agent'] = self.user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = self.user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
response_code = resp.status
if response_code in [301, 302]:
uri = resp['location']
# Update the stored credential if it becomes invalid.
if response_code == 401:
logging.info('Access token no longer valid: %s' % content)
self._invalid = True
if self.store is not None:
self.store(self)
raise CredentialsInvalidError("Credentials are no longer valid.")
return resp, content
http.request = new_request
return http
class TwoLeggedOAuthCredentials(Credentials):
"""Two Legged Credentials object for OAuth 1.0a.
The Two Legged object is created directly, not from a flow. Once you
authorize and httplib2.Http instance you can change the requestor and that
change will propogate to the authorized httplib2.Http instance. For example:
http = httplib2.Http()
http = credentials.authorize(http)
credentials.requestor = 'foo@example.info'
http.request(...)
credentials.requestor = 'bar@example.info'
http.request(...)
"""
def __init__(self, consumer_key, consumer_secret, user_agent):
"""
Args:
consumer_key: string, An OAuth 1.0 consumer key
consumer_secret: string, An OAuth 1.0 consumer secret
user_agent: string, The HTTP User-Agent to provide for this application.
"""
self.consumer = oauth.Consumer(consumer_key, consumer_secret)
self.user_agent = user_agent
self.store = None
# email address of the user to act on the behalf of.
self._requestor = None
@property
def invalid(self):
"""True if the credentials are invalid, such as being revoked.
Always returns False for Two Legged Credentials.
"""
return False
def getrequestor(self):
return self._requestor
def setrequestor(self, email):
self._requestor = email
requestor = property(getrequestor, setrequestor, None,
'The email address of the user to act on behalf of')
def set_store(self, store):
"""Set the storage for the credential.
Args:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has been revoked.
"""
self.store = store
def __getstate__(self):
"""Trim the state down to something that can be pickled."""
d = copy.copy(self.__dict__)
del d['store']
return d
def __setstate__(self, state):
"""Reconstitute the state of the object from being pickled."""
self.__dict__.update(state)
self.store = None
def authorize(self, http):
"""Authorize an httplib2.Http instance with these Credentials
Args:
http - An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can't create a new OAuth
subclass of httplib2.Authenication because
it never gets passed the absolute URI, which is
needed for signing. So instead we have to overload
'request' with a closure that adds in the
Authorization header and then calls the original version
of 'request()'.
"""
request_orig = http.request
signer = oauth.SignatureMethod_HMAC_SHA1()
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the appropriate
Authorization header."""
response_code = 302
http.follow_redirects = False
while response_code in [301, 302]:
# add in xoauth_requestor_id=self._requestor to the uri
if self._requestor is None:
raise MissingParameter(
'Requestor must be set before using TwoLeggedOAuthCredentials')
parsed = list(urlparse.urlparse(uri))
q = parse_qsl(parsed[4])
q.append(('xoauth_requestor_id', self._requestor))
parsed[4] = urllib.urlencode(q)
uri = urlparse.urlunparse(parsed)
req = oauth.Request.from_consumer_and_token(
self.consumer, None, http_method=method, http_url=uri)
req.sign_request(signer, self.consumer, None)
if headers is None:
headers = {}
headers.update(req.to_header())
if 'user-agent' in headers:
headers['user-agent'] = self.user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = self.user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
response_code = resp.status
if response_code in [301, 302]:
uri = resp['location']
if response_code == 401:
logging.info('Access token no longer valid: %s' % content)
# Do not store the invalid state of the Credentials because
# being 2LO they could be reinstated in the future.
raise CredentialsInvalidError("Credentials are invalid.")
return resp, content
http.request = new_request
return http
class FlowThreeLegged(Flow):
"""Does the Three Legged Dance for OAuth 1.0a.
"""
def __init__(self, discovery, consumer_key, consumer_secret, user_agent,
**kwargs):
"""
discovery - Section of the API discovery document that describes
the OAuth endpoints.
consumer_key - OAuth consumer key
consumer_secret - OAuth consumer secret
user_agent - The HTTP User-Agent that identifies the application.
**kwargs - The keyword arguments are all optional and required
parameters for the OAuth calls.
"""
self.discovery = discovery
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.user_agent = user_agent
self.params = kwargs
self.request_token = {}
required = {}
for uriinfo in discovery.itervalues():
for name, value in uriinfo['parameters'].iteritems():
if value['required'] and not name.startswith('oauth_'):
required[name] = 1
for key in required.iterkeys():
if key not in self.params:
raise MissingParameter('Required parameter %s not supplied' % key)
def step1_get_authorize_url(self, oauth_callback='oob'):
"""Returns a URI to redirect to the provider.
oauth_callback - Either the string 'oob' for a non-web-based application,
or a URI that handles the callback from the authorization
server.
If oauth_callback is 'oob' then pass in the
generated verification code to step2_exchange,
otherwise pass in the query parameters received
at the callback uri to step2_exchange.
"""
consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
client = oauth.Client(consumer)
headers = {
'user-agent': self.user_agent,
'content-type': 'application/x-www-form-urlencoded'
}
body = urllib.urlencode({'oauth_callback': oauth_callback})
uri = _oauth_uri('request', self.discovery, self.params)
resp, content = client.request(uri, 'POST', headers=headers,
body=body)
if resp['status'] != '200':
logging.error('Failed to retrieve temporary authorization: %s', content)
raise RequestError('Invalid response %s.' % resp['status'])
self.request_token = dict(parse_qsl(content))
auth_params = copy.copy(self.params)
auth_params['oauth_token'] = self.request_token['oauth_token']
return _oauth_uri('authorize', self.discovery, auth_params)
def step2_exchange(self, verifier):
"""Exhanges an authorized request token
for OAuthCredentials.
Args:
verifier: string, dict - either the verifier token, or a dictionary
of the query parameters to the callback, which contains
the oauth_verifier.
Returns:
The Credentials object.
"""
if not (isinstance(verifier, str) or isinstance(verifier, unicode)):
verifier = verifier['oauth_verifier']
token = oauth.Token(
self.request_token['oauth_token'],
self.request_token['oauth_token_secret'])
token.set_verifier(verifier)
consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
client = oauth.Client(consumer, token)
headers = {
'user-agent': self.user_agent,
'content-type': 'application/x-www-form-urlencoded'
}
uri = _oauth_uri('access', self.discovery, self.params)
resp, content = client.request(uri, 'POST', headers=headers)
if resp['status'] != '200':
logging.error('Failed to retrieve access token: %s', content)
raise RequestError('Invalid response %s.' % resp['status'])
oauth_params = dict(parse_qsl(content))
token = oauth.Token(
oauth_params['oauth_token'],
oauth_params['oauth_token_secret'])
return OAuthCredentials(consumer, token, self.user_agent)
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model objects for requests and responses.
Each API may support one or more serializations, such
as JSON, Atom, etc. The model classes are responsible
for converting between the wire format and the Python
object representation.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import logging
import urllib
from errors import HttpError
from oauth2client.anyjson import simplejson
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('dump_request_response', False,
'Dump all http server requests and responses. '
)
def _abstract():
raise NotImplementedError('You need to override this function')
class Model(object):
"""Model base class.
All Model classes should implement this interface.
The Model serializes and de-serializes between a wire
format such as JSON and a Python object representation.
"""
def request(self, headers, path_params, query_params, body_value):
"""Updates outgoing requests with a serialized body.
Args:
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query_params: dict, parameters that appear in the query
body_value: object, the request body as a Python object, which must be
serializable.
Returns:
A tuple of (headers, path_params, query, body)
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query: string, query part of the request URI
body: string, the body serialized in the desired wire format.
"""
_abstract()
def response(self, resp, content):
"""Convert the response wire format into a Python object.
Args:
resp: httplib2.Response, the HTTP response headers and status
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
Raises:
apiclient.errors.HttpError if a non 2xx response is received.
"""
_abstract()
class BaseModel(Model):
"""Base model class.
Subclasses should provide implementations for the "serialize" and
"deserialize" methods, as well as values for the following class attributes.
Attributes:
accept: The value to use for the HTTP Accept header.
content_type: The value to use for the HTTP Content-type header.
no_content_response: The value to return when deserializing a 204 "No
Content" response.
alt_param: The value to supply as the "alt" query parameter for requests.
"""
accept = None
content_type = None
no_content_response = None
alt_param = None
def _log_request(self, headers, path_params, query, body):
"""Logs debugging information about the request if requested."""
if FLAGS.dump_request_response:
logging.info('--request-start--')
logging.info('-headers-start-')
for h, v in headers.iteritems():
logging.info('%s: %s', h, v)
logging.info('-headers-end-')
logging.info('-path-parameters-start-')
for h, v in path_params.iteritems():
logging.info('%s: %s', h, v)
logging.info('-path-parameters-end-')
logging.info('body: %s', body)
logging.info('query: %s', query)
logging.info('--request-end--')
def request(self, headers, path_params, query_params, body_value):
"""Updates outgoing requests with a serialized body.
Args:
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query_params: dict, parameters that appear in the query
body_value: object, the request body as a Python object, which must be
serializable by simplejson.
Returns:
A tuple of (headers, path_params, query, body)
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query: string, query part of the request URI
body: string, the body serialized as JSON
"""
query = self._build_query(query_params)
headers['accept'] = self.accept
headers['accept-encoding'] = 'gzip, deflate'
if 'user-agent' in headers:
headers['user-agent'] += ' '
else:
headers['user-agent'] = ''
headers['user-agent'] += 'google-api-python-client/1.0'
if body_value is not None:
headers['content-type'] = self.content_type
body_value = self.serialize(body_value)
self._log_request(headers, path_params, query, body_value)
return (headers, path_params, query, body_value)
def _build_query(self, params):
"""Builds a query string.
Args:
params: dict, the query parameters
Returns:
The query parameters properly encoded into an HTTP URI query string.
"""
if self.alt_param is not None:
params.update({'alt': self.alt_param})
astuples = []
for key, value in params.iteritems():
if type(value) == type([]):
for x in value:
x = x.encode('utf-8')
astuples.append((key, x))
else:
if getattr(value, 'encode', False) and callable(value.encode):
value = value.encode('utf-8')
astuples.append((key, value))
return '?' + urllib.urlencode(astuples)
def _log_response(self, resp, content):
"""Logs debugging information about the response if requested."""
if FLAGS.dump_request_response:
logging.info('--response-start--')
for h, v in resp.iteritems():
logging.info('%s: %s', h, v)
if content:
logging.info(content)
logging.info('--response-end--')
def response(self, resp, content):
"""Convert the response wire format into a Python object.
Args:
resp: httplib2.Response, the HTTP response headers and status
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
Raises:
apiclient.errors.HttpError if a non 2xx response is received.
"""
self._log_response(resp, content)
# Error handling is TBD, for example, do we retry
# for some operation/error combinations?
if resp.status < 300:
if resp.status == 204:
# A 204: No Content response should be treated differently
# to all the other success states
return self.no_content_response
return self.deserialize(content)
else:
logging.debug('Content from bad request was: %s' % content)
raise HttpError(resp, content)
def serialize(self, body_value):
"""Perform the actual Python object serialization.
Args:
body_value: object, the request body as a Python object.
Returns:
string, the body in serialized form.
"""
_abstract()
def deserialize(self, content):
"""Perform the actual deserialization from response string to Python
object.
Args:
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
"""
_abstract()
class JsonModel(BaseModel):
"""Model class for JSON.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request and response bodies.
"""
accept = 'application/json'
content_type = 'application/json'
alt_param = 'json'
def __init__(self, data_wrapper=False):
"""Construct a JsonModel.
Args:
data_wrapper: boolean, wrap requests and responses in a data wrapper
"""
self._data_wrapper = data_wrapper
def serialize(self, body_value):
if (isinstance(body_value, dict) and 'data' not in body_value and
self._data_wrapper):
body_value = {'data': body_value}
return simplejson.dumps(body_value)
def deserialize(self, content):
body = simplejson.loads(content)
if isinstance(body, dict) and 'data' in body:
body = body['data']
return body
@property
def no_content_response(self):
return {}
class RawModel(JsonModel):
"""Model class for requests that don't return JSON.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request, and returns the raw bytes
of the response body.
"""
accept = '*/*'
content_type = 'application/json'
alt_param = None
def deserialize(self, content):
return content
@property
def no_content_response(self):
return ''
class MediaModel(JsonModel):
"""Model class for requests that return Media.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request, and returns the raw bytes
of the response body.
"""
accept = '*/*'
content_type = 'application/json'
alt_param = 'media'
def deserialize(self, content):
return content
@property
def no_content_response(self):
return ''
class ProtocolBufferModel(BaseModel):
"""Model class for protocol buffers.
Serializes and de-serializes the binary protocol buffer sent in the HTTP
request and response bodies.
"""
accept = 'application/x-protobuf'
content_type = 'application/x-protobuf'
alt_param = 'proto'
def __init__(self, protocol_buffer):
"""Constructs a ProtocolBufferModel.
The serialzed protocol buffer returned in an HTTP response will be
de-serialized using the given protocol buffer class.
Args:
protocol_buffer: The protocol buffer class used to de-serialize a
response from the API.
"""
self._protocol_buffer = protocol_buffer
def serialize(self, body_value):
return body_value.SerializeToString()
def deserialize(self, content):
return self._protocol_buffer.FromString(content)
@property
def no_content_response(self):
return self._protocol_buffer()
def makepatch(original, modified):
"""Create a patch object.
Some methods support PATCH, an efficient way to send updates to a resource.
This method allows the easy construction of patch bodies by looking at the
differences between a resource before and after it was modified.
Args:
original: object, the original deserialized resource
modified: object, the modified deserialized resource
Returns:
An object that contains only the changes from original to modified, in a
form suitable to pass to a PATCH method.
Example usage:
item = service.activities().get(postid=postid, userid=userid).execute()
original = copy.deepcopy(item)
item['object']['content'] = 'This is updated.'
service.activities.patch(postid=postid, userid=userid,
body=makepatch(original, item)).execute()
"""
patch = {}
for key, original_value in original.iteritems():
modified_value = modified.get(key, None)
if modified_value is None:
# Use None to signal that the element is deleted
patch[key] = None
elif original_value != modified_value:
if type(original_value) == type({}):
# Recursively descend objects
patch[key] = makepatch(original_value, modified_value)
else:
# In the case of simple types or arrays we just replace
patch[key] = modified_value
else:
# Don't add anything to patch if there's no change
pass
for key in modified:
if key not in original:
patch[key] = modified[key]
return patch
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Client for discovery based APIs
A client library for Google's discovery based APIs.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
__all__ = [
'build',
'build_from_document'
'fix_method_name',
'key2param'
]
import copy
import httplib2
import logging
import os
import random
import re
import uritemplate
import urllib
import urlparse
import mimeparse
import mimetypes
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
from apiclient.errors import HttpError
from apiclient.errors import InvalidJsonError
from apiclient.errors import MediaUploadSizeError
from apiclient.errors import UnacceptableMimeTypeError
from apiclient.errors import UnknownApiNameOrVersion
from apiclient.errors import UnknownLinkType
from apiclient.http import HttpRequest
from apiclient.http import MediaFileUpload
from apiclient.http import MediaUpload
from apiclient.model import JsonModel
from apiclient.model import MediaModel
from apiclient.model import RawModel
from apiclient.schema import Schemas
from email.mime.multipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart
from oauth2client.anyjson import simplejson
logger = logging.getLogger(__name__)
URITEMPLATE = re.compile('{[^}]*}')
VARNAME = re.compile('[a-zA-Z0-9_-]+')
DISCOVERY_URI = ('https://www.googleapis.com/discovery/v1/apis/'
'{api}/{apiVersion}/rest')
DEFAULT_METHOD_DOC = 'A description of how to use this function'
# Parameters accepted by the stack, but not visible via discovery.
STACK_QUERY_PARAMETERS = ['trace', 'pp', 'userip', 'strict']
# Python reserved words.
RESERVED_WORDS = ['and', 'assert', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'exec', 'finally', 'for', 'from',
'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or',
'pass', 'print', 'raise', 'return', 'try', 'while' ]
def fix_method_name(name):
"""Fix method names to avoid reserved word conflicts.
Args:
name: string, method name.
Returns:
The name with a '_' prefixed if the name is a reserved word.
"""
if name in RESERVED_WORDS:
return name + '_'
else:
return name
def _add_query_parameter(url, name, value):
"""Adds a query parameter to a url.
Replaces the current value if it already exists in the URL.
Args:
url: string, url to add the query parameter to.
name: string, query parameter name.
value: string, query parameter value.
Returns:
Updated query parameter. Does not update the url if value is None.
"""
if value is None:
return url
else:
parsed = list(urlparse.urlparse(url))
q = dict(parse_qsl(parsed[4]))
q[name] = value
parsed[4] = urllib.urlencode(q)
return urlparse.urlunparse(parsed)
def key2param(key):
"""Converts key names into parameter names.
For example, converting "max-results" -> "max_results"
Args:
key: string, the method key name.
Returns:
A safe method name based on the key name.
"""
result = []
key = list(key)
if not key[0].isalpha():
result.append('x')
for c in key:
if c.isalnum():
result.append(c)
else:
result.append('_')
return ''.join(result)
def build(serviceName,
version,
http=None,
discoveryServiceUrl=DISCOVERY_URI,
developerKey=None,
model=None,
requestBuilder=HttpRequest):
"""Construct a Resource for interacting with an API.
Construct a Resource object for interacting with an API. The serviceName and
version are the names from the Discovery service.
Args:
serviceName: string, name of the service.
version: string, the version of the service.
http: httplib2.Http, An instance of httplib2.Http or something that acts
like it that HTTP requests will be made through.
discoveryServiceUrl: string, a URI Template that points to the location of
the discovery service. It should have two parameters {api} and
{apiVersion} that when filled in produce an absolute URI to the discovery
document for that service.
developerKey: string, key obtained from
https://code.google.com/apis/console.
model: apiclient.Model, converts to and from the wire format.
requestBuilder: apiclient.http.HttpRequest, encapsulator for an HTTP
request.
Returns:
A Resource object with methods for interacting with the service.
"""
params = {
'api': serviceName,
'apiVersion': version
}
if http is None:
http = httplib2.Http()
requested_url = uritemplate.expand(discoveryServiceUrl, params)
# REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment
# variable that contains the network address of the client sending the
# request. If it exists then add that to the request for the discovery
# document to avoid exceeding the quota on discovery requests.
if 'REMOTE_ADDR' in os.environ:
requested_url = _add_query_parameter(requested_url, 'userIp',
os.environ['REMOTE_ADDR'])
logger.info('URL being requested: %s' % requested_url)
resp, content = http.request(requested_url)
if resp.status == 404:
raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName,
version))
if resp.status >= 400:
raise HttpError(resp, content, requested_url)
try:
service = simplejson.loads(content)
except ValueError, e:
logger.error('Failed to parse as JSON: ' + content)
raise InvalidJsonError()
return build_from_document(content, discoveryServiceUrl, http=http,
developerKey=developerKey, model=model, requestBuilder=requestBuilder)
def build_from_document(
service,
base,
future=None,
http=None,
developerKey=None,
model=None,
requestBuilder=HttpRequest):
"""Create a Resource for interacting with an API.
Same as `build()`, but constructs the Resource object from a discovery
document that is it given, as opposed to retrieving one over HTTP.
Args:
service: string, discovery document.
base: string, base URI for all HTTP requests, usually the discovery URI.
future: string, discovery document with future capabilities (deprecated).
http: httplib2.Http, An instance of httplib2.Http or something that acts
like it that HTTP requests will be made through.
developerKey: string, Key for controlling API usage, generated
from the API Console.
model: Model class instance that serializes and de-serializes requests and
responses.
requestBuilder: Takes an http request and packages it up to be executed.
Returns:
A Resource object with methods for interacting with the service.
"""
# future is no longer used.
future = {}
service = simplejson.loads(service)
base = urlparse.urljoin(base, service['basePath'])
schema = Schemas(service)
if model is None:
features = service.get('features', [])
model = JsonModel('dataWrapper' in features)
resource = _createResource(http, base, model, requestBuilder, developerKey,
service, service, schema)
return resource
def _cast(value, schema_type):
"""Convert value to a string based on JSON Schema type.
See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on
JSON Schema.
Args:
value: any, the value to convert
schema_type: string, the type that value should be interpreted as
Returns:
A string representation of 'value' based on the schema_type.
"""
if schema_type == 'string':
if type(value) == type('') or type(value) == type(u''):
return value
else:
return str(value)
elif schema_type == 'integer':
return str(int(value))
elif schema_type == 'number':
return str(float(value))
elif schema_type == 'boolean':
return str(bool(value)).lower()
else:
if type(value) == type('') or type(value) == type(u''):
return value
else:
return str(value)
MULTIPLIERS = {
"KB": 2 ** 10,
"MB": 2 ** 20,
"GB": 2 ** 30,
"TB": 2 ** 40,
}
def _media_size_to_long(maxSize):
"""Convert a string media size, such as 10GB or 3TB into an integer.
Args:
maxSize: string, size as a string, such as 2MB or 7GB.
Returns:
The size as an integer value.
"""
if len(maxSize) < 2:
return 0
units = maxSize[-2:].upper()
multiplier = MULTIPLIERS.get(units, 0)
if multiplier:
return int(maxSize[:-2]) * multiplier
else:
return int(maxSize)
def _createResource(http, baseUrl, model, requestBuilder,
developerKey, resourceDesc, rootDesc, schema):
"""Build a Resource from the API description.
Args:
http: httplib2.Http, Object to make http requests with.
baseUrl: string, base URL for the API. All requests are relative to this
URI.
model: apiclient.Model, converts to and from the wire format.
requestBuilder: class or callable that instantiates an
apiclient.HttpRequest object.
developerKey: string, key obtained from
https://code.google.com/apis/console
resourceDesc: object, section of deserialized discovery document that
describes a resource. Note that the top level discovery document
is considered a resource.
rootDesc: object, the entire deserialized discovery document.
schema: object, mapping of schema names to schema descriptions.
Returns:
An instance of Resource with all the methods attached for interacting with
that resource.
"""
class Resource(object):
"""A class for interacting with a resource."""
def __init__(self):
self._http = http
self._baseUrl = baseUrl
self._model = model
self._developerKey = developerKey
self._requestBuilder = requestBuilder
def createMethod(theclass, methodName, methodDesc, rootDesc):
"""Creates a method for attaching to a Resource.
Args:
theclass: type, the class to attach methods to.
methodName: string, name of the method to use.
methodDesc: object, fragment of deserialized discovery document that
describes the method.
rootDesc: object, the entire deserialized discovery document.
"""
methodName = fix_method_name(methodName)
pathUrl = methodDesc['path']
httpMethod = methodDesc['httpMethod']
methodId = methodDesc['id']
mediaPathUrl = None
accept = []
maxSize = 0
if 'mediaUpload' in methodDesc:
mediaUpload = methodDesc['mediaUpload']
# TODO(jcgregorio) Use URLs from discovery once it is updated.
parsed = list(urlparse.urlparse(baseUrl))
basePath = parsed[2]
mediaPathUrl = '/upload' + basePath + pathUrl
accept = mediaUpload['accept']
maxSize = _media_size_to_long(mediaUpload.get('maxSize', ''))
if 'parameters' not in methodDesc:
methodDesc['parameters'] = {}
# Add in the parameters common to all methods.
for name, desc in rootDesc.get('parameters', {}).iteritems():
methodDesc['parameters'][name] = desc
# Add in undocumented query parameters.
for name in STACK_QUERY_PARAMETERS:
methodDesc['parameters'][name] = {
'type': 'string',
'location': 'query'
}
if httpMethod in ['PUT', 'POST', 'PATCH'] and 'request' in methodDesc:
methodDesc['parameters']['body'] = {
'description': 'The request body.',
'type': 'object',
'required': True,
}
if 'request' in methodDesc:
methodDesc['parameters']['body'].update(methodDesc['request'])
else:
methodDesc['parameters']['body']['type'] = 'object'
if 'mediaUpload' in methodDesc:
methodDesc['parameters']['media_body'] = {
'description': 'The filename of the media request body.',
'type': 'string',
'required': False,
}
if 'body' in methodDesc['parameters']:
methodDesc['parameters']['body']['required'] = False
argmap = {} # Map from method parameter name to query parameter name
required_params = [] # Required parameters
repeated_params = [] # Repeated parameters
pattern_params = {} # Parameters that must match a regex
query_params = [] # Parameters that will be used in the query string
path_params = {} # Parameters that will be used in the base URL
param_type = {} # The type of the parameter
enum_params = {} # Allowable enumeration values for each parameter
if 'parameters' in methodDesc:
for arg, desc in methodDesc['parameters'].iteritems():
param = key2param(arg)
argmap[param] = arg
if desc.get('pattern', ''):
pattern_params[param] = desc['pattern']
if desc.get('enum', ''):
enum_params[param] = desc['enum']
if desc.get('required', False):
required_params.append(param)
if desc.get('repeated', False):
repeated_params.append(param)
if desc.get('location') == 'query':
query_params.append(param)
if desc.get('location') == 'path':
path_params[param] = param
param_type[param] = desc.get('type', 'string')
for match in URITEMPLATE.finditer(pathUrl):
for namematch in VARNAME.finditer(match.group(0)):
name = key2param(namematch.group(0))
path_params[name] = name
if name in query_params:
query_params.remove(name)
def method(self, **kwargs):
# Don't bother with doc string, it will be over-written by createMethod.
for name in kwargs.iterkeys():
if name not in argmap:
raise TypeError('Got an unexpected keyword argument "%s"' % name)
# Remove args that have a value of None.
keys = kwargs.keys()
for name in keys:
if kwargs[name] is None:
del kwargs[name]
for name in required_params:
if name not in kwargs:
raise TypeError('Missing required parameter "%s"' % name)
for name, regex in pattern_params.iteritems():
if name in kwargs:
if isinstance(kwargs[name], basestring):
pvalues = [kwargs[name]]
else:
pvalues = kwargs[name]
for pvalue in pvalues:
if re.match(regex, pvalue) is None:
raise TypeError(
'Parameter "%s" value "%s" does not match the pattern "%s"' %
(name, pvalue, regex))
for name, enums in enum_params.iteritems():
if name in kwargs:
# We need to handle the case of a repeated enum
# name differently, since we want to handle both
# arg='value' and arg=['value1', 'value2']
if (name in repeated_params and
not isinstance(kwargs[name], basestring)):
values = kwargs[name]
else:
values = [kwargs[name]]
for value in values:
if value not in enums:
raise TypeError(
'Parameter "%s" value "%s" is not an allowed value in "%s"' %
(name, value, str(enums)))
actual_query_params = {}
actual_path_params = {}
for key, value in kwargs.iteritems():
to_type = param_type.get(key, 'string')
# For repeated parameters we cast each member of the list.
if key in repeated_params and type(value) == type([]):
cast_value = [_cast(x, to_type) for x in value]
else:
cast_value = _cast(value, to_type)
if key in query_params:
actual_query_params[argmap[key]] = cast_value
if key in path_params:
actual_path_params[argmap[key]] = cast_value
body_value = kwargs.get('body', None)
media_filename = kwargs.get('media_body', None)
if self._developerKey:
actual_query_params['key'] = self._developerKey
model = self._model
# If there is no schema for the response then presume a binary blob.
if methodName.endswith('_media'):
model = MediaModel()
elif 'response' not in methodDesc:
model = RawModel()
headers = {}
headers, params, query, body = model.request(headers,
actual_path_params, actual_query_params, body_value)
expanded_url = uritemplate.expand(pathUrl, params)
url = urlparse.urljoin(self._baseUrl, expanded_url + query)
resumable = None
multipart_boundary = ''
if media_filename:
# Ensure we end up with a valid MediaUpload object.
if isinstance(media_filename, basestring):
(media_mime_type, encoding) = mimetypes.guess_type(media_filename)
if media_mime_type is None:
raise UnknownFileType(media_filename)
if not mimeparse.best_match([media_mime_type], ','.join(accept)):
raise UnacceptableMimeTypeError(media_mime_type)
media_upload = MediaFileUpload(media_filename, media_mime_type)
elif isinstance(media_filename, MediaUpload):
media_upload = media_filename
else:
raise TypeError('media_filename must be str or MediaUpload.')
# Check the maxSize
if maxSize > 0 and media_upload.size() > maxSize:
raise MediaUploadSizeError("Media larger than: %s" % maxSize)
# Use the media path uri for media uploads
expanded_url = uritemplate.expand(mediaPathUrl, params)
url = urlparse.urljoin(self._baseUrl, expanded_url + query)
if media_upload.resumable():
url = _add_query_parameter(url, 'uploadType', 'resumable')
if media_upload.resumable():
# This is all we need to do for resumable, if the body exists it gets
# sent in the first request, otherwise an empty body is sent.
resumable = media_upload
else:
# A non-resumable upload
if body is None:
# This is a simple media upload
headers['content-type'] = media_upload.mimetype()
body = media_upload.getbytes(0, media_upload.size())
url = _add_query_parameter(url, 'uploadType', 'media')
else:
# This is a multipart/related upload.
msgRoot = MIMEMultipart('related')
# msgRoot should not write out it's own headers
setattr(msgRoot, '_write_headers', lambda self: None)
# attach the body as one part
msg = MIMENonMultipart(*headers['content-type'].split('/'))
msg.set_payload(body)
msgRoot.attach(msg)
# attach the media as the second part
msg = MIMENonMultipart(*media_upload.mimetype().split('/'))
msg['Content-Transfer-Encoding'] = 'binary'
payload = media_upload.getbytes(0, media_upload.size())
msg.set_payload(payload)
msgRoot.attach(msg)
body = msgRoot.as_string()
multipart_boundary = msgRoot.get_boundary()
headers['content-type'] = ('multipart/related; '
'boundary="%s"') % multipart_boundary
url = _add_query_parameter(url, 'uploadType', 'multipart')
logger.info('URL being requested: %s' % url)
return self._requestBuilder(self._http,
model.response,
url,
method=httpMethod,
body=body,
headers=headers,
methodId=methodId,
resumable=resumable)
docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n']
if len(argmap) > 0:
docs.append('Args:\n')
# Skip undocumented params and params common to all methods.
skip_parameters = rootDesc.get('parameters', {}).keys()
skip_parameters.append(STACK_QUERY_PARAMETERS)
for arg in argmap.iterkeys():
if arg in skip_parameters:
continue
repeated = ''
if arg in repeated_params:
repeated = ' (repeated)'
required = ''
if arg in required_params:
required = ' (required)'
paramdesc = methodDesc['parameters'][argmap[arg]]
paramdoc = paramdesc.get('description', 'A parameter')
if '$ref' in paramdesc:
docs.append(
(' %s: object, %s%s%s\n The object takes the'
' form of:\n\n%s\n\n') % (arg, paramdoc, required, repeated,
schema.prettyPrintByName(paramdesc['$ref'])))
else:
paramtype = paramdesc.get('type', 'string')
docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required,
repeated))
enum = paramdesc.get('enum', [])
enumDesc = paramdesc.get('enumDescriptions', [])
if enum and enumDesc:
docs.append(' Allowed values\n')
for (name, desc) in zip(enum, enumDesc):
docs.append(' %s - %s\n' % (name, desc))
if 'response' in methodDesc:
if methodName.endswith('_media'):
docs.append('\nReturns:\n The media object as a string.\n\n ')
else:
docs.append('\nReturns:\n An object of the form:\n\n ')
docs.append(schema.prettyPrintSchema(methodDesc['response']))
setattr(method, '__doc__', ''.join(docs))
setattr(theclass, methodName, method)
def createNextMethod(theclass, methodName, methodDesc, rootDesc):
"""Creates any _next methods for attaching to a Resource.
The _next methods allow for easy iteration through list() responses.
Args:
theclass: type, the class to attach methods to.
methodName: string, name of the method to use.
methodDesc: object, fragment of deserialized discovery document that
describes the method.
rootDesc: object, the entire deserialized discovery document.
"""
methodName = fix_method_name(methodName)
methodId = methodDesc['id'] + '.next'
def methodNext(self, previous_request, previous_response):
"""Retrieves the next page of results.
Args:
previous_request: The request for the previous page.
previous_response: The response from the request for the previous page.
Returns:
A request object that you can call 'execute()' on to request the next
page. Returns None if there are no more items in the collection.
"""
# Retrieve nextPageToken from previous_response
# Use as pageToken in previous_request to create new request.
if 'nextPageToken' not in previous_response:
return None
request = copy.copy(previous_request)
pageToken = previous_response['nextPageToken']
parsed = list(urlparse.urlparse(request.uri))
q = parse_qsl(parsed[4])
# Find and remove old 'pageToken' value from URI
newq = [(key, value) for (key, value) in q if key != 'pageToken']
newq.append(('pageToken', pageToken))
parsed[4] = urllib.urlencode(newq)
uri = urlparse.urlunparse(parsed)
request.uri = uri
logger.info('URL being requested: %s' % uri)
return request
setattr(theclass, methodName, methodNext)
# Add basic methods to Resource
if 'methods' in resourceDesc:
for methodName, methodDesc in resourceDesc['methods'].iteritems():
createMethod(Resource, methodName, methodDesc, rootDesc)
# Add in _media methods. The functionality of the attached method will
# change when it sees that the method name ends in _media.
if methodDesc.get('supportsMediaDownload', False):
createMethod(Resource, methodName + '_media', methodDesc, rootDesc)
# Add in nested resources
if 'resources' in resourceDesc:
def createResourceMethod(theclass, methodName, methodDesc, rootDesc):
"""Create a method on the Resource to access a nested Resource.
Args:
theclass: type, the class to attach methods to.
methodName: string, name of the method to use.
methodDesc: object, fragment of deserialized discovery document that
describes the method.
rootDesc: object, the entire deserialized discovery document.
"""
methodName = fix_method_name(methodName)
def methodResource(self):
return _createResource(self._http, self._baseUrl, self._model,
self._requestBuilder, self._developerKey,
methodDesc, rootDesc, schema)
setattr(methodResource, '__doc__', 'A collection resource.')
setattr(methodResource, '__is_resource__', True)
setattr(theclass, methodName, methodResource)
for methodName, methodDesc in resourceDesc['resources'].iteritems():
createResourceMethod(Resource, methodName, methodDesc, rootDesc)
# Add _next() methods
# Look for response bodies in schema that contain nextPageToken, and methods
# that take a pageToken parameter.
if 'methods' in resourceDesc:
for methodName, methodDesc in resourceDesc['methods'].iteritems():
if 'response' in methodDesc:
responseSchema = methodDesc['response']
if '$ref' in responseSchema:
responseSchema = schema.get(responseSchema['$ref'])
hasNextPageToken = 'nextPageToken' in responseSchema.get('properties',
{})
hasPageToken = 'pageToken' in methodDesc.get('parameters', {})
if hasNextPageToken and hasPageToken:
createNextMethod(Resource, methodName + '_next',
resourceDesc['methods'][methodName],
methodName)
return Resource()
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth 1.0 credentials.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import pickle
import threading
from apiclient.oauth import Storage as BaseStorage
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from a file."""
def __init__(self, filename):
self._filename = filename
self._lock = threading.Lock()
def get(self):
"""Retrieve Credential from file.
Returns:
apiclient.oauth.Credentials
"""
self._lock.acquire()
try:
f = open(self._filename, 'r')
credentials = pickle.loads(f.read())
f.close()
credentials.set_store(self.put)
except:
credentials = None
self._lock.release()
return credentials
def put(self, credentials):
"""Write a pickled Credentials to file.
Args:
credentials: Credentials, the credentials to store.
"""
self._lock.acquire()
f = open(self._filename, 'w')
f.write(pickle.dumps(credentials))
f.close()
self._lock.release()
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import apiclient
import base64
import pickle
from django.db import models
class OAuthCredentialsField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self):
return 'VARCHAR'
def to_python(self, value):
if value is None:
return None
if isinstance(value, apiclient.oauth.Credentials):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value):
return base64.b64encode(pickle.dumps(value))
class FlowThreeLeggedField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self):
return 'VARCHAR'
def to_python(self, value):
print "In to_python", value
if value is None:
return None
if isinstance(value, apiclient.oauth.FlowThreeLegged):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value):
return base64.b64encode(pickle.dumps(value))
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for Google App Engine
Utilities for making it easier to use the
Google API Client for Python on Google App Engine.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import pickle
from google.appengine.ext import db
from apiclient.oauth import OAuthCredentials
from apiclient.oauth import FlowThreeLegged
class FlowThreeLeggedProperty(db.Property):
"""Utility property that allows easy
storage and retreival of an
apiclient.oauth.FlowThreeLegged"""
# Tell what the user type is.
data_type = FlowThreeLegged
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
flow = super(FlowThreeLeggedProperty,
self).get_value_for_datastore(model_instance)
return db.Blob(pickle.dumps(flow))
# For reading from datastore.
def make_value_from_datastore(self, value):
if value is None:
return None
return pickle.loads(value)
def validate(self, value):
if value is not None and not isinstance(value, FlowThreeLegged):
raise BadValueError('Property %s must be convertible '
'to a FlowThreeLegged instance (%s)' %
(self.name, value))
return super(FlowThreeLeggedProperty, self).validate(value)
def empty(self, value):
return not value
class OAuthCredentialsProperty(db.Property):
"""Utility property that allows easy
storage and retrieval of
apiclient.oath.OAuthCredentials
"""
# Tell what the user type is.
data_type = OAuthCredentials
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
cred = super(OAuthCredentialsProperty,
self).get_value_for_datastore(model_instance)
return db.Blob(pickle.dumps(cred))
# For reading from datastore.
def make_value_from_datastore(self, value):
if value is None:
return None
return pickle.loads(value)
def validate(self, value):
if value is not None and not isinstance(value, OAuthCredentials):
raise BadValueError('Property %s must be convertible '
'to an OAuthCredentials instance (%s)' %
(self.name, value))
return super(OAuthCredentialsProperty, self).validate(value)
def empty(self, value):
return not value
class StorageByKeyName(object):
"""Store and retrieve a single credential to and from
the App Engine datastore.
This Storage helper presumes the Credentials
have been stored as a CredenialsProperty
on a datastore model class, and that entities
are stored by key_name.
"""
def __init__(self, model, key_name, property_name):
"""Constructor for Storage.
Args:
model: db.Model, model class
key_name: string, key name for the entity that has the credentials
property_name: string, name of the property that is a CredentialsProperty
"""
self.model = model
self.key_name = key_name
self.property_name = property_name
def get(self):
"""Retrieve Credential from datastore.
Returns:
Credentials
"""
entity = self.model.get_or_insert(self.key_name)
credential = getattr(entity, self.property_name)
if credential and hasattr(credential, 'set_store'):
credential.set_store(self.put)
return credential
def put(self, credentials):
"""Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.
"""
entity = self.model.get_or_insert(self.key_name)
setattr(entity, self.property_name, credentials)
entity.put()
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command-line tools for authenticating via OAuth 1.0
Do the OAuth 1.0 Three Legged Dance for
a command line application. Stores the generated
credentials in a common file that is used by
other example apps in the same directory.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
__all__ = ["run"]
import BaseHTTPServer
import gflags
import logging
import socket
import sys
from optparse import OptionParser
from apiclient.oauth import RequestError
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('auth_local_webserver', True,
('Run a local web server to handle redirects during '
'OAuth authorization.'))
gflags.DEFINE_string('auth_host_name', 'localhost',
('Host name to use when running a local web server to '
'handle redirects during OAuth authorization.'))
gflags.DEFINE_multi_int('auth_host_port', [8080, 8090],
('Port to use when running a local web server to '
'handle redirects during OAuth authorization.'))
class ClientRedirectServer(BaseHTTPServer.HTTPServer):
"""A server to handle OAuth 1.0 redirects back to localhost.
Waits for a single request and parses the query parameters
into query_params and then stops serving.
"""
query_params = {}
class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""A handler for OAuth 1.0 redirects back to localhost.
Waits for a single request and parses the query parameters
into the servers query_params and then stops serving.
"""
def do_GET(s):
"""Handle a GET request
Parses the query parameters and prints a message
if the flow has completed. Note that we can't detect
if an error occurred.
"""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
query = s.path.split('?', 1)[-1]
query = dict(parse_qsl(query))
s.server.query_params = query
s.wfile.write("<html><head><title>Authentication Status</title></head>")
s.wfile.write("<body><p>The authentication flow has completed.</p>")
s.wfile.write("</body></html>")
def log_message(self, format, *args):
"""Do not log messages to stdout while running as command line program."""
pass
def run(flow, storage):
"""Core code for a command-line application.
Args:
flow: Flow, an OAuth 1.0 Flow to step through.
storage: Storage, a Storage to store the credential in.
Returns:
Credentials, the obtained credential.
Exceptions:
RequestError: if step2 of the flow fails.
Args:
"""
if FLAGS.auth_local_webserver:
success = False
port_number = 0
for port in FLAGS.auth_host_port:
port_number = port
try:
httpd = BaseHTTPServer.HTTPServer((FLAGS.auth_host_name, port),
ClientRedirectHandler)
except socket.error, e:
pass
else:
success = True
break
FLAGS.auth_local_webserver = success
if FLAGS.auth_local_webserver:
oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number)
else:
oauth_callback = 'oob'
authorize_url = flow.step1_get_authorize_url(oauth_callback)
print 'Go to the following link in your browser:'
print authorize_url
print
if FLAGS.auth_local_webserver:
print 'If your browser is on a different machine then exit and re-run this'
print 'application with the command-line parameter --noauth_local_webserver.'
print
if FLAGS.auth_local_webserver:
httpd.handle_request()
if 'error' in httpd.query_params:
sys.exit('Authentication request was rejected.')
if 'oauth_verifier' in httpd.query_params:
code = httpd.query_params['oauth_verifier']
else:
accepted = 'n'
while accepted.lower() == 'n':
accepted = raw_input('Have you authorized me? (y/n) ')
code = raw_input('What is the verification code? ').strip()
try:
credentials = flow.step2_exchange(code)
except RequestError:
sys.exit('The authentication has failed.')
storage.put(credentials)
credentials.set_store(storage.put)
print "You have successfully authenticated."
return credentials
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Errors for the library.
All exceptions defined by the library
should be defined in this file.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from oauth2client.anyjson import simplejson
class Error(Exception):
"""Base error for this module."""
pass
class HttpError(Error):
"""HTTP data was invalid or unexpected."""
def __init__(self, resp, content, uri=None):
self.resp = resp
self.content = content
self.uri = uri
def _get_reason(self):
"""Calculate the reason for the error from the response content."""
if self.resp.get('content-type', '').startswith('application/json'):
try:
data = simplejson.loads(self.content)
reason = data['error']['message']
except (ValueError, KeyError):
reason = self.content
else:
reason = self.resp.reason
return reason
def __repr__(self):
if self.uri:
return '<HttpError %s when requesting %s returned "%s">' % (
self.resp.status, self.uri, self._get_reason())
else:
return '<HttpError %s "%s">' % (self.resp.status, self._get_reason())
__str__ = __repr__
class InvalidJsonError(Error):
"""The JSON returned could not be parsed."""
pass
class UnknownLinkType(Error):
"""Link type unknown or unexpected."""
pass
class UnknownApiNameOrVersion(Error):
"""No API with that name and version exists."""
pass
class UnacceptableMimeTypeError(Error):
"""That is an unacceptable mimetype for this operation."""
pass
class MediaUploadSizeError(Error):
"""Media is larger than the method can accept."""
pass
class ResumableUploadError(Error):
"""Error occured during resumable upload."""
pass
class BatchError(HttpError):
"""Error occured during batch operations."""
def __init__(self, reason, resp=None, content=None):
self.resp = resp
self.content = content
self.reason = reason
def __repr__(self):
return '<BatchError %s "%s">' % (self.resp.status, self.reason)
__str__ = __repr__
class UnexpectedMethodError(Error):
"""Exception raised by RequestMockBuilder on unexpected calls."""
def __init__(self, methodId=None):
"""Constructor for an UnexpectedMethodError."""
super(UnexpectedMethodError, self).__init__(
'Received unexpected call %s' % methodId)
class UnexpectedBodyError(Error):
"""Exception raised by RequestMockBuilder on unexpected bodies."""
def __init__(self, expected, provided):
"""Constructor for an UnexpectedMethodError."""
super(UnexpectedBodyError, self).__init__(
'Expected: [%s] - Provided: [%s]' % (expected, provided))
| Python |
__version__ = "1.0c2"
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Schema processing for discovery based APIs
Schemas holds an APIs discovery schemas. It can return those schema as
deserialized JSON objects, or pretty print them as prototype objects that
conform to the schema.
For example, given the schema:
schema = \"\"\"{
"Foo": {
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of the collection."
},
"kind": {
"type": "string",
"description": "Type of the collection ('calendar#acl').",
"default": "calendar#acl"
},
"nextPageToken": {
"type": "string",
"description": "Token used to access the next
page of this result. Omitted if no further results are available."
}
}
}
}\"\"\"
s = Schemas(schema)
print s.prettyPrintByName('Foo')
Produces the following output:
{
"nextPageToken": "A String", # Token used to access the
# next page of this result. Omitted if no further results are available.
"kind": "A String", # Type of the collection ('calendar#acl').
"etag": "A String", # ETag of the collection.
},
The constructor takes a discovery document in which to look up named schema.
"""
# TODO(jcgregorio) support format, enum, minimum, maximum
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import copy
from oauth2client.anyjson import simplejson
class Schemas(object):
"""Schemas for an API."""
def __init__(self, discovery):
"""Constructor.
Args:
discovery: object, Deserialized discovery document from which we pull
out the named schema.
"""
self.schemas = discovery.get('schemas', {})
# Cache of pretty printed schemas.
self.pretty = {}
def _prettyPrintByName(self, name, seen=None, dent=0):
"""Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
if seen is None:
seen = []
if name in seen:
# Do not fall into an infinite loop over recursive definitions.
return '# Object with schema name: %s' % name
seen.append(name)
if name not in self.pretty:
self.pretty[name] = _SchemaToStruct(self.schemas[name],
seen, dent).to_str(self._prettyPrintByName)
seen.pop()
return self.pretty[name]
def prettyPrintByName(self, name):
"""Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
# Return with trailing comma and newline removed.
return self._prettyPrintByName(name, seen=[], dent=1)[:-2]
def _prettyPrintSchema(self, schema, seen=None, dent=0):
"""Get pretty printed object prototype of schema.
Args:
schema: object, Parsed JSON schema.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
if seen is None:
seen = []
return _SchemaToStruct(schema, seen, dent).to_str(self._prettyPrintByName)
def prettyPrintSchema(self, schema):
"""Get pretty printed object prototype of schema.
Args:
schema: object, Parsed JSON schema.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
# Return with trailing comma and newline removed.
return self._prettyPrintSchema(schema, dent=1)[:-2]
def get(self, name):
"""Get deserialized JSON schema from the schema name.
Args:
name: string, Schema name.
"""
return self.schemas[name]
class _SchemaToStruct(object):
"""Convert schema to a prototype object."""
def __init__(self, schema, seen, dent=0):
"""Constructor.
Args:
schema: object, Parsed JSON schema.
seen: list, List of names of schema already seen while parsing. Used to
handle recursive definitions.
dent: int, Initial indentation depth.
"""
# The result of this parsing kept as list of strings.
self.value = []
# The final value of the parsing.
self.string = None
# The parsed JSON schema.
self.schema = schema
# Indentation level.
self.dent = dent
# Method that when called returns a prototype object for the schema with
# the given name.
self.from_cache = None
# List of names of schema already seen while parsing.
self.seen = seen
def emit(self, text):
"""Add text as a line to the output.
Args:
text: string, Text to output.
"""
self.value.extend([" " * self.dent, text, '\n'])
def emitBegin(self, text):
"""Add text to the output, but with no line terminator.
Args:
text: string, Text to output.
"""
self.value.extend([" " * self.dent, text])
def emitEnd(self, text, comment):
"""Add text and comment to the output with line terminator.
Args:
text: string, Text to output.
comment: string, Python comment.
"""
if comment:
divider = '\n' + ' ' * (self.dent + 2) + '# '
lines = comment.splitlines()
lines = [x.rstrip() for x in lines]
comment = divider.join(lines)
self.value.extend([text, ' # ', comment, '\n'])
else:
self.value.extend([text, '\n'])
def indent(self):
"""Increase indentation level."""
self.dent += 1
def undent(self):
"""Decrease indentation level."""
self.dent -= 1
def _to_str_impl(self, schema):
"""Prototype object based on the schema, in Python code with comments.
Args:
schema: object, Parsed JSON schema file.
Returns:
Prototype object based on the schema, in Python code with comments.
"""
stype = schema.get('type')
if stype == 'object':
self.emitEnd('{', schema.get('description', ''))
self.indent()
for pname, pschema in schema.get('properties', {}).iteritems():
self.emitBegin('"%s": ' % pname)
self._to_str_impl(pschema)
self.undent()
self.emit('},')
elif '$ref' in schema:
schemaName = schema['$ref']
description = schema.get('description', '')
s = self.from_cache(schemaName, self.seen)
parts = s.splitlines()
self.emitEnd(parts[0], description)
for line in parts[1:]:
self.emit(line.rstrip())
elif stype == 'boolean':
value = schema.get('default', 'True or False')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'string':
value = schema.get('default', 'A String')
self.emitEnd('"%s",' % str(value), schema.get('description', ''))
elif stype == 'integer':
value = schema.get('default', '42')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'number':
value = schema.get('default', '3.14')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'null':
self.emitEnd('None,', schema.get('description', ''))
elif stype == 'any':
self.emitEnd('"",', schema.get('description', ''))
elif stype == 'array':
self.emitEnd('[', schema.get('description'))
self.indent()
self.emitBegin('')
self._to_str_impl(schema['items'])
self.undent()
self.emit('],')
else:
self.emit('Unknown type! %s' % stype)
self.emitEnd('', '')
self.string = ''.join(self.value)
return self.string
def to_str(self, from_cache):
"""Prototype object based on the schema, in Python code with comments.
Args:
from_cache: callable(name, seen), Callable that retrieves an object
prototype for a schema with the given name. Seen is a list of schema
names already seen as we recursively descend the schema definition.
Returns:
Prototype object based on the schema, in Python code with comments.
The lines of the code will all be properly indented.
"""
self.from_cache = from_cache
return self._to_str_impl(self.schema)
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility module to import a JSON module
Hides all the messy details of exactly where
we get a simplejson module from.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
try: # pragma: no cover
import simplejson
except ImportError: # pragma: no cover
try:
# Try to import from django, should work on App Engine
from django.utils import simplejson
except ImportError:
# Should work for Python2.6 and higher.
import json as simplejson
| Python |
# Early, and incomplete implementation of -04.
#
import re
import urllib
RESERVED = ":/?#[]@!$&'()*+,;="
OPERATOR = "+./;?|!@"
EXPLODE = "*+"
MODIFIER = ":^"
TEMPLATE = re.compile(r"{(?P<operator>[\+\./;\?|!@])?(?P<varlist>[^}]+)}", re.UNICODE)
VAR = re.compile(r"^(?P<varname>[^=\+\*:\^]+)((?P<explode>[\+\*])|(?P<partial>[:\^]-?[0-9]+))?(=(?P<default>.*))?$", re.UNICODE)
def _tostring(varname, value, explode, operator, safe=""):
if type(value) == type([]):
if explode == "+":
return ",".join([varname + "." + urllib.quote(x, safe) for x in value])
else:
return ",".join([urllib.quote(x, safe) for x in value])
if type(value) == type({}):
keys = value.keys()
keys.sort()
if explode == "+":
return ",".join([varname + "." + urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
return urllib.quote(value, safe)
def _tostring_path(varname, value, explode, operator, safe=""):
joiner = operator
if type(value) == type([]):
if explode == "+":
return joiner.join([varname + "." + urllib.quote(x, safe) for x in value])
elif explode == "*":
return joiner.join([urllib.quote(x, safe) for x in value])
else:
return ",".join([urllib.quote(x, safe) for x in value])
elif type(value) == type({}):
keys = value.keys()
keys.sort()
if explode == "+":
return joiner.join([varname + "." + urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys])
elif explode == "*":
return joiner.join([urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys])
else:
return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
if value:
return urllib.quote(value, safe)
else:
return ""
def _tostring_query(varname, value, explode, operator, safe=""):
joiner = operator
varprefix = ""
if operator == "?":
joiner = "&"
varprefix = varname + "="
if type(value) == type([]):
if 0 == len(value):
return ""
if explode == "+":
return joiner.join([varname + "=" + urllib.quote(x, safe) for x in value])
elif explode == "*":
return joiner.join([urllib.quote(x, safe) for x in value])
else:
return varprefix + ",".join([urllib.quote(x, safe) for x in value])
elif type(value) == type({}):
if 0 == len(value):
return ""
keys = value.keys()
keys.sort()
if explode == "+":
return joiner.join([varname + "." + urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys])
elif explode == "*":
return joiner.join([urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys])
else:
return varprefix + ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
if value:
return varname + "=" + urllib.quote(value, safe)
else:
return varname
TOSTRING = {
"" : _tostring,
"+": _tostring,
";": _tostring_query,
"?": _tostring_query,
"/": _tostring_path,
".": _tostring_path,
}
def expand(template, vars):
def _sub(match):
groupdict = match.groupdict()
operator = groupdict.get('operator')
if operator is None:
operator = ''
varlist = groupdict.get('varlist')
safe = "@"
if operator == '+':
safe = RESERVED
varspecs = varlist.split(",")
varnames = []
defaults = {}
for varspec in varspecs:
m = VAR.search(varspec)
groupdict = m.groupdict()
varname = groupdict.get('varname')
explode = groupdict.get('explode')
partial = groupdict.get('partial')
default = groupdict.get('default')
if default:
defaults[varname] = default
varnames.append((varname, explode, partial))
retval = []
joiner = operator
prefix = operator
if operator == "+":
prefix = ""
joiner = ","
if operator == "?":
joiner = "&"
if operator == "":
joiner = ","
for varname, explode, partial in varnames:
if varname in vars:
value = vars[varname]
#if not value and (type(value) == type({}) or type(value) == type([])) and varname in defaults:
if not value and value != "" and varname in defaults:
value = defaults[varname]
elif varname in defaults:
value = defaults[varname]
else:
continue
retval.append(TOSTRING[operator](varname, value, explode, operator, safe=safe))
if "".join(retval):
return prefix + joiner.join(retval)
else:
return ""
return TEMPLATE.sub(_sub, template)
| Python |
#!/usr/bin/env python
# Copyright (c) 2010, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Module to enforce different constraints on flags.
A validator represents an invariant, enforced over a one or more flags.
See 'FLAGS VALIDATORS' in gflags.py's docstring for a usage manual.
"""
__author__ = 'olexiy@google.com (Olexiy Oryeshko)'
class Error(Exception):
"""Thrown If validator constraint is not satisfied."""
class Validator(object):
"""Base class for flags validators.
Users should NOT overload these classes, and use gflags.Register...
methods instead.
"""
# Used to assign each validator an unique insertion_index
validators_count = 0
def __init__(self, checker, message):
"""Constructor to create all validators.
Args:
checker: function to verify the constraint.
Input of this method varies, see SimpleValidator and
DictionaryValidator for a detailed description.
message: string, error message to be shown to the user
"""
self.checker = checker
self.message = message
Validator.validators_count += 1
# Used to assert validators in the order they were registered (CL/18694236)
self.insertion_index = Validator.validators_count
def Verify(self, flag_values):
"""Verify that constraint is satisfied.
flags library calls this method to verify Validator's constraint.
Args:
flag_values: gflags.FlagValues, containing all flags
Raises:
Error: if constraint is not satisfied.
"""
param = self._GetInputToCheckerFunction(flag_values)
if not self.checker(param):
raise Error(self.message)
def GetFlagsNames(self):
"""Return the names of the flags checked by this validator.
Returns:
[string], names of the flags
"""
raise NotImplementedError('This method should be overloaded')
def PrintFlagsWithValues(self, flag_values):
raise NotImplementedError('This method should be overloaded')
def _GetInputToCheckerFunction(self, flag_values):
"""Given flag values, construct the input to be given to checker.
Args:
flag_values: gflags.FlagValues, containing all flags.
Returns:
Return type depends on the specific validator.
"""
raise NotImplementedError('This method should be overloaded')
class SimpleValidator(Validator):
"""Validator behind RegisterValidator() method.
Validates that a single flag passes its checker function. The checker function
takes the flag value and returns True (if value looks fine) or, if flag value
is not valid, either returns False or raises an Exception."""
def __init__(self, flag_name, checker, message):
"""Constructor.
Args:
flag_name: string, name of the flag.
checker: function to verify the validator.
input - value of the corresponding flag (string, boolean, etc).
output - Boolean. Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise Error.
message: string, error message to be shown to the user if validator's
condition is not satisfied
"""
super(SimpleValidator, self).__init__(checker, message)
self.flag_name = flag_name
def GetFlagsNames(self):
return [self.flag_name]
def PrintFlagsWithValues(self, flag_values):
return 'flag --%s=%s' % (self.flag_name, flag_values[self.flag_name].value)
def _GetInputToCheckerFunction(self, flag_values):
"""Given flag values, construct the input to be given to checker.
Args:
flag_values: gflags.FlagValues
Returns:
value of the corresponding flag.
"""
return flag_values[self.flag_name].value
class DictionaryValidator(Validator):
"""Validator behind RegisterDictionaryValidator method.
Validates that flag values pass their common checker function. The checker
function takes flag values and returns True (if values look fine) or,
if values are not valid, either returns False or raises an Exception.
"""
def __init__(self, flag_names, checker, message):
"""Constructor.
Args:
flag_names: [string], containing names of the flags used by checker.
checker: function to verify the validator.
input - dictionary, with keys() being flag_names, and value for each
key being the value of the corresponding flag (string, boolean, etc).
output - Boolean. Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise Error.
message: string, error message to be shown to the user if validator's
condition is not satisfied
"""
super(DictionaryValidator, self).__init__(checker, message)
self.flag_names = flag_names
def _GetInputToCheckerFunction(self, flag_values):
"""Given flag values, construct the input to be given to checker.
Args:
flag_values: gflags.FlagValues
Returns:
dictionary, with keys() being self.lag_names, and value for each key
being the value of the corresponding flag (string, boolean, etc).
"""
return dict([key, flag_values[key].value] for key in self.flag_names)
def PrintFlagsWithValues(self, flag_values):
prefix = 'flags '
flags_with_values = []
for key in self.flag_names:
flags_with_values.append('%s=%s' % (key, flag_values[key].value))
return prefix + ', '.join(flags_with_values)
def GetFlagsNames(self):
return self.flag_names
| Python |
"""SocksiPy - Python SOCKS module.
Version 1.00
Copyright 2006 Dan-Haim. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of Dan Haim nor the names of his contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE.
This module provides a standard socket-like interface for Python
for tunneling connections through SOCKS proxies.
"""
"""
Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
for use in PyLoris (http://pyloris.sourceforge.net/)
Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
mainly to merge bug fixes found in Sourceforge
"""
import base64
import socket
import struct
import sys
if getattr(socket, 'socket', None) is None:
raise ImportError('socket.socket missing, proxy support unusable')
PROXY_TYPE_SOCKS4 = 1
PROXY_TYPE_SOCKS5 = 2
PROXY_TYPE_HTTP = 3
PROXY_TYPE_HTTP_NO_TUNNEL = 4
_defaultproxy = None
_orgsocket = socket.socket
class ProxyError(Exception): pass
class GeneralProxyError(ProxyError): pass
class Socks5AuthError(ProxyError): pass
class Socks5Error(ProxyError): pass
class Socks4Error(ProxyError): pass
class HTTPError(ProxyError): pass
_generalerrors = ("success",
"invalid data",
"not connected",
"not available",
"bad proxy type",
"bad input")
_socks5errors = ("succeeded",
"general SOCKS server failure",
"connection not allowed by ruleset",
"Network unreachable",
"Host unreachable",
"Connection refused",
"TTL expired",
"Command not supported",
"Address type not supported",
"Unknown error")
_socks5autherrors = ("succeeded",
"authentication is required",
"all offered authentication methods were rejected",
"unknown username or invalid password",
"unknown error")
_socks4errors = ("request granted",
"request rejected or failed",
"request rejected because SOCKS server cannot connect to identd on the client",
"request rejected because the client program and identd report different user-ids",
"unknown error")
def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
"""setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets a default proxy which all further socksocket objects will use,
unless explicitly changed.
"""
global _defaultproxy
_defaultproxy = (proxytype, addr, port, rdns, username, password)
def wrapmodule(module):
"""wrapmodule(module)
Attempts to replace a module's socket library with a SOCKS socket. Must set
a default proxy using setdefaultproxy(...) first.
This will only work on modules that import socket directly into the namespace;
most of the Python Standard Library falls into this category.
"""
if _defaultproxy != None:
module.socket.socket = socksocket
else:
raise GeneralProxyError((4, "no proxy specified"))
class socksocket(socket.socket):
"""socksocket([family[, type[, proto]]]) -> socket object
Open a SOCKS enabled socket. The parameters are the same as
those of the standard socket init. In order for SOCKS to work,
you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
"""
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
_orgsocket.__init__(self, family, type, proto, _sock)
if _defaultproxy != None:
self.__proxy = _defaultproxy
else:
self.__proxy = (None, None, None, None, None, None)
self.__proxysockname = None
self.__proxypeername = None
self.__httptunnel = True
def __recvall(self, count):
"""__recvall(count) -> data
Receive EXACTLY the number of bytes requested from the socket.
Blocks until the required number of bytes have been received.
"""
data = self.recv(count)
while len(data) < count:
d = self.recv(count-len(data))
if not d: raise GeneralProxyError((0, "connection closed unexpectedly"))
data = data + d
return data
def sendall(self, content, *args):
""" override socket.socket.sendall method to rewrite the header
for non-tunneling proxies if needed
"""
if not self.__httptunnel:
content = self.__rewriteproxy(content)
return super(socksocket, self).sendall(content, *args)
def __rewriteproxy(self, header):
""" rewrite HTTP request headers to support non-tunneling proxies
(i.e. those which do not support the CONNECT method).
This only works for HTTP (not HTTPS) since HTTPS requires tunneling.
"""
host, endpt = None, None
hdrs = header.split("\r\n")
for hdr in hdrs:
if hdr.lower().startswith("host:"):
host = hdr
elif hdr.lower().startswith("get") or hdr.lower().startswith("post"):
endpt = hdr
if host and endpt:
hdrs.remove(host)
hdrs.remove(endpt)
host = host.split(" ")[1]
endpt = endpt.split(" ")
if (self.__proxy[4] != None and self.__proxy[5] != None):
hdrs.insert(0, self.__getauthheader())
hdrs.insert(0, "Host: %s" % host)
hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2]))
return "\r\n".join(hdrs)
def __getauthheader(self):
auth = self.__proxy[4] + ":" + self.__proxy[5]
return "Proxy-Authorization: Basic " + base64.b64encode(auth)
def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
"""setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxytype - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
addr - The address of the server (IP or DNS).
port - The port of the server. Defaults to 1080 for SOCKS
servers and 8080 for HTTP proxy servers.
rdns - Should DNS queries be preformed on the remote side
(rather than the local side). The default is True.
Note: This has no effect with SOCKS4 servers.
username - Username to authenticate with to the server.
The default is no authentication.
password - Password to authenticate with to the server.
Only relevant when username is also provided.
"""
self.__proxy = (proxytype, addr, port, rdns, username, password)
def __negotiatesocks5(self, destaddr, destport):
"""__negotiatesocks5(self,destaddr,destport)
Negotiates a connection through a SOCKS5 server.
"""
# First we'll send the authentication packages we support.
if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
# The username/password details were supplied to the
# setproxy method so we support the USERNAME/PASSWORD
# authentication (in addition to the standard none).
self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02))
else:
# No username/password were entered, therefore we
# only support connections with no authentication.
self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00))
# We'll receive the server's response to determine which
# method was selected
chosenauth = self.__recvall(2)
if chosenauth[0:1] != chr(0x05).encode():
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
# Check the chosen authentication method
if chosenauth[1:2] == chr(0x00).encode():
# No authentication is required
pass
elif chosenauth[1:2] == chr(0x02).encode():
# Okay, we need to perform a basic username/password
# authentication.
self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5])
authstat = self.__recvall(2)
if authstat[0:1] != chr(0x01).encode():
# Bad response
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if authstat[1:2] != chr(0x00).encode():
# Authentication failed
self.close()
raise Socks5AuthError((3, _socks5autherrors[3]))
# Authentication succeeded
else:
# Reaching here is always bad
self.close()
if chosenauth[1] == chr(0xFF).encode():
raise Socks5AuthError((2, _socks5autherrors[2]))
else:
raise GeneralProxyError((1, _generalerrors[1]))
# Now we can request the actual connection
req = struct.pack('BBB', 0x05, 0x01, 0x00)
# If the given destination address is an IP address, we'll
# use the IPv4 address request even if remote resolving was specified.
try:
ipaddr = socket.inet_aton(destaddr)
req = req + chr(0x01).encode() + ipaddr
except socket.error:
# Well it's not an IP number, so it's probably a DNS name.
if self.__proxy[3]:
# Resolve remotely
ipaddr = None
req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr
else:
# Resolve locally
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
req = req + chr(0x01).encode() + ipaddr
req = req + struct.pack(">H", destport)
self.sendall(req)
# Get the response
resp = self.__recvall(4)
if resp[0:1] != chr(0x05).encode():
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
elif resp[1:2] != chr(0x00).encode():
# Connection failed
self.close()
if ord(resp[1:2])<=8:
raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])]))
else:
raise Socks5Error((9, _socks5errors[9]))
# Get the bound address/port
elif resp[3:4] == chr(0x01).encode():
boundaddr = self.__recvall(4)
elif resp[3:4] == chr(0x03).encode():
resp = resp + self.recv(1)
boundaddr = self.__recvall(ord(resp[4:5]))
else:
self.close()
raise GeneralProxyError((1,_generalerrors[1]))
boundport = struct.unpack(">H", self.__recvall(2))[0]
self.__proxysockname = (boundaddr, boundport)
if ipaddr != None:
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
else:
self.__proxypeername = (destaddr, destport)
def getproxysockname(self):
"""getsockname() -> address info
Returns the bound IP address and port number at the proxy.
"""
return self.__proxysockname
def getproxypeername(self):
"""getproxypeername() -> address info
Returns the IP and port number of the proxy.
"""
return _orgsocket.getpeername(self)
def getpeername(self):
"""getpeername() -> address info
Returns the IP address and port number of the destination
machine (note: getproxypeername returns the proxy)
"""
return self.__proxypeername
def __negotiatesocks4(self,destaddr,destport):
"""__negotiatesocks4(self,destaddr,destport)
Negotiates a connection through a SOCKS4 server.
"""
# Check if the destination address provided is an IP address
rmtrslv = False
try:
ipaddr = socket.inet_aton(destaddr)
except socket.error:
# It's a DNS name. Check where it should be resolved.
if self.__proxy[3]:
ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01)
rmtrslv = True
else:
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
# Construct the request packet
req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr
# The username parameter is considered userid for SOCKS4
if self.__proxy[4] != None:
req = req + self.__proxy[4]
req = req + chr(0x00).encode()
# DNS name if remote resolving is required
# NOTE: This is actually an extension to the SOCKS4 protocol
# called SOCKS4A and may not be supported in all cases.
if rmtrslv:
req = req + destaddr + chr(0x00).encode()
self.sendall(req)
# Get the response from the server
resp = self.__recvall(8)
if resp[0:1] != chr(0x00).encode():
# Bad data
self.close()
raise GeneralProxyError((1,_generalerrors[1]))
if resp[1:2] != chr(0x5A).encode():
# Server returned an error
self.close()
if ord(resp[1:2]) in (91, 92, 93):
self.close()
raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90]))
else:
raise Socks4Error((94, _socks4errors[4]))
# Get the bound address/port
self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0])
if rmtrslv != None:
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
else:
self.__proxypeername = (destaddr, destport)
def __negotiatehttp(self, destaddr, destport):
"""__negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server.
"""
# If we need to resolve locally, we do this now
if not self.__proxy[3]:
addr = socket.gethostbyname(destaddr)
else:
addr = destaddr
headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"]
headers += ["Host: ", destaddr, "\r\n"]
if (self.__proxy[4] != None and self.__proxy[5] != None):
headers += [self.__getauthheader(), "\r\n"]
headers.append("\r\n")
self.sendall("".join(headers).encode())
# We read the response until we get the string "\r\n\r\n"
resp = self.recv(1)
while resp.find("\r\n\r\n".encode()) == -1:
resp = resp + self.recv(1)
# We just need the first line to check if the connection
# was successful
statusline = resp.splitlines()[0].split(" ".encode(), 2)
if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()):
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
try:
statuscode = int(statusline[1])
except ValueError:
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if statuscode != 200:
self.close()
raise HTTPError((statuscode, statusline[2]))
self.__proxysockname = ("0.0.0.0", 0)
self.__proxypeername = (addr, destport)
def connect(self, destpair):
"""connect(self, despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket's connect).
To select the proxy server use setproxy().
"""
# Do a minimal input check first
if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int):
raise GeneralProxyError((5, _generalerrors[5]))
if self.__proxy[0] == PROXY_TYPE_SOCKS5:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 1080
_orgsocket.connect(self, (self.__proxy[1], portnum))
self.__negotiatesocks5(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 1080
_orgsocket.connect(self,(self.__proxy[1], portnum))
self.__negotiatesocks4(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_HTTP:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 8080
_orgsocket.connect(self,(self.__proxy[1], portnum))
self.__negotiatehttp(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 8080
_orgsocket.connect(self,(self.__proxy[1],portnum))
if destpair[1] == 443:
self.__negotiatehttp(destpair[0],destpair[1])
else:
self.__httptunnel = False
elif self.__proxy[0] == None:
_orgsocket.connect(self, (destpair[0], destpair[1]))
else:
raise GeneralProxyError((4, _generalerrors[4]))
| Python |
"""
iri2uri
Converts an IRI to a URI.
"""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = []
__version__ = "1.0.0"
__license__ = "MIT"
__history__ = """
"""
import urlparse
# Convert an IRI to a URI following the rules in RFC 3987
#
# The characters we need to enocde and escape are defined in the spec:
#
# iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD
# ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
# / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
# / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
# / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
# / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
# / %xD0000-DFFFD / %xE1000-EFFFD
escape_range = [
(0xA0, 0xD7FF ),
(0xE000, 0xF8FF ),
(0xF900, 0xFDCF ),
(0xFDF0, 0xFFEF),
(0x10000, 0x1FFFD ),
(0x20000, 0x2FFFD ),
(0x30000, 0x3FFFD),
(0x40000, 0x4FFFD ),
(0x50000, 0x5FFFD ),
(0x60000, 0x6FFFD),
(0x70000, 0x7FFFD ),
(0x80000, 0x8FFFD ),
(0x90000, 0x9FFFD),
(0xA0000, 0xAFFFD ),
(0xB0000, 0xBFFFD ),
(0xC0000, 0xCFFFD),
(0xD0000, 0xDFFFD ),
(0xE1000, 0xEFFFD),
(0xF0000, 0xFFFFD ),
(0x100000, 0x10FFFD)
]
def encode(c):
retval = c
i = ord(c)
for low, high in escape_range:
if i < low:
break
if i >= low and i <= high:
retval = "".join(["%%%2X" % ord(o) for o in c.encode('utf-8')])
break
return retval
def iri2uri(uri):
"""Convert an IRI to a URI. Note that IRIs must be
passed in a unicode strings. That is, do not utf-8 encode
the IRI before passing it into the function."""
if isinstance(uri ,unicode):
(scheme, authority, path, query, fragment) = urlparse.urlsplit(uri)
authority = authority.encode('idna')
# For each character in 'ucschar' or 'iprivate'
# 1. encode as utf-8
# 2. then %-encode each octet of that utf-8
uri = urlparse.urlunsplit((scheme, authority, path, query, fragment))
uri = "".join([encode(c) for c in uri])
return uri
if __name__ == "__main__":
import unittest
class Test(unittest.TestCase):
def test_uris(self):
"""Test that URIs are invariant under the transformation."""
invariant = [
u"ftp://ftp.is.co.za/rfc/rfc1808.txt",
u"http://www.ietf.org/rfc/rfc2396.txt",
u"ldap://[2001:db8::7]/c=GB?objectClass?one",
u"mailto:John.Doe@example.com",
u"news:comp.infosystems.www.servers.unix",
u"tel:+1-816-555-1212",
u"telnet://192.0.2.16:80/",
u"urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ]
for uri in invariant:
self.assertEqual(uri, iri2uri(uri))
def test_iri(self):
""" Test that the right type of escaping is done for each part of the URI."""
self.assertEqual("http://xn--o3h.com/%E2%98%84", iri2uri(u"http://\N{COMET}.com/\N{COMET}"))
self.assertEqual("http://bitworking.org/?fred=%E2%98%84", iri2uri(u"http://bitworking.org/?fred=\N{COMET}"))
self.assertEqual("http://bitworking.org/#%E2%98%84", iri2uri(u"http://bitworking.org/#\N{COMET}"))
self.assertEqual("#%E2%98%84", iri2uri(u"#\N{COMET}"))
self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"))
self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")))
self.assertNotEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode('utf-8')))
unittest.main()
| Python |
from __future__ import generators
"""
httplib2
A caching http interface that supports ETags and gzip
to conserve bandwidth.
Requires Python 2.3 or later
Changelog:
2007-08-18, Rick: Modified so it's able to use a socks proxy if needed.
"""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = ["Thomas Broyer (t.broyer@ltgt.net)",
"James Antill",
"Xavier Verges Farrero",
"Jonathan Feinberg",
"Blair Zajac",
"Sam Ruby",
"Louis Nyffenegger"]
__license__ = "MIT"
__version__ = "0.7.2"
import re
import sys
import email
import email.Utils
import email.Message
import email.FeedParser
import StringIO
import gzip
import zlib
import httplib
import urlparse
import base64
import os
import copy
import calendar
import time
import random
import errno
# remove depracated warning in python2.6
try:
from hashlib import sha1 as _sha, md5 as _md5
except ImportError:
import sha
import md5
_sha = sha.new
_md5 = md5.new
import hmac
from gettext import gettext as _
import socket
try:
from httplib2 import socks
except ImportError:
socks = None
# Build the appropriate socket wrapper for ssl
try:
import ssl # python 2.6
ssl_SSLError = ssl.SSLError
def _ssl_wrap_socket(sock, key_file, cert_file,
disable_validation, ca_certs):
if disable_validation:
cert_reqs = ssl.CERT_NONE
else:
cert_reqs = ssl.CERT_REQUIRED
# We should be specifying SSL version 3 or TLS v1, but the ssl module
# doesn't expose the necessary knobs. So we need to go with the default
# of SSLv23.
return ssl.wrap_socket(sock, keyfile=key_file, certfile=cert_file,
cert_reqs=cert_reqs, ca_certs=ca_certs)
except (AttributeError, ImportError):
ssl_SSLError = None
def _ssl_wrap_socket(sock, key_file, cert_file,
disable_validation, ca_certs):
if not disable_validation:
raise CertificateValidationUnsupported(
"SSL certificate validation is not supported without "
"the ssl module installed. To avoid this error, install "
"the ssl module, or explicity disable validation.")
ssl_sock = socket.ssl(sock, key_file, cert_file)
return httplib.FakeSocket(sock, ssl_sock)
if sys.version_info >= (2,3):
from iri2uri import iri2uri
else:
def iri2uri(uri):
return uri
def has_timeout(timeout): # python 2.6
if hasattr(socket, '_GLOBAL_DEFAULT_TIMEOUT'):
return (timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT)
return (timeout is not None)
__all__ = ['Http', 'Response', 'ProxyInfo', 'HttpLib2Error',
'RedirectMissingLocation', 'RedirectLimit', 'FailedToDecompressContent',
'UnimplementedDigestAuthOptionError', 'UnimplementedHmacDigestAuthOptionError',
'debuglevel', 'ProxiesUnavailableError']
# The httplib debug level, set to a non-zero value to get debug output
debuglevel = 0
# Python 2.3 support
if sys.version_info < (2,4):
def sorted(seq):
seq.sort()
return seq
# Python 2.3 support
def HTTPResponse__getheaders(self):
"""Return list of (header, value) tuples."""
if self.msg is None:
raise httplib.ResponseNotReady()
return self.msg.items()
if not hasattr(httplib.HTTPResponse, 'getheaders'):
httplib.HTTPResponse.getheaders = HTTPResponse__getheaders
# All exceptions raised here derive from HttpLib2Error
class HttpLib2Error(Exception): pass
# Some exceptions can be caught and optionally
# be turned back into responses.
class HttpLib2ErrorWithResponse(HttpLib2Error):
def __init__(self, desc, response, content):
self.response = response
self.content = content
HttpLib2Error.__init__(self, desc)
class RedirectMissingLocation(HttpLib2ErrorWithResponse): pass
class RedirectLimit(HttpLib2ErrorWithResponse): pass
class FailedToDecompressContent(HttpLib2ErrorWithResponse): pass
class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse): pass
class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse): pass
class MalformedHeader(HttpLib2Error): pass
class RelativeURIError(HttpLib2Error): pass
class ServerNotFoundError(HttpLib2Error): pass
class ProxiesUnavailableError(HttpLib2Error): pass
class CertificateValidationUnsupported(HttpLib2Error): pass
class SSLHandshakeError(HttpLib2Error): pass
class NotSupportedOnThisPlatform(HttpLib2Error): pass
class CertificateHostnameMismatch(SSLHandshakeError):
def __init__(self, desc, host, cert):
HttpLib2Error.__init__(self, desc)
self.host = host
self.cert = cert
# Open Items:
# -----------
# Proxy support
# Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
# Pluggable cache storage (supports storing the cache in
# flat files by default. We need a plug-in architecture
# that can support Berkeley DB and Squid)
# == Known Issues ==
# Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
# Does not handle Cache-Control: max-stale
# Does not use Age: headers when calculating cache freshness.
# The number of redirections to follow before giving up.
# Note that only GET redirects are automatically followed.
# Will also honor 301 requests by saving that info and never
# requesting that URI again.
DEFAULT_MAX_REDIRECTS = 5
# Default CA certificates file bundled with httplib2.
CA_CERTS = os.path.join(
os.path.dirname(os.path.abspath(__file__ )), "cacerts.txt")
# Which headers are hop-by-hop headers by default
HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade']
def _get_end2end_headers(response):
hopbyhop = list(HOP_BY_HOP)
hopbyhop.extend([x.strip() for x in response.get('connection', '').split(',')])
return [header for header in response.keys() if header not in hopbyhop]
URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
def parse_uri(uri):
"""Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
"""
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8])
def urlnorm(uri):
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
authority = authority.lower()
scheme = scheme.lower()
if not path:
path = "/"
# Could do syntax based normalization of the URI before
# computing the digest. See Section 6.2.2 of Std 66.
request_uri = query and "?".join([path, query]) or path
scheme = scheme.lower()
defrag_uri = scheme + "://" + authority + request_uri
return scheme, authority, request_uri, defrag_uri
# Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
re_url_scheme = re.compile(r'^\w+://')
re_slash = re.compile(r'[?/:|]+')
def safename(filename):
"""Return a filename suitable for the cache.
Strips dangerous and common characters to create a filename we
can use to store the cache in.
"""
try:
if re_url_scheme.match(filename):
if isinstance(filename,str):
filename = filename.decode('utf-8')
filename = filename.encode('idna')
else:
filename = filename.encode('idna')
except UnicodeError:
pass
if isinstance(filename,unicode):
filename=filename.encode('utf-8')
filemd5 = _md5(filename).hexdigest()
filename = re_url_scheme.sub("", filename)
filename = re_slash.sub(",", filename)
# limit length of filename
if len(filename)>200:
filename=filename[:200]
return ",".join((filename, filemd5))
NORMALIZE_SPACE = re.compile(r'(?:\r\n)?[ \t]+')
def _normalize_headers(headers):
return dict([ (key.lower(), NORMALIZE_SPACE.sub(value, ' ').strip()) for (key, value) in headers.iteritems()])
def _parse_cache_control(headers):
retval = {}
if headers.has_key('cache-control'):
parts = headers['cache-control'].split(',')
parts_with_args = [tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=")]
parts_wo_args = [(name.strip().lower(), 1) for name in parts if -1 == name.find("=")]
retval = dict(parts_with_args + parts_wo_args)
return retval
# Whether to use a strict mode to parse WWW-Authenticate headers
# Might lead to bad results in case of ill-formed header value,
# so disabled by default, falling back to relaxed parsing.
# Set to true to turn on, usefull for testing servers.
USE_WWW_AUTH_STRICT_PARSING = 0
# In regex below:
# [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
# "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space
# Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both:
# \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?
WWW_AUTH_STRICT = re.compile(r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$")
WWW_AUTH_RELAXED = re.compile(r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$")
UNQUOTE_PAIRS = re.compile(r'\\(.)')
def _parse_www_authenticate(headers, headername='www-authenticate'):
"""Returns a dictionary of dictionaries, one dict
per auth_scheme."""
retval = {}
if headers.has_key(headername):
try:
authenticate = headers[headername].strip()
www_auth = USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
while authenticate:
# Break off the scheme at the beginning of the line
if headername == 'authentication-info':
(auth_scheme, the_rest) = ('digest', authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(" ", 1)
# Now loop over all the key value pairs that come after the scheme,
# being careful not to roll into the next scheme
match = www_auth.search(the_rest)
auth_params = {}
while match:
if match and len(match.groups()) == 3:
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub(r'\1', value) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader("WWW-Authenticate")
return retval
def _entry_disposition(response_headers, request_headers):
"""Determine freshness from the Date, Expires and Cache-Control headers.
We don't handle the following:
1. Cache-Control: max-stale
2. Age: headers are not used in the calculations.
Not that this algorithm is simpler than you might think
because we are operating as a private (non-shared) cache.
This lets us ignore 's-maxage'. We can also ignore
'proxy-invalidate' since we aren't a proxy.
We will never return a stale document as
fresh as a design decision, and thus the non-implementation
of 'max-stale'. This also lets us safely ignore 'must-revalidate'
since we operate as if every server has sent 'must-revalidate'.
Since we are private we get to ignore both 'public' and
'private' parameters. We also ignore 'no-transform' since
we don't do any transformations.
The 'no-store' parameter is handled at a higher level.
So the only Cache-Control parameters we look at are:
no-cache
only-if-cached
max-age
min-fresh
"""
retval = "STALE"
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if request_headers.has_key('pragma') and request_headers['pragma'].lower().find('no-cache') != -1:
retval = "TRANSPARENT"
if 'cache-control' not in request_headers:
request_headers['cache-control'] = 'no-cache'
elif cc.has_key('no-cache'):
retval = "TRANSPARENT"
elif cc_response.has_key('no-cache'):
retval = "STALE"
elif cc.has_key('only-if-cached'):
retval = "FRESH"
elif response_headers.has_key('date'):
date = calendar.timegm(email.Utils.parsedate_tz(response_headers['date']))
now = time.time()
current_age = max(0, now - date)
if cc_response.has_key('max-age'):
try:
freshness_lifetime = int(cc_response['max-age'])
except ValueError:
freshness_lifetime = 0
elif response_headers.has_key('expires'):
expires = email.Utils.parsedate_tz(response_headers['expires'])
if None == expires:
freshness_lifetime = 0
else:
freshness_lifetime = max(0, calendar.timegm(expires) - date)
else:
freshness_lifetime = 0
if cc.has_key('max-age'):
try:
freshness_lifetime = int(cc['max-age'])
except ValueError:
freshness_lifetime = 0
if cc.has_key('min-fresh'):
try:
min_fresh = int(cc['min-fresh'])
except ValueError:
min_fresh = 0
current_age += min_fresh
if freshness_lifetime > current_age:
retval = "FRESH"
return retval
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get('content-encoding', None)
if encoding in ['gzip', 'deflate']:
if encoding == 'gzip':
content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read()
if encoding == 'deflate':
content = zlib.decompress(content)
response['content-length'] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response['-content-encoding'] = response['content-encoding']
del response['content-encoding']
except IOError:
content = ""
raise FailedToDecompressContent(_("Content purported to be compressed with %s but failed to decompress.") % response.get('content-encoding'), response, content)
return content
def _updateCache(request_headers, response_headers, content, cache, cachekey):
if cachekey:
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if cc.has_key('no-store') or cc_response.has_key('no-store'):
cache.delete(cachekey)
else:
info = email.Message.Message()
for key, value in response_headers.iteritems():
if key not in ['status','content-encoding','transfer-encoding']:
info[key] = value
# Add annotations to the cache to indicate what headers
# are variant for this request.
vary = response_headers.get('vary', None)
if vary:
vary_headers = vary.lower().replace(' ', '').split(',')
for header in vary_headers:
key = '-varied-%s' % header
try:
info[key] = request_headers[header]
except KeyError:
pass
status = response_headers.status
if status == 304:
status = 200
status_header = 'status: %d\r\n' % status
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = "".join([status_header, header_str, content])
cache.set(cachekey, text)
def _cnonce():
dig = _md5("%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])).hexdigest()
return dig[:16]
def _wsse_username_token(cnonce, iso_now, password):
return base64.b64encode(_sha("%s%s%s" % (cnonce, iso_now, password)).digest()).strip()
# For credentials we need two things, first
# a pool of credential to try (not necesarily tied to BAsic, Digest, etc.)
# Then we also need a list of URIs that have already demanded authentication
# That list is tricky since sub-URIs can take the same auth, or the
# auth scheme may change as you descend the tree.
# So we also need each Auth instance to be able to tell us
# how close to the 'top' it is.
class Authentication(object):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
self.path = path
self.host = host
self.credentials = credentials
self.http = http
def depth(self, request_uri):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return request_uri[len(self.path):].count("/")
def inscope(self, host, request_uri):
# XXX Should we normalize the request_uri?
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return (host == self.host) and path.startswith(self.path)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header. Over-rise this in sub-classes."""
pass
def response(self, response, content):
"""Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary.
Return TRUE is the request is to be retried, for
example Digest may return stale=true.
"""
return False
class BasicAuthentication(Authentication):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'Basic ' + base64.b64encode("%s:%s" % self.credentials).strip()
class DigestAuthentication(Authentication):
"""Only do qop='auth' and MD5, since that
is all Apache currently implements"""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
self.challenge = challenge['digest']
qop = self.challenge.get('qop', 'auth')
self.challenge['qop'] = ('auth' in [x.strip() for x in qop.split()]) and 'auth' or None
if self.challenge['qop'] is None:
raise UnimplementedDigestAuthOptionError( _("Unsupported value for qop: %s." % qop))
self.challenge['algorithm'] = self.challenge.get('algorithm', 'MD5').upper()
if self.challenge['algorithm'] != 'MD5':
raise UnimplementedDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm']))
self.A1 = "".join([self.credentials[0], ":", self.challenge['realm'], ":", self.credentials[1]])
self.challenge['nc'] = 1
def request(self, method, request_uri, headers, content, cnonce = None):
"""Modify the request headers"""
H = lambda x: _md5(x).hexdigest()
KD = lambda s, d: H("%s:%s" % (s, d))
A2 = "".join([method, ":", request_uri])
self.challenge['cnonce'] = cnonce or _cnonce()
request_digest = '"%s"' % KD(H(self.A1), "%s:%s:%s:%s:%s" % (self.challenge['nonce'],
'%08x' % self.challenge['nc'],
self.challenge['cnonce'],
self.challenge['qop'], H(A2)
))
headers['authorization'] = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", algorithm=%s, response=%s, qop=%s, nc=%08x, cnonce="%s"' % (
self.credentials[0],
self.challenge['realm'],
self.challenge['nonce'],
request_uri,
self.challenge['algorithm'],
request_digest,
self.challenge['qop'],
self.challenge['nc'],
self.challenge['cnonce'],
)
if self.challenge.get('opaque'):
headers['authorization'] += ', opaque="%s"' % self.challenge['opaque']
self.challenge['nc'] += 1
def response(self, response, content):
if not response.has_key('authentication-info'):
challenge = _parse_www_authenticate(response, 'www-authenticate').get('digest', {})
if 'true' == challenge.get('stale'):
self.challenge['nonce'] = challenge['nonce']
self.challenge['nc'] = 1
return True
else:
updated_challenge = _parse_www_authenticate(response, 'authentication-info').get('digest', {})
if updated_challenge.has_key('nextnonce'):
self.challenge['nonce'] = updated_challenge['nextnonce']
self.challenge['nc'] = 1
return False
class HmacDigestAuthentication(Authentication):
"""Adapted from Robert Sayre's code and DigestAuthentication above."""
__author__ = "Thomas Broyer (t.broyer@ltgt.net)"
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
self.challenge = challenge['hmacdigest']
# TODO: self.challenge['domain']
self.challenge['reason'] = self.challenge.get('reason', 'unauthorized')
if self.challenge['reason'] not in ['unauthorized', 'integrity']:
self.challenge['reason'] = 'unauthorized'
self.challenge['salt'] = self.challenge.get('salt', '')
if not self.challenge.get('snonce'):
raise UnimplementedHmacDigestAuthOptionError( _("The challenge doesn't contain a server nonce, or this one is empty."))
self.challenge['algorithm'] = self.challenge.get('algorithm', 'HMAC-SHA-1')
if self.challenge['algorithm'] not in ['HMAC-SHA-1', 'HMAC-MD5']:
raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm']))
self.challenge['pw-algorithm'] = self.challenge.get('pw-algorithm', 'SHA-1')
if self.challenge['pw-algorithm'] not in ['SHA-1', 'MD5']:
raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge['pw-algorithm']))
if self.challenge['algorithm'] == 'HMAC-MD5':
self.hashmod = _md5
else:
self.hashmod = _sha
if self.challenge['pw-algorithm'] == 'MD5':
self.pwhashmod = _md5
else:
self.pwhashmod = _sha
self.key = "".join([self.credentials[0], ":",
self.pwhashmod.new("".join([self.credentials[1], self.challenge['salt']])).hexdigest().lower(),
":", self.challenge['realm']
])
self.key = self.pwhashmod.new(self.key).hexdigest().lower()
def request(self, method, request_uri, headers, content):
"""Modify the request headers"""
keys = _get_end2end_headers(headers)
keylist = "".join(["%s " % k for k in keys])
headers_val = "".join([headers[k] for k in keys])
created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())
cnonce = _cnonce()
request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val)
request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % (
self.credentials[0],
self.challenge['realm'],
self.challenge['snonce'],
cnonce,
request_uri,
created,
request_digest,
keylist,
)
def response(self, response, content):
challenge = _parse_www_authenticate(response, 'www-authenticate').get('hmacdigest', {})
if challenge.get('reason') in ['integrity', 'stale']:
return True
return False
class WsseAuthentication(Authentication):
"""This is thinly tested and should not be relied upon.
At this time there isn't any third party server to test against.
Blogger and TypePad implemented this algorithm at one point
but Blogger has since switched to Basic over HTTPS and
TypePad has implemented it wrong, by never issuing a 401
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'WSSE profile="UsernameToken"'
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers['X-WSSE'] = 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"' % (
self.credentials[0],
password_digest,
cnonce,
iso_now)
class GoogleLoginAuthentication(Authentication):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
from urllib import urlencode
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
service = challenge['googlelogin'].get('service', 'xapi')
# Bloggger actually returns the service in the challenge
# For the rest we guess based on the URI
if service == 'xapi' and request_uri.find("calendar") > 0:
service = "cl"
# No point in guessing Base or Spreadsheet
#elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers['user-agent'])
resp, content = self.http.request("https://www.google.com/accounts/ClientLogin", method="POST", body=urlencode(auth), headers={'Content-Type': 'application/x-www-form-urlencoded'})
lines = content.split('\n')
d = dict([tuple(line.split("=", 1)) for line in lines if line])
if resp.status == 403:
self.Auth = ""
else:
self.Auth = d['Auth']
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'GoogleLogin Auth=' + self.Auth
AUTH_SCHEME_CLASSES = {
"basic": BasicAuthentication,
"wsse": WsseAuthentication,
"digest": DigestAuthentication,
"hmacdigest": HmacDigestAuthentication,
"googlelogin": GoogleLoginAuthentication
}
AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
class FileCache(object):
"""Uses a local directory as a store for cached files.
Not really safe to use if multiple threads or processes are going to
be running on the same cache.
"""
def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache):
os.makedirs(self.cache)
def get(self, key):
retval = None
cacheFullPath = os.path.join(self.cache, self.safe(key))
try:
f = file(cacheFullPath, "rb")
retval = f.read()
f.close()
except IOError:
pass
return retval
def set(self, key, value):
cacheFullPath = os.path.join(self.cache, self.safe(key))
f = file(cacheFullPath, "wb")
f.write(value)
f.close()
def delete(self, key):
cacheFullPath = os.path.join(self.cache, self.safe(key))
if os.path.exists(cacheFullPath):
os.remove(cacheFullPath)
class Credentials(object):
def __init__(self):
self.credentials = []
def add(self, name, password, domain=""):
self.credentials.append((domain.lower(), name, password))
def clear(self):
self.credentials = []
def iter(self, domain):
for (cdomain, name, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (name, password)
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
pass
class ProxyInfo(object):
"""Collect information required to use a proxy."""
def __init__(self, proxy_type, proxy_host, proxy_port, proxy_rdns=None, proxy_user=None, proxy_pass=None):
"""The parameter proxy_type must be set to one of socks.PROXY_TYPE_XXX
constants. For example:
p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost', proxy_port=8000)
"""
self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass = proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass
def astuple(self):
return (self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns,
self.proxy_user, self.proxy_pass)
def isgood(self):
return (self.proxy_host != None) and (self.proxy_port != None)
class HTTPConnectionWithTimeout(httplib.HTTPConnection):
"""
HTTPConnection subclass that supports timeouts
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None):
httplib.HTTPConnection.__init__(self, host, port, strict)
self.timeout = timeout
self.proxy_info = proxy_info
def connect(self):
"""Connect to the host and port specified in __init__."""
# Mostly verbatim from httplib.py.
if self.proxy_info and socks is None:
raise ProxiesUnavailableError(
'Proxy support missing but proxy use was requested!')
msg = "getaddrinfo returns an empty list"
for res in socket.getaddrinfo(self.host, self.port, 0,
socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
if self.proxy_info and self.proxy_info.isgood():
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(*self.proxy_info.astuple())
else:
self.sock = socket.socket(af, socktype, proto)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# Different from httplib: support timeouts.
if has_timeout(self.timeout):
self.sock.settimeout(self.timeout)
# End of difference from httplib.
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
self.sock.connect(sa)
except socket.error, msg:
if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
class HTTPSConnectionWithTimeout(httplib.HTTPSConnection):
"""
This class allows communication via SSL.
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None,
ca_certs=None, disable_ssl_certificate_validation=False):
httplib.HTTPSConnection.__init__(self, host, port=port, key_file=key_file,
cert_file=cert_file, strict=strict)
self.timeout = timeout
self.proxy_info = proxy_info
if ca_certs is None:
ca_certs = CA_CERTS
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = \
disable_ssl_certificate_validation
# The following two methods were adapted from https_wrapper.py, released
# with the Google Appengine SDK at
# http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py
# under the following license:
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
def _GetValidHostsForCert(self, cert):
"""Returns a list of valid host globs for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
Returns:
list: A list of valid host globs.
"""
if 'subjectAltName' in cert:
return [x[1] for x in cert['subjectAltName']
if x[0].lower() == 'dns']
else:
return [x[0][1] for x in cert['subject']
if x[0][0].lower() == 'commonname']
def _ValidateCertificateHostname(self, cert, hostname):
"""Validates that a given hostname is valid for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
hostname: The hostname to test.
Returns:
bool: Whether or not the hostname is valid for this certificate.
"""
hosts = self._GetValidHostsForCert(cert)
for host in hosts:
host_re = host.replace('.', '\.').replace('*', '[^.]*')
if re.search('^%s$' % (host_re,), hostname, re.I):
return True
return False
def connect(self):
"Connect to a host on a given (SSL) port."
msg = "getaddrinfo returns an empty list"
for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo(
self.host, self.port, 0, socket.SOCK_STREAM):
try:
if self.proxy_info and self.proxy_info.isgood():
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(*self.proxy_info.astuple())
else:
sock = socket.socket(family, socktype, proto)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if has_timeout(self.timeout):
sock.settimeout(self.timeout)
sock.connect((self.host, self.port))
self.sock =_ssl_wrap_socket(
sock, self.key_file, self.cert_file,
self.disable_ssl_certificate_validation, self.ca_certs)
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
if not self.disable_ssl_certificate_validation:
cert = self.sock.getpeercert()
hostname = self.host.split(':', 0)[0]
if not self._ValidateCertificateHostname(cert, hostname):
raise CertificateHostnameMismatch(
'Server presented certificate that does not match '
'host %s: %s' % (hostname, cert), hostname, cert)
except ssl_SSLError, e:
if sock:
sock.close()
if self.sock:
self.sock.close()
self.sock = None
# Unfortunately the ssl module doesn't seem to provide any way
# to get at more detailed error information, in particular
# whether the error is due to certificate validation or
# something else (such as SSL protocol mismatch).
if e.errno == ssl.SSL_ERROR_SSL:
raise SSLHandshakeError(e)
else:
raise
except (socket.timeout, socket.gaierror):
raise
except socket.error, msg:
if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
SCHEME_TO_CONNECTION = {
'http': HTTPConnectionWithTimeout,
'https': HTTPSConnectionWithTimeout
}
# Use a different connection object for Google App Engine
try:
from google.appengine.api import apiproxy_stub_map
if apiproxy_stub_map.apiproxy.GetStub('urlfetch') is None:
raise ImportError # Bail out; we're not actually running on App Engine.
from google.appengine.api.urlfetch import fetch
from google.appengine.api.urlfetch import InvalidURLError
from google.appengine.api.urlfetch import DownloadError
from google.appengine.api.urlfetch import ResponseTooLargeError
from google.appengine.api.urlfetch import SSLCertificateError
class ResponseDict(dict):
"""Is a dictionary that also has a read() method, so
that it can pass itself off as an httlib.HTTPResponse()."""
def read(self):
pass
class AppEngineHttpConnection(object):
"""Emulates an httplib.HTTPConnection object, but actually uses the Google
App Engine urlfetch library. This allows the timeout to be properly used on
Google App Engine, and avoids using httplib, which on Google App Engine is
just another wrapper around urlfetch.
"""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None, ca_certs=None,
disable_certificate_validation=False):
self.host = host
self.port = port
self.timeout = timeout
if key_file or cert_file or proxy_info or ca_certs:
raise NotSupportedOnThisPlatform()
self.response = None
self.scheme = 'http'
self.validate_certificate = not disable_certificate_validation
self.sock = True
def request(self, method, url, body, headers):
# Calculate the absolute URI, which fetch requires
netloc = self.host
if self.port:
netloc = '%s:%s' % (self.host, self.port)
absolute_uri = '%s://%s%s' % (self.scheme, netloc, url)
try:
response = fetch(absolute_uri, payload=body, method=method,
headers=headers, allow_truncated=False, follow_redirects=False,
deadline=self.timeout,
validate_certificate=self.validate_certificate)
self.response = ResponseDict(response.headers)
self.response['status'] = str(response.status_code)
self.response.status = response.status_code
setattr(self.response, 'read', lambda : response.content)
# Make sure the exceptions raised match the exceptions expected.
except InvalidURLError:
raise socket.gaierror('')
except (DownloadError, ResponseTooLargeError, SSLCertificateError):
raise httplib.HTTPException()
def getresponse(self):
if self.response:
return self.response
else:
raise httplib.HTTPException()
def set_debuglevel(self, level):
pass
def connect(self):
pass
def close(self):
pass
class AppEngineHttpsConnection(AppEngineHttpConnection):
"""Same as AppEngineHttpConnection, but for HTTPS URIs."""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None):
AppEngineHttpConnection.__init__(self, host, port, key_file, cert_file,
strict, timeout, proxy_info)
self.scheme = 'https'
# Update the connection classes to use the Googel App Engine specific ones.
SCHEME_TO_CONNECTION = {
'http': AppEngineHttpConnection,
'https': AppEngineHttpsConnection
}
except ImportError:
pass
class Http(object):
"""An HTTP client that handles:
- all methods
- caching
- ETags
- compression,
- HTTPS
- Basic
- Digest
- WSSE
and more.
"""
def __init__(self, cache=None, timeout=None, proxy_info=None,
ca_certs=None, disable_ssl_certificate_validation=False):
"""
The value of proxy_info is a ProxyInfo instance.
If 'cache' is a string then it is used as a directory name for
a disk cache. Otherwise it must be an object that supports the
same interface as FileCache.
All timeouts are in seconds. If None is passed for timeout
then Python's default timeout for sockets will be used. See
for example the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
ca_certs is the path of a file containing root CA certificates for SSL
server certificate validation. By default, a CA cert file bundled with
httplib2 is used.
If disable_ssl_certificate_validation is true, SSL cert validation will
not be performed.
"""
self.proxy_info = proxy_info
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = \
disable_ssl_certificate_validation
# Map domain name to an httplib connection
self.connections = {}
# The location of the cache, for now a directory
# where cached responses are held.
if cache and isinstance(cache, basestring):
self.cache = FileCache(cache)
else:
self.cache = cache
# Name/password
self.credentials = Credentials()
# Key/cert
self.certificates = KeyCerts()
# authorization objects
self.authorizations = []
# If set to False then no redirects are followed, even safe ones.
self.follow_redirects = True
# Which HTTP methods do we apply optimistic concurrency to, i.e.
# which methods get an "if-match:" etag header added to them.
self.optimistic_concurrency_methods = ["PUT", "PATCH"]
# If 'follow_redirects' is True, and this is set to True then
# all redirecs are followed, including unsafe ones.
self.follow_all_redirects = False
self.ignore_etag = False
self.force_exception_to_status_code = False
self.timeout = timeout
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, 'www-authenticate')
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if challenges.has_key(scheme):
yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self)
def add_credentials(self, name, password, domain=""):
"""Add a name and password that will be used
any time a request requires authentication."""
self.credentials.add(name, password, domain)
def add_certificate(self, key, cert, domain):
"""Add a key and cert that will be used
any time a request requires authentication."""
self.certificates.add(key, cert, domain)
def clear_credentials(self):
"""Remove all the names and passwords
that are used for authentication"""
self.credentials.clear()
self.authorizations = []
def _conn_request(self, conn, request_uri, method, body, headers):
for i in range(2):
try:
if conn.sock is None:
conn.connect()
conn.request(method, request_uri, body, headers)
except socket.timeout:
raise
except socket.gaierror:
conn.close()
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
except ssl_SSLError:
conn.close()
raise
except socket.error, e:
err = 0
if hasattr(e, 'args'):
err = getattr(e, 'args')[0]
else:
err = e.errno
if err == errno.ECONNREFUSED: # Connection refused
raise
except httplib.HTTPException:
# Just because the server closed the connection doesn't apparently mean
# that the server didn't send a response.
if conn.sock is None:
if i == 0:
conn.close()
conn.connect()
continue
else:
conn.close()
raise
if i == 0:
conn.close()
conn.connect()
continue
try:
response = conn.getresponse()
except (socket.error, httplib.HTTPException):
if i == 0:
conn.close()
conn.connect()
continue
else:
raise
else:
content = ""
if method == "HEAD":
response.close()
else:
content = response.read()
response = Response(response)
if method != "HEAD":
content = _decompressContent(response, content)
break
return (response, content)
def _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey):
"""Do the actual request using the connection object
and also follow one level of redirects if necessary"""
auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)]
auth = auths and sorted(auths)[0][1] or None
if auth:
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
if auth:
if auth.response(response, body):
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers )
response._stale_digest = 1
if response.status == 401:
for authorization in self._auth_from_challenge(host, request_uri, headers, response, content):
authorization.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers, )
if response.status != 401:
self.authorizations.append(authorization)
authorization.response(response, body)
break
if (self.follow_all_redirects or (method in ["GET", "HEAD"]) or response.status == 303):
if self.follow_redirects and response.status in [300, 301, 302, 303, 307]:
# Pick out the location header and basically start from the beginning
# remembering first to strip the ETag header and decrement our 'depth'
if redirections:
if not response.has_key('location') and response.status != 300:
raise RedirectMissingLocation( _("Redirected but the response is missing a Location: header."), response, content)
# Fix-up relative redirects (which violate an RFC 2616 MUST)
if response.has_key('location'):
location = response['location']
(scheme, authority, path, query, fragment) = parse_uri(location)
if authority == None:
response['location'] = urlparse.urljoin(absolute_uri, location)
if response.status == 301 and method in ["GET", "HEAD"]:
response['-x-permanent-redirect-url'] = response['location']
if not response.has_key('content-location'):
response['content-location'] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
if headers.has_key('if-none-match'):
del headers['if-none-match']
if headers.has_key('if-modified-since'):
del headers['if-modified-since']
if response.has_key('location'):
location = response['location']
old_response = copy.deepcopy(response)
if not old_response.has_key('content-location'):
old_response['content-location'] = absolute_uri
redirect_method = method
if response.status in [302, 303]:
redirect_method = "GET"
body = None
(response, content) = self.request(location, redirect_method, body=body, headers = headers, redirections = redirections - 1)
response.previous = old_response
else:
raise RedirectLimit("Redirected more times than rediection_limit allows.", response, content)
elif response.status in [200, 203] and method in ["GET", "HEAD"]:
# Don't cache 206's since we aren't going to handle byte range requests
if not response.has_key('content-location'):
response['content-location'] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
return (response, content)
def _normalize_headers(self, headers):
return _normalize_headers(headers)
# Need to catch and rebrand some exceptions
# Then need to optionally turn all exceptions into status codes
# including all socket.* and httplib.* exceptions.
def request(self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None):
""" Performs a single HTTP request.
The 'uri' is the URI of the HTTP resource and can begin
with either 'http' or 'https'. The value of 'uri' must be an absolute URI.
The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc.
There is no restriction on the methods allowed.
The 'body' is the entity body to be sent with the request. It is a string
object.
Any extra headers that are to be sent with the request should be provided in the
'headers' dictionary.
The maximum number of redirect to follow before raising an
exception is 'redirections. The default is 5.
The return value is a tuple of (response, content), the first
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
try:
if headers is None:
headers = {}
else:
headers = self._normalize_headers(headers)
if not headers.has_key('user-agent'):
headers['user-agent'] = "Python-httplib2/%s (gzip)" % __version__
uri = iri2uri(uri)
(scheme, authority, request_uri, defrag_uri) = urlnorm(uri)
domain_port = authority.split(":")[0:2]
if len(domain_port) == 2 and domain_port[1] == '443' and scheme == 'http':
scheme = 'https'
authority = domain_port[0]
conn_key = scheme+":"+authority
if conn_key in self.connections:
conn = self.connections[conn_key]
else:
if not connection_type:
connection_type = SCHEME_TO_CONNECTION[scheme]
certs = list(self.certificates.iter(authority))
if issubclass(connection_type, HTTPSConnectionWithTimeout):
if certs:
conn = self.connections[conn_key] = connection_type(
authority, key_file=certs[0][0],
cert_file=certs[0][1], timeout=self.timeout,
proxy_info=self.proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=
self.disable_ssl_certificate_validation)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout,
proxy_info=self.proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=
self.disable_ssl_certificate_validation)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout,
proxy_info=self.proxy_info)
conn.set_debuglevel(debuglevel)
if 'range' not in headers and 'accept-encoding' not in headers:
headers['accept-encoding'] = 'gzip, deflate'
info = email.Message.Message()
cached_value = None
if self.cache:
cachekey = defrag_uri
cached_value = self.cache.get(cachekey)
if cached_value:
# info = email.message_from_string(cached_value)
#
# Need to replace the line above with the kludge below
# to fix the non-existent bug not fixed in this
# bug report: http://mail.python.org/pipermail/python-bugs-list/2005-September/030289.html
try:
info, content = cached_value.split('\r\n\r\n', 1)
feedparser = email.FeedParser.FeedParser()
feedparser.feed(info)
info = feedparser.close()
feedparser._parse = None
except IndexError:
self.cache.delete(cachekey)
cachekey = None
cached_value = None
else:
cachekey = None
if method in self.optimistic_concurrency_methods and self.cache and info.has_key('etag') and not self.ignore_etag and 'if-match' not in headers:
# http://www.w3.org/1999/04/Editing/
headers['if-match'] = info['etag']
if method not in ["GET", "HEAD"] and self.cache and cachekey:
# RFC 2616 Section 13.10
self.cache.delete(cachekey)
# Check the vary header in the cache to see if this request
# matches what varies in the cache.
if method in ['GET', 'HEAD'] and 'vary' in info:
vary = info['vary']
vary_headers = vary.lower().replace(' ', '').split(',')
for header in vary_headers:
key = '-varied-%s' % header
value = info[key]
if headers.get(header, None) != value:
cached_value = None
break
if cached_value and method in ["GET", "HEAD"] and self.cache and 'range' not in headers:
if info.has_key('-x-permanent-redirect-url'):
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit("Redirected more times than rediection_limit allows.", {}, "")
(response, new_content) = self.request(info['-x-permanent-redirect-url'], "GET", headers = headers, redirections = redirections - 1)
response.previous = Response(info)
response.previous.fromcache = True
else:
# Determine our course of action:
# Is the cached entry fresh or stale?
# Has the client requested a non-cached response?
#
# There seems to be three possible answers:
# 1. [FRESH] Return the cache entry w/o doing a GET
# 2. [STALE] Do the GET (but add in cache validators if available)
# 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request
entry_disposition = _entry_disposition(info, headers)
if entry_disposition == "FRESH":
if not cached_value:
info['status'] = '504'
content = ""
response = Response(info)
if cached_value:
response.fromcache = True
return (response, content)
if entry_disposition == "STALE":
if info.has_key('etag') and not self.ignore_etag and not 'if-none-match' in headers:
headers['if-none-match'] = info['etag']
if info.has_key('last-modified') and not 'last-modified' in headers:
headers['if-modified-since'] = info['last-modified']
elif entry_disposition == "TRANSPARENT":
pass
(response, new_content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
if response.status == 304 and method == "GET":
# Rewrite the cache entry with the new end-to-end headers
# Take all headers that are in response
# and overwrite their values in info.
# unless they are hop-by-hop, or are listed in the connection header.
for key in _get_end2end_headers(response):
info[key] = response[key]
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(headers, merged_response, content, self.cache, cachekey)
response = merged_response
response.status = 200
response.fromcache = True
elif response.status == 200:
content = new_content
else:
self.cache.delete(cachekey)
content = new_content
else:
cc = _parse_cache_control(headers)
if cc.has_key('only-if-cached'):
info['status'] = '504'
response = Response(info)
content = ""
else:
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
except Exception, e:
if self.force_exception_to_status_code:
if isinstance(e, HttpLib2ErrorWithResponse):
response = e.response
content = e.content
response.status = 500
response.reason = str(e)
elif isinstance(e, socket.timeout):
content = "Request Timeout"
response = Response( {
"content-type": "text/plain",
"status": "408",
"content-length": len(content)
})
response.reason = "Request Timeout"
else:
content = str(e)
response = Response( {
"content-type": "text/plain",
"status": "400",
"content-length": len(content)
})
response.reason = "Bad Request"
else:
raise
return (response, content)
class Response(dict):
"""An object more like email.Message than httplib.HTTPResponse."""
"""Is this response from our local cache"""
fromcache = False
"""HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1. """
version = 11
"Status code returned by server. "
status = 200
"""Reason phrase returned by server."""
reason = "Ok"
previous = None
def __init__(self, info):
# info is either an email.Message or
# an httplib.HTTPResponse object.
if isinstance(info, httplib.HTTPResponse):
for key, value in info.getheaders():
self[key.lower()] = value
self.status = info.status
self['status'] = str(self.status)
self.reason = info.reason
self.version = info.version
elif isinstance(info, email.Message.Message):
for key, value in info.items():
self[key] = value
self.status = int(self['status'])
else:
for key, value in info.iteritems():
self[key] = value
self.status = int(self.get('status', self.status))
def __getattr__(self, name):
if name == 'dict':
return self
else:
raise AttributeError, name
| Python |
#!/usr/bin/env python
#
# Copyright (c) 2002, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ---
# Author: Chad Lester
# Design and style contributions by:
# Amit Patel, Bogdan Cocosel, Daniel Dulitz, Eric Tiedemann,
# Eric Veach, Laurence Gonsalves, Matthew Springer
# Code reorganized a bit by Craig Silverstein
"""This module is used to define and parse command line flags.
This module defines a *distributed* flag-definition policy: rather than
an application having to define all flags in or near main(), each python
module defines flags that are useful to it. When one python module
imports another, it gains access to the other's flags. (This is
implemented by having all modules share a common, global registry object
containing all the flag information.)
Flags are defined through the use of one of the DEFINE_xxx functions.
The specific function used determines how the flag is parsed, checked,
and optionally type-converted, when it's seen on the command line.
IMPLEMENTATION: DEFINE_* creates a 'Flag' object and registers it with a
'FlagValues' object (typically the global FlagValues FLAGS, defined
here). The 'FlagValues' object can scan the command line arguments and
pass flag arguments to the corresponding 'Flag' objects for
value-checking and type conversion. The converted flag values are
available as attributes of the 'FlagValues' object.
Code can access the flag through a FlagValues object, for instance
gflags.FLAGS.myflag. Typically, the __main__ module passes the command
line arguments to gflags.FLAGS for parsing.
At bottom, this module calls getopt(), so getopt functionality is
supported, including short- and long-style flags, and the use of -- to
terminate flags.
Methods defined by the flag module will throw 'FlagsError' exceptions.
The exception argument will be a human-readable string.
FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags
take a name, default value, help-string, and optional 'short' name
(one-letter name). Some flags have other arguments, which are described
with the flag.
DEFINE_string: takes any input, and interprets it as a string.
DEFINE_bool or
DEFINE_boolean: typically does not take an argument: say --myflag to
set FLAGS.myflag to true, or --nomyflag to set
FLAGS.myflag to false. Alternately, you can say
--myflag=true or --myflag=t or --myflag=1 or
--myflag=false or --myflag=f or --myflag=0
DEFINE_float: takes an input and interprets it as a floating point
number. Takes optional args lower_bound and upper_bound;
if the number specified on the command line is out of
range, it will raise a FlagError.
DEFINE_integer: takes an input and interprets it as an integer. Takes
optional args lower_bound and upper_bound as for floats.
DEFINE_enum: takes a list of strings which represents legal values. If
the command-line value is not in this list, raise a flag
error. Otherwise, assign to FLAGS.flag as a string.
DEFINE_list: Takes a comma-separated list of strings on the commandline.
Stores them in a python list object.
DEFINE_spaceseplist: Takes a space-separated list of strings on the
commandline. Stores them in a python list object.
Example: --myspacesepflag "foo bar baz"
DEFINE_multistring: The same as DEFINE_string, except the flag can be
specified more than once on the commandline. The
result is a python list object (list of strings),
even if the flag is only on the command line once.
DEFINE_multi_int: The same as DEFINE_integer, except the flag can be
specified more than once on the commandline. The
result is a python list object (list of ints), even if
the flag is only on the command line once.
SPECIAL FLAGS: There are a few flags that have special meaning:
--help prints a list of all the flags in a human-readable fashion
--helpshort prints a list of all key flags (see below).
--helpxml prints a list of all flags, in XML format. DO NOT parse
the output of --help and --helpshort. Instead, parse
the output of --helpxml. For more info, see
"OUTPUT FOR --helpxml" below.
--flagfile=foo read flags from file foo.
--undefok=f1,f2 ignore unrecognized option errors for f1,f2.
For boolean flags, you should use --undefok=boolflag, and
--boolflag and --noboolflag will be accepted. Do not use
--undefok=noboolflag.
-- as in getopt(), terminates flag-processing
FLAGS VALIDATORS: If your program:
- requires flag X to be specified
- needs flag Y to match a regular expression
- or requires any more general constraint to be satisfied
then validators are for you!
Each validator represents a constraint over one flag, which is enforced
starting from the initial parsing of the flags and until the program
terminates.
Also, lower_bound and upper_bound for numerical flags are enforced using flag
validators.
Howto:
If you want to enforce a constraint over one flag, use
gflags.RegisterValidator(flag_name,
checker,
message='Flag validation failed',
flag_values=FLAGS)
After flag values are initially parsed, and after any change to the specified
flag, method checker(flag_value) will be executed. If constraint is not
satisfied, an IllegalFlagValue exception will be raised. See
RegisterValidator's docstring for a detailed explanation on how to construct
your own checker.
EXAMPLE USAGE:
FLAGS = gflags.FLAGS
gflags.DEFINE_integer('my_version', 0, 'Version number.')
gflags.DEFINE_string('filename', None, 'Input file name', short_name='f')
gflags.RegisterValidator('my_version',
lambda value: value % 2 == 0,
message='--my_version must be divisible by 2')
gflags.MarkFlagAsRequired('filename')
NOTE ON --flagfile:
Flags may be loaded from text files in addition to being specified on
the commandline.
Any flags you don't feel like typing, throw them in a file, one flag per
line, for instance:
--myflag=myvalue
--nomyboolean_flag
You then specify your file with the special flag '--flagfile=somefile'.
You CAN recursively nest flagfile= tokens OR use multiple files on the
command line. Lines beginning with a single hash '#' or a double slash
'//' are comments in your flagfile.
Any flagfile=<file> will be interpreted as having a relative path from
the current working directory rather than from the place the file was
included from:
myPythonScript.py --flagfile=config/somefile.cfg
If somefile.cfg includes further --flagfile= directives, these will be
referenced relative to the original CWD, not from the directory the
including flagfile was found in!
The caveat applies to people who are including a series of nested files
in a different dir than they are executing out of. Relative path names
are always from CWD, not from the directory of the parent include
flagfile. We do now support '~' expanded directory names.
Absolute path names ALWAYS work!
EXAMPLE USAGE:
FLAGS = gflags.FLAGS
# Flag names are globally defined! So in general, we need to be
# careful to pick names that are unlikely to be used by other libraries.
# If there is a conflict, we'll get an error at import time.
gflags.DEFINE_string('name', 'Mr. President', 'your name')
gflags.DEFINE_integer('age', None, 'your age in years', lower_bound=0)
gflags.DEFINE_boolean('debug', False, 'produces debugging output')
gflags.DEFINE_enum('gender', 'male', ['male', 'female'], 'your gender')
def main(argv):
try:
argv = FLAGS(argv) # parse flags
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS)
sys.exit(1)
if FLAGS.debug: print 'non-flag arguments:', argv
print 'Happy Birthday', FLAGS.name
if FLAGS.age is not None:
print 'You are a %d year old %s' % (FLAGS.age, FLAGS.gender)
if __name__ == '__main__':
main(sys.argv)
KEY FLAGS:
As we already explained, each module gains access to all flags defined
by all the other modules it transitively imports. In the case of
non-trivial scripts, this means a lot of flags ... For documentation
purposes, it is good to identify the flags that are key (i.e., really
important) to a module. Clearly, the concept of "key flag" is a
subjective one. When trying to determine whether a flag is key to a
module or not, assume that you are trying to explain your module to a
potential user: which flags would you really like to mention first?
We'll describe shortly how to declare which flags are key to a module.
For the moment, assume we know the set of key flags for each module.
Then, if you use the app.py module, you can use the --helpshort flag to
print only the help for the flags that are key to the main module, in a
human-readable format.
NOTE: If you need to parse the flag help, do NOT use the output of
--help / --helpshort. That output is meant for human consumption, and
may be changed in the future. Instead, use --helpxml; flags that are
key for the main module are marked there with a <key>yes</key> element.
The set of key flags for a module M is composed of:
1. Flags defined by module M by calling a DEFINE_* function.
2. Flags that module M explictly declares as key by using the function
DECLARE_key_flag(<flag_name>)
3. Key flags of other modules that M specifies by using the function
ADOPT_module_key_flags(<other_module>)
This is a "bulk" declaration of key flags: each flag that is key for
<other_module> becomes key for the current module too.
Notice that if you do not use the functions described at points 2 and 3
above, then --helpshort prints information only about the flags defined
by the main module of our script. In many cases, this behavior is good
enough. But if you move part of the main module code (together with the
related flags) into a different module, then it is nice to use
DECLARE_key_flag / ADOPT_module_key_flags and make sure --helpshort
lists all relevant flags (otherwise, your code refactoring may confuse
your users).
Note: each of DECLARE_key_flag / ADOPT_module_key_flags has its own
pluses and minuses: DECLARE_key_flag is more targeted and may lead a
more focused --helpshort documentation. ADOPT_module_key_flags is good
for cases when an entire module is considered key to the current script.
Also, it does not require updates to client scripts when a new flag is
added to the module.
EXAMPLE USAGE 2 (WITH KEY FLAGS):
Consider an application that contains the following three files (two
auxiliary modules and a main module)
File libfoo.py:
import gflags
gflags.DEFINE_integer('num_replicas', 3, 'Number of replicas to start')
gflags.DEFINE_boolean('rpc2', True, 'Turn on the usage of RPC2.')
... some code ...
File libbar.py:
import gflags
gflags.DEFINE_string('bar_gfs_path', '/gfs/path',
'Path to the GFS files for libbar.')
gflags.DEFINE_string('email_for_bar_errors', 'bar-team@google.com',
'Email address for bug reports about module libbar.')
gflags.DEFINE_boolean('bar_risky_hack', False,
'Turn on an experimental and buggy optimization.')
... some code ...
File myscript.py:
import gflags
import libfoo
import libbar
gflags.DEFINE_integer('num_iterations', 0, 'Number of iterations.')
# Declare that all flags that are key for libfoo are
# key for this module too.
gflags.ADOPT_module_key_flags(libfoo)
# Declare that the flag --bar_gfs_path (defined in libbar) is key
# for this module.
gflags.DECLARE_key_flag('bar_gfs_path')
... some code ...
When myscript is invoked with the flag --helpshort, the resulted help
message lists information about all the key flags for myscript:
--num_iterations, --num_replicas, --rpc2, and --bar_gfs_path.
Of course, myscript uses all the flags declared by it (in this case,
just --num_replicas) or by any of the modules it transitively imports
(e.g., the modules libfoo, libbar). E.g., it can access the value of
FLAGS.bar_risky_hack, even if --bar_risky_hack is not declared as a key
flag for myscript.
OUTPUT FOR --helpxml:
The --helpxml flag generates output with the following structure:
<?xml version="1.0"?>
<AllFlags>
<program>PROGRAM_BASENAME</program>
<usage>MAIN_MODULE_DOCSTRING</usage>
(<flag>
[<key>yes</key>]
<file>DECLARING_MODULE</file>
<name>FLAG_NAME</name>
<meaning>FLAG_HELP_MESSAGE</meaning>
<default>DEFAULT_FLAG_VALUE</default>
<current>CURRENT_FLAG_VALUE</current>
<type>FLAG_TYPE</type>
[OPTIONAL_ELEMENTS]
</flag>)*
</AllFlags>
Notes:
1. The output is intentionally similar to the output generated by the
C++ command-line flag library. The few differences are due to the
Python flags that do not have a C++ equivalent (at least not yet),
e.g., DEFINE_list.
2. New XML elements may be added in the future.
3. DEFAULT_FLAG_VALUE is in serialized form, i.e., the string you can
pass for this flag on the command-line. E.g., for a flag defined
using DEFINE_list, this field may be foo,bar, not ['foo', 'bar'].
4. CURRENT_FLAG_VALUE is produced using str(). This means that the
string 'false' will be represented in the same way as the boolean
False. Using repr() would have removed this ambiguity and simplified
parsing, but would have broken the compatibility with the C++
command-line flags.
5. OPTIONAL_ELEMENTS describe elements relevant for certain kinds of
flags: lower_bound, upper_bound (for flags that specify bounds),
enum_value (for enum flags), list_separator (for flags that consist of
a list of values, separated by a special token).
6. We do not provide any example here: please use --helpxml instead.
This module requires at least python 2.2.1 to run.
"""
import cgi
import getopt
import os
import re
import string
import struct
import sys
# pylint: disable-msg=C6204
try:
import fcntl
except ImportError:
fcntl = None
try:
# Importing termios will fail on non-unix platforms.
import termios
except ImportError:
termios = None
import gflags_validators
# pylint: enable-msg=C6204
# Are we running under pychecker?
_RUNNING_PYCHECKER = 'pychecker.python' in sys.modules
def _GetCallingModuleObjectAndName():
"""Returns the module that's calling into this module.
We generally use this function to get the name of the module calling a
DEFINE_foo... function.
"""
# Walk down the stack to find the first globals dict that's not ours.
for depth in range(1, sys.getrecursionlimit()):
if not sys._getframe(depth).f_globals is globals():
globals_for_frame = sys._getframe(depth).f_globals
module, module_name = _GetModuleObjectAndName(globals_for_frame)
if module_name is not None:
return module, module_name
raise AssertionError("No module was found")
def _GetCallingModule():
"""Returns the name of the module that's calling into this module."""
return _GetCallingModuleObjectAndName()[1]
def _GetThisModuleObjectAndName():
"""Returns: (module object, module name) for this module."""
return _GetModuleObjectAndName(globals())
# module exceptions:
class FlagsError(Exception):
"""The base class for all flags errors."""
pass
class DuplicateFlag(FlagsError):
"""Raised if there is a flag naming conflict."""
pass
class CantOpenFlagFileError(FlagsError):
"""Raised if flagfile fails to open: doesn't exist, wrong permissions, etc."""
pass
class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag):
"""Special case of DuplicateFlag -- SWIG flag value can't be set to None.
This can be raised when a duplicate flag is created. Even if allow_override is
True, we still abort if the new value is None, because it's currently
impossible to pass None default value back to SWIG. See FlagValues.SetDefault
for details.
"""
pass
class DuplicateFlagError(DuplicateFlag):
"""A DuplicateFlag whose message cites the conflicting definitions.
A DuplicateFlagError conveys more information than a DuplicateFlag,
namely the modules where the conflicting definitions occur. This
class was created to avoid breaking external modules which depend on
the existing DuplicateFlags interface.
"""
def __init__(self, flagname, flag_values, other_flag_values=None):
"""Create a DuplicateFlagError.
Args:
flagname: Name of the flag being redefined.
flag_values: FlagValues object containing the first definition of
flagname.
other_flag_values: If this argument is not None, it should be the
FlagValues object where the second definition of flagname occurs.
If it is None, we assume that we're being called when attempting
to create the flag a second time, and we use the module calling
this one as the source of the second definition.
"""
self.flagname = flagname
first_module = flag_values.FindModuleDefiningFlag(
flagname, default='<unknown>')
if other_flag_values is None:
second_module = _GetCallingModule()
else:
second_module = other_flag_values.FindModuleDefiningFlag(
flagname, default='<unknown>')
msg = "The flag '%s' is defined twice. First from %s, Second from %s" % (
self.flagname, first_module, second_module)
DuplicateFlag.__init__(self, msg)
class IllegalFlagValue(FlagsError):
"""The flag command line argument is illegal."""
pass
class UnrecognizedFlag(FlagsError):
"""Raised if a flag is unrecognized."""
pass
# An UnrecognizedFlagError conveys more information than an UnrecognizedFlag.
# Since there are external modules that create DuplicateFlags, the interface to
# DuplicateFlag shouldn't change. The flagvalue will be assigned the full value
# of the flag and its argument, if any, allowing handling of unrecognized flags
# in an exception handler.
# If flagvalue is the empty string, then this exception is an due to a
# reference to a flag that was not already defined.
class UnrecognizedFlagError(UnrecognizedFlag):
def __init__(self, flagname, flagvalue=''):
self.flagname = flagname
self.flagvalue = flagvalue
UnrecognizedFlag.__init__(
self, "Unknown command line flag '%s'" % flagname)
# Global variable used by expvar
_exported_flags = {}
_help_width = 80 # width of help output
def GetHelpWidth():
"""Returns: an integer, the width of help lines that is used in TextWrap."""
if (not sys.stdout.isatty()) or (termios is None) or (fcntl is None):
return _help_width
try:
data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234')
columns = struct.unpack('hh', data)[1]
# Emacs mode returns 0.
# Here we assume that any value below 40 is unreasonable
if columns >= 40:
return columns
# Returning an int as default is fine, int(int) just return the int.
return int(os.getenv('COLUMNS', _help_width))
except (TypeError, IOError, struct.error):
return _help_width
def CutCommonSpacePrefix(text):
"""Removes a common space prefix from the lines of a multiline text.
If the first line does not start with a space, it is left as it is and
only in the remaining lines a common space prefix is being searched
for. That means the first line will stay untouched. This is especially
useful to turn doc strings into help texts. This is because some
people prefer to have the doc comment start already after the
apostrophe and then align the following lines while others have the
apostrophes on a separate line.
The function also drops trailing empty lines and ignores empty lines
following the initial content line while calculating the initial
common whitespace.
Args:
text: text to work on
Returns:
the resulting text
"""
text_lines = text.splitlines()
# Drop trailing empty lines
while text_lines and not text_lines[-1]:
text_lines = text_lines[:-1]
if text_lines:
# We got some content, is the first line starting with a space?
if text_lines[0] and text_lines[0][0].isspace():
text_first_line = []
else:
text_first_line = [text_lines.pop(0)]
# Calculate length of common leading whitespace (only over content lines)
common_prefix = os.path.commonprefix([line for line in text_lines if line])
space_prefix_len = len(common_prefix) - len(common_prefix.lstrip())
# If we have a common space prefix, drop it from all lines
if space_prefix_len:
for index in xrange(len(text_lines)):
if text_lines[index]:
text_lines[index] = text_lines[index][space_prefix_len:]
return '\n'.join(text_first_line + text_lines)
return ''
def TextWrap(text, length=None, indent='', firstline_indent=None, tabs=' '):
"""Wraps a given text to a maximum line length and returns it.
We turn lines that only contain whitespace into empty lines. We keep
new lines and tabs (e.g., we do not treat tabs as spaces).
Args:
text: text to wrap
length: maximum length of a line, includes indentation
if this is None then use GetHelpWidth()
indent: indent for all but first line
firstline_indent: indent for first line; if None, fall back to indent
tabs: replacement for tabs
Returns:
wrapped text
Raises:
FlagsError: if indent not shorter than length
FlagsError: if firstline_indent not shorter than length
"""
# Get defaults where callee used None
if length is None:
length = GetHelpWidth()
if indent is None:
indent = ''
if len(indent) >= length:
raise FlagsError('Indent must be shorter than length')
# In line we will be holding the current line which is to be started
# with indent (or firstline_indent if available) and then appended
# with words.
if firstline_indent is None:
firstline_indent = ''
line = indent
else:
line = firstline_indent
if len(firstline_indent) >= length:
raise FlagsError('First line indent must be shorter than length')
# If the callee does not care about tabs we simply convert them to
# spaces If callee wanted tabs to be single space then we do that
# already here.
if not tabs or tabs == ' ':
text = text.replace('\t', ' ')
else:
tabs_are_whitespace = not tabs.strip()
line_regex = re.compile('([ ]*)(\t*)([^ \t]+)', re.MULTILINE)
# Split the text into lines and the lines with the regex above. The
# resulting lines are collected in result[]. For each split we get the
# spaces, the tabs and the next non white space (e.g. next word).
result = []
for text_line in text.splitlines():
# Store result length so we can find out whether processing the next
# line gave any new content
old_result_len = len(result)
# Process next line with line_regex. For optimization we do an rstrip().
# - process tabs (changes either line or word, see below)
# - process word (first try to squeeze on line, then wrap or force wrap)
# Spaces found on the line are ignored, they get added while wrapping as
# needed.
for spaces, current_tabs, word in line_regex.findall(text_line.rstrip()):
# If tabs weren't converted to spaces, handle them now
if current_tabs:
# If the last thing we added was a space anyway then drop
# it. But let's not get rid of the indentation.
if (((result and line != indent) or
(not result and line != firstline_indent)) and line[-1] == ' '):
line = line[:-1]
# Add the tabs, if that means adding whitespace, just add it at
# the line, the rstrip() code while shorten the line down if
# necessary
if tabs_are_whitespace:
line += tabs * len(current_tabs)
else:
# if not all tab replacement is whitespace we prepend it to the word
word = tabs * len(current_tabs) + word
# Handle the case where word cannot be squeezed onto current last line
if len(line) + len(word) > length and len(indent) + len(word) <= length:
result.append(line.rstrip())
line = indent + word
word = ''
# No space left on line or can we append a space?
if len(line) + 1 >= length:
result.append(line.rstrip())
line = indent
else:
line += ' '
# Add word and shorten it up to allowed line length. Restart next
# line with indent and repeat, or add a space if we're done (word
# finished) This deals with words that cannot fit on one line
# (e.g. indent + word longer than allowed line length).
while len(line) + len(word) >= length:
line += word
result.append(line[:length])
word = line[length:]
line = indent
# Default case, simply append the word and a space
if word:
line += word + ' '
# End of input line. If we have content we finish the line. If the
# current line is just the indent but we had content in during this
# original line then we need to add an empty line.
if (result and line != indent) or (not result and line != firstline_indent):
result.append(line.rstrip())
elif len(result) == old_result_len:
result.append('')
line = indent
return '\n'.join(result)
def DocToHelp(doc):
"""Takes a __doc__ string and reformats it as help."""
# Get rid of starting and ending white space. Using lstrip() or even
# strip() could drop more than maximum of first line and right space
# of last line.
doc = doc.strip()
# Get rid of all empty lines
whitespace_only_line = re.compile('^[ \t]+$', re.M)
doc = whitespace_only_line.sub('', doc)
# Cut out common space at line beginnings
doc = CutCommonSpacePrefix(doc)
# Just like this module's comment, comments tend to be aligned somehow.
# In other words they all start with the same amount of white space
# 1) keep double new lines
# 2) keep ws after new lines if not empty line
# 3) all other new lines shall be changed to a space
# Solution: Match new lines between non white space and replace with space.
doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M)
return doc
def _GetModuleObjectAndName(globals_dict):
"""Returns the module that defines a global environment, and its name.
Args:
globals_dict: A dictionary that should correspond to an environment
providing the values of the globals.
Returns:
A pair consisting of (1) module object and (2) module name (a
string). Returns (None, None) if the module could not be
identified.
"""
# The use of .items() (instead of .iteritems()) is NOT a mistake: if
# a parallel thread imports a module while we iterate over
# .iteritems() (not nice, but possible), we get a RuntimeError ...
# Hence, we use the slightly slower but safer .items().
for name, module in sys.modules.items():
if getattr(module, '__dict__', None) is globals_dict:
if name == '__main__':
# Pick a more informative name for the main module.
name = sys.argv[0]
return (module, name)
return (None, None)
def _GetMainModule():
"""Returns: string, name of the module from which execution started."""
# First, try to use the same logic used by _GetCallingModuleObjectAndName(),
# i.e., call _GetModuleObjectAndName(). For that we first need to
# find the dictionary that the main module uses to store the
# globals.
#
# That's (normally) the same dictionary object that the deepest
# (oldest) stack frame is using for globals.
deepest_frame = sys._getframe(0)
while deepest_frame.f_back is not None:
deepest_frame = deepest_frame.f_back
globals_for_main_module = deepest_frame.f_globals
main_module_name = _GetModuleObjectAndName(globals_for_main_module)[1]
# The above strategy fails in some cases (e.g., tools that compute
# code coverage by redefining, among other things, the main module).
# If so, just use sys.argv[0]. We can probably always do this, but
# it's safest to try to use the same logic as _GetCallingModuleObjectAndName()
if main_module_name is None:
main_module_name = sys.argv[0]
return main_module_name
class FlagValues:
"""Registry of 'Flag' objects.
A 'FlagValues' can then scan command line arguments, passing flag
arguments through to the 'Flag' objects that it owns. It also
provides easy access to the flag values. Typically only one
'FlagValues' object is needed by an application: gflags.FLAGS
This class is heavily overloaded:
'Flag' objects are registered via __setitem__:
FLAGS['longname'] = x # register a new flag
The .value attribute of the registered 'Flag' objects can be accessed
as attributes of this 'FlagValues' object, through __getattr__. Both
the long and short name of the original 'Flag' objects can be used to
access its value:
FLAGS.longname # parsed flag value
FLAGS.x # parsed flag value (short name)
Command line arguments are scanned and passed to the registered 'Flag'
objects through the __call__ method. Unparsed arguments, including
argv[0] (e.g. the program name) are returned.
argv = FLAGS(sys.argv) # scan command line arguments
The original registered Flag objects can be retrieved through the use
of the dictionary-like operator, __getitem__:
x = FLAGS['longname'] # access the registered Flag object
The str() operator of a 'FlagValues' object provides help for all of
the registered 'Flag' objects.
"""
def __init__(self):
# Since everything in this class is so heavily overloaded, the only
# way of defining and using fields is to access __dict__ directly.
# Dictionary: flag name (string) -> Flag object.
self.__dict__['__flags'] = {}
# Dictionary: module name (string) -> list of Flag objects that are defined
# by that module.
self.__dict__['__flags_by_module'] = {}
# Dictionary: module id (int) -> list of Flag objects that are defined by
# that module.
self.__dict__['__flags_by_module_id'] = {}
# Dictionary: module name (string) -> list of Flag objects that are
# key for that module.
self.__dict__['__key_flags_by_module'] = {}
# Set if we should use new style gnu_getopt rather than getopt when parsing
# the args. Only possible with Python 2.3+
self.UseGnuGetOpt(False)
def UseGnuGetOpt(self, use_gnu_getopt=True):
"""Use GNU-style scanning. Allows mixing of flag and non-flag arguments.
See http://docs.python.org/library/getopt.html#getopt.gnu_getopt
Args:
use_gnu_getopt: wether or not to use GNU style scanning.
"""
self.__dict__['__use_gnu_getopt'] = use_gnu_getopt
def IsGnuGetOpt(self):
return self.__dict__['__use_gnu_getopt']
def FlagDict(self):
return self.__dict__['__flags']
def FlagsByModuleDict(self):
"""Returns the dictionary of module_name -> list of defined flags.
Returns:
A dictionary. Its keys are module names (strings). Its values
are lists of Flag objects.
"""
return self.__dict__['__flags_by_module']
def FlagsByModuleIdDict(self):
"""Returns the dictionary of module_id -> list of defined flags.
Returns:
A dictionary. Its keys are module IDs (ints). Its values
are lists of Flag objects.
"""
return self.__dict__['__flags_by_module_id']
def KeyFlagsByModuleDict(self):
"""Returns the dictionary of module_name -> list of key flags.
Returns:
A dictionary. Its keys are module names (strings). Its values
are lists of Flag objects.
"""
return self.__dict__['__key_flags_by_module']
def _RegisterFlagByModule(self, module_name, flag):
"""Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we
can later sort the flags by module.
Args:
module_name: A string, the name of a Python module.
flag: A Flag object, a flag that is key to the module.
"""
flags_by_module = self.FlagsByModuleDict()
flags_by_module.setdefault(module_name, []).append(flag)
def _RegisterFlagByModuleId(self, module_id, flag):
"""Records the module that defines a specific flag.
Args:
module_id: An int, the ID of the Python module.
flag: A Flag object, a flag that is key to the module.
"""
flags_by_module_id = self.FlagsByModuleIdDict()
flags_by_module_id.setdefault(module_id, []).append(flag)
def _RegisterKeyFlagForModule(self, module_name, flag):
"""Specifies that a flag is a key flag for a module.
Args:
module_name: A string, the name of a Python module.
flag: A Flag object, a flag that is key to the module.
"""
key_flags_by_module = self.KeyFlagsByModuleDict()
# The list of key flags for the module named module_name.
key_flags = key_flags_by_module.setdefault(module_name, [])
# Add flag, but avoid duplicates.
if flag not in key_flags:
key_flags.append(flag)
def _GetFlagsDefinedByModule(self, module):
"""Returns the list of flags defined by a module.
Args:
module: A module object or a module name (a string).
Returns:
A new list of Flag objects. Caller may update this list as he
wishes: none of those changes will affect the internals of this
FlagValue object.
"""
if not isinstance(module, str):
module = module.__name__
return list(self.FlagsByModuleDict().get(module, []))
def _GetKeyFlagsForModule(self, module):
"""Returns the list of key flags for a module.
Args:
module: A module object or a module name (a string)
Returns:
A new list of Flag objects. Caller may update this list as he
wishes: none of those changes will affect the internals of this
FlagValue object.
"""
if not isinstance(module, str):
module = module.__name__
# Any flag is a key flag for the module that defined it. NOTE:
# key_flags is a fresh list: we can update it without affecting the
# internals of this FlagValues object.
key_flags = self._GetFlagsDefinedByModule(module)
# Take into account flags explicitly declared as key for a module.
for flag in self.KeyFlagsByModuleDict().get(module, []):
if flag not in key_flags:
key_flags.append(flag)
return key_flags
def FindModuleDefiningFlag(self, flagname, default=None):
"""Return the name of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The name of the module which registered the flag with this name.
If no such module exists (i.e. no flag with this name exists),
we return default.
"""
for module, flags in self.FlagsByModuleDict().iteritems():
for flag in flags:
if flag.name == flagname or flag.short_name == flagname:
return module
return default
def FindModuleIdDefiningFlag(self, flagname, default=None):
"""Return the ID of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The ID of the module which registered the flag with this name.
If no such module exists (i.e. no flag with this name exists),
we return default.
"""
for module_id, flags in self.FlagsByModuleIdDict().iteritems():
for flag in flags:
if flag.name == flagname or flag.short_name == flagname:
return module_id
return default
def AppendFlagValues(self, flag_values):
"""Appends flags registered in another FlagValues instance.
Args:
flag_values: registry to copy from
"""
for flag_name, flag in flag_values.FlagDict().iteritems():
# Each flags with shortname appears here twice (once under its
# normal name, and again with its short name). To prevent
# problems (DuplicateFlagError) with double flag registration, we
# perform a check to make sure that the entry we're looking at is
# for its normal name.
if flag_name == flag.name:
try:
self[flag_name] = flag
except DuplicateFlagError:
raise DuplicateFlagError(flag_name, self,
other_flag_values=flag_values)
def RemoveFlagValues(self, flag_values):
"""Remove flags that were previously appended from another FlagValues.
Args:
flag_values: registry containing flags to remove.
"""
for flag_name in flag_values.FlagDict():
self.__delattr__(flag_name)
def __setitem__(self, name, flag):
"""Registers a new flag variable."""
fl = self.FlagDict()
if not isinstance(flag, Flag):
raise IllegalFlagValue(flag)
if not isinstance(name, type("")):
raise FlagsError("Flag name must be a string")
if len(name) == 0:
raise FlagsError("Flag name cannot be empty")
# If running under pychecker, duplicate keys are likely to be
# defined. Disable check for duplicate keys when pycheck'ing.
if (name in fl and not flag.allow_override and
not fl[name].allow_override and not _RUNNING_PYCHECKER):
module, module_name = _GetCallingModuleObjectAndName()
if (self.FindModuleDefiningFlag(name) == module_name and
id(module) != self.FindModuleIdDefiningFlag(name)):
# If the flag has already been defined by a module with the same name,
# but a different ID, we can stop here because it indicates that the
# module is simply being imported a subsequent time.
return
raise DuplicateFlagError(name, self)
short_name = flag.short_name
if short_name is not None:
if (short_name in fl and not flag.allow_override and
not fl[short_name].allow_override and not _RUNNING_PYCHECKER):
raise DuplicateFlagError(short_name, self)
fl[short_name] = flag
fl[name] = flag
global _exported_flags
_exported_flags[name] = flag
def __getitem__(self, name):
"""Retrieves the Flag object for the flag --name."""
return self.FlagDict()[name]
def __getattr__(self, name):
"""Retrieves the 'value' attribute of the flag --name."""
fl = self.FlagDict()
if name not in fl:
raise AttributeError(name)
return fl[name].value
def __setattr__(self, name, value):
"""Sets the 'value' attribute of the flag --name."""
fl = self.FlagDict()
fl[name].value = value
self._AssertValidators(fl[name].validators)
return value
def _AssertAllValidators(self):
all_validators = set()
for flag in self.FlagDict().itervalues():
for validator in flag.validators:
all_validators.add(validator)
self._AssertValidators(all_validators)
def _AssertValidators(self, validators):
"""Assert if all validators in the list are satisfied.
Asserts validators in the order they were created.
Args:
validators: Iterable(gflags_validators.Validator), validators to be
verified
Raises:
AttributeError: if validators work with a non-existing flag.
IllegalFlagValue: if validation fails for at least one validator
"""
for validator in sorted(
validators, key=lambda validator: validator.insertion_index):
try:
validator.Verify(self)
except gflags_validators.Error, e:
message = validator.PrintFlagsWithValues(self)
raise IllegalFlagValue('%s: %s' % (message, str(e)))
def _FlagIsRegistered(self, flag_obj):
"""Checks whether a Flag object is registered under some name.
Note: this is non trivial: in addition to its normal name, a flag
may have a short name too. In self.FlagDict(), both the normal and
the short name are mapped to the same flag object. E.g., calling
only "del FLAGS.short_name" is not unregistering the corresponding
Flag object (it is still registered under the longer name).
Args:
flag_obj: A Flag object.
Returns:
A boolean: True iff flag_obj is registered under some name.
"""
flag_dict = self.FlagDict()
# Check whether flag_obj is registered under its long name.
name = flag_obj.name
if flag_dict.get(name, None) == flag_obj:
return True
# Check whether flag_obj is registered under its short name.
short_name = flag_obj.short_name
if (short_name is not None and
flag_dict.get(short_name, None) == flag_obj):
return True
# The flag cannot be registered under any other name, so we do not
# need to do a full search through the values of self.FlagDict().
return False
def __delattr__(self, flag_name):
"""Deletes a previously-defined flag from a flag object.
This method makes sure we can delete a flag by using
del flag_values_object.<flag_name>
E.g.,
gflags.DEFINE_integer('foo', 1, 'Integer flag.')
del gflags.FLAGS.foo
Args:
flag_name: A string, the name of the flag to be deleted.
Raises:
AttributeError: When there is no registered flag named flag_name.
"""
fl = self.FlagDict()
if flag_name not in fl:
raise AttributeError(flag_name)
flag_obj = fl[flag_name]
del fl[flag_name]
if not self._FlagIsRegistered(flag_obj):
# If the Flag object indicated by flag_name is no longer
# registered (please see the docstring of _FlagIsRegistered), then
# we delete the occurrences of the flag object in all our internal
# dictionaries.
self.__RemoveFlagFromDictByModule(self.FlagsByModuleDict(), flag_obj)
self.__RemoveFlagFromDictByModule(self.FlagsByModuleIdDict(), flag_obj)
self.__RemoveFlagFromDictByModule(self.KeyFlagsByModuleDict(), flag_obj)
def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj):
"""Removes a flag object from a module -> list of flags dictionary.
Args:
flags_by_module_dict: A dictionary that maps module names to lists of
flags.
flag_obj: A flag object.
"""
for unused_module, flags_in_module in flags_by_module_dict.iteritems():
# while (as opposed to if) takes care of multiple occurrences of a
# flag in the list for the same module.
while flag_obj in flags_in_module:
flags_in_module.remove(flag_obj)
def SetDefault(self, name, value):
"""Changes the default value of the named flag object."""
fl = self.FlagDict()
if name not in fl:
raise AttributeError(name)
fl[name].SetDefault(value)
self._AssertValidators(fl[name].validators)
def __contains__(self, name):
"""Returns True if name is a value (flag) in the dict."""
return name in self.FlagDict()
has_key = __contains__ # a synonym for __contains__()
def __iter__(self):
return iter(self.FlagDict())
def __call__(self, argv):
"""Parses flags from argv; stores parsed flags into this FlagValues object.
All unparsed arguments are returned. Flags are parsed using the GNU
Program Argument Syntax Conventions, using getopt:
http://www.gnu.org/software/libc/manual/html_mono/libc.html#Getopt
Args:
argv: argument list. Can be of any type that may be converted to a list.
Returns:
The list of arguments not parsed as options, including argv[0]
Raises:
FlagsError: on any parsing error
"""
# Support any sequence type that can be converted to a list
argv = list(argv)
shortopts = ""
longopts = []
fl = self.FlagDict()
# This pre parses the argv list for --flagfile=<> options.
argv = argv[:1] + self.ReadFlagsFromFiles(argv[1:], force_gnu=False)
# Correct the argv to support the google style of passing boolean
# parameters. Boolean parameters may be passed by using --mybool,
# --nomybool, --mybool=(true|false|1|0). getopt does not support
# having options that may or may not have a parameter. We replace
# instances of the short form --mybool and --nomybool with their
# full forms: --mybool=(true|false).
original_argv = list(argv) # list() makes a copy
shortest_matches = None
for name, flag in fl.items():
if not flag.boolean:
continue
if shortest_matches is None:
# Determine the smallest allowable prefix for all flag names
shortest_matches = self.ShortestUniquePrefixes(fl)
no_name = 'no' + name
prefix = shortest_matches[name]
no_prefix = shortest_matches[no_name]
# Replace all occurrences of this boolean with extended forms
for arg_idx in range(1, len(argv)):
arg = argv[arg_idx]
if arg.find('=') >= 0: continue
if arg.startswith('--'+prefix) and ('--'+name).startswith(arg):
argv[arg_idx] = ('--%s=true' % name)
elif arg.startswith('--'+no_prefix) and ('--'+no_name).startswith(arg):
argv[arg_idx] = ('--%s=false' % name)
# Loop over all of the flags, building up the lists of short options
# and long options that will be passed to getopt. Short options are
# specified as a string of letters, each letter followed by a colon
# if it takes an argument. Long options are stored in an array of
# strings. Each string ends with an '=' if it takes an argument.
for name, flag in fl.items():
longopts.append(name + "=")
if len(name) == 1: # one-letter option: allow short flag type also
shortopts += name
if not flag.boolean:
shortopts += ":"
longopts.append('undefok=')
undefok_flags = []
# In case --undefok is specified, loop to pick up unrecognized
# options one by one.
unrecognized_opts = []
args = argv[1:]
while True:
try:
if self.__dict__['__use_gnu_getopt']:
optlist, unparsed_args = getopt.gnu_getopt(args, shortopts, longopts)
else:
optlist, unparsed_args = getopt.getopt(args, shortopts, longopts)
break
except getopt.GetoptError, e:
if not e.opt or e.opt in fl:
# Not an unrecognized option, re-raise the exception as a FlagsError
raise FlagsError(e)
# Remove offender from args and try again
for arg_index in range(len(args)):
if ((args[arg_index] == '--' + e.opt) or
(args[arg_index] == '-' + e.opt) or
(args[arg_index].startswith('--' + e.opt + '='))):
unrecognized_opts.append((e.opt, args[arg_index]))
args = args[0:arg_index] + args[arg_index+1:]
break
else:
# We should have found the option, so we don't expect to get
# here. We could assert, but raising the original exception
# might work better.
raise FlagsError(e)
for name, arg in optlist:
if name == '--undefok':
flag_names = arg.split(',')
undefok_flags.extend(flag_names)
# For boolean flags, if --undefok=boolflag is specified, then we should
# also accept --noboolflag, in addition to --boolflag.
# Since we don't know the type of the undefok'd flag, this will affect
# non-boolean flags as well.
# NOTE: You shouldn't use --undefok=noboolflag, because then we will
# accept --nonoboolflag here. We are choosing not to do the conversion
# from noboolflag -> boolflag because of the ambiguity that flag names
# can start with 'no'.
undefok_flags.extend('no' + name for name in flag_names)
continue
if name.startswith('--'):
# long option
name = name[2:]
short_option = 0
else:
# short option
name = name[1:]
short_option = 1
if name in fl:
flag = fl[name]
if flag.boolean and short_option: arg = 1
flag.Parse(arg)
# If there were unrecognized options, raise an exception unless
# the options were named via --undefok.
for opt, value in unrecognized_opts:
if opt not in undefok_flags:
raise UnrecognizedFlagError(opt, value)
if unparsed_args:
if self.__dict__['__use_gnu_getopt']:
# if using gnu_getopt just return the program name + remainder of argv.
ret_val = argv[:1] + unparsed_args
else:
# unparsed_args becomes the first non-flag detected by getopt to
# the end of argv. Because argv may have been modified above,
# return original_argv for this region.
ret_val = argv[:1] + original_argv[-len(unparsed_args):]
else:
ret_val = argv[:1]
self._AssertAllValidators()
return ret_val
def Reset(self):
"""Resets the values to the point before FLAGS(argv) was called."""
for f in self.FlagDict().values():
f.Unparse()
def RegisteredFlags(self):
"""Returns: a list of the names and short names of all registered flags."""
return list(self.FlagDict())
def FlagValuesDict(self):
"""Returns: a dictionary that maps flag names to flag values."""
flag_values = {}
for flag_name in self.RegisteredFlags():
flag = self.FlagDict()[flag_name]
flag_values[flag_name] = flag.value
return flag_values
def __str__(self):
"""Generates a help string for all known flags."""
return self.GetHelp()
def GetHelp(self, prefix=''):
"""Generates a help string for all known flags."""
helplist = []
flags_by_module = self.FlagsByModuleDict()
if flags_by_module:
modules = sorted(flags_by_module)
# Print the help for the main module first, if possible.
main_module = _GetMainModule()
if main_module in modules:
modules.remove(main_module)
modules = [main_module] + modules
for module in modules:
self.__RenderOurModuleFlags(module, helplist)
self.__RenderModuleFlags('gflags',
_SPECIAL_FLAGS.FlagDict().values(),
helplist)
else:
# Just print one long list of flags.
self.__RenderFlagList(
self.FlagDict().values() + _SPECIAL_FLAGS.FlagDict().values(),
helplist, prefix)
return '\n'.join(helplist)
def __RenderModuleFlags(self, module, flags, output_lines, prefix=""):
"""Generates a help string for a given module."""
if not isinstance(module, str):
module = module.__name__
output_lines.append('\n%s%s:' % (prefix, module))
self.__RenderFlagList(flags, output_lines, prefix + " ")
def __RenderOurModuleFlags(self, module, output_lines, prefix=""):
"""Generates a help string for a given module."""
flags = self._GetFlagsDefinedByModule(module)
if flags:
self.__RenderModuleFlags(module, flags, output_lines, prefix)
def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=""):
"""Generates a help string for the key flags of a given module.
Args:
module: A module object or a module name (a string).
output_lines: A list of strings. The generated help message
lines will be appended to this list.
prefix: A string that is prepended to each generated help line.
"""
key_flags = self._GetKeyFlagsForModule(module)
if key_flags:
self.__RenderModuleFlags(module, key_flags, output_lines, prefix)
def ModuleHelp(self, module):
"""Describe the key flags of a module.
Args:
module: A module object or a module name (a string).
Returns:
string describing the key flags of a module.
"""
helplist = []
self.__RenderOurModuleKeyFlags(module, helplist)
return '\n'.join(helplist)
def MainModuleHelp(self):
"""Describe the key flags of the main module.
Returns:
string describing the key flags of a module.
"""
return self.ModuleHelp(_GetMainModule())
def __RenderFlagList(self, flaglist, output_lines, prefix=" "):
fl = self.FlagDict()
special_fl = _SPECIAL_FLAGS.FlagDict()
flaglist = [(flag.name, flag) for flag in flaglist]
flaglist.sort()
flagset = {}
for (name, flag) in flaglist:
# It's possible this flag got deleted or overridden since being
# registered in the per-module flaglist. Check now against the
# canonical source of current flag information, the FlagDict.
if fl.get(name, None) != flag and special_fl.get(name, None) != flag:
# a different flag is using this name now
continue
# only print help once
if flag in flagset: continue
flagset[flag] = 1
flaghelp = ""
if flag.short_name: flaghelp += "-%s," % flag.short_name
if flag.boolean:
flaghelp += "--[no]%s" % flag.name + ":"
else:
flaghelp += "--%s" % flag.name + ":"
flaghelp += " "
if flag.help:
flaghelp += flag.help
flaghelp = TextWrap(flaghelp, indent=prefix+" ",
firstline_indent=prefix)
if flag.default_as_str:
flaghelp += "\n"
flaghelp += TextWrap("(default: %s)" % flag.default_as_str,
indent=prefix+" ")
if flag.parser.syntactic_help:
flaghelp += "\n"
flaghelp += TextWrap("(%s)" % flag.parser.syntactic_help,
indent=prefix+" ")
output_lines.append(flaghelp)
def get(self, name, default):
"""Returns the value of a flag (if not None) or a default value.
Args:
name: A string, the name of a flag.
default: Default value to use if the flag value is None.
"""
value = self.__getattr__(name)
if value is not None: # Can't do if not value, b/c value might be '0' or ""
return value
else:
return default
def ShortestUniquePrefixes(self, fl):
"""Returns: dictionary; maps flag names to their shortest unique prefix."""
# Sort the list of flag names
sorted_flags = []
for name, flag in fl.items():
sorted_flags.append(name)
if flag.boolean:
sorted_flags.append('no%s' % name)
sorted_flags.sort()
# For each name in the sorted list, determine the shortest unique
# prefix by comparing itself to the next name and to the previous
# name (the latter check uses cached info from the previous loop).
shortest_matches = {}
prev_idx = 0
for flag_idx in range(len(sorted_flags)):
curr = sorted_flags[flag_idx]
if flag_idx == (len(sorted_flags) - 1):
next = None
else:
next = sorted_flags[flag_idx+1]
next_len = len(next)
for curr_idx in range(len(curr)):
if (next is None
or curr_idx >= next_len
or curr[curr_idx] != next[curr_idx]):
# curr longer than next or no more chars in common
shortest_matches[curr] = curr[:max(prev_idx, curr_idx) + 1]
prev_idx = curr_idx
break
else:
# curr shorter than (or equal to) next
shortest_matches[curr] = curr
prev_idx = curr_idx + 1 # next will need at least one more char
return shortest_matches
def __IsFlagFileDirective(self, flag_string):
"""Checks whether flag_string contain a --flagfile=<foo> directive."""
if isinstance(flag_string, type("")):
if flag_string.startswith('--flagfile='):
return 1
elif flag_string == '--flagfile':
return 1
elif flag_string.startswith('-flagfile='):
return 1
elif flag_string == '-flagfile':
return 1
else:
return 0
return 0
def ExtractFilename(self, flagfile_str):
"""Returns filename from a flagfile_str of form -[-]flagfile=filename.
The cases of --flagfile foo and -flagfile foo shouldn't be hitting
this function, as they are dealt with in the level above this
function.
"""
if flagfile_str.startswith('--flagfile='):
return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip())
elif flagfile_str.startswith('-flagfile='):
return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip())
else:
raise FlagsError('Hit illegal --flagfile type: %s' % flagfile_str)
def __GetFlagFileLines(self, filename, parsed_file_list):
"""Returns the useful (!=comments, etc) lines from a file with flags.
Args:
filename: A string, the name of the flag file.
parsed_file_list: A list of the names of the files we have
already read. MUTATED BY THIS FUNCTION.
Returns:
List of strings. See the note below.
NOTE(springer): This function checks for a nested --flagfile=<foo>
tag and handles the lower file recursively. It returns a list of
all the lines that _could_ contain command flags. This is
EVERYTHING except whitespace lines and comments (lines starting
with '#' or '//').
"""
line_list = [] # All line from flagfile.
flag_line_list = [] # Subset of lines w/o comments, blanks, flagfile= tags.
try:
file_obj = open(filename, 'r')
except IOError, e_msg:
raise CantOpenFlagFileError('ERROR:: Unable to open flagfile: %s' % e_msg)
line_list = file_obj.readlines()
file_obj.close()
parsed_file_list.append(filename)
# This is where we check each line in the file we just read.
for line in line_list:
if line.isspace():
pass
# Checks for comment (a line that starts with '#').
elif line.startswith('#') or line.startswith('//'):
pass
# Checks for a nested "--flagfile=<bar>" flag in the current file.
# If we find one, recursively parse down into that file.
elif self.__IsFlagFileDirective(line):
sub_filename = self.ExtractFilename(line)
# We do a little safety check for reparsing a file we've already done.
if not sub_filename in parsed_file_list:
included_flags = self.__GetFlagFileLines(sub_filename,
parsed_file_list)
flag_line_list.extend(included_flags)
else: # Case of hitting a circularly included file.
sys.stderr.write('Warning: Hit circular flagfile dependency: %s\n' %
(sub_filename,))
else:
# Any line that's not a comment or a nested flagfile should get
# copied into 2nd position. This leaves earlier arguments
# further back in the list, thus giving them higher priority.
flag_line_list.append(line.strip())
return flag_line_list
def ReadFlagsFromFiles(self, argv, force_gnu=True):
"""Processes command line args, but also allow args to be read from file.
Args:
argv: A list of strings, usually sys.argv[1:], which may contain one or
more flagfile directives of the form --flagfile="./filename".
Note that the name of the program (sys.argv[0]) should be omitted.
force_gnu: If False, --flagfile parsing obeys normal flag semantics.
If True, --flagfile parsing instead follows gnu_getopt semantics.
*** WARNING *** force_gnu=False may become the future default!
Returns:
A new list which has the original list combined with what we read
from any flagfile(s).
References: Global gflags.FLAG class instance.
This function should be called before the normal FLAGS(argv) call.
This function scans the input list for a flag that looks like:
--flagfile=<somefile>. Then it opens <somefile>, reads all valid key
and value pairs and inserts them into the input list between the
first item of the list and any subsequent items in the list.
Note that your application's flags are still defined the usual way
using gflags DEFINE_flag() type functions.
Notes (assuming we're getting a commandline of some sort as our input):
--> Flags from the command line argv _should_ always take precedence!
--> A further "--flagfile=<otherfile.cfg>" CAN be nested in a flagfile.
It will be processed after the parent flag file is done.
--> For duplicate flags, first one we hit should "win".
--> In a flagfile, a line beginning with # or // is a comment.
--> Entirely blank lines _should_ be ignored.
"""
parsed_file_list = []
rest_of_args = argv
new_argv = []
while rest_of_args:
current_arg = rest_of_args[0]
rest_of_args = rest_of_args[1:]
if self.__IsFlagFileDirective(current_arg):
# This handles the case of -(-)flagfile foo. In this case the
# next arg really is part of this one.
if current_arg == '--flagfile' or current_arg == '-flagfile':
if not rest_of_args:
raise IllegalFlagValue('--flagfile with no argument')
flag_filename = os.path.expanduser(rest_of_args[0])
rest_of_args = rest_of_args[1:]
else:
# This handles the case of (-)-flagfile=foo.
flag_filename = self.ExtractFilename(current_arg)
new_argv.extend(
self.__GetFlagFileLines(flag_filename, parsed_file_list))
else:
new_argv.append(current_arg)
# Stop parsing after '--', like getopt and gnu_getopt.
if current_arg == '--':
break
# Stop parsing after a non-flag, like getopt.
if not current_arg.startswith('-'):
if not force_gnu and not self.__dict__['__use_gnu_getopt']:
break
if rest_of_args:
new_argv.extend(rest_of_args)
return new_argv
def FlagsIntoString(self):
"""Returns a string with the flags assignments from this FlagValues object.
This function ignores flags whose value is None. Each flag
assignment is separated by a newline.
NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString
from http://code.google.com/p/google-gflags
"""
s = ''
for flag in self.FlagDict().values():
if flag.value is not None:
s += flag.Serialize() + '\n'
return s
def AppendFlagsIntoFile(self, filename):
"""Appends all flags assignments from this FlagInfo object to a file.
Output will be in the format of a flagfile.
NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile
from http://code.google.com/p/google-gflags
"""
out_file = open(filename, 'a')
out_file.write(self.FlagsIntoString())
out_file.close()
def WriteHelpInXMLFormat(self, outfile=None):
"""Outputs flag documentation in XML format.
NOTE: We use element names that are consistent with those used by
the C++ command-line flag library, from
http://code.google.com/p/google-gflags
We also use a few new elements (e.g., <key>), but we do not
interfere / overlap with existing XML elements used by the C++
library. Please maintain this consistency.
Args:
outfile: File object we write to. Default None means sys.stdout.
"""
outfile = outfile or sys.stdout
outfile.write('<?xml version=\"1.0\"?>\n')
outfile.write('<AllFlags>\n')
indent = ' '
_WriteSimpleXMLElement(outfile, 'program', os.path.basename(sys.argv[0]),
indent)
usage_doc = sys.modules['__main__'].__doc__
if not usage_doc:
usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0]
else:
usage_doc = usage_doc.replace('%s', sys.argv[0])
_WriteSimpleXMLElement(outfile, 'usage', usage_doc, indent)
# Get list of key flags for the main module.
key_flags = self._GetKeyFlagsForModule(_GetMainModule())
# Sort flags by declaring module name and next by flag name.
flags_by_module = self.FlagsByModuleDict()
all_module_names = list(flags_by_module.keys())
all_module_names.sort()
for module_name in all_module_names:
flag_list = [(f.name, f) for f in flags_by_module[module_name]]
flag_list.sort()
for unused_flag_name, flag in flag_list:
is_key = flag in key_flags
flag.WriteInfoInXMLFormat(outfile, module_name,
is_key=is_key, indent=indent)
outfile.write('</AllFlags>\n')
outfile.flush()
def AddValidator(self, validator):
"""Register new flags validator to be checked.
Args:
validator: gflags_validators.Validator
Raises:
AttributeError: if validators work with a non-existing flag.
"""
for flag_name in validator.GetFlagsNames():
flag = self.FlagDict()[flag_name]
flag.validators.append(validator)
# end of FlagValues definition
# The global FlagValues instance
FLAGS = FlagValues()
def _StrOrUnicode(value):
"""Converts value to a python string or, if necessary, unicode-string."""
try:
return str(value)
except UnicodeEncodeError:
return unicode(value)
def _MakeXMLSafe(s):
"""Escapes <, >, and & from s, and removes XML 1.0-illegal chars."""
s = cgi.escape(s) # Escape <, >, and &
# Remove characters that cannot appear in an XML 1.0 document
# (http://www.w3.org/TR/REC-xml/#charsets).
#
# NOTE: if there are problems with current solution, one may move to
# XML 1.1, which allows such chars, if they're entity-escaped (&#xHH;).
s = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', s)
# Convert non-ascii characters to entities. Note: requires python >=2.3
s = s.encode('ascii', 'xmlcharrefreplace') # u'\xce\x88' -> 'uΈ'
return s
def _WriteSimpleXMLElement(outfile, name, value, indent):
"""Writes a simple XML element.
Args:
outfile: File object we write the XML element to.
name: A string, the name of XML element.
value: A Python object, whose string representation will be used
as the value of the XML element.
indent: A string, prepended to each line of generated output.
"""
value_str = _StrOrUnicode(value)
if isinstance(value, bool):
# Display boolean values as the C++ flag library does: no caps.
value_str = value_str.lower()
safe_value_str = _MakeXMLSafe(value_str)
outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name))
class Flag:
"""Information about a command-line flag.
'Flag' objects define the following fields:
.name - the name for this flag
.default - the default value for this flag
.default_as_str - default value as repr'd string, e.g., "'true'" (or None)
.value - the most recent parsed value of this flag; set by Parse()
.help - a help string or None if no help is available
.short_name - the single letter alias for this flag (or None)
.boolean - if 'true', this flag does not accept arguments
.present - true if this flag was parsed from command line flags.
.parser - an ArgumentParser object
.serializer - an ArgumentSerializer object
.allow_override - the flag may be redefined without raising an error
The only public method of a 'Flag' object is Parse(), but it is
typically only called by a 'FlagValues' object. The Parse() method is
a thin wrapper around the 'ArgumentParser' Parse() method. The parsed
value is saved in .value, and the .present attribute is updated. If
this flag was already present, a FlagsError is raised.
Parse() is also called during __init__ to parse the default value and
initialize the .value attribute. This enables other python modules to
safely use flags even if the __main__ module neglects to parse the
command line arguments. The .present attribute is cleared after
__init__ parsing. If the default value is set to None, then the
__init__ parsing step is skipped and the .value attribute is
initialized to None.
Note: The default value is also presented to the user in the help
string, so it is important that it be a legal value for this flag.
"""
def __init__(self, parser, serializer, name, default, help_string,
short_name=None, boolean=0, allow_override=0):
self.name = name
if not help_string:
help_string = '(no help available)'
self.help = help_string
self.short_name = short_name
self.boolean = boolean
self.present = 0
self.parser = parser
self.serializer = serializer
self.allow_override = allow_override
self.value = None
self.validators = []
self.SetDefault(default)
def __hash__(self):
return hash(id(self))
def __eq__(self, other):
return self is other
def __lt__(self, other):
if isinstance(other, Flag):
return id(self) < id(other)
return NotImplemented
def __GetParsedValueAsString(self, value):
if value is None:
return None
if self.serializer:
return repr(self.serializer.Serialize(value))
if self.boolean:
if value:
return repr('true')
else:
return repr('false')
return repr(_StrOrUnicode(value))
def Parse(self, argument):
try:
self.value = self.parser.Parse(argument)
except ValueError, e: # recast ValueError as IllegalFlagValue
raise IllegalFlagValue("flag --%s=%s: %s" % (self.name, argument, e))
self.present += 1
def Unparse(self):
if self.default is None:
self.value = None
else:
self.Parse(self.default)
self.present = 0
def Serialize(self):
if self.value is None:
return ''
if self.boolean:
if self.value:
return "--%s" % self.name
else:
return "--no%s" % self.name
else:
if not self.serializer:
raise FlagsError("Serializer not present for flag %s" % self.name)
return "--%s=%s" % (self.name, self.serializer.Serialize(self.value))
def SetDefault(self, value):
"""Changes the default value (and current value too) for this Flag."""
# We can't allow a None override because it may end up not being
# passed to C++ code when we're overriding C++ flags. So we
# cowardly bail out until someone fixes the semantics of trying to
# pass None to a C++ flag. See swig_flags.Init() for details on
# this behavior.
# TODO(olexiy): Users can directly call this method, bypassing all flags
# validators (we don't have FlagValues here, so we can not check
# validators).
# The simplest solution I see is to make this method private.
# Another approach would be to store reference to the corresponding
# FlagValues with each flag, but this seems to be an overkill.
if value is None and self.allow_override:
raise DuplicateFlagCannotPropagateNoneToSwig(self.name)
self.default = value
self.Unparse()
self.default_as_str = self.__GetParsedValueAsString(self.value)
def Type(self):
"""Returns: a string that describes the type of this Flag."""
# NOTE: we use strings, and not the types.*Type constants because
# our flags can have more exotic types, e.g., 'comma separated list
# of strings', 'whitespace separated list of strings', etc.
return self.parser.Type()
def WriteInfoInXMLFormat(self, outfile, module_name, is_key=False, indent=''):
"""Writes common info about this flag, in XML format.
This is information that is relevant to all flags (e.g., name,
meaning, etc.). If you defined a flag that has some other pieces of
info, then please override _WriteCustomInfoInXMLFormat.
Please do NOT override this method.
Args:
outfile: File object we write to.
module_name: A string, the name of the module that defines this flag.
is_key: A boolean, True iff this flag is key for main module.
indent: A string that is prepended to each generated line.
"""
outfile.write(indent + '<flag>\n')
inner_indent = indent + ' '
if is_key:
_WriteSimpleXMLElement(outfile, 'key', 'yes', inner_indent)
_WriteSimpleXMLElement(outfile, 'file', module_name, inner_indent)
# Print flag features that are relevant for all flags.
_WriteSimpleXMLElement(outfile, 'name', self.name, inner_indent)
if self.short_name:
_WriteSimpleXMLElement(outfile, 'short_name', self.short_name,
inner_indent)
if self.help:
_WriteSimpleXMLElement(outfile, 'meaning', self.help, inner_indent)
# The default flag value can either be represented as a string like on the
# command line, or as a Python object. We serialize this value in the
# latter case in order to remain consistent.
if self.serializer and not isinstance(self.default, str):
default_serialized = self.serializer.Serialize(self.default)
else:
default_serialized = self.default
_WriteSimpleXMLElement(outfile, 'default', default_serialized, inner_indent)
_WriteSimpleXMLElement(outfile, 'current', self.value, inner_indent)
_WriteSimpleXMLElement(outfile, 'type', self.Type(), inner_indent)
# Print extra flag features this flag may have.
self._WriteCustomInfoInXMLFormat(outfile, inner_indent)
outfile.write(indent + '</flag>\n')
def _WriteCustomInfoInXMLFormat(self, outfile, indent):
"""Writes extra info about this flag, in XML format.
"Extra" means "not already printed by WriteInfoInXMLFormat above."
Args:
outfile: File object we write to.
indent: A string that is prepended to each generated line.
"""
# Usually, the parser knows the extra details about the flag, so
# we just forward the call to it.
self.parser.WriteCustomInfoInXMLFormat(outfile, indent)
# End of Flag definition
class _ArgumentParserCache(type):
"""Metaclass used to cache and share argument parsers among flags."""
_instances = {}
def __call__(mcs, *args, **kwargs):
"""Returns an instance of the argument parser cls.
This method overrides behavior of the __new__ methods in
all subclasses of ArgumentParser (inclusive). If an instance
for mcs with the same set of arguments exists, this instance is
returned, otherwise a new instance is created.
If any keyword arguments are defined, or the values in args
are not hashable, this method always returns a new instance of
cls.
Args:
args: Positional initializer arguments.
kwargs: Initializer keyword arguments.
Returns:
An instance of cls, shared or new.
"""
if kwargs:
return type.__call__(mcs, *args, **kwargs)
else:
instances = mcs._instances
key = (mcs,) + tuple(args)
try:
return instances[key]
except KeyError:
# No cache entry for key exists, create a new one.
return instances.setdefault(key, type.__call__(mcs, *args))
except TypeError:
# An object in args cannot be hashed, always return
# a new instance.
return type.__call__(mcs, *args)
class ArgumentParser(object):
"""Base class used to parse and convert arguments.
The Parse() method checks to make sure that the string argument is a
legal value and convert it to a native type. If the value cannot be
converted, it should throw a 'ValueError' exception with a human
readable explanation of why the value is illegal.
Subclasses should also define a syntactic_help string which may be
presented to the user to describe the form of the legal values.
Argument parser classes must be stateless, since instances are cached
and shared between flags. Initializer arguments are allowed, but all
member variables must be derived from initializer arguments only.
"""
__metaclass__ = _ArgumentParserCache
syntactic_help = ""
def Parse(self, argument):
"""Default implementation: always returns its argument unmodified."""
return argument
def Type(self):
return 'string'
def WriteCustomInfoInXMLFormat(self, outfile, indent):
pass
class ArgumentSerializer:
"""Base class for generating string representations of a flag value."""
def Serialize(self, value):
return _StrOrUnicode(value)
class ListSerializer(ArgumentSerializer):
def __init__(self, list_sep):
self.list_sep = list_sep
def Serialize(self, value):
return self.list_sep.join([_StrOrUnicode(x) for x in value])
# Flags validators
def RegisterValidator(flag_name,
checker,
message='Flag validation failed',
flag_values=FLAGS):
"""Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
Args:
flag_name: string, name of the flag to be checked.
checker: method to validate the flag.
input - value of the corresponding flag (string, boolean, etc.
This value will be passed to checker by the library). See file's
docstring for examples.
output - Boolean.
Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise gflags_validators.Error(desired_error_message).
message: error text to be shown to the user if checker returns False.
If checker raises gflags_validators.Error, message from the raised
Error will be shown.
flag_values: FlagValues
Raises:
AttributeError: if flag_name is not registered as a valid flag name.
"""
flag_values.AddValidator(gflags_validators.SimpleValidator(flag_name,
checker,
message))
def MarkFlagAsRequired(flag_name, flag_values=FLAGS):
"""Ensure that flag is not None during program execution.
Registers a flag validator, which will follow usual validator
rules.
Args:
flag_name: string, name of the flag
flag_values: FlagValues
Raises:
AttributeError: if flag_name is not registered as a valid flag name.
"""
RegisterValidator(flag_name,
lambda value: value is not None,
message='Flag --%s must be specified.' % flag_name,
flag_values=flag_values)
def _RegisterBoundsValidatorIfNeeded(parser, name, flag_values):
"""Enforce lower and upper bounds for numeric flags.
Args:
parser: NumericParser (either FloatParser or IntegerParser). Provides lower
and upper bounds, and help text to display.
name: string, name of the flag
flag_values: FlagValues
"""
if parser.lower_bound is not None or parser.upper_bound is not None:
def Checker(value):
if value is not None and parser.IsOutsideBounds(value):
message = '%s is not %s' % (value, parser.syntactic_help)
raise gflags_validators.Error(message)
return True
RegisterValidator(name,
Checker,
flag_values=flag_values)
# The DEFINE functions are explained in mode details in the module doc string.
def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None,
**args):
"""Registers a generic Flag object.
NOTE: in the docstrings of all DEFINE* functions, "registers" is short
for "creates a new flag and registers it".
Auxiliary function: clients should use the specialized DEFINE_<type>
function instead.
Args:
parser: ArgumentParser that is used to parse the flag arguments.
name: A string, the flag name.
default: The default value of the flag.
help: A help string.
flag_values: FlagValues object the flag will be registered with.
serializer: ArgumentSerializer that serializes the flag value.
args: Dictionary with extra keyword args that are passes to the
Flag __init__.
"""
DEFINE_flag(Flag(parser, serializer, name, default, help, **args),
flag_values)
def DEFINE_flag(flag, flag_values=FLAGS):
"""Registers a 'Flag' object with a 'FlagValues' object.
By default, the global FLAGS 'FlagValue' object is used.
Typical users will use one of the more specialized DEFINE_xxx
functions, such as DEFINE_string or DEFINE_integer. But developers
who need to create Flag objects themselves should use this function
to register their flags.
"""
# copying the reference to flag_values prevents pychecker warnings
fv = flag_values
fv[flag.name] = flag
# Tell flag_values who's defining the flag.
if isinstance(flag_values, FlagValues):
# Regarding the above isinstance test: some users pass funny
# values of flag_values (e.g., {}) in order to avoid the flag
# registration (in the past, there used to be a flag_values ==
# FLAGS test here) and redefine flags with the same name (e.g.,
# debug). To avoid breaking their code, we perform the
# registration only if flag_values is a real FlagValues object.
module, module_name = _GetCallingModuleObjectAndName()
flag_values._RegisterFlagByModule(module_name, flag)
flag_values._RegisterFlagByModuleId(id(module), flag)
def _InternalDeclareKeyFlags(flag_names,
flag_values=FLAGS, key_flag_values=None):
"""Declares a flag as key for the calling module.
Internal function. User code should call DECLARE_key_flag or
ADOPT_module_key_flags instead.
Args:
flag_names: A list of strings that are names of already-registered
Flag objects.
flag_values: A FlagValues object that the flags listed in
flag_names have registered with (the value of the flag_values
argument from the DEFINE_* calls that defined those flags).
This should almost never need to be overridden.
key_flag_values: A FlagValues object that (among possibly many
other things) keeps track of the key flags for each module.
Default None means "same as flag_values". This should almost
never need to be overridden.
Raises:
UnrecognizedFlagError: when we refer to a flag that was not
defined yet.
"""
key_flag_values = key_flag_values or flag_values
module = _GetCallingModule()
for flag_name in flag_names:
if flag_name not in flag_values:
raise UnrecognizedFlagError(flag_name)
flag = flag_values.FlagDict()[flag_name]
key_flag_values._RegisterKeyFlagForModule(module, flag)
def DECLARE_key_flag(flag_name, flag_values=FLAGS):
"""Declares one flag as key to the current module.
Key flags are flags that are deemed really important for a module.
They are important when listing help messages; e.g., if the
--helpshort command-line flag is used, then only the key flags of the
main module are listed (instead of all flags, as in the case of
--help).
Sample usage:
gflags.DECLARED_key_flag('flag_1')
Args:
flag_name: A string, the name of an already declared flag.
(Redeclaring flags as key, including flags implicitly key
because they were declared in this module, is a no-op.)
flag_values: A FlagValues object. This should almost never
need to be overridden.
"""
if flag_name in _SPECIAL_FLAGS:
# Take care of the special flags, e.g., --flagfile, --undefok.
# These flags are defined in _SPECIAL_FLAGS, and are treated
# specially during flag parsing, taking precedence over the
# user-defined flags.
_InternalDeclareKeyFlags([flag_name],
flag_values=_SPECIAL_FLAGS,
key_flag_values=flag_values)
return
_InternalDeclareKeyFlags([flag_name], flag_values=flag_values)
def ADOPT_module_key_flags(module, flag_values=FLAGS):
"""Declares that all flags key to a module are key to the current module.
Args:
module: A module object.
flag_values: A FlagValues object. This should almost never need
to be overridden.
Raises:
FlagsError: When given an argument that is a module name (a
string), instead of a module object.
"""
# NOTE(salcianu): an even better test would be if not
# isinstance(module, types.ModuleType) but I didn't want to import
# types for such a tiny use.
if isinstance(module, str):
raise FlagsError('Received module name %s; expected a module object.'
% module)
_InternalDeclareKeyFlags(
[f.name for f in flag_values._GetKeyFlagsForModule(module.__name__)],
flag_values=flag_values)
# If module is this flag module, take _SPECIAL_FLAGS into account.
if module == _GetThisModuleObjectAndName()[0]:
_InternalDeclareKeyFlags(
# As we associate flags with _GetCallingModuleObjectAndName(), the
# special flags defined in this module are incorrectly registered with
# a different module. So, we can't use _GetKeyFlagsForModule.
# Instead, we take all flags from _SPECIAL_FLAGS (a private
# FlagValues, where no other module should register flags).
[f.name for f in _SPECIAL_FLAGS.FlagDict().values()],
flag_values=_SPECIAL_FLAGS,
key_flag_values=flag_values)
#
# STRING FLAGS
#
def DEFINE_string(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value can be any string."""
parser = ArgumentParser()
serializer = ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
#
# BOOLEAN FLAGS
#
class BooleanParser(ArgumentParser):
"""Parser of boolean values."""
def Convert(self, argument):
"""Converts the argument to a boolean; raise ValueError on errors."""
if type(argument) == str:
if argument.lower() in ['true', 't', '1']:
return True
elif argument.lower() in ['false', 'f', '0']:
return False
bool_argument = bool(argument)
if argument == bool_argument:
# The argument is a valid boolean (True, False, 0, or 1), and not just
# something that always converts to bool (list, string, int, etc.).
return bool_argument
raise ValueError('Non-boolean argument to boolean flag', argument)
def Parse(self, argument):
val = self.Convert(argument)
return val
def Type(self):
return 'bool'
class BooleanFlag(Flag):
"""Basic boolean flag.
Boolean flags do not take any arguments, and their value is either
True (1) or False (0). The false value is specified on the command
line by prepending the word 'no' to either the long or the short flag
name.
For example, if a Boolean flag was created whose long name was
'update' and whose short name was 'x', then this flag could be
explicitly unset through either --noupdate or --nox.
"""
def __init__(self, name, default, help, short_name=None, **args):
p = BooleanParser()
Flag.__init__(self, p, None, name, default, help, short_name, 1, **args)
if not self.help: self.help = "a boolean value"
def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args):
"""Registers a boolean flag.
Such a boolean flag does not take an argument. If a user wants to
specify a false value explicitly, the long option beginning with 'no'
must be used: i.e. --noflag
This flag will have a value of None, True or False. None is possible
if default=None and the user does not specify the flag on the command
line.
"""
DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values)
# Match C++ API to unconfuse C++ people.
DEFINE_bool = DEFINE_boolean
class HelpFlag(BooleanFlag):
"""
HelpFlag is a special boolean flag that prints usage information and
raises a SystemExit exception if it is ever found in the command
line arguments. Note this is called with allow_override=1, so other
apps can define their own --help flag, replacing this one, if they want.
"""
def __init__(self):
BooleanFlag.__init__(self, "help", 0, "show this help",
short_name="?", allow_override=1)
def Parse(self, arg):
if arg:
doc = sys.modules["__main__"].__doc__
flags = str(FLAGS)
print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0])
if flags:
print "flags:"
print flags
sys.exit(1)
class HelpXMLFlag(BooleanFlag):
"""Similar to HelpFlag, but generates output in XML format."""
def __init__(self):
BooleanFlag.__init__(self, 'helpxml', False,
'like --help, but generates XML output',
allow_override=1)
def Parse(self, arg):
if arg:
FLAGS.WriteHelpInXMLFormat(sys.stdout)
sys.exit(1)
class HelpshortFlag(BooleanFlag):
"""
HelpshortFlag is a special boolean flag that prints usage
information for the "main" module, and rasies a SystemExit exception
if it is ever found in the command line arguments. Note this is
called with allow_override=1, so other apps can define their own
--helpshort flag, replacing this one, if they want.
"""
def __init__(self):
BooleanFlag.__init__(self, "helpshort", 0,
"show usage only for this module", allow_override=1)
def Parse(self, arg):
if arg:
doc = sys.modules["__main__"].__doc__
flags = FLAGS.MainModuleHelp()
print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0])
if flags:
print "flags:"
print flags
sys.exit(1)
#
# Numeric parser - base class for Integer and Float parsers
#
class NumericParser(ArgumentParser):
"""Parser of numeric values.
Parsed value may be bounded to a given upper and lower bound.
"""
def IsOutsideBounds(self, val):
return ((self.lower_bound is not None and val < self.lower_bound) or
(self.upper_bound is not None and val > self.upper_bound))
def Parse(self, argument):
val = self.Convert(argument)
if self.IsOutsideBounds(val):
raise ValueError("%s is not %s" % (val, self.syntactic_help))
return val
def WriteCustomInfoInXMLFormat(self, outfile, indent):
if self.lower_bound is not None:
_WriteSimpleXMLElement(outfile, 'lower_bound', self.lower_bound, indent)
if self.upper_bound is not None:
_WriteSimpleXMLElement(outfile, 'upper_bound', self.upper_bound, indent)
def Convert(self, argument):
"""Default implementation: always returns its argument unmodified."""
return argument
# End of Numeric Parser
#
# FLOAT FLAGS
#
class FloatParser(NumericParser):
"""Parser of floating point values.
Parsed value may be bounded to a given upper and lower bound.
"""
number_article = "a"
number_name = "number"
syntactic_help = " ".join((number_article, number_name))
def __init__(self, lower_bound=None, upper_bound=None):
super(FloatParser, self).__init__()
self.lower_bound = lower_bound
self.upper_bound = upper_bound
sh = self.syntactic_help
if lower_bound is not None and upper_bound is not None:
sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound))
elif lower_bound == 0:
sh = "a non-negative %s" % self.number_name
elif upper_bound == 0:
sh = "a non-positive %s" % self.number_name
elif upper_bound is not None:
sh = "%s <= %s" % (self.number_name, upper_bound)
elif lower_bound is not None:
sh = "%s >= %s" % (self.number_name, lower_bound)
self.syntactic_help = sh
def Convert(self, argument):
"""Converts argument to a float; raises ValueError on errors."""
return float(argument)
def Type(self):
return 'float'
# End of FloatParser
def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value must be a float.
If lower_bound or upper_bound are set, then this flag must be
within the given range.
"""
parser = FloatParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
_RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values)
#
# INTEGER FLAGS
#
class IntegerParser(NumericParser):
"""Parser of an integer value.
Parsed value may be bounded to a given upper and lower bound.
"""
number_article = "an"
number_name = "integer"
syntactic_help = " ".join((number_article, number_name))
def __init__(self, lower_bound=None, upper_bound=None):
super(IntegerParser, self).__init__()
self.lower_bound = lower_bound
self.upper_bound = upper_bound
sh = self.syntactic_help
if lower_bound is not None and upper_bound is not None:
sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound))
elif lower_bound == 1:
sh = "a positive %s" % self.number_name
elif upper_bound == -1:
sh = "a negative %s" % self.number_name
elif lower_bound == 0:
sh = "a non-negative %s" % self.number_name
elif upper_bound == 0:
sh = "a non-positive %s" % self.number_name
elif upper_bound is not None:
sh = "%s <= %s" % (self.number_name, upper_bound)
elif lower_bound is not None:
sh = "%s >= %s" % (self.number_name, lower_bound)
self.syntactic_help = sh
def Convert(self, argument):
__pychecker__ = 'no-returnvalues'
if type(argument) == str:
base = 10
if len(argument) > 2 and argument[0] == "0" and argument[1] == "x":
base = 16
return int(argument, base)
else:
return int(argument)
def Type(self):
return 'int'
def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value must be an integer.
If lower_bound, or upper_bound are set, then this flag must be
within the given range.
"""
parser = IntegerParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
_RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values)
#
# ENUM FLAGS
#
class EnumParser(ArgumentParser):
"""Parser of a string enum value (a string value from a given set).
If enum_values (see below) is not specified, any string is allowed.
"""
def __init__(self, enum_values=None):
super(EnumParser, self).__init__()
self.enum_values = enum_values
def Parse(self, argument):
if self.enum_values and argument not in self.enum_values:
raise ValueError("value should be one of <%s>" %
"|".join(self.enum_values))
return argument
def Type(self):
return 'string enum'
class EnumFlag(Flag):
"""Basic enum flag; its value can be any string from list of enum_values."""
def __init__(self, name, default, help, enum_values=None,
short_name=None, **args):
enum_values = enum_values or []
p = EnumParser(enum_values)
g = ArgumentSerializer()
Flag.__init__(self, p, g, name, default, help, short_name, **args)
if not self.help: self.help = "an enum string"
self.help = "<%s>: %s" % ("|".join(enum_values), self.help)
def _WriteCustomInfoInXMLFormat(self, outfile, indent):
for enum_value in self.parser.enum_values:
_WriteSimpleXMLElement(outfile, 'enum_value', enum_value, indent)
def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS,
**args):
"""Registers a flag whose value can be any string from enum_values."""
DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args),
flag_values)
#
# LIST FLAGS
#
class BaseListParser(ArgumentParser):
"""Base class for a parser of lists of strings.
To extend, inherit from this class; from the subclass __init__, call
BaseListParser.__init__(self, token, name)
where token is a character used to tokenize, and name is a description
of the separator.
"""
def __init__(self, token=None, name=None):
assert name
super(BaseListParser, self).__init__()
self._token = token
self._name = name
self.syntactic_help = "a %s separated list" % self._name
def Parse(self, argument):
if isinstance(argument, list):
return argument
elif argument == '':
return []
else:
return [s.strip() for s in argument.split(self._token)]
def Type(self):
return '%s separated list of strings' % self._name
class ListParser(BaseListParser):
"""Parser for a comma-separated list of strings."""
def __init__(self):
BaseListParser.__init__(self, ',', 'comma')
def WriteCustomInfoInXMLFormat(self, outfile, indent):
BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent)
_WriteSimpleXMLElement(outfile, 'list_separator', repr(','), indent)
class WhitespaceSeparatedListParser(BaseListParser):
"""Parser for a whitespace-separated list of strings."""
def __init__(self):
BaseListParser.__init__(self, None, 'whitespace')
def WriteCustomInfoInXMLFormat(self, outfile, indent):
BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent)
separators = list(string.whitespace)
separators.sort()
for ws_char in string.whitespace:
_WriteSimpleXMLElement(outfile, 'list_separator', repr(ws_char), indent)
def DEFINE_list(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value is a comma-separated list of strings."""
parser = ListParser()
serializer = ListSerializer(',')
DEFINE(parser, name, default, help, flag_values, serializer, **args)
def DEFINE_spaceseplist(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value is a whitespace-separated list of strings.
Any whitespace can be used as a separator.
"""
parser = WhitespaceSeparatedListParser()
serializer = ListSerializer(' ')
DEFINE(parser, name, default, help, flag_values, serializer, **args)
#
# MULTI FLAGS
#
class MultiFlag(Flag):
"""A flag that can appear multiple time on the command-line.
The value of such a flag is a list that contains the individual values
from all the appearances of that flag on the command-line.
See the __doc__ for Flag for most behavior of this class. Only
differences in behavior are described here:
* The default value may be either a single value or a list of values.
A single value is interpreted as the [value] singleton list.
* The value of the flag is always a list, even if the option was
only supplied once, and even if the default value is a single
value
"""
def __init__(self, *args, **kwargs):
Flag.__init__(self, *args, **kwargs)
self.help += ';\n repeat this option to specify a list of values'
def Parse(self, arguments):
"""Parses one or more arguments with the installed parser.
Args:
arguments: a single argument or a list of arguments (typically a
list of default values); a single argument is converted
internally into a list containing one item.
"""
if not isinstance(arguments, list):
# Default value may be a list of values. Most other arguments
# will not be, so convert them into a single-item list to make
# processing simpler below.
arguments = [arguments]
if self.present:
# keep a backup reference to list of previously supplied option values
values = self.value
else:
# "erase" the defaults with an empty list
values = []
for item in arguments:
# have Flag superclass parse argument, overwriting self.value reference
Flag.Parse(self, item) # also increments self.present
values.append(self.value)
# put list of option values back in the 'value' attribute
self.value = values
def Serialize(self):
if not self.serializer:
raise FlagsError("Serializer not present for flag %s" % self.name)
if self.value is None:
return ''
s = ''
multi_value = self.value
for self.value in multi_value:
if s: s += ' '
s += Flag.Serialize(self)
self.value = multi_value
return s
def Type(self):
return 'multi ' + self.parser.Type()
def DEFINE_multi(parser, serializer, name, default, help, flag_values=FLAGS,
**args):
"""Registers a generic MultiFlag that parses its args with a given parser.
Auxiliary function. Normal users should NOT use it directly.
Developers who need to create their own 'Parser' classes for options
which can appear multiple times can call this module function to
register their flags.
"""
DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args),
flag_values)
def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of any strings.
Use the flag on the command line multiple times to place multiple
string values into the list. The 'default' may be a single string
(which will be converted into a single-element list) or a list of
strings.
"""
parser = ArgumentParser()
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of arbitrary integers.
Use the flag on the command line multiple times to place multiple
integer values into the list. The 'default' may be a single integer
(which will be converted into a single-element list) or a list of
integers.
"""
parser = IntegerParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
def DEFINE_multi_float(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of arbitrary floats.
Use the flag on the command line multiple times to place multiple
float values into the list. The 'default' may be a single float
(which will be converted into a single-element list) or a list of
floats.
"""
parser = FloatParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
# Now register the flags that we want to exist in all applications.
# These are all defined with allow_override=1, so user-apps can use
# these flagnames for their own purposes, if they want.
DEFINE_flag(HelpFlag())
DEFINE_flag(HelpshortFlag())
DEFINE_flag(HelpXMLFlag())
# Define special flags here so that help may be generated for them.
# NOTE: Please do NOT use _SPECIAL_FLAGS from outside this module.
_SPECIAL_FLAGS = FlagValues()
DEFINE_string(
'flagfile', "",
"Insert flag definitions from the given file into the command line.",
_SPECIAL_FLAGS)
DEFINE_string(
'undefok', "",
"comma-separated list of flag names that it is okay to specify "
"on the command line even if the program does not define a flag "
"with that name. IMPORTANT: flags in this list that have "
"arguments MUST use the --flag=value format.", _SPECIAL_FLAGS)
| Python |
# Para hacer el ejecutable:
# python setup.py py2exe
#
"Creador de instalador para PyAfipWs (WSMTXCA)"
__author__ = "Mariano Reingart (mariano@nsis.com.ar)"
__copyright__ = "Copyright (C) 2010 Mariano Reingart"
from distutils.core import setup
import py2exe
import glob, sys
# includes for py2exe
includes=['email.generator', 'email.iterators', 'email.message', 'email.utils']
# don't pull in all this MFC stuff used by the makepy UI.
excludes=["pywin", "pywin.dialogs", "pywin.dialogs.list", "win32ui"]
opts = {
'py2exe': {
'includes':includes,
'optimize':2,
'excludes': excludes,
}}
data_files = [
(".", ["wsfev1_wsdl.xml","wsfev1_wsdl_homo.xml", "licencia.txt", "rece.ini.dist"]),
("cache", glob.glob("cache/*")),
]
import wsfev1
from nsis import build_installer
setup(
name="WSFEV1",
version=wsfev1.__version__ + (wsfev1.HOMO and '-homo' or '-full'),
description="Interfaz PyAfipWs WSFEv1 %s",
long_description=wsfev1.__doc__,
author="Mariano Reingart",
author_email="reingart@gmail.com",
url="http://www.sistemasagiles.com.ar",
license="GNU GPL v3",
com_server = ["wsfev1"],
console=['wsfev1.py', 'rece1.py', 'wsaa.py'],
options=opts,
data_files = data_files,
cmdclass = {"py2exe": build_installer}
)
| Python |
# Para hacer el ejecutable:
# python setup.py py2exe
#
"""
__version__ = "$Revision: 1.3 $"
__date__ = "$Date: 2005/04/05 18:44:54 $"
"""
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2008 Mariano Reingart"
from distutils.core import setup
import py2exe
import sys
if sys.platform == 'darwin':
import py2app
buildstyle = 'app'
else:
import py2exe
buildstyle = 'windows'
# find pythoncard resources, to add as 'data_files'
import os
pycard_resources=[]
for filename in os.listdir('.'):
if filename.find('.rsrc.')>-1:
pycard_resources+=[filename]
# includes for py2exe
includes=[]
for comp in ['button','image','staticbox','radiogroup', 'imagebutton',
'statictext','textarea','textfield','passwordfield', 'checkbox',
'tree','multicolumnlist','list','gauge','choice',
]:
includes += ['PythonCard.components.'+comp]
print 'includes',includes
includes+=['email.generator', 'email.iterators', 'email.message', 'email.utils']
opts = {
'py2exe': {
'includes':includes,
'optimize':2}
}
import pyrece
from nsis import build_installer
class Target():
def __init__(self, **kw):
self.__dict__.update(kw)
# for the version info resources (Properties -- Version)
# convertir 1.21a en 1.21.1
self.version = pyrece.__version__[:-1]+"."+str(ord(pyrece.__version__[-1])-96)
self.description = pyrece.__doc__
self.company_name = "Sistemas Agiles"
self.copyright = pyrece.__copyright__
self.name = pyrece.__doc__
import glob
data_files = [
(".", ["wsfev1_wsdl.xml","wsfev1_wsdl_homo.xml", "licencia.txt",
"C:\python25\lib\site-packages\wx-2.8-msw-unicode\wx\MSVCP71.dll",
"C:\python25\lib\site-packages\wx-2.8-msw-unicode\wx\gdiplus.dll",
"logo.png",
"rece.ini.dist", "factura.csv", "homo/facturas.csv"]),
("cache", glob.glob("cache/*")),
]
setup( name = "PyRece",
version=pyrece.__version__ + (pyrece.HOMO and '-homo' or '-full'),
description="PyRece %s" % pyrece.__version__,
long_description=pyrece.__doc__,
author="Mariano Reingart",
author_email="reingart@gmail.com",
url="http://www.sistemasagiles.com.ar",
license="GNU GPL v3",
data_files = [ (".", pycard_resources),
(".",["logo.png",]) ] + data_files,
options=opts,
cmdclass = {"py2exe": build_installer},
**{buildstyle: [Target(script='pyrece.py')],
'console': [Target(script="pyrece.py", dest_base="pyrece_consola")]
}
)
| Python |
# Para hacer el ejecutable:
# python setup.py py2exe
#
"Creador de instalador para PyAfipWs (WSAA)"
__author__ = "Mariano Reingart (mariano@nsis.com.ar)"
__copyright__ = "Copyright (C) 2011 Mariano Reingart"
from distutils.core import setup
import py2exe
import glob, sys
# includes for py2exe
includes=['email.generator', 'email.iterators', 'email.message', 'email.utils']
# don't pull in all this MFC stuff used by the makepy UI.
excludes=["pywin", "pywin.dialogs", "pywin.dialogs.list", "win32ui"]
opts = {
'py2exe': {
'includes':includes,
'optimize':2,
'excludes': excludes,
}}
data_files = [
(".", ["licencia.txt"]),
("cache", glob.glob("cache/*")),
]
import wsaa
from nsis import build_installer
setup(
name="WSAA",
version=wsaa.__version__ + (wsaa.HOMO and '-homo' or '-full'),
description="Interfaz PyAfipWs WSAA %s",
long_description=wsaa.__doc__,
author="Mariano Reingart",
author_email="reingart@gmail.com",
url="http://www.sistemasagiles.com.ar",
license="GNU GPL v3",
com_server = ["wsaa"],
console=['wsaa.py'],
options=opts,
data_files = data_files,
cmdclass = {"py2exe": build_installer}
)
| Python |
# Para hacer el ejecutable:
# python setup.py py2exe
#
"Creador de instalador para PyAfipWs"
__author__ = "Mariano Reingart (mariano@nsis.com.ar)"
__copyright__ = "Copyright (C) 2008 Mariano Reingart"
from distutils.core import setup
import py2exe
import sys
# includes for py2exe
includes=['email.generator', 'email.iterators', 'email.message', 'email.utils']
opts = {
'py2exe': {
'includes':includes,
'optimize':2}
}
setup( name = "PyAfipWs",
com_server = ["pyafipws"],
console=['rece.py', 'receb.py', 'recex.py', 'rg1361.py', 'wsaa.py', 'wsfex.py', 'wsbfe.py'],
options=opts,
)
| Python |
#!/usr/bin/python
# -*- coding: latin-1 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
"Py2Exe extension to build NSIS Installers"
# Based on py2exe/samples/extending/setup.py:
# "A setup script showing how to extend py2exe."
# Copyright (c) 2000-2008 Thomas Heller, Mark Hammond, Jimmy Retzlaff
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2011 Mariano Reingart"
__license__ = "GPL 3.0"
import os
import sys
from py2exe.build_exe import py2exe
nsi_base_script = """\
; base.nsi
; WARNING: This script has been created by py2exe. Changes to this script
; will be overwritten the next time py2exe is run!
XPStyle on
Page license
Page directory
;Page components
Page instfiles
RequestExecutionLevel admin
LoadLanguageFile "${NSISDIR}\Contrib\Language files\English.nlf"
LoadLanguageFile "${NSISDIR}\Contrib\Language files\Spanish.nlf"
# set license page
LicenseText ""
LicenseData "licencia.txt"
LicenseForceSelection checkbox
; use the default string for the directory page.
DirText ""
Name "%(description)s"
OutFile "%(out_file)s"
;SetCompress off ; disable compression (testing)
SetCompressor /SOLID lzma
;InstallDir %(install_dir)s
InstallDir $PROGRAMFILES\%(install_dir)s
InstallDirRegKey HKLM "Software\%(reg_key)s" "Install_Dir"
VIProductVersion "%(product_version)s"
VIAddVersionKey /LANG=${LANG_ENGLISH} "ProductName" "%(name)s"
VIAddVersionKey /LANG=${LANG_ENGLISH} "FileDescription" "%(description)s"
VIAddVersionKey /LANG=${LANG_ENGLISH} "CompanyName" "%(company_name)s"
VIAddVersionKey /LANG=${LANG_ENGLISH} "FileVersion" "%(product_version)s"
VIAddVersionKey /LANG=${LANG_ENGLISH} "LegalCopyright" "%(copyright)s"
;VIAddVersionKey /LANG=${LANG_ENGLISH} "InternalName" "FileSetup.exe"
Section %(name)s
; uninstall old version
ReadRegStr $R0 HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\%(reg_key)s" "UninstallString"
StrCmp $R0 "" notistalled
ExecWait '$R0 /S _?=$INSTDIR'
notistalled:
SectionIn RO
SetOutPath $INSTDIR
File /r dist\*.*
IfFileExists $INSTDIR\\rece.ini.dist 0 +3
IfFileExists $INSTDIR\\rece.ini +2 0
CopyFiles $INSTDIR\\rece.ini.dist $INSTDIR\\rece.ini
WriteRegStr HKLM SOFTWARE\%(reg_key)s "Install_Dir" "$INSTDIR"
; Write the uninstall keys for Windows
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\%(reg_key)s" "DisplayName" "%(description)s (solo eliminar)"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\%(reg_key)s" "UninstallString" "$INSTDIR\Uninst.exe"
WriteUninstaller "Uninst.exe"
;To Register a DLL
%(register_com_servers)s
SectionEnd
Section "Uninstall"
;To Unregister a DLL
%(unregister_com_servers)s
;Delete Files
;Delete Uninstaller And Unistall Registry Entries
Delete "$INSTDIR\Uninst.exe"
DeleteRegKey HKEY_LOCAL_MACHINE "SOFTWARE\%(reg_key)s"
DeleteRegKey HKEY_LOCAL_MACHINE "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\%(reg_key)s"
RMDir "$INSTDIR"
SectionEnd
;--------------------------------
Function .onInit
IfSilent nolangdialog
;Language selection dialog
Push ""
Push ${LANG_ENGLISH}
Push English
Push ${LANG_SPANISH}
Push Spanish
Push A ; A means auto count languages
; for the auto count to work the first empty push (Push "") must remain
LangDLL::LangDialog "Installer Language" "Please select the language of the installer"
Pop $LANGUAGE
StrCmp $LANGUAGE "cancel" 0 +2
Abort
nolangdialog:
FunctionEnd
"""
register_com_server = """\
RegDLL "$INSTDIR\%s"
"""
unregister_com_server= """\
UnRegDLL "$INSTDIR\%s"
"""
class build_installer(py2exe):
# This class first builds the exe file(s), then creates a Windows installer.
# You need NSIS (Nullsoft Scriptable Install System) for it.
def run(self):
# Clean up
os.system("del /S /Q dist")
# First, let py2exe do it's work.
py2exe.run(self)
lib_dir = self.lib_dir
dist_dir = self.dist_dir
comserver_files = self.comserver_files
metadata = self.distribution.metadata
# create the Installer, using the files py2exe has created.
script = NSISScript(metadata,
lib_dir,
dist_dir,
self.windows_exe_files,
self.lib_files,
comserver_files)
print "*** creating the nsis script***"
script.create()
print "*** compiling the nsis script***"
script.compile()
# Note: By default the final setup.exe will be in an Output subdirectory.
class NSISScript:
def __init__(self,
metadata,
lib_dir,
dist_dir,
windows_exe_files = [],
lib_files = [],
comserver_files = []):
self.lib_dir = lib_dir
self.dist_dir = dist_dir
if not self.dist_dir[-1] in "\\/":
self.dist_dir += "\\"
self.name = metadata.get_name()
self.description = metadata.get_name()
self.version = metadata.get_version()
self.copyright = metadata.get_author()
self.url = metadata.get_url()
self.windows_exe_files = [self.chop(p) for p in windows_exe_files]
self.lib_files = [self.chop(p) for p in lib_files]
self.comserver_files = [self.chop(p) for p in comserver_files if p.lower().endswith(".dll")]
def chop(self, pathname):
assert pathname.startswith(self.dist_dir)
return pathname[len(self.dist_dir):]
def create(self, pathname="base.nsi"):
self.pathname = pathname
ofi = self.file = open(pathname, "w")
ver = self.version
if "-" in ver:
ver = ver[:ver.index("-")]
rev = self.version.endswith("-full") and ".1" or ".0"
ver= [c in '0123456789.' and c or ".%s" % (ord(c)-96) for c in ver]+[rev]
ofi.write(nsi_base_script % {
'name': self.name,
'description': "%s version %s" % (self.description, self.version),
'product_version': ''.join(ver),
'company_name': self.url,
'copyright': self.copyright,
'install_dir': self.name,
'reg_key': self.name,
'out_file': "instalador-%s-%s.exe" % (self.name, self.version),
'register_com_servers': ''.join([register_com_server % comserver for comserver in self.comserver_files]),
'unregister_com_servers': ''.join([unregister_com_server % comserver for comserver in self.comserver_files]),
})
def compile(self, pathname="base.nsi"):
os.startfile(pathname, 'compile') | Python |
import wsaa
import os,sys
from subprocess import Popen, PIPE
from base64 import b64encode
def sign_tra(tra,cert,privatekey):
"Firmar PKCS#7 el TRA y devolver CMS (recortando los headers SMIME)"
# Firmar el texto (tra)
out = Popen(["openssl", "smime", "-sign",
"-signer", cert, "-inkey", privatekey,
"-outform","DER",
"-out", "cms.bin" , "-nodetach"],
stdin=PIPE,stdout=PIPE).communicate(tra)[0]
out = open("cms.bin","rb").read()
return b64encode(out)
tra = wsaa.create_tra("wsfex")
print tra
cms = sign_tra(tra,"reingart.crt","reingart.key")
print cms
open("tra.cms","w").write(cms)
ta = wsaa.call_wsaa(cms)
print ta
open("TA.xml","w").write(ta)
| Python |
# Para hacer el ejecutable:
# python setup.py py2exe
#
"Creador de instalador para PyAfipWs (WSMTXCA)"
__author__ = "Mariano Reingart (mariano@nsis.com.ar)"
__copyright__ = "Copyright (C) 2010 Mariano Reingart"
from distutils.core import setup
import py2exe
import glob, sys
# includes for py2exe
includes=['email.generator', 'email.iterators', 'email.message', 'email.utils']
# don't pull in all this MFC stuff used by the makepy UI.
excludes=["pywin", "pywin.dialogs", "pywin.dialogs.list", "win32ui"]
opts = {
'py2exe': {
'includes':includes,
'optimize':2,
'excludes': excludes,
}}
import wsmtx
from nsis import build_installer
data_files = [
(".", ["wsfev1_wsdl.xml","wsfev1_wsdl_homo.xml", "licencia.txt", 'rece.ini.dist']),
("cache", glob.glob("cache/*")),
]
setup( name = "WSMTXCA",
version=wsmtx.__version__ + (wsmtx.HOMO and '-homo' or '-full'),
description="Interfaz PyAfipWs WSMTXCA %s",
long_description=wsmtx.__doc__,
author="Mariano Reingart",
author_email="reingart@gmail.com",
url="http://www.sistemasagiles.com.ar",
license="GNU GPL v3",
com_server = ["wsmtx"],
console=['wsmtx.py', 'wsaa.py', 'recem.py'],
options=opts,
data_files = data_files,
cmdclass = {"py2exe": build_installer}
) | Python |
#!/usr/bin/python
# -*- coding: latin-1 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
"Manejo de XML simple"
__author__ = "Mariano Reingart (mariano@nsis.com.ar)"
__copyright__ = "Copyright (C) 2008/009 Mariano Reingart"
__license__ = "LGPL 3.0"
__version__ = "1.0"
import xml.dom.minidom
DEBUG = False
class SimpleXMLElement(object):
"Clase para Manejo simple de XMLs (simil PHP)"
def __init__(self, text = None, elements = None, document = None, namespace = None, prefix=None):
self.__ns = namespace
self.__prefix = prefix
if text:
try:
self.__document = xml.dom.minidom.parseString(text)
except:
if DEBUG: print text
raise
self.__elements = [self.__document.documentElement]
else:
self.__elements = elements
self.__document = document
def addChild(self,tag,text=None,ns=True):
if not ns or not self.__ns:
if DEBUG: print "adding %s ns %s %s" % (tag, self.__ns,ns)
element = self.__document.createElement(tag)
else:
if DEBUG: print "adding %s ns %s %s" % (tag, self.__ns,ns)
element = self.__document.createElementNS(self.__ns, "%s:%s" % (self.__prefix, tag))
if text:
if isinstance(text, unicode):
element.appendChild(self.__document.createTextNode(text))
else:
element.appendChild(self.__document.createTextNode(str(text)))
self.__element.appendChild(element)
return SimpleXMLElement(
elements=[element],
document=self.__document,
namespace=self.__ns,
prefix=self.__prefix)
def asXML(self,filename=None):
return self.__document.toxml('UTF-8')
def __getattr__(self,tag):
try:
if self.__ns:
if DEBUG: print "searching %s by ns=%s" % (tag,self.__ns)
elements = self.__elements[0].getElementsByTagNameNS(self.__ns, tag)
if not self.__ns or not elements:
if DEBUG: print "searching %s " % (tag)
elements = self.__elements[0].getElementsByTagName(tag)
if not elements:
if DEBUG: print self.__elements[0].toxml()
raise AttributeError("Sin elementos")
return SimpleXMLElement(
elements=elements,
document=self.__document,
namespace=self.__ns,
prefix=self.__prefix)
except AttributeError, e:
raise AttributeError("Tag not found: %s (%s)" % (tag, str(e)))
def __iter__(self):
"Iterate over xml tags"
try:
for __element in self.__elements:
yield SimpleXMLElement(
elements=[__element],
document=self.__document,
namespace=self.__ns,
prefix=self.__prefix)
except:
raise
def __getitem__(self,item):
"Return xml attribute"
return getattr(self.__element, item)
def __contains__( self, item):
return self.__element.getElementsByTagName(item)
def __unicode__(self):
return self.__element.childNodes[0].data
def __str__(self):
if self.__element.childNodes:
rc = ""
for node in self.__element.childNodes:
if node.nodeType == node.TEXT_NODE:
rc = rc + node.data.encode("utf8","ignore")
return rc
return ''
def __repr__(self):
return repr(self.__str__())
def __int__(self):
return int(self.__str__())
def __float__(self):
try:
return float(self.__str__())
except:
raise IndexError(self.__element.toxml())
__element = property(lambda self: self.__elements[0])
if __name__ == "__main__":
span = SimpleXMLElement('<span><a href="google.com">google</a><prueba><i>1</i><float>1.5</float></prueba></span>')
print str(span.a)
print int(span.prueba.i)
print float(span.prueba.float)
span = SimpleXMLElement('<span><a href="google.com">google</a><a>yahoo</a><a>hotmail</a></span>')
for a in span.a:
print str(a)
span.addChild('a','altavista')
print span.asXML() | Python |
#!/usr/bin/env python
import sys
from PyQt4 import Qt
# We instantiate a QApplication passing the arguments of the script to it:
a = Qt.QApplication(sys.argv)
# Add a basic widget to this application:
# The first argument is the text we want this QWidget to show, the second
# one is the parent widget. Since Our "hello" is the only thing we use (the
# so-called "MainWidget", it does not have a parent.
hello = Qt.QLabel("Hello, World")
# ... and that it should be shown.
hello.show()
# Now we can start it.
a.exec_()
| Python |
#!/usr/bin/env python
import sys
from PyQt4 import Qt
a = Qt.QApplication(sys.argv)
# Our function to call when the button is clicked
def sayHello():
print "Hello, World!"
# Instantiate the button
hellobutton = Qt.QPushButton("Say 'Hello world!'",None)
# And connect the action "sayHello" to the event "button has been clicked"
a.connect(hellobutton, Qt.SIGNAL("clicked()"), sayHello)
# The rest is known already...
#a.setMainWidget(hellobutton)
hellobutton.show()
a.exec_()
| Python |
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
class HelloWorld:
def on_combo_changed(self, widget, data=None):
print self.combo.get_active_text()
def on_window_destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("destroy", self.on_window_destroy)
self.window.set_border_width(5)
self.combo = gtk.combo_box_new_text()
self.combo.append_text("GNU/Linux")
self.combo.append_text("Windows")
self.combo.append_text("Mac OS X")
self.combo.connect("changed", self.on_combo_changed)
self.window.add(self.combo)
self.window.show_all()
def main(self):
gtk.main()
if __name__ == "__main__":
hello = HelloWorld()
hello.main()
| Python |
#!/usr/bin/env python
import sys
from PyQt4 import Qt
# We instantiate a QApplication passing the arguments of the script to it:
a = Qt.QApplication(sys.argv)
# Add a basic widget to this application:
# The first argument is the text we want this QWidget to show, the second
# one is the parent widget. Since Our "hello" is the only thing we use (the
# so-called "MainWidget", it does not have a parent.
hello = Qt.QLabel("Hello, World")
# ... and that it should be shown.
hello.show()
# Now we can start it.
a.exec_()
| Python |
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
class HelloWorld:
def on_button_clicked(self, widget, data=None):
print "Hello World"
def on_window_destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("destroy", self.on_window_destroy)
self.window.set_border_width(5)
self.button = gtk.Button("Hello World")
self.button.connect("clicked", self.on_button_clicked)
self.window.add(self.button)
self.window.show_all()
def main(self):
gtk.main()
if __name__ == "__main__":
hello = HelloWorld()
hello.main()
| Python |
#!/usr/bin/env python
import sys
from PyQt4 import Qt
a = Qt.QApplication(sys.argv)
# Our function to call when the button is clicked
def sayHello():
print "Hello, World!"
# Instantiate the button
hellobutton = Qt.QPushButton("Say 'Hello world!'",None)
# And connect the action "sayHello" to the event "button has been clicked"
a.connect(hellobutton, Qt.SIGNAL("clicked()"), sayHello)
# The rest is known already...
#a.setMainWidget(hellobutton)
hellobutton.show()
a.exec_()
| Python |
import pygtk
pygtk.require('2.0')
import gtk
class Conversion:
def on_convert_clicked(self,widget):
usd = self.usd_entry.get_text()
usd = int(usd)
inr = usd * 44.75
self.inr_entry.set_text(str(inr))
def on_window_destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("destroy", self.on_window_destroy)
self.window.set_border_width(5)
table = gtk.Table(4, 2, homogeneous=False)
self.window.add(table)
ef = gtk.EXPAND | gtk.FILL
self.usd_label = gtk.Label("Enter USD Amount: ")
table.attach(self.usd_label, 0, 1, 0, 1, 0, 0, 5, 5)
self.usd_entry = gtk.Entry(0)
table.attach(self.usd_entry, 1, 2, 0, 1, ef, 0, 5, 5)
self.inr_label = gtk.Label("Indian Value Is (INR): ")
table.attach(self.inr_label, 0, 1, 1, 2, 0, 0, 5, 5)
self.inr_entry = gtk.Entry(0)
table.attach(self.inr_entry, 1, 2, 1, 2, ef, 0, 5, 5)
self.convert_button = gtk.Button("Convert")
self.convert_button.connect("clicked", self.on_convert_clicked)
table.attach(self.convert_button, 0, 2, 3, 4, ef, 0, 5, 5)
self.window.show_all()
def main(self):
gtk.main()
if __name__ == "__main__":
conversion = Conversion()
conversion.main()
| Python |
import pygtk
pygtk.require('2.0')
import gtk
import pango
class SysInfo:
def on_button_clicked(self, button, filename):
text = open("/proc/" + filename).read()
self.info_view.get_buffer().set_text(text)
def on_window_destroy(self, window):
gtk.main_quit();
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("destroy", self.on_window_destroy)
self.window.set_border_width(5)
self.main_hbox = gtk.HBox()
self.window.add(self.main_hbox)
self.button_vbox = gtk.VBox()
self.main_hbox.pack_start(self.button_vbox, expand=False)
filename_list = ["cpuinfo", "meminfo", "interrupts"]
for filename in filename_list:
button = gtk.Button(filename)
self.button_vbox.pack_start(button, expand=False)
button.connect("clicked", self.on_button_clicked, filename)
self.scroll_win = gtk.ScrolledWindow()
self.main_hbox.pack_start(self.scroll_win, expand=True, fill=True)
self.info_view = gtk.TextView()
self.scroll_win.add(self.info_view)
self.info_view.set_editable(False)
self.info_view.modify_font(pango.FontDescription("courier"))
self.window.show_all()
def main(self):
gtk.main()
if __name__ == "__main__":
sysinfo = SysInfo()
sysinfo.main()
| Python |
import pygtk
pygtk.require('2.0')
import gtk
class HelloWorld:
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_border_width(5)
self.button = gtk.Button("Hello World!")
self.window.add(self.button)
self.window.show_all()
def main(self):
gtk.main()
if __name__ == "__main__":
hello = HelloWorld()
hello.main()
| Python |
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
class HelloWorld:
def on_button_clicked(self, widget, data=None):
print "Hello World"
def on_window_destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("destroy", self.on_window_destroy)
self.window.set_border_width(5)
self.button = gtk.Button("Hello World")
self.button.connect("clicked", self.on_button_clicked)
self.window.add(self.button)
self.window.show_all()
def main(self):
gtk.main()
if __name__ == "__main__":
hello = HelloWorld()
hello.main()
| Python |
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
class HelloWorld:
def on_combo_changed(self, widget, data=None):
print self.combo.get_active_text()
def on_window_destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("destroy", self.on_window_destroy)
self.window.set_border_width(5)
self.combo = gtk.combo_box_new_text()
self.combo.append_text("GNU/Linux")
self.combo.append_text("Windows")
self.combo.append_text("Mac OS X")
self.combo.connect("changed", self.on_combo_changed)
self.window.add(self.combo)
self.window.show_all()
def main(self):
gtk.main()
if __name__ == "__main__":
hello = HelloWorld()
hello.main()
| Python |
import sys
import random
def open_capitals():
try:
# Throws IOError, if open fails.
return open("capitals.txt")
except IOError as e:
print "error opening capitals.txt: %s" % e.strerror
sys.exit(1)
def parse_capitals(cfile):
capitals = {}
for i, line in enumerate(cfile):
try:
# Throws ValueError, if no. of elements in LHS and RHS
# does not match.
country, capital = line.split(":")
country = country.strip()
capital = capital.strip()
capitals[country] = capital
except ValueError:
print "error parsing line %d" % (i+1)
sys.exit(1)
return capitals
def quiz():
cfile = open_capitals()
capitals = parse_capitals(cfile)
country_list = capitals.keys()
while len(country_list) > 0:
country = random.choice(country_list)
capital = capitals[country]
country_list.remove(country)
user_input = raw_input("%s ? " % country)
if user_input.upper() != capital.upper():
print "Wrong, the answer is '%s'." % capital
if __name__ == "__main__":
quiz()
| Python |
import MySQLdb as db
import sys
import conf
conn = db.connect("shark", conf.username, conf.password, conf.database)
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS accounts")
# Create Tables
sql = """CREATE TABLE accounts (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
balance DECIMAL(10, 2))"""
cursor.execute(sql)
# Insert into Tables
sql = """INSERT INTO accounts (name, balance) VALUES ('Alice', 500.00),
('Bob', 50000.00),
('Charlie', 100.00)"""
cursor.execute(sql)
| Python |
import MySQLdb as db
import conf
from decimal import Decimal
def input_num(msg, numtype):
while True:
try:
num = raw_input(msg)
num = numtype(num)
return num
except ValueError, e:
print "Invalid number."
def get_balance(accno):
cursor.execute("SELECT balance FROM accounts WHERE id = %d" % accno)
row = cursor.fetchone()
if row == None:
return 0
else:
return row[0]
def set_balance(accno, balance):
cursor.execute("UPDATE accounts SET balance = %s WHERE id = %d" %
(balance, accno))
def transact():
while True:
accno = input_num("Enter Account No.: ", int)
if accno == -1: break
balance = get_balance(accno)
print "The current balance is", balance
amount = input_num("Enter amount to credit/debit: ", Decimal)
set_balance(accno, balance + amount)
print "The new balance is", get_balance(accno)
def main():
global cursor
conn = db.connect(conf.server, conf.username,
conf.password, conf.database)
cursor = conn.cursor()
transact()
if __name__ == "__main__":
main()
| Python |
server = "shark"
username = "erp1"
password = "erp1"
database = "erp1"
| Python |
import pygame, sys, math, random, time
pygame.init()
from Block import Block
from Player import Player
from HardBlock import HardBlock
from Enemy import Enemy
from Background import Background
from Bullet import Bullet
from transportblock import TransportBlock
clock = pygame.time.Clock()
width = 800
height = 600
size = width, height
blocksize = [50,50]
playersize = [40,40]
screen = pygame.display.set_mode(size)
bgColor = r,g,b = 0,0,0
blocks = pygame.sprite.Group()
transportBlocks = pygame.sprite.Group()
bullets = pygame.sprite.Group()
hardBlocks = pygame.sprite.Group()
enemies = pygame.sprite.Group()
backgrounds = pygame.sprite.Group()
players = pygame.sprite.Group()
all = pygame.sprite.OrderedUpdates()
Player.containers = (all, players)
Bullet.containers = (all, bullets)
Block.containers = (all, blocks)
HardBlock.containers = (all, hardBlocks, blocks)
Enemy.containers = (all, enemies)
Background.containers = (all, blocks)
TransportBlock.containers = (all, transportBlocks)
bg = Background("rsc/bg/mainbg.png", size)
def loadLevel(level, playerHealth):
f = open(level+".lvl", 'r')
lines = f.readlines()
f.close()
newlines = []
for line in lines:
newline = ""
for c in line:
if c != "\n":
newline += c
newlines += [newline]
for line in newlines:
print line
for y, line in enumerate(newlines):
for x, c in enumerate(line):
if c == "#":
HardBlock("rsc/blocks/mainBlock.png",
[(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
blocksize)
elif c == "p":
Block("rsc/blocks/purple.png",
[(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
blocksize)
elif c == "b":
Block("rsc/blocks/blue.png",
[(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
blocksize)
elif c == "k":
Block("rsc/blocks/wood crate.png",
[(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
blocksize)
elif c == "t":
Block("rsc/blocks/Prison-Cells.png",
[(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
blocksize)
elif c == "a":
TransportBlock([(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
blocksize)
f = open(level+".tng", 'r')
lines = f.readlines()
f.close()
newlines = []
for line in lines:
newline = ""
for c in line:
if c != "\n":
newline += c
newlines += [newline]
for line in newlines:
print line
for y, line in enumerate(newlines):
for x, c in enumerate(line):
if c == "@":
player = Player(playerHealth,
[(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
playersize,
size)
elif c == "e":
Enemy("rsc/enemy/red guy.png",
[(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
playersize)
for each in all.sprites():
each.fixLocation(player.offsetx, player.offsety)
def loadNextLevel(level):
print "?????????????????????"
time.sleep(.5)
playerHealth = player1.health
for each in all.sprites():
each.kill()
bg = Background("rsc/bg/mainbg.png", size)
screen.blit(bg.image, bg.rect)
loadLevel(levels[level], playerHealth)
return level
levels = ["rsc/levels/level1",
"rsc/levels/level2",
"rsc/levels/level3",
"rsc/levels/level4",
"rsc/levels/level5",]
level = 0
loadLevel(levels[level], 100)
player1 = players.sprites()[0]
while True:
while player1.living:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
if level < len(levels)-1:
level += 1
else:
level = 0
playerHealth = player1.health
for each in all.sprites():
each.kill()
bg = Background("rsc/bg/mainbg.png", size)
screen.blit(bg.image, bg.rect)
loadLevel(levels[level], playerHealth)
player1 = players.sprites()[0]
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
player1.direction("right")
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
player1.direction("left")
if event.key == pygame.K_w or event.key == pygame.K_UP:
player1.direction("up")
if event.key == pygame.K_s or event.key == pygame.K_DOWN:
player1.direction("down")
if event.key == pygame.K_SPACE:
player1.direction("jump")
if event.type == pygame.KEYUP:
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
player1.direction("stop right")
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
player1.direction("stop left")
if event.key == pygame.K_w or event.key == pygame.K_UP:
player1.direction("stop up")
if event.key == pygame.K_s or event.key == pygame.K_DOWN:
player1.direction("stop down")
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
Bullet(player1.headingx, player1.rect.center)
playersHitBlocks = pygame.sprite.groupcollide(players, hardBlocks, False, False)
playersHitEnemies = pygame.sprite.groupcollide(players, enemies, False, False)
enemiesHitBlocks = pygame.sprite.groupcollide(enemies, hardBlocks, False, False)
bulletsHitBlocks = pygame.sprite.groupcollide(bullets, hardBlocks, True, False)
enemiesHitEnemies = pygame.sprite.groupcollide(enemies, enemies, False, False)
bulletsHitEnemies = pygame.sprite.groupcollide(bullets, enemies, True, True)
playersHitTransportBlocks = pygame.sprite.groupcollide(players, transportBlocks, False, False)
for player in playersHitBlocks:
for block in playersHitBlocks[player]:
player.collideBlock(block)
for player in playersHitTransportBlocks:
for block in playersHitTransportBlocks[player]:
print "---------------------------------"
time.sleep(.5)
level = loadNextLevel(level+1)
player1 = players.sprites()[0]
for player in playersHitEnemies:
for enemy in playersHitEnemies[player]:
player.collideEnemy(enemy)
for enemy in enemiesHitBlocks:
for block in enemiesHitBlocks[enemy]:
enemy.collideBlock(block)
for enemy in enemiesHitEnemies:
for otherEnemy in enemiesHitEnemies[enemy]:
enemy.collideBlock(otherEnemy)
all.update(size,
player1.speedx,
player1.speedy,
player1.scrollingx,
player1.scrollingy,
player1.realx,
player1.realy)
dirty = all.draw(screen)
pygame.display.update(dirty)
pygame.display.flip()
clock.tick(30)
for each in all.sprites():
each.kill()
bg = Background("rsc/bg/endscreen.png", size)
while not player1.living:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
all.update(size,
player1.speedx,
player1.speedy,
player1.scrollingx,
player1.scrollingy,
player1.realx,
player1.realy)
dirty = all.draw(screen)
pygame.display.update(dirty)
pygame.display.flip()
clock.tick(30)
| Python |
import pygame, sys, math
class Background(pygame.sprite.Sprite):
def __init__(self, image, size):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = pygame.image.load(image)
self.image = pygame.transform.scale(self.image, size)
self.rect = self.image.get_rect()
def update(*args):
pass
def fixLocation(self, x, y):
pass
| Python |
import pygame, sys, math
class Player(pygame.sprite.Sprite):
def __init__(self, health, pos = (0,0), blocksize = [50,50], screensize = [800,600]):
pygame.sprite.Sprite.__init__(self, self.containers)
self.screensize = screensize
self.upImages = [pygame.image.load("rsc/player/playerBall_up1.png"),
pygame.image.load("rsc/player/playerBall_up2.png")]
self.upImages = [pygame.transform.scale(self.upImages[0], blocksize),
pygame.transform.scale(self.upImages[1], blocksize)]
self.downImages = [pygame.image.load("rsc/player/playerBall_down1.png"),
pygame.image.load("rsc/player/playerBall_down2.png")]
self.downImages = [pygame.transform.scale(self.downImages[0], blocksize),
pygame.transform.scale(self.downImages[1], blocksize)]
self.rightImages = [pygame.image.load("rsc/player/playerBall_right1.png"),
pygame.image.load("rsc/player/playerBall_right2.png")]
self.rightImages = [pygame.transform.scale(self.rightImages[0], blocksize),
pygame.transform.scale(self.rightImages[1], blocksize)]
self.leftImages = [pygame.image.load("rsc/player/playerBall_left1.png"),
pygame.image.load("rsc/player/playerBall_left2.png")]
self.leftImages = [pygame.transform.scale(self.leftImages[0], blocksize),
pygame.transform.scale(self.leftImages[1], blocksize)]
self.images = self.rightImages
self.frame = 0
self.maxFrame = len(self.images) - 1
self.waitCount = 0
self.waitCountMax = 5
self.image = self.images[self.frame]
self.rect = self.image.get_rect()
self.maxSpeed = blocksize[0]/5.0
self.speed = [0,0]
self.speedx = 0
self.speedy = 0
self.g = blocksize[0]/10
self.jumpSpeed = 0
self.jumpSpeedMax = 30
self.fallSpeedMax = int(blocksize[0]/2) -3
self.realx = pos[0]
self.realy = pos[1]
self.x = screensize[0]/2
self.y = screensize[1]/2
self.offsetx = self.x - self.realx
self.offsety = self.y - self.realy
self.scrollingx = False
self.scrollingy = False
self.scrollBoundry = 200
self.headingx = "right"
self.headingy = "up"
self.lastHeading = "right"
self.headingChanged = False
self.radius = self.rect.width/2
self.living = True
self.place(pos)
self.health=health
self.onfloor = False
self.floor = screensize[1]
self.touchFloor = False
def place(self, pos):
self.rect.center = pos
def fixLocation(self, x, y):
pass
def update(*args):
self = args[0]
self.collideWall(self.screensize)
if (self.rect.bottom < self.floor) and self.headingy == "none":
self.headingy = "down"
self.animate()
self.move()
self.headingChanged = False
if self.health <= 0:
self.living = False
self.touchFloor = False
def animate(self):
if self.headingChanged:
if self.lastHeading == "up":
self.images = self.upImages
if self.lastHeading == "down":
self.images = self.downImages
if self.lastHeading == "right":
self.images = self.rightImages
if self.lastHeading == "left":
self.images = self.leftImages
self.image = self.images[self.frame]
if self.waitCount < self.waitCountMax:
self.waitCount += 1
else:
self.waitCount = 0
if self.frame < self.maxFrame:
self.frame += 1
else:
self.frame = 0
self.image = self.images[self.frame]
def move(self):
if not self.touchFloor:
self.headingy = "down"
if self.headingy == "down":
if self.speedy < self.fallSpeedMax:
self.speedy += self.g
else:
self.speedy = self.fallSpeedMax
self.realx += self.speedx
self.realy += self.speedy
if not self.scrollingx:
self.x += self.speedx
if self.x > self.screensize[0] - self.scrollBoundry and self.headingx == "right":
self.scrollingx = True
elif self.x < self.scrollBoundry and self.headingx == "left":
self.scrollingx = True
else:
self.scrollingx = False
if not self.scrollingy:
self.y += self.speedy
if self.y > self.screensize[1] - self.scrollBoundry and self.headingy == "down":
self.scrollingy = True
elif self.y < self.scrollBoundry and self.headingy == "up":
self.scrollingy = True
else:
self.scrollingy = False
self.rect.center = (round(self.x), round(self.y))
def collideWall(self, size):
if self.rect.left < 0 and self.headingx == "left":
self.speedx = 0
elif self.rect.right > size[0] and self.headingx == "right":
self.speedx = 0
if self.rect.top < 0 and self.headingy == "up":
self.speedy = 0
elif self.rect.bottom > size[1] and self.headingy == "down":
self.speedy = 0
def collideEnemy(self, enemy):
self.health -= enemy.damage
print self.health
def collideBlock(self, block):
print self.rect, self.headingx, self.headingy
if self.floor == block.rect.top + 2 and self.headingy == "none":
self.touchFloor = True
print "on the floor"
self.jumping = False
else:
if self.realx < block.realx and self.headingx == "right":
self.speedx = 0
self.realx -= 1
self.x -= 1
print "hit right"
if self.realx > block.realx and self.headingx == "left":
self.speedx = 0
self.realx += 1
self.x += 1
print "hit left"
if self.realy < block.realy and self.headingy == "up":
self.speedy = 0
self.realy += 1
self.y += 1
print "hit up"
if self.realy > block.realy and self.headingy == "down":
self.touchFloor = True
self.speedy = 0
self.realy -= self.g + 2
self.headingy = "none"
self.floor = block.rect.top+2
self.y = self.floor - self.rect.height/2
print "///////////////////////hit down"
def direction(self, dir):
if dir == "right":
self.headingx = "right"
self.speedx = self.maxSpeed
self.lastHeading = "right"
self.headingChanged = True
if dir == "stop right":
self.headingx = "right"
self.speedx = 0
if dir == "left":
self.headingx = "left"
self.speedx = -self.maxSpeed
self.lastHeading = "left"
self.headingChanged = True
if dir == "stop left":
self.headingx = "left"
self.speedx = 0
if dir == "jump":
if not self.jumping:
self.jumping = True
self.headingy = "up"
self.jumpSpeed = self.jumpSpeedMax
self.speedy = -self.jumpSpeed
self.headingChanged = True
self.touchingFloor = False
if dir == "up":
self.headingy = "up"
self.speedy = -self.maxSpeed
self.lastHeading = "up"
self.headingChanged = True
if dir == "stop up":
self.headingy = "up"
self.speedy = 0
if dir == "down":
self.headingy = "down"
self.speedy = self.maxSpeed
self.lastHeading = "down"
self.headingChanged = True
if dir == "stop down":
self.headingy = "down"
self.speedy = 0
| Python |
import pygame, sys, math
class Bullet(pygame.sprite.Sprite):
def __init__(self, direction, pos = (0,0)):
if direction == "right":
image = "rsc/weapons/bulletR.png"
else:
image = "rsc/weapons/bulletL.png"
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = pygame.image.load(image)
self.image = pygame.transform.scale(self.image, [10,5])
self.rect = self.image.get_rect()
self.realx = pos[0]
self.realy = pos[1]
self.x = pos[0]
self.y = pos[1]
self.place(pos)
if direction == "right":
self.speedx = 25
else:
self.speedx = -25
self.speedy = 0
self.scrollingx = False
self.scrollingy = False
self.offsetx = 0
self.offsety = 0
def place(self, pos):
self.rect.center = pos
def fixLocation(self, x, y):
self.x += x
self.y += y
def update(*args):
self = args[0]
self.playerspeedx = args[2]
self.playerspeedy = args[3]
self.scrollingx = args[4]
self.scrollingy = args[5]
self.move()
def move(self):
self.realx += self.speedx
if self.scrollingx:
self.offsetx -= self.playerspeedx
if self.scrollingy:
self.offsety -= self.playerspeedy
self.x = self.realx + self.offsetx
self.y = self.realy + self.offsety
self.rect.center = (round(self.x), round(self.y))
| Python |
import pygame, sys, math
from Block import Block
class TransportBlock(Block):
def __init__(self, pos = (0,0), blocksize = [50,50]):
Block.__init__(self, "rsc/blocks/transportblock.png", pos, blocksize) | Python |
import pygame, sys, math
from Block import Block
class HardBlock(Block):
def __init__(self, image, pos = (0,0), blocksize = [50,50]):
Block.__init__(self, image, pos, blocksize)
| Python |
import pygame, sys, math
from Block import Block
class HardBlock(Block):
def __init__(self, image, pos = (0,0), blocksize = [50,50]):
Block.__init__(self, image, pos, blocksize)
| Python |
import pygame, sys, math
class Block(pygame.sprite.Sprite):
def __init__(self, image, pos = (0,0), blocksize = [50,50]):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = pygame.image.load(image)
self.image = pygame.transform.scale(self.image, blocksize)
self.rect = self.image.get_rect()
self.realx = pos[0]
self.realy = pos[1]
self.x = pos[0]
self.y = pos[1]
self.place(pos)
self.speedx = 0
self.speedy = 0
self.scrollingx = False
self.scrollingy = False
def place(self, pos):
self.rect.center = pos
def fixLocation(self, x, y):
self.x += x
self.y += y
def update(*args):
self = args[0]
self.speedx = args[2]
self.speedy = args[3]
self.scrollingx = args[4]
self.scrollingy = args[5]
self.move()
def move(self):
if self.scrollingx:
self.x -= self.speedx
if self.scrollingy:
self.y -= self.speedy
self.rect.center = (round(self.x), round(self.y))
| Python |
import pygame, sys, math, random
from Block import Block
class Enemy(Block):
def __init__(self, image, pos = (0,0), blocksize = [50,50]):
Block.__init__(self, image, pos, blocksize)
self.maxSpeed = blocksize[0]/14.0
self.living = True
self.detectRange = 100
self.seePlayer = False
self.headingx = "right"
self.headingy = "up"
self.directionCount = 0
self.realx = pos[0]
self.realy = pos[1]
self.x = pos[0]
self.y = pos[1]
self.offsetx = 0
self.offsety = 0
self.damage = 5
def fixLocation(self, x, y):
self.offsetx += x
self.offsety += y
def update(*args):
self = args[0]
self.playerspeedx = args[2]
self.playerspeedy = args[3]
self.scrollingx = args[4]
self.scrollingy = args[5]
playerx = args[6]
playery = args[7]
#print "enemy:", self.realx, self.realy, "player:", playerx, playery
self.move()
self.detectPlayer(playerx, playery)
if not self.seePlayer:
self.ai()
def detectPlayer(self, playerx, playery):
if self.distanceToPoint([playerx, playery]) < self.detectRange:
#print "I seeeee you!!!"
self.seePlayer = True
self.speedx = self.maxSpeed
self.speedy = self.maxSpeed
#print playerx, self.realx, playery, self.realy
if playerx > self.realx:
self.headingx = "right"
elif playerx < self.realx:
self.headingx = "left"
if playery > self.realy:
self.headingy = "down"
elif playery < self.realy:
self.headingy = "up"
else:
self.seePlayer = False
#print "Where are you?"
def move(self):
#print "enemy", self.realx, self.speedx
if self.headingx == "right":
self.realx += self.speedx
else:
self.realx -= self.speedx
if self.headingy == "down":
self.realy += self.speedy
else:
self.realy -= self.speedy
if self.scrollingx:
self.offsetx -= self.playerspeedx
if self.scrollingy:
self.offsety -= self.playerspeedy
self.x = self.realx + self.offsetx
self.y = self.realy + self.offsety
self.rect.center = (round(self.x), round(self.y))
def ai(self):
if self.directionCount > 0:
self.directionCount -= 1
else:
self.directionCount = random.randint(10,100)
dir = random.randint(0,3);
if dir == 0:
self.headingx = "right"
self.headingy = "up"
if dir == 1:
self.headingx = "right"
self.headingy = "down"
if dir == 2:
self.headingx = "left"
self.headingy = "down"
if dir == 3:
self.headingx = "left"
self.headingy = "up"
self.speedx = random.randint(0, int(self.maxSpeed))
self.speedy = random.randint(0, int(self.maxSpeed))
def collideBlock(self, block):
#print self.rect, self.headingx, self.headingy
if self.realx < block.realx and self.headingx == "right":
self.speedx = 0
self.realx -= 1
self.x -= 1
#print "hit right"
self.directionCount = 0
if self.realx > block.realx and self.headingx == "left":
self.speedx = 0
self.realx += 1
self.x += 1
#print "hit left"
self.directionCount = 0
if self.realy > block.realy and self.headingy == "up":
self.speedy = 0
self.realy += 1
self.y += 1
#print "hit up"
self.directionCount = 0
if self.realy < block.realy and self.headingy == "down":
self.speedy = 0
self.realy -= 1
self.y -= 1
#print "hit down"
self.directionCount = 0
def distanceToPoint(self, pt):
x1 = self.realx
y1 = self.realy
x2 = pt[0]
y2 = pt[1]
return math.sqrt(((x2-x1)**2)+((y2-y1)**2))
| Python |
'''OpenAnything: a kind and thoughtful library for HTTP web services
This program is part of 'Dive Into Python', a free Python book for
experienced programmers. Visit http://diveintopython.org/ for the
latest version.
'''
__author__ = 'Mark Pilgrim (mark@diveintopython.org)'
__version__ = '$Revision: 1.6 $'[11:-2]
__date__ = '$Date: 2004/04/16 21:16:24 $'
__copyright__ = 'Copyright (c) 2004 Mark Pilgrim'
__license__ = 'Python'
import urllib2, urlparse, gzip
from StringIO import StringIO
USER_AGENT = 'OpenAnything/%s +http://diveintopython.org/http_web_services/' % __version__
class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_301(
self, req, fp, code, msg, headers)
result.status = code
return result
def http_error_302(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_302(
self, req, fp, code, msg, headers)
result.status = code
return result
class DefaultErrorHandler(urllib2.HTTPDefaultErrorHandler):
def http_error_default(self, req, fp, code, msg, headers):
result = urllib2.HTTPError(
req.get_full_url(), code, msg, headers, fp)
result.status = code
return result
def openAnything(source, etag=None, lastmodified=None, agent=USER_AGENT):
"""URL, filename, or string --> stream
This function lets you define parsers that take any input source
(URL, pathname to local or network file, or actual data as a string)
and deal with it in a uniform manner. Returned object is guaranteed
to have all the basic stdio read methods (read, readline, readlines).
Just .close() the object when you're done with it.
If the etag argument is supplied, it will be used as the value of an
If-None-Match request header.
If the lastmodified argument is supplied, it must be a formatted
date/time string in GMT (as returned in the Last-Modified header of
a previous request). The formatted date/time will be used
as the value of an If-Modified-Since request header.
If the agent argument is supplied, it will be used as the value of a
User-Agent request header.
"""
if hasattr(source, 'read'):
return source
if source == '-':
return sys.stdin
if urlparse.urlparse(source)[0] == 'http':
# open URL with urllib2
request = urllib2.Request(source)
request.add_header('User-Agent', agent)
if lastmodified:
request.add_header('If-Modified-Since', lastmodified)
if etag:
request.add_header('If-None-Match', etag)
request.add_header('Accept-encoding', 'gzip')
opener = urllib2.build_opener(SmartRedirectHandler(), DefaultErrorHandler())
return opener.open(request)
# try to open with native open function (if source is a filename)
try:
return open(source)
except (IOError, OSError):
pass
# treat source as string
return StringIO(str(source))
def fetch(source, etag=None, lastmodified=None, agent=USER_AGENT):
'''Fetch data and metadata from a URL, file, stream, or string'''
result = {}
f = openAnything(source, etag, lastmodified, agent)
result['data'] = f.read()
if hasattr(f, 'headers'):
# save ETag, if the server sent one
result['etag'] = f.headers.get('ETag')
# save Last-Modified header, if the server sent one
result['lastmodified'] = f.headers.get('Last-Modified')
if f.headers.get('content-encoding') == 'gzip':
# data came back gzip-compressed, decompress it
result['data'] = gzip.GzipFile(fileobj=StringIO(result['data'])).read()
if hasattr(f, 'url'):
result['url'] = f.url
result['status'] = 200
if hasattr(f, 'status'):
result['status'] = f.status
f.close()
return result
| Python |
#!/usr/bin/python
"""
Manipulates Fortran Namelists
Defines
Namelist class
TODO: == As a Stand alone program ==
Print info about Fortran Namelists
Usage: namelist.py -f FILENAME [-n NAMELIST [-p PARNAME]]
FILENAME: path/name of config file
NAMELIST: namelist name (since a file may contain many namelists)
PARNAME: Name of parameter to print value for
if NAMELIST is not provided,
print the list of namelist present in file in list form:
['name1','name2',...]
if NAMELIST is provided (PARNAME not provided),
print all namelist param sin a "param=value" format, one per line
for multiple values of same param, print each one
as "param=value" format, one per line
if NAMELIST and PARNAME is provided,
if not specify, print all param in a "param=value" format
if specify and exist, print PARNAME's value only
for multiple values of same param, print each PARNAME's
values, one per line
This script is a generic Fortan namelist parser
and will recognize all namelist in a file with the following format,
and ignores the rest.
&namelistname
opt1 = value1
...
/
"""
__author__ = 'Stephane Chamberland (stephane.chamberland@ec.gc.ca)'
__version__ = '$Revision: 1.0 $'[11:-2]
__date__ = '$Date: 2006/09/05 21:16:24 $'
__copyright__ = 'Copyright (c) 2006 RPN'
__license__ = 'LGPL'
import sys
#sys.path.append("/usr/local/env/armnlib/modeles/SURF/python")
import re
from settings import Settings
# import sys
# import getopt
# import string
class Namelist(Settings):
"""
Namelist class
Scan a Fortran Namelist file and put Section/Parameters into a dictionary
Intentiation:
foo = Namelist(NamelistFile)
where NamelistFile can be a filename, an URL or a string
Functions:
[Pending]
This is a generic Fortan namelist parser
it will recognize all namelist in a file with the following format,
and ignores the rest.
&namelistname
opt1 = value1
...
/
"""
def parse(self):
"""Config file parser, called from the class initialization"""
varname = r'\b[a-zA-Z][a-zA-Z0-9_]*\b'
valueInt = re.compile(r'[+-]?[0-9]+')
valueReal = re.compile(r'[+-]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)')
valueNumber = re.compile(r'\b(([\+\-]?[0-9]+)?\.)?[0-9]*([eE][-+]?[0-9]+)?')
valueBool = re.compile(r"(\.(true|false|t|f)\.)",re.I)
valueTrue = re.compile(r"(\.(true|t)\.)",re.I)
spaces = r'[\s\t]*'
quote = re.compile(r"[\s\t]*[\'\"]")
namelistname = re.compile(r"^[\s\t]*&(" + varname + r")[\s\t]*$")
paramname = re.compile(r"[\s\t]*(" + varname+r')[\s\t]*=[\s\t]*')
namlistend = re.compile(r"^" + spaces + r"/" + spaces + r"$")
#split sections/namelists
mynmlfile = {}
mynmlname = ''
for item in self.clean(self._setContent.split("\n"),cleancomma=1):
if re.match(namelistname,item):
mynmlname = re.sub(namelistname,r"\1",item)
mynmlfile[mynmlname] = {
'raw' : [],
'par' : [{}]
}
elif re.match(namlistend,item):
mynmlname = ''
else:
if mynmlname:
mynmlfile[mynmlname]['raw'].append(item)
#parse param in each section/namelist
for mynmlname in mynmlfile.keys():
#split strings
bb = []
for item in mynmlfile[mynmlname]['raw']:
bb.extend(self.splitstring(item))
#split comma and =
aa = []
for item in bb:
if not re.match(quote,item):
aa.extend(re.sub(r"[\s\t]*=",r" =\n",re.sub(r",+",r"\n",item)).split("\n"))
else:
aa.append(item)
del(bb)
aa = self.clean(aa,cleancomma=1)
myparname = ''
for item in aa:
if re.search(paramname,item):
myparname = re.sub(paramname,r"\1",item).lower()
mynmlfile[mynmlname]['par'][0][myparname] = []
elif paramname:
#removed quotes, spaces (then how to distinguish .t. of ".t."?)
if re.match(valueBool,item):
if re.match(valueTrue,item):
mynmlfile[mynmlname]['par'][0][myparname].append('.true.')
else:
mynmlfile[mynmlname]['par'][0][myparname].append('.false.')
else:
mynmlfile[mynmlname]['par'][0][myparname].append(re.sub(r"(^[\'\"]|[\'\"]$)",r"",item.strip()).strip())
return mynmlfile
# def usage():
# """Print usage"""
# print main.__doc__
#
#
# def main(argv):
# """Print info about Fortran Namelists
#
# Usage: namelist.py -f FILENAME [-n NAMELIST [-p PARNAME]]
#
# FILENAME: path/name of config file
# NAMELIST: namelist name (since a file may contain many namelists)
# PARNAME: Name of parameter to print value for
#
# if NAMELIST is not provided,
# print the list of namelist present in file in list form:
# ['name1','name2',...]
# if NAMELIST is provided (PARNAME not provided),
# print all namelist param sin a "param=value" format, one per line
# for multiple values of same param, print each one
# as "param=value" format, one per line
# if NAMELIST and PARNAME is provided,
# if not specify, print all param in a "param=value" format
# if specify and exist, print PARNAME's value only
# for multiple values of same param, print each PARNAME's
# values, one per line
#
# This script is a generic Fortan namelist parser
# and will recognize all namelist in a file with the following format,
# and ignores the rest.
#
# &namelistname
# opt1 = value1
# ...
# /
#
# """
# filename = ""
# nmlname = ""
# param = ""
# metafile = ""
# try:
# opts, args = getopt.getopt(argv, \
# "Hf:n:p:m:", \
# ["help","file=","nml=","param=","metafile="])
# except getopt.GetoptError:
# usage()
# sys.exit(2)
# for opt, arg in opts:
# if opt in ("-H", "--help"):
# usage()
# sys.exit(1)
# elif opt in ("-f","--file"):
# filename = arg
# elif opt in ("-n","--nml"):
# nmlname = arg.lower()
# elif opt in ("-p","--param"):
# param = arg.lower()
# #...metafile disabled for now...
# #elif opt in ("-m","--metafile"):
# # metafile = arg
# #Get namelist opt/val
# if (filename):
# nmlopt = getnmlopt(filename)
# if (nmlname):
# if (param):
# try:
# for myval in nmlopt[nmlname][param]:
# #print param," = ",myval
# print myval
# except:
# pass
# elif (metafile):
# pass
# else:
# try:
# for mykey in nmlopt[nmlname].keys():
# for myval in nmlopt[nmlname][mykey]:
# print mykey," = ",myval
# except:
# print
# else:
# try:
# print nmlopt.keys()
# except:
# pass
# else:
# usage()
# sys.exit(2)
#
# if __name__ == '__main__':
# main(sys.argv[1:])
| Python |
#!/usr/bin/python
"""
General settings class to read/manipulate data from settings file
This class is meant to be subclassed to parse the settings file data, print the settings...
"""
__author__ = 'Stephane Chamberland (stephane.chamberland@ec.gc.ca)'
__version__ = '$Revision: 1.0 $'[11:-2]
__date__ = '$Date: 2006/08/31 21:16:24 $'
__copyright__ = 'Copyright (c) 2006 RPN'
__license__ = 'LGPL'
import sys
#sys.path.append("/usr/local/env/armnlib/modeles/SURF/python")
import re
from openanything import openAnything
class Settings(dict):
"""
the dict is organised as
dict[secName]['raw'] = ['sectionContent w/o comments, empty lines, lead/trail blanks']
dict[secName]['par'][subSec#][parName] = [val1,val2...]
"""
def __init__(self,settingFile):
dict.__init__(self)
self._setFile = settingFile
self._setContent = openAnything(settingFile).read()
self.update(self.parse())
#==== Helper functions for Parsing of files
def clean(self,mystringlist,commentexpr=r"^[\s\t]*\#.*$",spacemerge=0,cleancomma=0):
"""
Remove leading and trailing blanks, comments/empty lines from a list of strings
mystringlist = foo.clean(mystringlist,spacemerge=0,commentline=r"^[\s\t]*\#",cleancharlist="")
commentline: definition of commentline
spacemerge: if <>0, merge/collapse multi space
cleancomma: Remove leading and trailing commas
"""
aa = mystringlist
if cleancomma:
aa = [re.sub("(^([\s\t]*\,)+)|((\,[\s\t]*)+$)","",item).strip() for item in aa]
if commentexpr:
aa = [re.sub(commentexpr,"",item).strip() for item in aa]
if spacemerge:
aa = [re.sub("[\s\t]+"," ",item).strip() for item in aa if len(item.strip()) <> 0]
else:
aa = [item.strip() for item in aa if len(item.strip()) <> 0]
return aa
def splitstring(self,mystr):
"""
Split a string in a list of strings at quote boundaries
Input: String
Output: list of strings
"""
dquote=r'(^[^\"\']*)(\"[^"]*\")(.*)$'
squote=r"(^[^\"\']*)(\'[^']*\')(.*$)"
mystrarr = re.sub(dquote,r"\1\n\2\n\3",re.sub(squote,r"\1\n\2\n\3",mystr)).split("\n")
#remove zerolenght items
mystrarr = [item for item in mystrarr if len(item) <> 0]
if len(mystrarr) > 1:
mystrarr2 = []
for item in mystrarr:
mystrarr2.extend(self.splitstring(item))
mystrarr = mystrarr2
return mystrarr
#==== Virtual function that derived class must implement
def parse(self):
"""
Virtual function that must be implemented by derived class
Parse the file content in the self._setContent string
Return a dictionary of the parsed setting file organized as:
dict[secName]['raw'] = 'sectionContent w/o comments; w/ collapsed spaces'
dict[secName]['par'][subSec#][parName] = [val1,val2...]
"""
return { all: {'par': [] ,'raw': self.clean(self._setContent.split("\n"))}}
#==== Output function
def sec_string(self,secname):
"""
Return a string containing the "cleaned" content of a sectionContent
mysecstring = foo.sec_string(secname)
"""
try:
return "\n".join(self[secname]['raw'])
except:
return ''
def param_singleval(self,secname,parname):
aa = self.param_vallist(secname,parname)
if aa[0]:
return self.param_vallist(secname,parname)[0][0]
else:
return ''
def param_vallist(self,secname,parname,subsec=-1):
"""
Return a list of values for the specified section/param
myvallist = foo.param_vallist(secname,parname,subsec=-1)
if subsec is not specified, the list contain the values for param in each subsec
"""
try:
if subsec>=0:
return self[secname]['par'][subsec][parname]
else:
return [item[parname] for item in self[secname]['par']]
except:
if subsec>=0:
return []
else:
return [[]]
def param_string(self,secname,parname,subsec=-1):
"""
Return a string of comma separated list of values for the specified section/param
myvalliststring = foo.param_string(secname,parname,subsec=-1)
if subsec is not specified, the list contain the values for param in each subsec
"""
try:
return self.param_vallist(secname,parname,subsec).__repr__()[1:-1]
#alternate way:
#return "\n".join(self.param_vallist(secname,parname,subsec))
except:
return ''
if __name__ == '__main__':
print __doc__
| Python |
#!/usr/bin/python
"""
Manipulates Fortran Namelists
Defines
Namelist class
TODO: == As a Stand alone program ==
Print info about Fortran Namelists
Usage: namelist.py -f FILENAME [-n NAMELIST [-p PARNAME]]
FILENAME: path/name of config file
NAMELIST: namelist name (since a file may contain many namelists)
PARNAME: Name of parameter to print value for
if NAMELIST is not provided,
print the list of namelist present in file in list form:
['name1','name2',...]
if NAMELIST is provided (PARNAME not provided),
print all namelist param sin a "param=value" format, one per line
for multiple values of same param, print each one
as "param=value" format, one per line
if NAMELIST and PARNAME is provided,
if not specify, print all param in a "param=value" format
if specify and exist, print PARNAME's value only
for multiple values of same param, print each PARNAME's
values, one per line
This script is a generic Fortan namelist parser
and will recognize all namelist in a file with the following format,
and ignores the rest.
&namelistname
opt1 = value1
...
/
"""
__author__ = 'Stephane Chamberland (stephane.chamberland@ec.gc.ca)'
__version__ = '$Revision: 1.0 $'[11:-2]
__date__ = '$Date: 2006/09/05 21:16:24 $'
__copyright__ = 'Copyright (c) 2006 RPN'
__license__ = 'LGPL'
import sys
#sys.path.append("/usr/local/env/armnlib/modeles/SURF/python")
import re
from settings import Settings
# import sys
# import getopt
# import string
class Namelist(Settings):
"""
Namelist class
Scan a Fortran Namelist file and put Section/Parameters into a dictionary
Intentiation:
foo = Namelist(NamelistFile)
where NamelistFile can be a filename, an URL or a string
Functions:
[Pending]
This is a generic Fortan namelist parser
it will recognize all namelist in a file with the following format,
and ignores the rest.
&namelistname
opt1 = value1
...
/
"""
def parse(self):
"""Config file parser, called from the class initialization"""
varname = r'\b[a-zA-Z][a-zA-Z0-9_]*\b'
valueInt = re.compile(r'[+-]?[0-9]+')
valueReal = re.compile(r'[+-]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)')
valueNumber = re.compile(r'\b(([\+\-]?[0-9]+)?\.)?[0-9]*([eE][-+]?[0-9]+)?')
valueBool = re.compile(r"(\.(true|false|t|f)\.)",re.I)
valueTrue = re.compile(r"(\.(true|t)\.)",re.I)
spaces = r'[\s\t]*'
quote = re.compile(r"[\s\t]*[\'\"]")
namelistname = re.compile(r"^[\s\t]*&(" + varname + r")[\s\t]*$")
paramname = re.compile(r"[\s\t]*(" + varname+r')[\s\t]*=[\s\t]*')
namlistend = re.compile(r"^" + spaces + r"/" + spaces + r"$")
#split sections/namelists
mynmlfile = {}
mynmlname = ''
for item in self.clean(self._setContent.split("\n"),cleancomma=1):
if re.match(namelistname,item):
mynmlname = re.sub(namelistname,r"\1",item)
mynmlfile[mynmlname] = {
'raw' : [],
'par' : [{}]
}
elif re.match(namlistend,item):
mynmlname = ''
else:
if mynmlname:
mynmlfile[mynmlname]['raw'].append(item)
#parse param in each section/namelist
for mynmlname in mynmlfile.keys():
#split strings
bb = []
for item in mynmlfile[mynmlname]['raw']:
bb.extend(self.splitstring(item))
#split comma and =
aa = []
for item in bb:
if not re.match(quote,item):
aa.extend(re.sub(r"[\s\t]*=",r" =\n",re.sub(r",+",r"\n",item)).split("\n"))
else:
aa.append(item)
del(bb)
aa = self.clean(aa,cleancomma=1)
myparname = ''
for item in aa:
if re.search(paramname,item):
myparname = re.sub(paramname,r"\1",item).lower()
mynmlfile[mynmlname]['par'][0][myparname] = []
elif paramname:
#removed quotes, spaces (then how to distinguish .t. of ".t."?)
if re.match(valueBool,item):
if re.match(valueTrue,item):
mynmlfile[mynmlname]['par'][0][myparname].append('.true.')
else:
mynmlfile[mynmlname]['par'][0][myparname].append('.false.')
else:
mynmlfile[mynmlname]['par'][0][myparname].append(re.sub(r"(^[\'\"]|[\'\"]$)",r"",item.strip()).strip())
return mynmlfile
# def usage():
# """Print usage"""
# print main.__doc__
#
#
# def main(argv):
# """Print info about Fortran Namelists
#
# Usage: namelist.py -f FILENAME [-n NAMELIST [-p PARNAME]]
#
# FILENAME: path/name of config file
# NAMELIST: namelist name (since a file may contain many namelists)
# PARNAME: Name of parameter to print value for
#
# if NAMELIST is not provided,
# print the list of namelist present in file in list form:
# ['name1','name2',...]
# if NAMELIST is provided (PARNAME not provided),
# print all namelist param sin a "param=value" format, one per line
# for multiple values of same param, print each one
# as "param=value" format, one per line
# if NAMELIST and PARNAME is provided,
# if not specify, print all param in a "param=value" format
# if specify and exist, print PARNAME's value only
# for multiple values of same param, print each PARNAME's
# values, one per line
#
# This script is a generic Fortan namelist parser
# and will recognize all namelist in a file with the following format,
# and ignores the rest.
#
# &namelistname
# opt1 = value1
# ...
# /
#
# """
# filename = ""
# nmlname = ""
# param = ""
# metafile = ""
# try:
# opts, args = getopt.getopt(argv, \
# "Hf:n:p:m:", \
# ["help","file=","nml=","param=","metafile="])
# except getopt.GetoptError:
# usage()
# sys.exit(2)
# for opt, arg in opts:
# if opt in ("-H", "--help"):
# usage()
# sys.exit(1)
# elif opt in ("-f","--file"):
# filename = arg
# elif opt in ("-n","--nml"):
# nmlname = arg.lower()
# elif opt in ("-p","--param"):
# param = arg.lower()
# #...metafile disabled for now...
# #elif opt in ("-m","--metafile"):
# # metafile = arg
# #Get namelist opt/val
# if (filename):
# nmlopt = getnmlopt(filename)
# if (nmlname):
# if (param):
# try:
# for myval in nmlopt[nmlname][param]:
# #print param," = ",myval
# print myval
# except:
# pass
# elif (metafile):
# pass
# else:
# try:
# for mykey in nmlopt[nmlname].keys():
# for myval in nmlopt[nmlname][mykey]:
# print mykey," = ",myval
# except:
# print
# else:
# try:
# print nmlopt.keys()
# except:
# pass
# else:
# usage()
# sys.exit(2)
#
# if __name__ == '__main__':
# main(sys.argv[1:])
| Python |
#!/usr/bin/python
"""
General settings class to read/manipulate data from settings file
This class is meant to be subclassed to parse the settings file data, print the settings...
"""
__author__ = 'Stephane Chamberland (stephane.chamberland@ec.gc.ca)'
__version__ = '$Revision: 1.0 $'[11:-2]
__date__ = '$Date: 2006/08/31 21:16:24 $'
__copyright__ = 'Copyright (c) 2006 RPN'
__license__ = 'LGPL'
import sys
#sys.path.append("/usr/local/env/armnlib/modeles/SURF/python")
import re
from openanything import openAnything
class Settings(dict):
"""
the dict is organised as
dict[secName]['raw'] = ['sectionContent w/o comments, empty lines, lead/trail blanks']
dict[secName]['par'][subSec#][parName] = [val1,val2...]
"""
def __init__(self,settingFile):
dict.__init__(self)
self._setFile = settingFile
self._setContent = openAnything(settingFile).read()
self.update(self.parse())
#==== Helper functions for Parsing of files
def clean(self,mystringlist,commentexpr=r"^[\s\t]*\#.*$",spacemerge=0,cleancomma=0):
"""
Remove leading and trailing blanks, comments/empty lines from a list of strings
mystringlist = foo.clean(mystringlist,spacemerge=0,commentline=r"^[\s\t]*\#",cleancharlist="")
commentline: definition of commentline
spacemerge: if <>0, merge/collapse multi space
cleancomma: Remove leading and trailing commas
"""
aa = mystringlist
if cleancomma:
aa = [re.sub("(^([\s\t]*\,)+)|((\,[\s\t]*)+$)","",item).strip() for item in aa]
if commentexpr:
aa = [re.sub(commentexpr,"",item).strip() for item in aa]
if spacemerge:
aa = [re.sub("[\s\t]+"," ",item).strip() for item in aa if len(item.strip()) <> 0]
else:
aa = [item.strip() for item in aa if len(item.strip()) <> 0]
return aa
def splitstring(self,mystr):
"""
Split a string in a list of strings at quote boundaries
Input: String
Output: list of strings
"""
dquote=r'(^[^\"\']*)(\"[^"]*\")(.*)$'
squote=r"(^[^\"\']*)(\'[^']*\')(.*$)"
mystrarr = re.sub(dquote,r"\1\n\2\n\3",re.sub(squote,r"\1\n\2\n\3",mystr)).split("\n")
#remove zerolenght items
mystrarr = [item for item in mystrarr if len(item) <> 0]
if len(mystrarr) > 1:
mystrarr2 = []
for item in mystrarr:
mystrarr2.extend(self.splitstring(item))
mystrarr = mystrarr2
return mystrarr
#==== Virtual function that derived class must implement
def parse(self):
"""
Virtual function that must be implemented by derived class
Parse the file content in the self._setContent string
Return a dictionary of the parsed setting file organized as:
dict[secName]['raw'] = 'sectionContent w/o comments; w/ collapsed spaces'
dict[secName]['par'][subSec#][parName] = [val1,val2...]
"""
return { all: {'par': [] ,'raw': self.clean(self._setContent.split("\n"))}}
#==== Output function
def sec_string(self,secname):
"""
Return a string containing the "cleaned" content of a sectionContent
mysecstring = foo.sec_string(secname)
"""
try:
return "\n".join(self[secname]['raw'])
except:
return ''
def param_singleval(self,secname,parname):
aa = self.param_vallist(secname,parname)
if aa[0]:
return self.param_vallist(secname,parname)[0][0]
else:
return ''
def param_vallist(self,secname,parname,subsec=-1):
"""
Return a list of values for the specified section/param
myvallist = foo.param_vallist(secname,parname,subsec=-1)
if subsec is not specified, the list contain the values for param in each subsec
"""
try:
if subsec>=0:
return self[secname]['par'][subsec][parname]
else:
return [item[parname] for item in self[secname]['par']]
except:
if subsec>=0:
return []
else:
return [[]]
def param_string(self,secname,parname,subsec=-1):
"""
Return a string of comma separated list of values for the specified section/param
myvalliststring = foo.param_string(secname,parname,subsec=-1)
if subsec is not specified, the list contain the values for param in each subsec
"""
try:
return self.param_vallist(secname,parname,subsec).__repr__()[1:-1]
#alternate way:
#return "\n".join(self.param_vallist(secname,parname,subsec))
except:
return ''
if __name__ == '__main__':
print __doc__
| Python |
#!/usr/bin/env python
""" Test Viewer Application for Foscam Camera module """
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
import foscam
import Image
from StringIO import StringIO
ImageReadyEventId = 1382
class ImageReadyEvent(QEvent):
def __init__(self, image):
QEvent.__init__(self, ImageReadyEventId)
self._image = image
def image(self):
return self._image
def videoCallback(frame, userdata=None):
ire = ImageReadyEvent(frame)
qApp.postEvent(userdata, ire)
class ViewApp(QWidget):
def __init__(self, *args, **kw):
apply(QWidget.__init__, (self,)+args, kw)
bup = QPushButton('Up', self)
bdn = QPushButton('Down', self)
ble = QPushButton('Left', self)
bri = QPushButton('Right', self)
play = QPushButton('Play', self)
stop = QPushButton('Stop', self)
hbox = QHBoxLayout(self)
self.setLayout(hbox)
frame = QWidget(self)
grid = QGridLayout(frame)
frame.setLayout(grid)
grid.addWidget(bup, 0, 1)
grid.addWidget(bdn, 2, 1)
grid.addWidget(ble, 1, 0)
grid.addWidget(bri, 1, 2)
grid.addWidget(play, 7, 1)
grid.addWidget(stop, 8, 1)
hbox.addWidget(frame)
self.image_label = QLabel('Hello', self)
self.image_label.resize(640, 480)
hbox.addWidget(self.image_label)
buttons = [bup, bdn, ble, bri]
downs = [self.up, self.down, self.left, self.right]
for i in range(len(buttons)):
buttons[i].pressed.connect(downs[i])
buttons[i].released.connect(self.stop)
play.clicked.connect(self.playVideo)
stop.clicked.connect(self.stopVideo)
qApp.lastWindowClosed.connect(self.stopVideo)
self.direction = 0
self.foscam = foscam.FoscamCamera('192.168.0.120', 'admin')
def up(self):
self.direction = self.foscam.UP
self.foscam.move(self.direction)
def down(self):
self.direction = self.foscam.DOWN
self.foscam.move(self.direction)
def left(self):
self.direction = self.foscam.LEFT
self.foscam.move(self.direction)
def right(self):
self.direction = self.foscam.RIGHT
self.foscam.move(self.direction)
def stop(self):
self.foscam.move(self.direction + 1)
def playVideo(self):
self.foscam.startVideo(videoCallback, self)
def stopVideo(self):
self.foscam.stopVideo()
def event(self, e):
if e.type() == ImageReadyEventId:
data = e.image()
im = Image.open(StringIO(data))
self.qim = QImage(im.tostring(), im.size[0], im.size[1], QImage.Format_RGB888)
self.pm = QPixmap.fromImage(self.qim)
self.image_label.setPixmap(self.pm)
self.image_label.update()
return 1
return QWidget.event(self, e)
if __name__ == '__main__':
app = QApplication(sys.argv)
mw = ViewApp()
mw.resize(720, 480)
mw.show()
app.exec_()
| Python |
#!/usr/bin/env python
"""
A simple module to exploit my Foscam F1891W pan/tilt camera.
I obtained information on the CGI interface from Foscam's document
entitled "MJPEG Camera CGI v1.21.pdf" from www.foscam.com
Only the functionality that interested me is implemented here.
Additional functions can be easily added by referencing the above
CGI documentation.
Ken Ramsey, 18Feb2013
"""
import urllib
import time
from threading import Thread
import sys
def dummy_videoframe_handler(frame, userdata=None):
"""test video frame handler. It assumes the userdata coming
in is a Counter object with an increment method and a count method"""
sys.stdout.write('Got frame %d\r' % userdata.count())
sys.stdout.flush()
userdata.increment()
def findFrame(parent, fp, callback=None, userdata=None):
while parent.isPlaying():
line = fp.readline()
if line[:len('--ipcamera')] == '--ipcamera':
fp.readline()
content_length = int(fp.readline().split(':')[1].strip())
fp.readline()
jpeg = fp.read(content_length)
if callback:
callback(jpeg, userdata)
class FoscamCamera(object):
UP = 0
STOP_UP = 1
DOWN = 2
STOP_DOWN = 3
LEFT = 4
STOP_LEFT = 5
RIGHT = 6
STOP_RIGHT = 7
def __init__(self, url='', user='', pwd=''):
super(FoscamCamera, self).__init__()
self._user = user
self._pwd = pwd
self._url = url
self._isPlaying = 0
def isPlaying(self):
return self._isPlaying
def setIsPlaying(self, val):
self._isPlaying = val
def setURL(self, url):
self._url = url
def url(self):
return self._url
def setUser(self, usr):
self._user = usr
def user(self):
return self._user
def setPassword(self, pwd):
self._pwd = pwd
def password(self):
return self._pwd
def setUserAndPassword(self, user, password):
self.setUser(user)
self.setPassword(password)
def move(self, direction):
cmd = {'command':direction}
f = self.sendCommand('decoder_control.cgi', cmd)
def snapshot(self):
f = self.sendCommand('snapshot.cgi', {})
return f.read()
def startVideo(self, callback=None, userdata=None):
if not self.isPlaying():
cmds = { 'resolution':32, 'rate':0 }
f = self.sendCommand('videostream.cgi', cmds)
self.videothread = Thread(target=findFrame,
args=(self, f, callback, userdata))
self.setIsPlaying(1)
self.videothread.start()
def stopVideo(self):
if self.isPlaying():
self.setIsPlaying(0)
self.videothread.join()
def sendCommand(self, cgi, parameterDict):
url = 'http://%s/%s?user=%s&pwd=%s' % (self.url(),
cgi,
self.user(),
self.password())
for param in parameterDict:
url = url + '&%s=%s' % (param, parameterDict[param])
return urllib.urlopen(url)
if __name__ == '__main__':
TESTURL = '192.168.0.120'
print
print 'testing the Foscam camera code'
print
foscam = FoscamCamera(TESTURL, 'admin')
def move_a_little(fos, go, stop):
fos.move(go)
time.sleep(2)
print ' - stopping move'
fos.move(stop)
print 'moving up'
move_a_little(foscam, foscam.UP, foscam.STOP_UP)
print 'moving down'
move_a_little(foscam, foscam.DOWN, foscam.STOP_DOWN)
print 'moving left'
move_a_little(foscam, foscam.LEFT, foscam.STOP_LEFT)
print 'moving right'
move_a_little(foscam, foscam.RIGHT, foscam.STOP_RIGHT)
print
print 'taking a few snapshots'
for i in xrange(1, 11):
data = foscam.snapshot()
open('snapshot-%02d.jpg' % i, 'wb').write(data)
sys.stdout.write('wrote snapshot %d\r' % i)
sys.stdout.flush()
print
class Counter(object):
def __init__(self):
super(Counter,self).__init__()
self._count = 0
def increment(self):
self._count += 1
def count(self):
return self._count
print
print 'playing a little video (30 seconds worth)'
counter = Counter()
foscam.startVideo(dummy_videoframe_handler, counter)
time.sleep(30)
print
print 'stopping video'
foscam.stopVideo()
print
nframes = counter.count() - 1
print
print nframes, 'frames in ~30 secs for ~', nframes/30.0, 'fps'
print
print 'done!'
| Python |
#!/usr/bin/env python
#
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for pytracker."""
__author__ = 'dcoker@google.com (Doug Coker)'
import unittest
import pytracker
class StoryTest(unittest.TestCase):
STORY_A = """
<story>
<id type="integer">129150</id>
<story_type>release</story_type>
<url>http://tracker/story/show/129150</url>
<current_state>unstarted</current_state>
<description></description>
<name>last frontend push before Google IO</name>
<requested_by>Gorbachev</requested_by>
<owned_by>Stalin</owned_by>
<created_at type="datetime">2009/04/17 00:47:50 GMT</created_at>
<deadline type="datetime">2009/05/21 19:00:00 GMT</deadline>
<iteration>
<number>5</number>
<start type="datetime">2009/05/26 00:00:04 GMT</start>
<finish type="datetime">2009/06/09 00:00:04 GMT</finish>
</iteration>
</story>
"""
def testFromXmlA(self):
s = pytracker.Story.FromXml(self.STORY_A)
self.assertEquals(129150, s.GetStoryId())
self.assertEquals('release', s.GetStoryType())
self.assertEquals('http://tracker/story/show/129150', s.GetUrl())
self.assertEquals('unstarted', s.GetCurrentState())
self.assertEquals('', s.GetDescription())
self.assertEquals('Gorbachev', s.GetRequestedBy())
self.assertEquals('Stalin', s.GetOwnedBy())
self.assertEquals(1239929270, s.GetCreatedAt())
self.assertEquals(1242932400, s.GetDeadline())
self.assertEquals(5, s.GetIteration())
STORY_B = """
<story>
<id type="integer">129150</id>
<story_type>release</story_type>
<url>http://tracker/story/show/129150</url>
<current_state>unstarted</current_state>
<name>last frontend push before Google IO</name>
<requested_by>Gorbachev</requested_by>
<created_at type="datetime">2009/04/17 00:47:50 GMT</created_at>
<deadline type="datetime">2009/05/21 19:00:00 GMT</deadline>
<iteration>
<number>5</number>
<start type="datetime">2009/05/26 00:00:04 GMT</start>
<finish type="datetime">2009/06/09 00:00:04 GMT</finish>
</iteration>
</story>
"""
def testFromXmlB(self):
s = pytracker.Story.FromXml(self.STORY_B)
self.assertEquals(129150, s.GetStoryId())
self.assertEquals('release', s.GetStoryType())
self.assertEquals('http://tracker/story/show/129150', s.GetUrl())
self.assertEquals('unstarted', s.GetCurrentState())
# missing fields default to None, but distinguished from empty string!
self.assertEquals(None, s.GetDescription())
self.assertEquals('Gorbachev', s.GetRequestedBy())
self.assertEquals(None, s.GetOwnedBy())
self.assertEquals(1239929270, s.GetCreatedAt())
self.assertEquals(1242932400, s.GetDeadline())
self.assertEquals(5, s.GetIteration())
STORY_C = """
<story>
<id type="integer">1234</id>
<story_type>bug</story_type>
<url>http://www.pivotaltracker.com/story/show/1234</url>
<estimate type="integer">-1</estimate>
<current_state>started</current_state>
<description>Now, Scotty!</description>
<name>More power to shields</name>
<requested_by>James Kirk</requested_by>
<owned_by>Montgomery Scott</owned_by>
<created_at type="datetime">2008/12/10 00:00:00 UTC</created_at>
<accepted_at type="datetime">2008/12/10 00:00:00 UTC</accepted_at>
<iteration>
<number>3</number>
<start type="datetime">2009/01/05 00:00:02 UTC</start>
<finish type="datetime">2009/01/19 00:00:02 UTC</finish>
</iteration>
<labels>label 1,label 2,label 3</labels>
</story>
"""
def testFromXmlC(self):
s = pytracker.Story.FromXml(self.STORY_C)
self.assertEquals(1234, s.GetStoryId())
self.assertEquals('bug', s.GetStoryType())
self.assertEquals('http://www.pivotaltracker.com/story/show/1234',
s.GetUrl())
self.assertEquals('started', s.GetCurrentState())
self.assertEquals('Now, Scotty!', s.GetDescription())
self.assertEquals('More power to shields', s.GetName())
self.assertEquals('James Kirk', s.GetRequestedBy())
self.assertEquals('Montgomery Scott', s.GetOwnedBy())
self.assertEquals(1228867200, s.GetCreatedAt())
self.assertEquals(None, s.GetDeadline())
self.assertEquals(3, s.GetIteration())
self.assertEquals('label 1,label 2,label 3', s.GetLabelsAsString())
def testAddLabels(self):
s = pytracker.Story.FromXml(self.STORY_A)
self.assertEquals(None, s.GetLabelsAsString()) # no labels initially
s.AddLabel('bbq')
self.assertEquals('bbq', s.GetLabelsAsString())
s.AddLabel('alpha')
self.assertEquals('alpha,bbq', s.GetLabelsAsString())
def testAddRemoveLabels(self):
s = pytracker.Story.FromXml(self.STORY_C)
self.assertEquals('label 1,label 2,label 3', s.GetLabelsAsString())
s.RemoveLabel('label 1')
self.assertEquals('label 2,label 3', s.GetLabelsAsString())
s.AddLabel('label 1')
self.assertEquals('label 1,label 2,label 3', s.GetLabelsAsString())
s.RemoveLabel('label 1')
self.assertEquals('label 2,label 3', s.GetLabelsAsString())
s.RemoveLabel('label 2')
self.assertEquals('label 3', s.GetLabelsAsString())
s.RemoveLabel('label 3')
self.assertEquals('', s.GetLabelsAsString())
s.RemoveLabel('label 4') # removing nonexistant labels is OK!
self.assertEquals('', s.GetLabelsAsString())
EMPTY_STORY = """<?xml version="1.0" encoding="utf-8"?><story/>"""
def testNewStory(self):
s = pytracker.Story()
self.assertEquals(self.EMPTY_STORY, s.ToXml())
s.AddLabel('red')
self.assertEquals(
"""<?xml version="1.0" encoding="utf-8"?><story>"""
"""<labels>red</labels></story>""", s.ToXml())
s.AddLabel('green')
self.assertEquals(
"""<?xml version="1.0" encoding="utf-8"?><story>"""
"""<labels>green,red</labels></story>""", s.ToXml())
s.SetEstimate(3)
self.assertEquals(
"""<?xml version="1.0" encoding="utf-8"?><story>"""
"""<estimate>3</estimate><labels>green,red</labels></story>""",
s.ToXml())
def testSetDescription(self):
story = pytracker.Story()
story.SetDescription('day after day the sun')
self.assertEquals('day after day the sun', story.GetDescription())
story.SetDescription('')
self.assertEquals('', story.GetDescription())
self.assertEquals('<?xml version="1.0" encoding="utf-8"?><story><description></description></story>',
story.ToXml())
def testSetOwnedBy(self):
story = pytracker.Story()
story.SetOwnedBy('dcoker')
self.assertEquals('<?xml version="1.0" encoding="utf-8"?><story><owned_by>dcoker</owned_by></story>',
story.ToXml())
def testSetReportedBy(self):
story = pytracker.Story()
story.SetRequestedBy('dcoker')
self.assertEquals('<?xml version="1.0" encoding="utf-8"?><story><requested_by>dcoker</requested_by></story>',
story.ToXml())
def testSetDeadline(self):
story = pytracker.Story()
story.SetDeadline(1290153802.0)
self.assertEquals('<?xml version="1.0" encoding="utf-8"?><story><deadline type="datetime">2010/11/19 08:03:22 UTC</deadline></story>',
story.ToXml())
def testSetCreatedAt(self):
story = pytracker.Story()
story.SetCreatedAt(1290153802.0)
self.assertEquals('<?xml version="1.0" encoding="utf-8"?><story><created_at type="datetime">2010/11/19 08:03:22 UTC</created_at></story>',
story.ToXml())
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
#
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""pytracker is a Python wrapper around the Tracker API."""
__author__ = 'dcoker@google.com (Doug Coker)'
import calendar
import cookielib
import re
import time
import urllib
import urllib2
import xml.dom
from xml.dom import minidom
import xml.parsers.expat
import xml.sax.saxutils
DEFAULT_BASE_API_URL = 'https://www.pivotaltracker.com/services/v2/'
# Some fields specify UTC, some GMT?
_TRACKER_DATETIME_RE = re.compile(r'^\d{4}/\d{2}/\d{2} .*(GMT|UTC)$')
def TrackerDatetimeToYMD(pdt):
assert _TRACKER_DATETIME_RE.match(pdt)
pdt = pdt.split()[0]
pdt = pdt.replace('/', '-')
return pdt
class Tracker(object):
"""Tracker API."""
def __init__(self, project_id, auth,
base_api_url=DEFAULT_BASE_API_URL):
"""Constructor.
If you are debugging API calls, you may want to use a non-HTTPS API URL:
base_api_url="http://www.pivotaltracker.com/services/v2/"
Args:
project_id: the Tracker ID (integer).
auth: a TrackerAuth instance.
base_api_url: the base URL of the HTTP API (with trailing /).
"""
self.project_id = project_id
self.base_api_url = base_api_url
cookies = cookielib.CookieJar()
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
self.token = auth.EstablishAuthToken(self.opener)
def _Api(self, request, method, body=None):
url = self.base_api_url + 'projects/%d/%s' % (self.project_id,
request)
headers = {}
if self.token:
headers['X-TrackerToken'] = self.token
if not body and method == 'GET':
# Do a GET
req = urllib2.Request(url, None, headers)
else:
headers['Content-Type'] = 'application/xml'
req = urllib2.Request(url, body, headers)
req.get_method = lambda: method
try:
res = self.opener.open(req)
except urllib2.HTTPError, e:
message = "HTTP Status Code: %s\nMessage: %s\nURL: %s\nError: %s" % (e.code, e.msg, e.geturl(), e.read())
raise TrackerApiException(message)
return res.read()
def _ApiQueryStories(self, query=None):
if query:
output = self._Api('stories?filter=' + urllib.quote_plus(query),
'GET')
else:
output = self._Api('stories', 'GET')
# Hack: throw an exception if we didn't get valid XML.
xml.parsers.expat.ParserCreate('utf-8').Parse(output, True)
return output
def GetStoriesXml(self):
return self._ApiQueryStories()
def GetReleaseStoriesXml(self):
return self._ApiQueryStories('type:release')
def GetStories(self, filt=None):
"""Fetch all Stories that satisfy the filter.
Args:
filt: a Tracker search filter.
Returns:
List of Story().
"""
stories = self._ApiQueryStories(filt)
parsed = xml.dom.minidom.parseString(stories)
els = parsed.getElementsByTagName('story')
lst = []
for el in els:
lst.append(Story.FromXml(el.toxml()))
return lst
def GetStory(self, story_id):
story_xml = self._Api('stories/%d' % story_id, 'GET')
return Story.FromXml(story_xml)
def AddComment(self, story_id, comment):
comment = '<note><text>%s</text></note>' % xml.sax.saxutils.escape(comment)
self._Api('stories/%d/notes' % story_id, 'POST', comment)
def AddNewStory(self, story):
"""Persists a new story to Tracker and returns the new Story."""
story_xml = story.ToXml()
res = self._Api('stories', 'POST', story_xml)
story = Story.FromXml(res)
return story
def UpdateStoryById(self, story_id, story):
"""Persist changes to an existing story to Tracker.
Use this method if you are changing a story without first retreiving the
story.
Args:
story_id: The ID of the story to mutate
story: The Story containing values to change.
Returns:
The updated Story().
"""
story_xml = story.ToXml()
res = self._Api('stories/%d' % story_id, 'PUT', story_xml)
return Story.FromXml(res)
def UpdateStory(self, story):
"""Persists changes to an existing story to Tracker.
Use this method if you have a full Story object created by one of the query
methods.
Args:
story: a Story()
Returns:
The updated Story().
"""
story_xml = story.ToXml()
res = self._Api('stories/%d' % story.GetStoryId(), 'PUT', story_xml)
return Story.FromXml(res)
def DeleteStory(self, story_id):
"""Deletes a story by story ID."""
self._Api('stories/%d' % story_id, 'DELETE', '')
class TrackerAuth(object):
"""Abstract base class for establishing credentials for pytracker."""
def __init__(self, username, password):
self.username = username
self.password = password
def EstablishAuthToken(self, opener):
"""Returns the value for use as the X-TrackerToken HTTP header, or None.
This method may mutate the cookie jar via opener.
Args:
opener: a urllib2.OpenerDirector instance that will be used for
subsequent HTTP API calls.
"""
raise NotImplementedError()
class TrackerAuthException(Exception):
"""Raised when something goes wrong with authentication."""
class NoTokensAvailableException(Exception):
"""Raised when HostedTrackerAuth can't find any tokens for this user."""
class TrackerApiException(Exception):
"""Raised when Tracker returns an error."""
class HostedTrackerAuth(TrackerAuth):
"""Authentication rules for hosted Tracker instances."""
def EstablishAuthToken(self, opener):
"""Returns the first auth token returned by /services/tokens/active."""
url = 'https://www.pivotaltracker.com/services/tokens/active'
data = urllib.urlencode((('username', self.username),
('password', self.password)))
try:
req = opener.open(url, data)
except urllib2.HTTPError, e:
if e.code == 404:
raise NoTokensAvailableException(
'Did you create any? Check https://www.pivotaltracker.com/profile')
else:
raise
res = req.read()
dom = minidom.parseString(res)
token = dom.getElementsByTagName('guid')[0].firstChild.data
return token
class Story(object):
"""Represents a Story.
This class can be used to represent a complete Story (generally queried from
the Tracker class), or can contain partial information for update or create
operations (constructed with default constructor).
Internally, Story uses None to indicate that the client has not specified a
value for the field or that it has not been parsed from XML. This enables us
to use the same Story object to define an update to multiple stories, without
requiring that the client first fetch, parse, and update an existing story.
This is supported by all mutable fields except for labels, which are
represented by Tracker as a comma-separated list of strings in a single tag
body. For label operations on existing stories to be performed correctly,
the Story must first be fetched from the server so that the existing labels
are not lost.
"""
# Fields that can be treated as strings when embedding in XML.
UPDATE_FIELDS = ('story_type', 'current_state', 'name',
'description', 'estimate', 'requested_by', 'owned_by')
# Type: immutable ints.
story_id = None
iteration_number = None
# Type: immutable times (secs since epoch)
created_at = None
# Type: mutable time (secs since epoch)
deadline = None
# Type: mutable set (API methods expose as string)
labels = None
# Type: immutable strings
url = None
# Type: mutable strings
requested_by = None
owned_by = None
story_type = None
current_state = None
description = None
name = None
estimate = None
def __str__(self):
return "Story(%r)" % self.__dict__
@staticmethod
def FromXml(as_xml):
"""Parses an XML string into a Story.
Args:
as_xml: a full XML document from the Tracker API.
Returns:
Story()
"""
parsed = minidom.parseString(as_xml.encode('utf-8'))
story = Story()
story.story_id = int(parsed.getElementsByTagName('id')[0].firstChild.data)
story.url = parsed.getElementsByTagName('url')[0].firstChild.data
story.owned_by = Story._GetDataFromTag(parsed, 'owned_by')
story.created_at = Story._ParseDatetimeIntoSecs(parsed, 'created_at')
story.requested_by = Story._GetDataFromTag(parsed, 'requested_by')
iteration = Story._GetDataFromTag(parsed, 'number')
if iteration:
story.iteration_number = int(iteration)
story.SetStoryType(
parsed.getElementsByTagName('story_type')[0].firstChild.data)
story.SetCurrentState(
parsed.getElementsByTagName('current_state')[0].firstChild.data)
story.SetName(Story._GetDataFromTag(parsed, 'name'))
story.SetDescription(Story._GetDataFromTag(parsed, 'description'))
story.SetDeadline(Story._ParseDatetimeIntoSecs(parsed, 'deadline'))
estimate = Story._GetDataFromTag(parsed, 'estimate')
if estimate is not None:
story.estimate = estimate
labels = Story._GetDataFromTag(parsed, 'labels')
if labels is not None:
story.AddLabelsFromString(labels)
return story
@staticmethod
def _GetDataFromTag(dom, tag):
"""Retrieve value associated with the tag, if any.
Args:
dom: XML DOM object
tag: name of the desired tag
Returns:
None (if tag doesn't exist), empty string (if tag exists, but body is
empty), or the tag body.
"""
tags = dom.getElementsByTagName(tag)
if not tags:
return None
elif tags[0].hasChildNodes():
return tags[0].firstChild.data
else:
return ''
@staticmethod
def _ParseDatetimeIntoSecs(dom, tag):
"""Returns the tag body parsed into seconds-since-epoch."""
el = dom.getElementsByTagName(tag)
if not el:
return None
assert el[0].getAttribute('type') == 'datetime'
data = el[0].firstChild.data
# Tracker emits datetime strings in UTC or GMT.
# The [:-4] strips the timezone indicator
when = time.strptime(data[:-4], '%Y/%m/%d %H:%M:%S')
# calendar.timegm treats the tuple as GMT
return calendar.timegm(when)
# Immutable fields
def GetStoryId(self):
return self.story_id
def GetIteration(self):
return self.iteration_number
def GetUrl(self):
return self.url
# Mutable fields
def GetRequestedBy(self):
return self.requested_by
def SetRequestedBy(self, requested_by):
self.requested_by = requested_by
def GetOwnedBy(self):
return self.owned_by
def SetOwnedBy(self, owned_by):
self.owned_by = owned_by
def GetStoryType(self):
return self.story_type
def SetStoryType(self, story_type):
assert story_type in ['bug', 'chore', 'release', 'feature']
self.story_type = story_type
def GetCurrentState(self):
return self.current_state
def SetCurrentState(self, current_state):
self.current_state = current_state
def GetName(self):
return self.name
def SetName(self, name):
self.name = name
def GetEstimate(self):
return self.estimate
def SetEstimate(self, estimate):
self.estimate = estimate
def GetDescription(self):
return self.description
def SetDescription(self, description):
self.description = description
def GetDeadline(self):
return self.deadline
def SetDeadline(self, secs_since_epoch):
self.deadline = secs_since_epoch
def GetCreatedAt(self):
return self.created_at
def SetCreatedAt(self, secs_since_epoch):
self.created_at = secs_since_epoch
def AddLabel(self, label):
"""Adds a label (see caveat in class comment)."""
if self.labels is None:
self.labels = set()
self.labels.add(label)
def RemoveLabel(self, label):
"""Removes a label (see caveat in class comment)."""
if self.labels is None:
self.labels = set()
else:
try:
self.labels.remove(label)
except KeyError:
pass
def AddLabelsFromString(self, labels):
"""Adds a set of labels from a comma-delimited string (see class caveat)."""
if self.labels is None:
self.labels = set()
self.labels = self.labels.union([x.strip() for x in labels.split(',')])
def GetLabelsAsString(self):
"""Returns the labels as a comma delimited list of strings."""
if self.labels is None:
return None
lst = list(self.labels)
lst.sort()
return ','.join(lst)
def ToXml(self):
"""Converts this Story to an XML string."""
doc = xml.dom.getDOMImplementation().createDocument(None, 'story', None)
story = doc.getElementsByTagName('story')[0]
# Most fields are just simple strings or ints, so we treat them all in the
# same way.
for field_name in self.UPDATE_FIELDS:
v = getattr(self, field_name)
if v is not None:
new_tag = doc.createElement(field_name)
new_tag.appendChild(doc.createTextNode(unicode(v)))
story.appendChild(new_tag)
# Labels are represented internally as sets.
if self.labels:
labels_tag = doc.createElement('labels')
labels_tag.appendChild(doc.createTextNode(self.GetLabelsAsString()))
story.appendChild(labels_tag)
# Dates are special
DATE_FORMAT = '%Y/%m/%d %H:%M:%S UTC'
if self.deadline:
formatted = time.strftime(DATE_FORMAT, time.gmtime(self.deadline))
deadline_tag = doc.createElement('deadline')
deadline_tag.setAttribute('type', 'datetime')
deadline_tag.appendChild(doc.createTextNode(formatted))
story.appendChild(deadline_tag)
if self.created_at:
formatted = time.strftime(DATE_FORMAT, time.gmtime(self.created_at))
created_at_tag = doc.createElement('created_at')
created_at_tag.setAttribute('type', 'datetime')
created_at_tag.appendChild(doc.createTextNode(formatted))
story.appendChild(created_at_tag)
return doc.toxml('utf-8')
| Python |
#!/usr/bin/python2.5
#
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Updates a Google Calendar with releases from a Pivotal Tracker project.
Dependencies:
gdata-python-client:
Download: http://code.google.com/p/gdata-python-client/downloads/list
Ubuntu package: python-gdata
beautifulsoup:
Download: http://www.crummy.com/software/BeautifulSoup/
Ubuntu package: python-beautifulsoup
To use:
- Create a ~/.tracker2gcal-auth.ini file containing:
[tracker]
username: username
password: password
[calendar]
username: username@google.com
password: password
- Get the calendar ID from the "Settings" pane of the calendar in Google
Calendar. Example:
google.com_t60bvmdcq9e2ai7el5lk00ns9s@group.calendar.google.com
- Get the Tracker Project ID from the URL of the Tracker UI.
- Run tracker2gcal:
tracker2gcal.py -t 1728 -c YOUR_CALENDAR_ID
"""
__author__ = 'dcoker@google.com (Doug Coker)'
import ConfigParser
import logging
import optparse
import os
import re
import sys
import time
import urllib
import atom
import atom.service
from BeautifulSoup import BeautifulStoneSoup
import gdata.calendar
import gdata.calendar.service
import gdata.service
import pytracker
import pytrackergoogle
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
_DATESTRING_RE = re.compile(r'^\d{4}-\d{2}-\d{2}')
_DEFAULT_TRACKER_BASE_API_URL = pytracker.DEFAULT_BASE_API_URL
def YMDToSeconds(ds):
assert _DATESTRING_RE.match(ds)
return time.mktime(time.strptime(ds, '%Y-%m-%d'))
def YMDPlusOneDay(ds):
assert _DATESTRING_RE.match(ds)
next = time.strftime('%Y-%m-%d',
time.localtime(time.mktime(
time.strptime(ds, '%Y-%m-%d')) + 86400))
return next
class Calendar(object):
"""Wrapper for the Google Calendar GData API."""
def __init__(self, calendar_id, auth):
self.calendar_id = calendar_id
self.cal_client = gdata.calendar.service.CalendarService()
self.cal_client.email = auth[0]
self.cal_client.password = auth[1]
self.cal_client.source = 'tracker2gcal'
self.cal_client.ProgrammaticLogin()
self.feed = self._GetEventFeed()
def _GetEventFeedUri(self):
return ('/calendar/feeds/%s/private/full' %
urllib.quote_plus(self.calendar_id))
def _GetBatchEventFeedUri(self):
return self._GetEventFeedUri() + '/batch'
def _GetEventFeed(self):
return self.cal_client.GetCalendarEventFeed(uri=self._GetEventFeedUri())
def Visit(self, filt, callback):
"""Visits all events in the calendar that satisfy filt with callback."""
events = self._GetEventFeed()
for event in events.entry:
if filt(event):
callback(event)
def DeleteEventVisitor(self, event):
"""A Visitor that deletes the event."""
logging.info('deleting %s', event.title.text)
self.cal_client.DeleteEvent(event.GetEditLink().href)
def CreateForBatch(self, title, when, content=''):
"""Creates an Event for batch operation.
Args:
title: title of event
when: date only, in %Y/%m/%d format
content: content event body
Returns:
The populated CalendarEventEntry.
"""
event = gdata.calendar.CalendarEventEntry()
event.title = atom.Title(text=title)
event.content = atom.Content(text=content)
stop = YMDPlusOneDay(when)
event.when.append(gdata.calendar.When(start_time=when, end_time=stop))
event.batch_id = gdata.BatchId(text='insert-request')
return event
def GetEventFeedForBatch(self):
"""Returns an Event feed intended for batch operations."""
return gdata.calendar.CalendarEventFeed()
def RunBatch(self, event_feed):
"""Executes the adds in event_feed."""
response_feed = self.cal_client.ExecuteBatch(
event_feed,
url=self._GetBatchEventFeedUri())
for entry in response_feed.entry:
logging.info('id %s / status %s / reason %s',
entry.batch_id.text,
entry.batch_status.code,
entry.batch_status.reason)
def GetCredentials(parser, scope):
u = parser.get(scope, 'username')
p = parser.get(scope, 'password')
assert u
assert p
return (u, p)
def main(opts):
parser = ConfigParser.RawConfigParser()
parser.read(opts.credentials)
cal_auth = GetCredentials(parser, 'calendar')
tracker_auth = GetCredentials(parser, 'tracker')
c = Calendar(opts.calendar_id, cal_auth)
if opts.tracker_base_api_url.find('.google.com') != -1:
tracker_auth = pytrackergoogle.TrackerAtGoogleAuth(*tracker_auth)
else:
tracker_auth = pytracker.HostedTrackerAuth(*tracker_auth)
t = pytracker.Tracker(opts.tracker_id, tracker_auth,
base_api_url=opts.tracker_base_api_url)
# For now, we care only about type:release stories.
# We could extend this to also include stories with
# specific tags.
def FilterForReleases(event):
return event.title.text.find('[release') != -1
c.Visit(FilterForReleases, c.DeleteEventVisitor)
xml = t.GetReleaseStoriesXml()
soup = BeautifulStoneSoup(xml)
batch = c.GetEventFeedForBatch()
releases = soup.stories.findAll('story')
logging.info('found %d releases', len(releases))
for e in releases:
url = e.url.contents[0]
# can't use .name -- soup would return the tag name.
title = e.find('name').contents[0]
# The release date is computed by Tracker and is an estimate of story
# completion.
release_date = pytracker.TrackerDatetimeToYMD(
e.iteration.finish.contents[0])
suffix = '[release, floating]'
calendar_date = release_date
body = (url + '\n\n\n\n'
'[This event was automatically created based on data from Tracker]')
# Hard deadlines are special.
if e.find('deadline'):
scheduled_date = pytracker.TrackerDatetimeToYMD(e.deadline.contents[0])
suffix = '[release, hard]'
# Prefix the event with "SLIPPING" if release > deadline
scheduled_secs = YMDToSeconds(scheduled_date)
release_secs = YMDToSeconds(release_date)
delta = release_secs - scheduled_secs
if release_secs > scheduled_secs:
title = 'SLIPPING %.1f days: %s' % (delta / 86400, title)
calendar_date = scheduled_date
title = title + ' ' + suffix
batch.AddInsert(entry=c.CreateForBatch(title, calendar_date, body))
logging.info('%s: %s / %s', url, title, calendar_date)
c.RunBatch(batch)
def ParseOpts():
"""Parses the command line arguments and returns a dictionary of flags."""
parser = optparse.OptionParser()
default_credentials_file = os.path.join(os.environ['HOME'],
'.tracker2gcal-auth.ini')
parser.add_option('-u', '--credentials-file', dest='credentials',
help='file containing authentication details',
default=default_credentials_file)
parser.add_option('-c', '--calendar-id', dest='calendar_id',
help='target calendar id', metavar='ID')
parser.add_option('-t', '--tracker-id', dest='tracker_id',
help='tracker id', metavar='ID', type='int')
parser.add_option('-b', '--tracker-base-api-url',
dest='tracker_base_api_url',
help='the base URL of the Tracker API (including trailing '
'slash).',
default=_DEFAULT_TRACKER_BASE_API_URL)
(options, _) = parser.parse_args()
# Check for errors
errors = False
if getattr(options, 'tracker_id') is None:
logging.error('Missing -t/--tracker-id option')
errors = True
if not re.match(r'^https?://[^/]+.*/$',
getattr(options, 'tracker_base_api_url')):
logging.error('-b/--tracker-base-api-url does not look like a valid URL.')
errors = True
if getattr(options, 'calendar_id') is None:
logging.error('Missing -c/--calendar-id option')
errors = True
else:
if not re.search(r'@group.calendar.google.com$', options.calendar_id):
logging.error('%s does not look like a valid calendar ID.',
options.calendar_id)
errors = True
if errors:
parser.print_help()
sys.exit(1)
return options
if __name__ == '__main__':
main(ParseOpts())
| Python |
#! /usr/bin/env python
from PyQt4 import QtGui,QtCore
import heapq
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow,self).__init__()
self.setGeometry(100,100,1000,800)
self.MasterWidget=QtGui.QWidget(self)
self.MasterLayout = QtGui.QHBoxLayout(self.MasterWidget)
self.TheGrid = TheGrid(self)
self.MasterLayout.addWidget(self.TheGrid)
self.setCentralWidget(self.MasterWidget)
class TheGrid(QtGui.QWidget):
def __init__(self,parent = None):
super(TheGrid,self).__init__()
self.MasterLayout = QtGui.QGridLayout()
self.setLayout(self.MasterLayout)
self.MasterLayout.setSpacing(0)
self.Cells = []
# self.setFixedSize(1000,800)
gridsize = 30
for x in range(gridsize):
self.Cells.append([])
for y in range(gridsize):
print "x :", x, " y: ",y
string = "%s-%s" % (x,y)
temp = Cell(x,y)
self.Cells[x].append(temp)
self.MasterLayout.addWidget(temp,y,x)
button = QtGui.QPushButton('go')
self.MasterLayout.addWidget(button,gridsize,0,1,gridsize)
button.clicked.connect(self.GO)
def GO(self):
startx,starty = self.getStart()
print "start: %s-%s" % (startx,starty)
goalx,goaly = self.getGoal()
print "Goal: %s-%s" % (goalx,goaly)
path = self.findPath(startx,starty,goalx,goaly)
def getStart(self):
for i in range(len(self.Cells)):
for j in range(len(self.Cells[i])):
if self.Cells[i][j].status == 2:
return self.Cells[i][j].xx,self.Cells[i][j].yy
return -1,-1
def getGoal(self):
for i in range(len(self.Cells)):
for j in range(len(self.Cells[i])):
if self.Cells[i][j].status == 3:
return self.Cells[i][j].xx,self.Cells[i][j].yy
return -1,-1
def findPath(self,startx,starty,goalx,goaly):
OpenList=[]
ClosedList=[]
# calc H for the start cell
self.Cells[startx][starty].calcHScore(goalx,goaly)
self.Cells[startx][starty].calcFScore()
heapq.heappush(OpenList,(self.Cells[startx][starty].F,self.Cells[startx][starty]))
# calc H for all cells attached to the start square
while len(OpenList) > 0:
currentF,currentcell=heapq.heappop(OpenList)
ClosedList.append(currentcell)
for cx in range(0,2,1):
for cy in range(0,2,1):
# we start at the upper left of the attached cells
x = (currentcell.xx - 1) + cx
y = (currentcell.yy - 1) + cy
# does the cell exist
if self.Cells[x][y]:
print "found a cell: %s-%s" % (x,y)
# check if it is in the closed list:
if self.Cells[x][y] in ClosedList:
continue
# check if it is a wall
if self.Cells[x][y].status == 1:
continue
if self.Cells[x][y].status == 3:
ClosedList.append(currentcell)
print ClosedList
break
if self.Cells[x][y] in OpenList:
# pass
if self.Cells[x][y].G < currentcell.G:
self.Cell[x][y].parent = currentcell
# recalc G F
# resort
else:
# set parent to the currentcell
self.Cells[x][y].parent = currentcell
# not in open list calc F
self.Cells[x][y].calcHScore(goalx,goaly)
# set G score , the if decides if it is diagonally adjected or not
if (x == 0 and y == 0) or (x == 2 and y == 0) or (x == 0 and y == 2) or (x == 2 and y == 2):
# its diagonal
self.Cells[x][y].G=self.Cells[x][y].parent.G + 14
else:
# its orthogonal
self.Cells[x][y].G=self.Cells[x][y].parent.G + 10
self.Cells[x][y].calcFScore()
# add it to the openlist heap
heapq.heappush(OpenList,(self.Cells[x][y].F,self.Cells[x][y]))
else:
continue
class Cell(QtGui.QWidget):
def __init__(self,xx,yy,parent = None):
super(Cell,self).__init__()
self.xx = xx
self.yy = yy
self.coords = "%s-%s" % (xx,yy)
self.status = 0
# status :
# 0 empty
# 1 wall
# 2 start
# 3 finish
self.F = 0
self.G = 0
self.H = 0
def paintEvent(self,e):
painter = QtGui.QPainter(self)
painter.fillRect(self.rect(),colors[self.status])
def mousePressEvent(self,e):
print self.coords
self.status +=1
if self.status == 4:
self.status = 0
self.update()
def calcHScore(self,goalx,goaly):
print self.xx,goalx,self.yy,goaly
temp = abs(self.xx - goalx) + abs(self.yy - goaly)
temp = temp * 10
self.H = temp
print "coords: " + self.coords + "H: " + str(self.H)
def calcFScore(self):
self.F = self.H + self.G
print "coords: " + self.coords + " F: " + str(self.F)
#
Application=QtGui.QApplication([])
pathfinder=MainWindow()
colors=[QtGui.QColor('#AAAAAA'),QtGui.QColor('#000000'),QtGui.QColor('#FF0000'),QtGui.QColor('#00FF00')]
pathfinder.show()
Application.exec_()
| Python |
#! /usr/bin/env python
from PyQt4 import QtGui,QtCore
import heapq
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow,self).__init__()
self.setGeometry(100,100,1000,800)
self.MasterWidget=QtGui.QWidget(self)
self.MasterLayout = QtGui.QHBoxLayout(self.MasterWidget)
self.TheGrid = TheGrid(self)
self.MasterLayout.addWidget(self.TheGrid)
self.setCentralWidget(self.MasterWidget)
class TheGrid(QtGui.QWidget):
def __init__(self,parent = None):
super(TheGrid,self).__init__()
self.MasterLayout = QtGui.QGridLayout()
self.setLayout(self.MasterLayout)
self.MasterLayout.setSpacing(0)
self.Cells = []
# self.setFixedSize(1000,800)
gridsize = 30
for x in range(gridsize):
self.Cells.append([])
for y in range(gridsize):
print "x :", x, " y: ",y
string = "%s-%s" % (x,y)
temp = Cell(x,y)
self.Cells[x].append(temp)
self.MasterLayout.addWidget(temp,y,x)
button = QtGui.QPushButton('go')
self.MasterLayout.addWidget(button,gridsize,0,1,gridsize)
button.clicked.connect(self.GO)
def GO(self):
startx,starty = self.getStart()
print "start: %s-%s" % (startx,starty)
goalx,goaly = self.getGoal()
print "Goal: %s-%s" % (goalx,goaly)
path = self.findPath(startx,starty,goalx,goaly)
def getStart(self):
for i in range(len(self.Cells)):
for j in range(len(self.Cells[i])):
if self.Cells[i][j].status == 2:
return self.Cells[i][j].xx,self.Cells[i][j].yy
return -1,-1
def getGoal(self):
for i in range(len(self.Cells)):
for j in range(len(self.Cells[i])):
if self.Cells[i][j].status == 3:
return self.Cells[i][j].xx,self.Cells[i][j].yy
return -1,-1
def findPath(self,startx,starty,goalx,goaly):
OpenList=[]
ClosedList=[]
# calc H for the start cell
self.Cells[startx][starty].calcHScore(goalx,goaly)
self.Cells[startx][starty].calcFScore()
heapq.heappush(OpenList,(self.Cells[startx][starty].F,self.Cells[startx][starty]))
# calc H for all cells attached to the start square
while len(OpenList) > 0:
currentF,currentcell=heapq.heappop(OpenList)
ClosedList.append(currentcell)
for cx in range(0,2,1):
for cy in range(0,2,1):
# we start at the upper left of the attached cells
x = (currentcell.xx - 1) + cx
y = (currentcell.yy - 1) + cy
# does the cell exist
if self.Cells[x][y]:
print "found a cell: %s-%s" % (x,y)
# check if it is in the closed list:
if self.Cells[x][y] in ClosedList:
continue
# check if it is a wall
if self.Cells[x][y].status == 1:
continue
if self.Cells[x][y].status == 3:
ClosedList.append(currentcell)
print ClosedList
break
if self.Cells[x][y] in OpenList:
# pass
if self.Cells[x][y].G < currentcell.G:
self.Cell[x][y].parent = currentcell
# recalc G F
# resort
else:
# set parent to the currentcell
self.Cells[x][y].parent = currentcell
# not in open list calc F
self.Cells[x][y].calcHScore(goalx,goaly)
# set G score , the if decides if it is diagonally adjected or not
if (x == 0 and y == 0) or (x == 2 and y == 0) or (x == 0 and y == 2) or (x == 2 and y == 2):
# its diagonal
self.Cells[x][y].G=self.Cells[x][y].parent.G + 14
else:
# its orthogonal
self.Cells[x][y].G=self.Cells[x][y].parent.G + 10
self.Cells[x][y].calcFScore()
# add it to the openlist heap
heapq.heappush(OpenList,(self.Cells[x][y].F,self.Cells[x][y]))
else:
continue
class Cell(QtGui.QWidget):
def __init__(self,xx,yy,parent = None):
super(Cell,self).__init__()
self.xx = xx
self.yy = yy
self.coords = "%s-%s" % (xx,yy)
self.status = 0
# status :
# 0 empty
# 1 wall
# 2 start
# 3 finish
self.F = 0
self.G = 0
self.H = 0
def paintEvent(self,e):
painter = QtGui.QPainter(self)
painter.fillRect(self.rect(),colors[self.status])
def mousePressEvent(self,e):
print self.coords
self.status +=1
if self.status == 4:
self.status = 0
self.update()
def calcHScore(self,goalx,goaly):
print self.xx,goalx,self.yy,goaly
temp = abs(self.xx - goalx) + abs(self.yy - goaly)
temp = temp * 10
self.H = temp
print "coords: " + self.coords + "H: " + str(self.H)
def calcFScore(self):
self.F = self.H + self.G
print "coords: " + self.coords + " F: " + str(self.F)
#
Application=QtGui.QApplication([])
pathfinder=MainWindow()
colors=[QtGui.QColor('#AAAAAA'),QtGui.QColor('#000000'),QtGui.QColor('#FF0000'),QtGui.QColor('#00FF00')]
pathfinder.show()
Application.exec_()
| Python |
'''
Created on May 6, 2013
@author: lord voltron
'''
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtDeclarative import *
import myAstar
class ImageProvider(QDeclarativeImageProvider):
# changed = Signal()
def __init__(self,parent = None):
QDeclarativeImageProvider.__init__(self, QDeclarativeImageProvider.Image)
self.parent = parent
def requestImage(self,id,size,requestedSize):
print "requestImage: ", id
if "path" in id:
return self.parent.astar.path
class astarWrapper(QObject):
def __init__(self):
QObject.__init__(self)
self.astar = myAstar.AStar()
@Slot(int,int)
def setStart(self,x,y):
self.astar.setStart(x, y)
@Slot(int,int)
def setEnd(self,x,y):
self.astar.setEnd(x, y)
@Slot()
def updatePath(self):
self.astar.process()
# Our main window
class MainWindow(QDeclarativeView):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle("Main Window")
# Renders 'view.qml'
#com = communicate()
pathfinder = astarWrapper()
self.ip = ImageProvider(pathfinder)
#pathfinder.astar.processDone.connect(self.ip.emitChanged)
#pathfinder.astar.processDone.connect(self.sepp)
engine = self.engine()
engine.addImageProvider("path",self.ip)
rc = self.rootContext()
#rc.setContextProperty("communicate",com)
rc.setContextProperty("pathfinder",pathfinder)
self.setSource(QUrl.fromLocalFile('view.qml'))
# QML resizes to main window
view = self.rootObject()
self.setResizeMode(QDeclarativeView.SizeRootObjectToView)
pathfinder.astar.processDone.connect(view.updatePathImage)
if __name__ == '__main__':
# Create the Qt Application
app = QApplication(sys.argv)
# Create and show the main window
window = MainWindow()
window.show()
# Run the main Qt loop
sys.exit(app.exec_()) | Python |
import Image
im = Image.open("hurga.png")
sizex,sizey = im.size
count = 0
for i in range(sizex):
for j in range(sizey):
pixel = im.getpixel((i,j))
if pixel != (0,0,0,0):
count += 1
print count
| Python |
#! /usr/bin/env python
import heapq
import Image
import sys
from time import time
from PySide import QtCore,QtGui
class Cell(object):
def __init__(self, x, y, reachable):
"""
the cell ansich, x und y sind selbsterklaerend
type ist walkable,impassable, some kind of walkable
"""
self.reachable = reachable # fuer den anfang ist es ein bool
self.x = x
self.y = y
self.parent = None
self.g = 0 # wieviel kostet es mich vom start punkt aus zu dieser zelle ?
self.h = 0 # wieviele kostet es mich von mir aus zum ziel punkt (heuristic)
self.f = 0 # die summe aus G und H ergibt den gesammt wert der zelle
self.diagonal = False # ob die zelle diagonal zur referenz zelle ist. das is ein versuch
self.closed = False
def setReachable(self, pixel):
walkable = (255,255,255,255) # white is walkable
if pixel == walkable:
self.reachable = True
else:
self.reachable = False
class AStar(QtCore.QObject):
processDone = QtCore.Signal()
def __init__(self):
QtCore.QObject.__init__(self)
self.cells = []
self.gridHeight = -1
self.gridWidth = -1
self.init_lists()
self.init_grid()
def init_lists(self):
self.op = []
heapq.heapify(self.op)
self.cl = set()
self.cellsvisited = 0
def reset_cells(self):
for i in self.cells:
i.parent=None
i.g=0
i.h=0
i.f=0
i.diagonal=False
i.closed=False
def init_grid(self):
print "Initializing Grid .."
im = Image.open(open('summonersrift-astar-map20.png',"rb"))
self.im = im
self.gridHeight = im.size[1]
self.gridWidth = im.size[0]
self.gridHeightminus = im.size[1]-1
self.gridWidthminus = im.size[0]-1
for y in range(0, self.gridHeight-1):
for x in range(0, self.gridWidth-1):
#print x,y
tempcell = Cell(x, y, False)
tempcell.setReachable(im.getpixel((x,y)))
self.cells.append(tempcell)
print "Grid Stats: "
print " Height: " + str(self.gridHeight)
print " Width: " + str(self.gridWidth)
print " Size: " + str(len(self.cells))
print "Done.\n"
self.path = QtGui.QImage(QtCore.QSize(self.gridWidth,self.gridHeight),QtGui.QImage.Format_ARGB32_Premultiplied)
self.path.fill(QtCore.Qt.transparent)
def setStart(self,x,y):
self.start = self.get_cell(int(x),int(y))
print self.start
def setEnd(self,x,y):
self.end = self.get_cell(int(x),int(y))
print self.end
def get_heuristic(self, cell):
"""
rechnet den heuristischen wert aus.
das ist wieviele x und y muss ich gehen um zum ziel zu kommen, aber wirklich laenge und breite nicht die diagonale
"""
return 10 * (abs(cell.x - self.end.x) + abs(cell.y - self.end.y))
def get_cell(self, x, y):
"""
gibt die passende zelle zu den koordianten zurueck, da die self.cells ein eindimensionales feld ist
wird y * width + x gerechnet
"""
return self.cells[y * (self.gridWidth -1) + x]
def get_adjacent_cells(self, cell):
#print cell.x,cell.y
cells = []
#cells postions
# -1,-1 0,-1 1,-1
# -1,0 0,0 1,0
# -1,1 0,1 1,1
#x = cell.x
#y = cell.y
# folgendes if trifft alle zellen die innerhalb des grid liegens und eine einheit vom rand entfernt sind
# alle die an den kanten liegen ignorier ich. weil der ist eh schwarz
if (cell.y - 1) >= 0 and (cell.y + 1) <= (self.gridHeightminus) and (cell.x - 1) >= 0 and (cell.x + 1) <= (self.gridWidthminus):
# -1 , -1
tmpcell = self.get_cell(cell.x - 1, cell.y - 1)
tmpcell.diagonal = True
cells.append(tmpcell)
# 0,-1
tmpcell = self.get_cell(cell.x - 0, cell.y - 1)
#tmpcell.diagonal = False
cells.append(tmpcell)
# 1,-1
tmpcell = self.get_cell(cell.x + 1, cell.y - 1)
tmpcell.diagonal = True
cells.append(tmpcell)
# -1 , 0
tmpcell = self.get_cell(cell.x - 1, cell.y)
#tmpcell.diagonal = False
cells.append(tmpcell)
# 0,0 bin ich selbst, das tumma nicht dazu
# 1,0
# -1 , -1
tmpcell = self.get_cell(cell.x + 1, cell.y)
#tmpcell.diagonal = False
cells.append(tmpcell)
# -1 , 1
tmpcell = self.get_cell(cell.x - 1, cell.y + 1)
tmpcell.diagonal = True
cells.append(tmpcell)
# 0,1
tmpcell = self.get_cell(cell.x, cell.y + 1)
#tmpcell.diagonal = False
cells.append(tmpcell)
# 1,1
# -1 , -1
tmpcell = self.get_cell(cell.x + 1, cell.y + 1)
tmpcell.diagonal = True
cells.append(tmpcell)
return cells
def display_path(self,timetaken):
print "drawing path"
cell = self.end
count = 0
painter = QtGui.QPainter(self.path)
pen = QtGui.QPen()
pen.setColor(QtGui.QColor(255,0,255))
painter.setPen(pen)
thepath = []
while cell.parent is not self.start:
cell = cell.parent
count += 1
try:
#print "path: cell: %d,%d'" % (cell.x,cell.y)
self.im.putpixel((cell.x,cell.y),(255,0,255,255))
except AttributeError,e:
print e
self.im.putpixel((self.start.x,self.start.y),(0,255,0,255))
self.im.putpixel((self.end.x,self.end.y),(0,0,255,255))
self.im.show()
thepath.append((cell.x,cell.y))
#painter.drawPoint(cell.x,cell.y)
print "cells visited %s steps: %s - time: %s" %(self.cellsvisited,count,timetaken)
painter.end()
self.smoothpath(thepath)
self.path.save("hurga.png")
self.processDone.emit()
# self.showImage()
def smoothpath(self,path):
totallength=0
revpath = []
for i in reversed(path):
revpath.append(i)
newpath = []
currentStart = revpath[0]
newpath.append(currentStart)
currentCell = revpath[1]
for i in range(1,len(revpath)-1):
status,deltalength = self.checkWalkable(currentStart,currentCell)
if status:
currentCell = revpath[i+1]
else:
status,deltalength = self.checkWalkable(currentStart,revpath[i-1])
totallength += int(deltalength)
currentStart = currentCell
currentCell = revpath[i+1]
newpath.append(currentStart)
newpath.append(revpath[len(revpath)-1])
print newpath
painter = QtGui.QPainter(self.path)
pen = QtGui.QPen()
pen.setColor(QtGui.QColor(255,215,0))
painter.setPen(pen)
for i in range(len(newpath)-1):
x1,y1 = newpath[i]
x2,y2 = newpath[i+1]
painter.drawLine(x1,y1,x2,y2)
painter.end()
print "totallength: ",totallength
self.calcpathlength()
def calcpathlength(self):
# this is slow and stupid but at the moment the most accurate
count = 0
for i in range(self.gridWidth-1):
for j in range(self.gridHeight -1 ):
#print self.path.pixel(i,j)
if self.path.pixel(i,j) != 0:
count += 1
print "pixel count: ",count
# 700 units = 70 px
# 1px = 10 units
# 380 u/s default movement speed
mvspeed = 380.0
multiplicator = 10.0
totalunits = count * multiplicator
time = float(totalunits/mvspeed)
print "time: ",time
def checkWalkable(self,start,end):
coords = self.bresenham_line(start,end)
for i in coords:
tempcell = self.get_cell(i[0], i[1])
if tempcell.reachable:
pass
else:
return False, None
return True,len(coords)
def bresenham_line(self,(x,y),(x2,y2)):
"""Brensenham line algorithm"""
steep = 0
coords = []
dx = abs(x2 - x)
if (x2 - x) > 0: sx = 1
else: sx = -1
dy = abs(y2 - y)
if (y2 - y) > 0: sy = 1
else: sy = -1
if dy > dx:
steep = 1
x,y = y,x
dx,dy = dy,dx
sx,sy = sy,sx
d = (2 * dy) - dx
for i in range(0,dx):
if steep: coords.append((y,x))
else: coords.append((x,y))
while d >= 0:
y = y + sy
d = d - (2 * dx)
x = x + sx
d = d + (2 * dy)
coords.append((x2,y2))
return coords
def update_cell(self, adj, cell):
"""
Update adjacent cell
@param adj adjacent cell to current cell
@param cell current cell being processed
"""
if adj.diagonal:
adj.g = cell.g + 14
else:
adj.g = cell.g + 10
adj.h = self.get_heuristic(adj)
adj.parent = cell
adj.f = adj.h + adj.g
def process(self):
print "starting process"
self.init_lists()
self.reset_cells()
self.path = QtGui.QImage(QtCore.QSize(self.gridWidth,self.gridHeight),QtGui.QImage.Format_ARGB32_Premultiplied)
self.path.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(self.path)
pen = QtGui.QPen()
pen.setColor(QtGui.QColor(22,210,230))
painter.setPen(pen)
starttime=time()
# add starting cell to open heap queue
heapq.heappush(self.op, (self.start.f, self.start))
while len(self.op):
self.cellsvisited += 1
# pop cell from heap queue
f, cell = heapq.heappop(self.op)
# add cell to closed list so we don't process it twice
self.cl.add(cell)
#cell.closed = True
#self.im.putpixel((cell.x,cell.y),(200,200,200,255))
#painter.drawPoint(cell.x,cell.y)
# if ending cell, display found path
if cell is self.end:
stoptime=time()
painter.end()
self.display_path(stoptime-starttime)
break
# get adjacent cells for cell
adj_cells = self.get_adjacent_cells(cell)
for c in adj_cells:
#print c.x, c.y, c.reachable
if c.reachable and c not in self.cl:
#print "meep"
if (c.f, c) in self.op:
#print c.reachable
# if adj cell in open list, check if current path is
# better than the one previously found for this adj
# cell.
if c.g > cell.g + 10:
self.update_cell(c, cell)
else:
self.update_cell(c, cell)
# add adj cell to open list
heapq.heappush(self.op, (c.f, c))
def showImage(self):
self.im.putpixel((self.start.x,self.start.y),(0,255,0,255))
self.im.putpixel((self.end.x,self.end.y),(0,0,255,255))
self.im.show()
#findme = AStar()
#findme.process()
| Python |
#! /usr/bin/env python
import heapq
import Image
import sys
from time import time
from PySide import QtCore,QtGui
class Cell(object):
def __init__(self, x, y, reachable):
"""
the cell ansich, x und y sind selbsterklaerend
type ist walkable,impassable, some kind of walkable
"""
self.reachable = reachable # fuer den anfang ist es ein bool
self.x = x
self.y = y
self.parent = None
self.g = 0 # wieviel kostet es mich vom start punkt aus zu dieser zelle ?
self.h = 0 # wieviele kostet es mich von mir aus zum ziel punkt (heuristic)
self.f = 0 # die summe aus G und H ergibt den gesammt wert der zelle
self.diagonal = False # ob die zelle diagonal zur referenz zelle ist. das is ein versuch
self.closed = False
def setReachable(self, pixel):
walkable = (255,255,255,255) # white is walkable
if pixel == walkable:
self.reachable = True
else:
self.reachable = False
class AStar(QtCore.QObject):
processDone = QtCore.Signal()
def __init__(self):
QtCore.QObject.__init__(self)
self.cells = []
self.gridHeight = -1
self.gridWidth = -1
self.init_lists()
self.init_grid()
def init_lists(self):
self.op = []
heapq.heapify(self.op)
self.cl = set()
self.cellsvisited = 0
def reset_cells(self):
for i in self.cells:
i.parent=None
i.g=0
i.h=0
i.f=0
i.diagonal=False
i.closed=False
def init_grid(self):
print "Initializing Grid .."
im = Image.open(open('summonersrift-astar-map20.png',"rb"))
self.im = im
self.gridHeight = im.size[1]
self.gridWidth = im.size[0]
self.gridHeightminus = im.size[1]-1
self.gridWidthminus = im.size[0]-1
for y in range(0, self.gridHeight-1):
for x in range(0, self.gridWidth-1):
#print x,y
tempcell = Cell(x, y, False)
tempcell.setReachable(im.getpixel((x,y)))
self.cells.append(tempcell)
print "Grid Stats: "
print " Height: " + str(self.gridHeight)
print " Width: " + str(self.gridWidth)
print " Size: " + str(len(self.cells))
print "Done.\n"
self.path = QtGui.QImage(QtCore.QSize(self.gridWidth,self.gridHeight),QtGui.QImage.Format_ARGB32_Premultiplied)
self.path.fill(QtCore.Qt.transparent)
def setStart(self,x,y):
self.start = self.get_cell(int(x),int(y))
print self.start
def setEnd(self,x,y):
self.end = self.get_cell(int(x),int(y))
print self.end
def get_heuristic(self, cell):
"""
rechnet den heuristischen wert aus.
das ist wieviele x und y muss ich gehen um zum ziel zu kommen, aber wirklich laenge und breite nicht die diagonale
"""
return 10 * (abs(cell.x - self.end.x) + abs(cell.y - self.end.y))
def get_cell(self, x, y):
"""
gibt die passende zelle zu den koordianten zurueck, da die self.cells ein eindimensionales feld ist
wird y * width + x gerechnet
"""
return self.cells[y * (self.gridWidth -1) + x]
def get_adjacent_cells(self, cell):
#print cell.x,cell.y
cells = []
#cells postions
# -1,-1 0,-1 1,-1
# -1,0 0,0 1,0
# -1,1 0,1 1,1
#x = cell.x
#y = cell.y
# folgendes if trifft alle zellen die innerhalb des grid liegens und eine einheit vom rand entfernt sind
# alle die an den kanten liegen ignorier ich. weil der ist eh schwarz
if (cell.y - 1) >= 0 and (cell.y + 1) <= (self.gridHeightminus) and (cell.x - 1) >= 0 and (cell.x + 1) <= (self.gridWidthminus):
# -1 , -1
tmpcell = self.get_cell(cell.x - 1, cell.y - 1)
tmpcell.diagonal = True
cells.append(tmpcell)
# 0,-1
tmpcell = self.get_cell(cell.x - 0, cell.y - 1)
#tmpcell.diagonal = False
cells.append(tmpcell)
# 1,-1
tmpcell = self.get_cell(cell.x + 1, cell.y - 1)
tmpcell.diagonal = True
cells.append(tmpcell)
# -1 , 0
tmpcell = self.get_cell(cell.x - 1, cell.y)
#tmpcell.diagonal = False
cells.append(tmpcell)
# 0,0 bin ich selbst, das tumma nicht dazu
# 1,0
# -1 , -1
tmpcell = self.get_cell(cell.x + 1, cell.y)
#tmpcell.diagonal = False
cells.append(tmpcell)
# -1 , 1
tmpcell = self.get_cell(cell.x - 1, cell.y + 1)
tmpcell.diagonal = True
cells.append(tmpcell)
# 0,1
tmpcell = self.get_cell(cell.x, cell.y + 1)
#tmpcell.diagonal = False
cells.append(tmpcell)
# 1,1
# -1 , -1
tmpcell = self.get_cell(cell.x + 1, cell.y + 1)
tmpcell.diagonal = True
cells.append(tmpcell)
return cells
def display_path(self,timetaken):
print "drawing path"
cell = self.end
count = 0
painter = QtGui.QPainter(self.path)
pen = QtGui.QPen()
pen.setColor(QtGui.QColor(255,0,255))
painter.setPen(pen)
thepath = []
while cell.parent is not self.start:
cell = cell.parent
count += 1
try:
#print "path: cell: %d,%d'" % (cell.x,cell.y)
self.im.putpixel((cell.x,cell.y),(255,0,255,255))
except AttributeError,e:
print e
self.im.putpixel((self.start.x,self.start.y),(0,255,0,255))
self.im.putpixel((self.end.x,self.end.y),(0,0,255,255))
self.im.show()
thepath.append((cell.x,cell.y))
#painter.drawPoint(cell.x,cell.y)
print "cells visited %s steps: %s - time: %s" %(self.cellsvisited,count,timetaken)
painter.end()
self.smoothpath(thepath)
self.path.save("hurga.png")
self.processDone.emit()
# self.showImage()
def smoothpath(self,path):
totallength=0
revpath = []
for i in reversed(path):
revpath.append(i)
newpath = []
currentStart = revpath[0]
newpath.append(currentStart)
currentCell = revpath[1]
for i in range(1,len(revpath)-1):
status,deltalength = self.checkWalkable(currentStart,currentCell)
if status:
currentCell = revpath[i+1]
else:
status,deltalength = self.checkWalkable(currentStart,revpath[i-1])
totallength += int(deltalength)
currentStart = currentCell
currentCell = revpath[i+1]
newpath.append(currentStart)
newpath.append(revpath[len(revpath)-1])
print newpath
painter = QtGui.QPainter(self.path)
pen = QtGui.QPen()
pen.setColor(QtGui.QColor(255,215,0))
painter.setPen(pen)
for i in range(len(newpath)-1):
x1,y1 = newpath[i]
x2,y2 = newpath[i+1]
painter.drawLine(x1,y1,x2,y2)
painter.end()
print "totallength: ",totallength
self.calcpathlength()
def calcpathlength(self):
# this is slow and stupid but at the moment the most accurate
count = 0
for i in range(self.gridWidth-1):
for j in range(self.gridHeight -1 ):
#print self.path.pixel(i,j)
if self.path.pixel(i,j) != 0:
count += 1
print "pixel count: ",count
# 700 units = 70 px
# 1px = 10 units
# 380 u/s default movement speed
mvspeed = 380.0
multiplicator = 10.0
totalunits = count * multiplicator
time = float(totalunits/mvspeed)
print "time: ",time
def checkWalkable(self,start,end):
coords = self.bresenham_line(start,end)
for i in coords:
tempcell = self.get_cell(i[0], i[1])
if tempcell.reachable:
pass
else:
return False, None
return True,len(coords)
def bresenham_line(self,(x,y),(x2,y2)):
"""Brensenham line algorithm"""
steep = 0
coords = []
dx = abs(x2 - x)
if (x2 - x) > 0: sx = 1
else: sx = -1
dy = abs(y2 - y)
if (y2 - y) > 0: sy = 1
else: sy = -1
if dy > dx:
steep = 1
x,y = y,x
dx,dy = dy,dx
sx,sy = sy,sx
d = (2 * dy) - dx
for i in range(0,dx):
if steep: coords.append((y,x))
else: coords.append((x,y))
while d >= 0:
y = y + sy
d = d - (2 * dx)
x = x + sx
d = d + (2 * dy)
coords.append((x2,y2))
return coords
def update_cell(self, adj, cell):
"""
Update adjacent cell
@param adj adjacent cell to current cell
@param cell current cell being processed
"""
if adj.diagonal:
adj.g = cell.g + 14
else:
adj.g = cell.g + 10
adj.h = self.get_heuristic(adj)
adj.parent = cell
adj.f = adj.h + adj.g
def process(self):
print "starting process"
self.init_lists()
self.reset_cells()
self.path = QtGui.QImage(QtCore.QSize(self.gridWidth,self.gridHeight),QtGui.QImage.Format_ARGB32_Premultiplied)
self.path.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(self.path)
pen = QtGui.QPen()
pen.setColor(QtGui.QColor(22,210,230))
painter.setPen(pen)
starttime=time()
# add starting cell to open heap queue
heapq.heappush(self.op, (self.start.f, self.start))
while len(self.op):
self.cellsvisited += 1
# pop cell from heap queue
f, cell = heapq.heappop(self.op)
# add cell to closed list so we don't process it twice
self.cl.add(cell)
#cell.closed = True
#self.im.putpixel((cell.x,cell.y),(200,200,200,255))
#painter.drawPoint(cell.x,cell.y)
# if ending cell, display found path
if cell is self.end:
stoptime=time()
painter.end()
self.display_path(stoptime-starttime)
break
# get adjacent cells for cell
adj_cells = self.get_adjacent_cells(cell)
for c in adj_cells:
#print c.x, c.y, c.reachable
if c.reachable and c not in self.cl:
#print "meep"
if (c.f, c) in self.op:
#print c.reachable
# if adj cell in open list, check if current path is
# better than the one previously found for this adj
# cell.
if c.g > cell.g + 10:
self.update_cell(c, cell)
else:
self.update_cell(c, cell)
# add adj cell to open list
heapq.heappush(self.op, (c.f, c))
def showImage(self):
self.im.putpixel((self.start.x,self.start.y),(0,255,0,255))
self.im.putpixel((self.end.x,self.end.y),(0,0,255,255))
self.im.show()
#findme = AStar()
#findme.process()
| Python |
#! /usr/bin/env python
version="Alpha 1.0"
from PyQt4 import QtGui
Application=QtGui.QApplication([])
from ftllibs.FTL import CHAMPS as CHAMPS
from ftllibs.ui.ChampionsTab import ChampTab
from ftllibs.ui.BuildTab import BuildTab
from ftllibs.ui.CompareTab import CompareTab
from ftllibs.ui.MasteriesTab import MasteriesTab
from ftllibs.ui.RunesTab import RunesTab
from ftllibs.ui.RecommendedTab import RecommendedTab
import os
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow,self).__init__()
self.setWindowTitle("For The LoLz - Version: %s - LoL Version: %s" % (version,"140"))
self.setGeometry(30,50,1200,800)
self.initUI(self)
def initUI(self,MainWindow):
self.MasterWidget=QtGui.QWidget(MainWindow)
self.MasterLayout = QtGui.QHBoxLayout(self.MasterWidget)
# Init Widgets
self.Champions = ChampTab()
self.Masteries = MasteriesTab()
self.Runes = RunesTab()
self.Options = QtGui.QWidget()
self.Compare = CompareTab()
self.Recommended = RecommendedTab(78)
# Tabs
self.MasterTab = QtGui.QTabWidget(MainWindow)
self.MasterTab.setTabsClosable(True)
self.MasterTab.setMovable(True)
self.MasterTab.addTab(self.Champions,"Champions")
self.MasterTab.addTab(self.Masteries,"Masteries")
self.MasterTab.addTab(self.Runes,"Runes")
self.MasterTab.addTab(self.Compare,"Compare")
self.MasterTab.addTab(self.Recommended,"Recom")
# layout stuff
self.MasterLayout.addWidget(self.MasterTab)
self.setCentralWidget(self.MasterWidget)
# Menu und Status Bar
exitAction = QtGui.QAction(QtGui.QIcon('images/icons/logout_normal_hover.png'), '&Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(QtGui.qApp.quit)
openMasteriesTabAction = QtGui.QAction(QtGui.QIcon('images/masteries/Mastermind.png'), '&Masteries',self)
openMasteriesTabAction.setShortcut('Ctrl+M')
openMasteriesTabAction.setStatusTip('Opens the Masteries Tab')
openMasteriesTabAction.triggered.connect(self.addMasteriesTab)
openRunesTabAction = QtGui.QAction(QtGui.QIcon('images/masteries/Archmages_Savvy_Mastery.png'), '&Runes',self)
openRunesTabAction.setShortcut('Ctrl+R')
openRunesTabAction.setStatusTip('Opens the Runes Tab')
openRunesTabAction.triggered.connect(self.addRunesTab)
openOptionsTabAction = QtGui.QAction(QtGui.QIcon('images/icons/settings_normal_hover.png'), '&Options',self)
openOptionsTabAction.setShortcut('Ctrl+R')
openOptionsTabAction.setStatusTip('Opens the Options Tab')
openOptionsTabAction.triggered.connect(self.addOptionsTab)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAction)
viewMenu = menubar.addMenu('&View')
viewMenu.addAction(openMasteriesTabAction)
viewMenu.addAction(openRunesTabAction)
viewMenu.addAction(openOptionsTabAction)
self.statusBar().showMessage('Welcome')
# Signals
self.MasterTab.tabCloseRequested[int].connect(self.tabClose)
self.Champions.S_OpenChampBuild[int].connect(self.addBuildTab)
def tabClose(self,tabnum):
if tabnum == 0:
pass
else:
if "Builds" in self.MasterTab.tabText(tabnum):
widget = self.MasterTab.widget(tabnum)
widget.RequestClose()
self.MasterTab.removeTab(tabnum)
def addMasteriesTab(self):
if self.MasterTab.indexOf(self.Masteries) != -1:
return
else:
self.MasterTab.addTab(self.Masteries,"Masteries")
def addRunesTab(self):
if self.MasterTab.indexOf(self.Runes) != -1:
return
else:
self.MasterTab.addTab(self.Runes,"Runes")
def addOptionsTab(self):
if self.MasterTab.indexOf(self.Options) != -1:
return
else:
self.MasterTab.addTab(self.Options,"Options")
def addBuildTab(self,ChampID):
found=False
print " addBuildTab -> champid ->",ChampID
ChampName=CHAMPS.GetChampName(ChampID)
TabString="%s's Builds" % (ChampName)
for i in range(0,self.MasterTab.count()):
if self.MasterTab.tabText(i) == TabString:
found=True
self.MasterTab.setCurrentIndex(i)
# TODO vieleicht TAB Widget Updaten ?
break
if not found:
Build=BuildTab(ChampID)
self.MasterTab.addTab(Build,TabString)
self.MasterTab.setCurrentWidget(Build)
# Ze App
#os.chdir("/home/stefan/mysvn/forthelolz/")
#Application=QtGui.QApplication([])
ForTheLoLz=MainWindow()
ForTheLoLz.show()
Application.exec_()
#### eval: (e2wm:start-management)
### emacs stuff
### Local Variables: ###
### mode:python ###
### comment-column: 0 ###
### comment-start: "###" ###
### comment-end:"###" ###
### compile-command: "/usr/bin/env python ~/mysvn/forthelolz/ForTheLoLz.py" ###
### eval: (svn-status-toggle-svn-verbose-flag) ###
### eval: (svn-status "~/mysvn/forthelolz") ###
### eval: (sit-for 1) ###
### eval: (switch-to-buffer "ForTheLoLz.py") ###
### eval: (e2wm:start-management) ###
### End: ###
| Python |
#! /usr/bin/env python
version="Alpha 1.0"
from PyQt4 import QtGui
Application=QtGui.QApplication([])
from ftllibs.FTL import CHAMPS as CHAMPS
from ftllibs.ui.ChampionsTab import ChampTab
from ftllibs.ui.BuildTab import BuildTab
from ftllibs.ui.CompareTab import CompareTab
from ftllibs.ui.MasteriesTab import MasteriesTab
from ftllibs.ui.RunesTab import RunesTab
from ftllibs.ui.RecommendedTab import RecommendedTab
import os
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow,self).__init__()
self.setWindowTitle("For The LoLz - Version: %s - LoL Version: %s" % (version,"140"))
self.setGeometry(30,50,1200,800)
self.initUI(self)
def initUI(self,MainWindow):
self.MasterWidget=QtGui.QWidget(MainWindow)
self.MasterLayout = QtGui.QHBoxLayout(self.MasterWidget)
# Init Widgets
self.Champions = ChampTab()
self.Masteries = MasteriesTab()
self.Runes = RunesTab()
self.Options = QtGui.QWidget()
self.Compare = CompareTab()
self.Recommended = RecommendedTab(78)
# Tabs
self.MasterTab = QtGui.QTabWidget(MainWindow)
self.MasterTab.setTabsClosable(True)
self.MasterTab.setMovable(True)
self.MasterTab.addTab(self.Champions,"Champions")
self.MasterTab.addTab(self.Masteries,"Masteries")
self.MasterTab.addTab(self.Runes,"Runes")
self.MasterTab.addTab(self.Compare,"Compare")
self.MasterTab.addTab(self.Recommended,"Recom")
# layout stuff
self.MasterLayout.addWidget(self.MasterTab)
self.setCentralWidget(self.MasterWidget)
# Menu und Status Bar
exitAction = QtGui.QAction(QtGui.QIcon('images/icons/logout_normal_hover.png'), '&Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(QtGui.qApp.quit)
openMasteriesTabAction = QtGui.QAction(QtGui.QIcon('images/masteries/Mastermind.png'), '&Masteries',self)
openMasteriesTabAction.setShortcut('Ctrl+M')
openMasteriesTabAction.setStatusTip('Opens the Masteries Tab')
openMasteriesTabAction.triggered.connect(self.addMasteriesTab)
openRunesTabAction = QtGui.QAction(QtGui.QIcon('images/masteries/Archmages_Savvy_Mastery.png'), '&Runes',self)
openRunesTabAction.setShortcut('Ctrl+R')
openRunesTabAction.setStatusTip('Opens the Runes Tab')
openRunesTabAction.triggered.connect(self.addRunesTab)
openOptionsTabAction = QtGui.QAction(QtGui.QIcon('images/icons/settings_normal_hover.png'), '&Options',self)
openOptionsTabAction.setShortcut('Ctrl+R')
openOptionsTabAction.setStatusTip('Opens the Options Tab')
openOptionsTabAction.triggered.connect(self.addOptionsTab)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAction)
viewMenu = menubar.addMenu('&View')
viewMenu.addAction(openMasteriesTabAction)
viewMenu.addAction(openRunesTabAction)
viewMenu.addAction(openOptionsTabAction)
self.statusBar().showMessage('Welcome')
# Signals
self.MasterTab.tabCloseRequested[int].connect(self.tabClose)
self.Champions.S_OpenChampBuild[int].connect(self.addBuildTab)
def tabClose(self,tabnum):
if tabnum == 0:
pass
else:
if "Builds" in self.MasterTab.tabText(tabnum):
widget = self.MasterTab.widget(tabnum)
widget.RequestClose()
self.MasterTab.removeTab(tabnum)
def addMasteriesTab(self):
if self.MasterTab.indexOf(self.Masteries) != -1:
return
else:
self.MasterTab.addTab(self.Masteries,"Masteries")
def addRunesTab(self):
if self.MasterTab.indexOf(self.Runes) != -1:
return
else:
self.MasterTab.addTab(self.Runes,"Runes")
def addOptionsTab(self):
if self.MasterTab.indexOf(self.Options) != -1:
return
else:
self.MasterTab.addTab(self.Options,"Options")
def addBuildTab(self,ChampID):
found=False
print " addBuildTab -> champid ->",ChampID
ChampName=CHAMPS.GetChampName(ChampID)
TabString="%s's Builds" % (ChampName)
for i in range(0,self.MasterTab.count()):
if self.MasterTab.tabText(i) == TabString:
found=True
self.MasterTab.setCurrentIndex(i)
# TODO vieleicht TAB Widget Updaten ?
break
if not found:
Build=BuildTab(ChampID)
self.MasterTab.addTab(Build,TabString)
self.MasterTab.setCurrentWidget(Build)
# Ze App
#os.chdir("/home/stefan/mysvn/forthelolz/")
#Application=QtGui.QApplication([])
ForTheLoLz=MainWindow()
ForTheLoLz.show()
Application.exec_()
#### eval: (e2wm:start-management)
### emacs stuff
### Local Variables: ###
### mode:python ###
### comment-column: 0 ###
### comment-start: "###" ###
### comment-end:"###" ###
### compile-command: "/usr/bin/env python ~/mysvn/forthelolz/ForTheLoLz.py" ###
### eval: (svn-status-toggle-svn-verbose-flag) ###
### eval: (svn-status "~/mysvn/forthelolz") ###
### eval: (sit-for 1) ###
### eval: (switch-to-buffer "ForTheLoLz.py") ###
### eval: (e2wm:start-management) ###
### End: ###
| Python |
class Item_3001():
def __init__(self):
self.parent=False
self.Name="Abyssal Scepter"
self.Icon="3001.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1026','1057']
self.Builds_Into=[]
self.Tags=['spell_block','spell_damage']
self.Costs = 1050
self.Total_Costs = 2650
self.Description="+70 Ability Power +57 Magic Resist UNIQUE Aura: Reduces the Magic Resist of nearby enemy champions by 20."
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 70.0
self.parent.Magic_Resist += 57.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3105():
def __init__(self):
self.parent=False
self.Name="Aegis of the Legion"
self.Icon="3105.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1028','1033','1029']
self.Builds_Into=[]
self.Tags=['health','spell_block','armor']
self.Costs = 750
self.Total_Costs = 1925
self.Description="+270 Health +18 Armor +24 Magic Resist UNIQUE Aura: Nearby allied champions gain 12 Armor, 15 Magic Resist, and 8 Attack Damage."
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Health += 270.0
self.parent.Armor += 18.0
self.parent.Magic_Resist += 24.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1052():
def __init__(self):
self.parent=False
self.Name="Amplifying Tome"
self.Icon="1052.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3098','3145','3041','3108','3057','3136','3135','3116','3152','3114','3187','3174']
self.Tags=['spell_damage']
self.Costs = 435
self.Total_Costs = 435
self.Description="+20 Ability Power"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3003():
def __init__(self):
self.parent=False
self.Name="Archangel's Staff"
self.Icon="3003.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3070','1027','1005','1026']
self.Builds_Into=[]
self.Tags=['spell_damage','mana','mana_regen']
self.Costs = 1000
self.Total_Costs = 2855
self.Description="+400 Mana +25 Mana Regen per 5 seconds +45 Ability Power Passive: Grants Ability Power equal to 3% of your maximum Mana. UNIQUE Passive: Each time you use an ability, your maximum Mana increases by 4 (3 second cooldown). Bonus caps at +1000 Mana. Does not stack with Tear of the Goddess or Manamune."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Mana += 400.0
self.parent.Mana_Regen_per_5_seconds += 25.0
self.parent.Ability_Power += 45.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3174():
def __init__(self):
self.parent=False
self.Name="Athene's Unholy Grail"
self.Icon="3174.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3108','1005','1052','1052','3028','1005','1033']
self.Builds_Into=[]
self.Tags=['spell_block','spell_damage','mana_regen','cooldown_reduction']
self.Costs = 500
self.Total_Costs = 2950
self.Description="+80 Ability Power +36 Magic Resist +15 Mana Regen per 5 seconds UNIQUE Passive: 15% Cooldown Reduction UNIQUE Passive: Restores 12% of your max Mana on Kill or Assist. UNIQUE Passive: Increases your Mana Regen by 1% per 1% Mana you are missing. Does not stack with Chalice of Harmony."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 80.0
self.parent.Magic_Resist += 36.0
self.parent.Mana_Regen_per_5_seconds += 15.0
self.parent.Cooldown_Reduction += 15.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3005():
def __init__(self):
self.parent=False
self.Name="Atma's Impaler"
self.Icon="3005.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1031','1018']
self.Builds_Into=[]
self.Tags=['armor','damage','critical_strike']
self.Costs = 825
self.Total_Costs = 2355
self.Description="+45 Armor +18% Critical Strike Chance UNIQUE Passive: Gain Attack Damage equal to 1.5% of your maximum Health."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Armor += 45.0
self.parent.Critical_Strike_Chance += 18.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3198():
def __init__(self):
self.parent=False
self.Name="Augment: Death"
self.Icon="3198.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3200']
self.Builds_Into=[]
self.Tags=['spell_damage','viktor']
self.Costs = 1000
self.Total_Costs = 1000
self.Description="+3 Ability Power per level +45 Ability Power Augment Ability: Death Ray sets fire to enemies, dealing 30% additional magic damage over 4 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power_per_level += 3.0
self.parent.Augment += 666.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3197():
def __init__(self):
self.parent=False
self.Name="Augment: Gravity"
self.Icon="3197.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3200']
self.Builds_Into=[]
self.Tags=['spell_damage','mana','cooldown_reduction','viktor']
self.Costs = 1000
self.Total_Costs = 1000
self.Description="+3 Ability Power per level +200 Mana +10% Cooldown Reduction +5 Mana Regen per 5 seconds Ability Augment: Gravity Field has an additional 30% cast range."
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power_per_level += 3.0
self.parent.Mana += 200.0
self.parent.Cooldown_Reduction += 10.0
# above is %
self.parent.Augment += 666.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3196():
def __init__(self):
self.parent=False
self.Name="Augment: Power"
self.Icon="3196.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3200']
self.Builds_Into=[]
self.Tags=['spell_damage','health','health_regen','movement','viktor']
self.Costs = 1000
self.Total_Costs = 1000
self.Description="+3 Ability Power per level +220 Health +6 Health Regen per 5 seconds Ability Augment: Power Transfer increases Viktor's Movement Speed by 30% for 3 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power_per_level += 3.0
self.parent.Health += 220.0
self.parent.Augment += 666.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3093():
def __init__(self):
self.parent=False
self.Name="Avarice Blade"
self.Icon="3093.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1051']
self.Builds_Into=['3142']
self.Tags=['critical_strike']
self.Costs = 350
self.Total_Costs = 750
self.Description="+12% Critical Strike Chance UNIQUE Passive: Gain an additional 5 Gold every 10 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Critical_Strike_Chance += 12.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1038():
def __init__(self):
self.parent=False
self.Name="B. F. Sword"
self.Icon="1038.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3031','3071','3072','3181','3184']
self.Tags=['damage']
self.Costs = 1650
self.Total_Costs = 1650
self.Description="+45 Attack Damage"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 45.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3102():
def __init__(self):
self.parent=False
self.Name="Banshee's Veil"
self.Icon="3102.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1057','3010','1028','1027']
self.Builds_Into=[]
self.Tags=['health','spell_block','mana']
self.Costs = 650
self.Total_Costs = 2715
self.Description="+375 Health +375 Mana +50 Magic Resist UNIQUE Passive: Gain a spell shield that blocks the next incoming enemy ability (45 second cooldown)."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 375.0
self.parent.Mana += 375.0
self.parent.Magic_Resist += 50.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3006():
def __init__(self):
self.parent=False
self.Name="Berserker's Greaves"
self.Icon="3006.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1001','1042']
self.Builds_Into=[]
self.Tags=['attack_speed','movement']
self.Costs = 150
self.Total_Costs = 920
self.Description=" +25% Attack Speed UNIQUE Passive: Enhanced Movement 2 (does not stack with other Boots)"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Speed += 25.0
# above is %
self.parent.Movement_Speed += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3144():
def __init__(self):
self.parent=False
self.Name="Bilgewater Cutlass"
self.Icon="3144.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1037','1053']
self.Builds_Into=['3146']
self.Tags=['damage','life_steal']
self.Costs = 400
self.Total_Costs = 1825
self.Description="+35 Attack Damage +15% Life Steal UNIQUE Active: Deals 150 magic damage and slows the target champion's Movement Speed by 50% for 3 seconds (60 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 35.0
self.parent.Life_Steal += 15.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1026():
def __init__(self):
self.parent=False
self.Name="Blasting Wand"
self.Icon="1026.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3001','3135','3027','3089','3100','3116','3128','3124','3170']
self.Tags=['spell_damage']
self.Costs = 860
self.Total_Costs = 860
self.Description="+40 Ability Power"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 40.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3117():
def __init__(self):
self.parent=False
self.Name="Boots of Mobility"
self.Icon="3117.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1001']
self.Builds_Into=[]
self.Tags=['movement']
self.Costs = 650
self.Total_Costs = 1000
self.Description="UNIQUE Passive: Enhanced Movement 2, increases to Enhanced Movement 5 when out of combat for 5 seconds (does not stack with other Boots)."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Movement_Speed += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1001():
def __init__(self):
self.parent=False
self.Name="Boots of Speed"
self.Icon="1001.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3006','3047','3020','3158','3111','3117']
self.Tags=['movement']
self.Costs = 350
self.Total_Costs = 350
self.Description="UNIQUE Passive: Enhanced Movement 1 (does not stack with other Boots)"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Movement_Speed += 50.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3009():
def __init__(self):
self.parent=False
self.Name="Boots of Swiftness"
self.Icon="3009.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1001']
self.Builds_Into=[]
self.Tags=['movement']
self.Costs = 650
self.Total_Costs = 1000
self.Description="UNIQUE Passive: Enhanced Movement 3 (does not stack with other Boots)"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Movement_Speed += 40.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1051():
def __init__(self):
self.parent=False
self.Name="Brawler's Gloves"
self.Icon="1051.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3086','3093','3123']
self.Tags=['critical_strike']
self.Costs = 400
self.Total_Costs = 400
self.Description="+8% Critical Strike Chance"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Critical_Strike_Chance += 8.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3010():
def __init__(self):
self.parent=False
self.Name="Catalyst the Protector"
self.Icon="3010.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1028','1027']
self.Builds_Into=['3027','3102','3180']
self.Tags=['health','mana']
self.Costs = 450
self.Total_Costs = 1325
self.Description="+290 Health +325 Mana UNIQUE Passive: On leveling up, restores 250 Health and 200 Mana over 8 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 290.0
self.parent.Mana += 325.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1031():
def __init__(self):
self.parent=False
self.Name="Chain Vest"
self.Icon="1031.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3026','3068','3082','3075','3005','3024','3157']
self.Tags=['armor']
self.Costs = 700
self.Total_Costs = 700
self.Description="+45 Armor"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Armor += 45.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3028():
def __init__(self):
self.parent=False
self.Name="Chalice of Harmony"
self.Icon="3028.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1005','1033']
self.Builds_Into=['3174']
self.Tags=['spell_block','mana_regen']
self.Costs = 100
self.Total_Costs = 890
self.Description="+30 Magic Resist +7.5 Mana Regen per 5 seconds UNIQUE Passive: Increases your Mana Regen by 1% per 1% Mana you are missing. Does not stack with Athene's Unholy Grail."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Magic_Resist += 30.0
self.parent.Mana_Regen_per_5_seconds += 7.5
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3172():
def __init__(self):
self.parent=False
self.Name="Cloak and Dagger"
self.Icon="3172.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1018','1042']
self.Builds_Into=[]
self.Tags=['critical_strike','attack_speed']
self.Costs = 200
self.Total_Costs = 1450
self.Description="+20% Attack Speed +20% Critical Strike Chance UNIQUE Passive: +35 Tenacity (Tenacity reduces the duration of stuns, slows, taunts, fears, silences, blinds and immobilizes. Does not stack with other Tenacity items.)"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Speed += 20.0
# above is %
self.parent.Critical_Strike_Chance += 20.0
# above is %
self.parent.Tenacity=True
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1018():
def __init__(self):
self.parent=False
self.Name="Cloak of Agility"
self.Icon="1018.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3005','3046','3031','3172']
self.Tags=['critical_strike']
self.Costs = 830
self.Total_Costs = 830
self.Description="+18% Critical Strike Chance"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Critical_Strike_Chance += 18.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1029():
def __init__(self):
self.parent=False
self.Name="Cloth Armor"
self.Icon="1029.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3026','3047','3106','3105','3110','3143']
self.Tags=['armor']
self.Costs = 300
self.Total_Costs = 300
self.Description="+18 Armor"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Armor += 18.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1042():
def __init__(self):
self.parent=False
self.Name="Dagger"
self.Icon="1042.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3006','3050','3086','3101','3114','3172','3046']
self.Tags=['attack_speed']
self.Costs = 420
self.Total_Costs = 420
self.Description="+15% Attack Speed"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Attack_Speed += 15.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3128():
def __init__(self):
self.parent=False
self.Name="Deathfire Grasp"
self.Icon="3128.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3098','1052','1026']
self.Builds_Into=[]
self.Tags=['spell_damage','cooldown_reduction']
self.Costs = 975
self.Total_Costs = 2600
self.Description="+80 Ability Power UNIQUE Passive: +15% Cooldown Reduction UNIQUE Active: Deals magic damage to target champion equal to 25% of their current Health (+4% per 100 Ability Power) with a minimum of 200 damage (60 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 80.0
self.parent.Cooldown_Reduction += 15.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1055():
def __init__(self):
self.parent=False
self.Name="Doran's Blade"
self.Icon="1055.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['health','attack_speed','life_steal','doran']
self.Costs = 475
self.Total_Costs = 475
self.Description="+80 Health +10 Attack Damage +3% Life Steal"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Health += 80.0
self.parent.Attack_Damage += 10.0
self.parent.Life_Steal += 3.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1056():
def __init__(self):
self.parent=False
self.Name="Doran's Ring"
self.Icon="1056.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['health','spell_damage','mana_regen','doran']
self.Costs = 475
self.Total_Costs = 475
self.Description="+80 Health +15 Ability Power +5 Mana Regen per 5 seconds"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Health += 80.0
self.parent.Ability_Power += 15.0
self.parent.Mana_Regen_per_5_seconds += 5.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1054():
def __init__(self):
self.parent=False
self.Name="Doran's Shield"
self.Icon="1054.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['health','armor','health_regen','doran']
self.Costs = 475
self.Total_Costs = 475
self.Description="+120 Health +10 Armor +8 Health Regen per 5 seconds"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Health += 120.0
self.parent.Armor += 10.0
self.parent.Health_Regen_per_5_seconds += 8.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3173():
def __init__(self):
self.parent=False
self.Name="Eleisa's Miracle"
self.Icon="3173.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3096','1004','1007']
self.Builds_Into=[]
self.Tags=['health_regen','mana_regen']
self.Costs = 500
self.Total_Costs = 1300
self.Description="+25 Health Regen per 5 seconds +20 Mana Regen per 5 seconds UNIQUE Passive: +35 Tenacity (Tenacity reduces the duration of stuns, slows, taunts, fears, silences, blinds and immobilizes. Does not stack with other Tenacity items.)"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health_Regen_per_5_seconds += 25.0
self.parent.Mana_Regen_per_5_seconds += 20.0
self.parent.Tenacity=True
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_2038():
def __init__(self):
self.parent=False
self.Name="Elixir of Agility"
self.Icon="2038.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['attack_speed','critical_strike','consumeable']
self.Costs = 250
self.Total_Costs = 250
self.Description="Click to Consume: Grants 12-22% Attack Speed, based on champion level, and 8% Critical Strike Chance for 4 minutes."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
pass
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_2039():
def __init__(self):
self.parent=False
self.Name="Elixir of Brilliance"
self.Icon="2039.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['spell_damage','cooldown_reduction','consumeable']
self.Costs = 250
self.Total_Costs = 250
self.Description="Click to Consume: Grants 20-40 Ability Power, based on champion level, and 10% Cooldown Reduction for 4 minutes."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
pass
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_2037():
def __init__(self):
self.parent=False
self.Name="Elixir of Fortitude"
self.Icon="2037.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['health','damage','consumeable']
self.Costs = 250
self.Total_Costs = 250
self.Description="Click to Consume: Grants 140-235 Health, based on champion level, and 10 Attack Damage for 4 minutes."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
pass
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3097():
def __init__(self):
self.parent=False
self.Name="Emblem of Valor"
self.Icon="3097.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1029','1006']
self.Builds_Into=['3190']
self.Tags=['health_regen','armor']
self.Costs = 350
self.Total_Costs = 900
self.Description="+25 Armor UNIQUE Aura: Nearby allied Champions gain 10 Health Regen per 5 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Armor += 25.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3184():
def __init__(self):
self.parent=False
self.Name="Entropy"
self.Icon="3184.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3044','1028','1036','1038']
self.Builds_Into=[]
self.Tags=['health','damage']
self.Costs = 600
self.Total_Costs = 3565
self.Description="+275 Health +70 Attack Damage UNIQUE Passive: Your basic attacks have a 25% chance to reduce your target's Movement Speed by 30% for 2.5 seconds. UNIQUE Active: For the next 5 seconds, your basic attacks reduce your target's Movement Speed by 30% and deal 80 true damage over 2.5 seconds (60 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 275.0
self.parent.Attack_Damage += 70.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3123():
def __init__(self):
self.parent=False
self.Name="Executioner's Calling"
self.Icon="3123.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1051','1053']
self.Builds_Into=[]
self.Tags=['critical_strike','life_steal']
self.Costs = 500
self.Total_Costs = 1350
self.Description="+18% Life Steal +15% Critical Strike Chance UNIQUE Passive: Your basic attacks apply a mark to the target that deals 4 bonus magic damage each second for 8 seconds. UNIQUE Active: Inflicts target enemy champion with Grievous Wound, causing 50% reduced healing and regeneration for 8 seconds (20 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Life_Steal += 18.0
# above is %
self.parent.Critical_Strike_Chance += 15.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1004():
def __init__(self):
self.parent=False
self.Name="Faerie Charm"
self.Icon="1004.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3037','3077','3096']
self.Tags=['mana_regen']
self.Costs = 180
self.Total_Costs = 180
self.Description="+3 Mana Regen per 5 seconds"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Mana_Regen_per_5_seconds += 3.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3108():
def __init__(self):
self.parent=False
self.Name="Fiendish Codex"
self.Icon="3108.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1005','1052']
self.Builds_Into=['3115','3174','3165']
self.Tags=['spell_damage','mana_regen','cooldown_reduction']
self.Costs = 300
self.Total_Costs = 1125
self.Description="+30 Ability Power +7 Mana Regen per 5 seconds UNIQUE Passive: +10% Cooldown Reduction"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 30.0
self.parent.Mana_Regen_per_5_seconds += 7.0
self.parent.Cooldown_Reduction += 10.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3109():
def __init__(self):
self.parent=False
self.Name="Force of Nature"
self.Icon="3109.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1007','1007','1057']
self.Builds_Into=[]
self.Tags=['spell_block','health_regen','movement']
self.Costs = 1000
self.Total_Costs = 2610
self.Description="+76 Magic Resist +40 Health Regen per 5 seconds +8% Movement Speed UNIQUE Passive: Restores 1.75% of your maxmium Health every 5 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Magic_Resist += 76.0
self.parent.Health_Regen_per_5_seconds += 40.0
self.parent.Movement_Speed += 8.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3110():
def __init__(self):
self.parent=False
self.Name="Frozen Heart"
self.Icon="3110.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1029','1029','3024','1027','1031']
self.Builds_Into=[]
self.Tags=['armor','mana','cooldown_reduction']
self.Costs = 650
self.Total_Costs = 2775
self.Description="+99 Armor +500 Mana UNIQUE Passive: +20% Cooldown Reduction UNIQUE Aura: Reduces the Attack Speed of nearby enemies by 20%."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Armor += 99.0
self.parent.Mana += 500.0
self.parent.Cooldown_Reduction += 20.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3022():
def __init__(self):
self.parent=False
self.Name="Frozen Mallet"
self.Icon="3022.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3044','1028','1036','1011']
self.Builds_Into=[]
self.Tags=['health','damage']
self.Costs = 825
self.Total_Costs = 3250
self.Description="+700 Health +20 Attack Damage UNIQUE Passive: Your basic attacks slow your target's Movement Speed by 40% for 2.5 seconds (30% for ranged attacks)."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 700.0
self.parent.Attack_Damage += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1011():
def __init__(self):
self.parent=False
self.Name="Giant's Belt"
self.Icon="1011.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3083','3022','3068','3116']
self.Tags=['health']
self.Costs = 1110
self.Total_Costs = 1110
self.Description="+430 Health"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Health += 430.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3024():
def __init__(self):
self.parent=False
self.Name="Glacial Shroud"
self.Icon="3024.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1027','1031']
self.Builds_Into=['3110']
self.Tags=['armor','mana','cooldown_reduction']
self.Costs = 425
self.Total_Costs = 1525
self.Description="+425 Mana +45 Armor UNIQUE Passive: +15% Cooldown Reduction"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Mana += 425.0
self.parent.Armor += 45.0
self.parent.Cooldown_Reduction += 15.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3026():
def __init__(self):
self.parent=False
self.Name="Guardian Angel"
self.Icon="3026.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1033','1029','1031']
self.Builds_Into=[]
self.Tags=['spell_block','armor']
self.Costs = 1200
self.Total_Costs = 2600
self.Description="+68 Armor +38 Magic Resist UNIQUE Passive: Revives your champion upon death, restoring 750 Health and 375 Mana (5 minute cooldown)."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Armor += 68.0
self.parent.Magic_Resist += 38.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3124():
def __init__(self):
self.parent=False
self.Name="Guinsoo's Rageblade"
self.Icon="3124.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1026','1037']
self.Builds_Into=[]
self.Tags=['damage','attack_speed','spell_damage']
self.Costs = 400
self.Total_Costs = 2235
self.Description="+35 Attack Damage +45 Ability Power UNIQUE Passive: On basic attack or ability use, increases your Attack Speed by 4% and Ability Power by 6 for 5 seconds (effect stacks up to 8 times)."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 35.0
self.parent.Ability_Power += 45.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3136():
def __init__(self):
self.parent=False
self.Name="Haunting Guise"
self.Icon="3136.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1028','1052']
self.Builds_Into=[]
self.Tags=['health','spell_damage']
self.Costs = 575
self.Total_Costs = 1485
self.Description="+25 Ability Power +200 Health UNIQUE Passive: +20 Magic Penetration"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 25.0
self.parent.Health += 200.0
self.parent.Magic_Penetration += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_2003():
def __init__(self):
self.parent=False
self.Name="Health Potion"
self.Icon="2003.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['health','consumeable']
self.Costs = 35
self.Total_Costs = 35
self.Description="Click to Consume: Restores 150 Health over 15 seconds."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
pass
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3132():
def __init__(self):
self.parent=False
self.Name="Heart of Gold"
self.Icon="3132.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1028']
self.Builds_Into=['3143','3190']
self.Tags=['health']
self.Costs = 350
self.Total_Costs = 825
self.Description="+250 Health UNIQUE Passive: Gain an additional 5 Gold every 10 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 250.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3155():
def __init__(self):
self.parent=False
self.Name="Hexdrinker"
self.Icon="3155.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1036','1033']
self.Builds_Into=['3156']
self.Tags=['spell_block','damage']
self.Costs = 585
self.Total_Costs = 1400
self.Description="+25 Attack Damage +30 Magic Resist UNIQUE Passive: If you would take magic damage that would leave you at less than 30% Health, you first gain a shield that absorbs 250 magic damage for 5 seconds (60 second cooldown)."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 25.0
self.parent.Magic_Resist += 30.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3146():
def __init__(self):
self.parent=False
self.Name="Hextech Gunblade"
self.Icon="3146.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3144','1037','1053','3145','1052','1052']
self.Builds_Into=[]
self.Tags=['damage','life_steal','spell_damage']
self.Costs = 600
self.Total_Costs = 3625
self.Description="+40 Attack Damage +70 Ability Power +15% Life Steal UNIQUE Passive: +20% Spell Vamp UNIQUE Active: Deals 300 magic damage and slows the target champion's Movement Speed by 50% for 3 seconds (60 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 40.0
self.parent.Ability_Power += 70.0
self.parent.Life_Steal += 15.0
# above is %
self.parent.Spell_Vamp += 20.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3145():
def __init__(self):
self.parent=False
self.Name="Hextech Revolver"
self.Icon="3145.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1052','1052']
self.Builds_Into=['3146','3152']
self.Tags=['spell_damage']
self.Costs = 330
self.Total_Costs = 1200
self.Description="+40 Ability Power UNIQUE Passive: +12% Spell Vamp"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 40.0
self.parent.Spell_Vamp += 12.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3187():
def __init__(self):
self.parent=False
self.Name="Hextech Sweeper"
self.Icon="3187.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1052','1052','3067','1028']
self.Builds_Into=[]
self.Tags=['health','spell_damage','cooldown_reduction']
self.Costs = 150
self.Total_Costs = 1870
self.Description="+40 Ability Power +300 Health UNIQUE Passive: +10% Cooldown Reduction UNIQUE Passive: Dealing spell damage grants vision of your target (including stealthed targets) for 4 seconds. UNIQUE Active: A stealth-detecting mist grants vision in the target area for 6 seconds (1 minute cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 40.0
self.parent.Health += 300.0
self.parent.Cooldown_Reduction += 10.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3031():
def __init__(self):
self.parent=False
self.Name="Infinity Edge"
self.Icon="3031.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1038','1037','1018']
self.Builds_Into=[]
self.Tags=['damage','critical_strike']
self.Costs = 375
self.Total_Costs = 3830
self.Description="+80 Attack Damage +25% Critical Strike Chance UNIQUE Passive: Your critical strikes now deal 250% damage instead of 200%."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 80.0
self.parent.Critical_Strike_Chance += 25.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3158():
def __init__(self):
self.parent=False
self.Name="Ionian Boots of Lucidity"
self.Icon="3158.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1001']
self.Builds_Into=[]
self.Tags=['movement','cooldown_reduction']
self.Costs = 700
self.Total_Costs = 1050
self.Description="UNIQUE Passive: +15% Cooldown Reduction UNIQUE Passive: Enhanced Movement 2 (does not stack with other Boots)"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Cooldown_Reduction += 15.0
# above is %
self.parent.Movement_Speed += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3178():
def __init__(self):
self.parent=False
self.Name="Ionic Spark"
self.Icon="3178.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1043','1028']
self.Builds_Into=[]
self.Tags=['health','attack_speed']
self.Costs = 775
self.Total_Costs = 2300
self.Description="+50% Attack Speed +250 Health UNIQUE Passive: Every fourth basic attack unleashes a chain lightning, dealing 110 magic damage to up to 4 targets."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Speed += 50.0
# above is %
self.parent.Health += 250.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3098():
def __init__(self):
self.parent=False
self.Name="Kage's Lucky Pick"
self.Icon="3098.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1052']
self.Builds_Into=['3165','3128']
self.Tags=['spell_damage']
self.Costs = 330
self.Total_Costs = 765
self.Description="+25 Ability Power UNIQUE Passive: Gain an additional 5 Gold every 10 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 25.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3067():
def __init__(self):
self.parent=False
self.Name="Kindlegem"
self.Icon="3067.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1028']
self.Builds_Into=['3069','3099','3065','3187','3050']
self.Tags=['health','cooldown_reduction']
self.Costs = 375
self.Total_Costs = 850
self.Description="+200 Health UNIQUE Passive: +10% Cooldown Reduction"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 200.0
self.parent.Cooldown_Reduction += 10.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3186():
def __init__(self):
self.parent=False
self.Name="Kitae's Bloodrazor"
self.Icon="3186.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1037','1043']
self.Builds_Into=[]
self.Tags=['damage','attack_speed']
self.Costs = 700
self.Total_Costs = 2725
self.Description="+30 Attack Damage +40% Attack Speed UNIQUE Passive: Your basic attacks deal magic damage equal to 2.5% of the target's maximum Health."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 30.0
self.parent.Attack_Speed += 40.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3035():
def __init__(self):
self.parent=False
self.Name="Last Whisper"
self.Icon="3035.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1037','1036']
self.Builds_Into=[]
self.Tags=['damage']
self.Costs = 900
self.Total_Costs = 2290
self.Description="+40 Attack Damage UNIQUE Passive: +40% Armor Penetration"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 40.0
self.parent.Armor_Penetration += 40.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3138():
def __init__(self):
self.parent=False
self.Name="Leviathan"
self.Icon="3138.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1028']
self.Builds_Into=[]
self.Tags=['health']
self.Costs = 800
self.Total_Costs = 1275
self.Description="+180 Health UNIQUE Passive: Your champion gains 32 Health per stack, receiving 2 stacks for a kill or 1 stack for an assist (stacks up to 20). You lose a third of your stacks on death. At 20 stacks, your champion takes 15% less damage."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 180.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3100():
def __init__(self):
self.parent=False
self.Name="Lich Bane"
self.Icon="3100.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1033','3057','1027','1052','1026']
self.Builds_Into=[]
self.Tags=['spell_block','spell_damage','mana','movement']
self.Costs = 950
self.Total_Costs = 3470
self.Description="+350 Mana +80 Ability Power +30 Magic Resist +7% Movement Speed UNIQUE Passive: After using an ability, your next basic attack gains bonus physical damage equal to your Ability Power (2 second cooldown). Does not stack with Sheen or Trinity Force."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Mana += 350.0
self.parent.Ability_Power += 80.0
self.parent.Magic_Resist += 30.0
self.parent.Movement_Speed += 7.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3190():
def __init__(self):
self.parent=False
self.Name="Locket of the Iron Solari"
self.Icon="3190.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3132','1028','3097','1029','1006']
self.Builds_Into=[]
self.Tags=['health','health_regen','armor']
self.Costs = 500
self.Total_Costs = 2225
self.Description="+300 Health +35 Armor UNIQUE Aura: Nearby allied Champions gain 15 Health Regen per 5 seconds. UNIQUE Active: Shield yourself and nearby allies for 5 seconds, absorbing up to 50 (+10 per level) damage (60 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Health += 300.0
self.parent.Armor += 35.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1036():
def __init__(self):
self.parent=False
self.Name="Long Sword"
self.Icon="1036.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3106','3044','3134','3141','3035','3155','3077','3154','3004','3185']
self.Tags=['damage']
self.Costs = 415
self.Total_Costs = 415
self.Description="+10 Attack Damage"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 10.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3126():
def __init__(self):
self.parent=False
self.Name="Madred's Bloodrazor"
self.Icon="3126.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3106','1029','1036','1037','1043']
self.Builds_Into=[]
self.Tags=['damage','attack_speed']
self.Costs = 775
self.Total_Costs = 3800
self.Description="+40 Attack Damage +40% Attack Speed +25 Armor UNIQUE Passive: Your basic attacks deal bonus magic damage equal to 4% of the target's maximum Health."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 40.0
self.parent.Attack_Speed += 40.0
# above is %
self.parent.Armor += 25.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3106():
def __init__(self):
self.parent=False
self.Name="Madred's Razors"
self.Icon="3106.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1029','1036']
self.Builds_Into=['3154','3126']
self.Tags=['armor','damage']
self.Costs = 285
self.Total_Costs = 1000
self.Description="+15 Attack Damage +23 Armor UNIQUE Passive: Your basic attacks against minions and monsters have a 20% chance to deal 300 bonus magic damage."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 15.0
self.parent.Armor += 23.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3114():
def __init__(self):
self.parent=False
self.Name="Malady"
self.Icon="3114.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1042','1042','1052']
self.Builds_Into=[]
self.Tags=['attack_speed','spell_damage']
self.Costs = 550
self.Total_Costs = 1825
self.Description="+25 Ability Power +50% Attack Speed UNIQUE Passive: Your basic attacks deal 20 bonus magic damage and reduce the target's Magic Resist by 6 for 8 seconds (effect stacks up to 4 times)."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 25.0
self.parent.Attack_Speed += 50.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3037():
def __init__(self):
self.parent=False
self.Name="Mana Manipulator"
self.Icon="3037.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1004','1004']
self.Builds_Into=['3099']
self.Tags=['mana_regen']
self.Costs = 115
self.Total_Costs = 475
self.Description="UNIQUE Aura: Nearby allied champions gain 7.2 Mana Regen per 5 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
pass
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_2004():
def __init__(self):
self.parent=False
self.Name="Mana Potion"
self.Icon="2004.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['mana','consumeable']
self.Costs = 40
self.Total_Costs = 40
self.Description="Click to Consume: Restores 100 Mana over 15 seconds."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
pass
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3004():
def __init__(self):
self.parent=False
self.Name="Manamune"
self.Icon="3004.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3070','1027','1005','1036']
self.Builds_Into=[]
self.Tags=['damage','mana','mana_regen']
self.Costs = 700
self.Total_Costs = 2110
self.Description="+350 Mana +7 Mana Regen per 5 seconds +20 Attack Damage UNIQUE Passive: Grants Attack Damage equal to 2% of your maximum Mana. UNIQUE Passive: Each time you basic attack, your maximum Mana increases by 1 (3 second cooldown). Each time you use an ability, your maximum Mana increases by 4 (3 second cooldown). Bonus caps at +1000 Mana. Does not stack with Tear of the Goddess or Archangel's Staff."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Mana += 350.0
self.parent.Mana_Regen_per_5_seconds += 7.0
self.parent.Attack_Damage += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3156():
def __init__(self):
self.parent=False
self.Name="Maw of Malmortius"
self.Icon="3156.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3155','1036','1033','1037']
self.Builds_Into=[]
self.Tags=['spell_block','damage']
self.Costs = 925
self.Total_Costs = 3300
self.Description="+55 Attack Damage +36 Magic Resist UNIQUE Passive: If you would take magic damage that would leave you at less than 30% Health, you first gain a shield that absorbs 400 magic damage for 5 seconds (60 second cooldown). UNIQUE Passive: +1 Attack Damage for every 2.5% of your Maximum Health that is missing."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 55.0
self.parent.Magic_Resist += 36.0
#self.parent.Attack_Damage += maxhealth - health = temp (maxhelth/temp)*100 = temp abs(temp/2.5) _for_every_2.5%_of_your_Maximum_Health_that_is_missing.=1.0
self.parent.Attack_Damage += 55.0
self.parent.Magic_Resist += 36.0
#self.parent.Attack_Damage += maxhealth - health = temp (maxhelth/temp)*100 = temp abs(temp/2.5) _for_every_2.5%_of_your_Maximum_Health_that_is_missing.=1.0
self.parent.Attack_Damage += 55.0
self.parent.Magic_Resist += 36.0
#self.parent.Attack_Damage += maxhealth - health = temp (maxhelth/temp)*100 = temp abs(temp/2.5) _for_every_2.5%_of_your_Maximum_Health_that_is_missing.=1.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3041():
def __init__(self):
self.parent=False
self.Name="Mejai's Soulstealer"
self.Icon="3041.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1052']
self.Builds_Into=[]
self.Tags=['spell_damage']
self.Costs = 800
self.Total_Costs = 1235
self.Description="+20 Ability Power UNIQUE Passive: Your champion gains 8 Ability Power per stack, receiving 2 stacks for a kill or 1 stack for an assist (stacks up to 20). You lose a third of your stacks on death. At 20 stacks, your champion gains 15% Cooldown Reduction."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1005():
def __init__(self):
self.parent=False
self.Name="Meki Pendant"
self.Icon="1005.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3028','3108','3070']
self.Tags=['mana_regen']
self.Costs = 390
self.Total_Costs = 390
self.Description="+7 Mana Regen per 5 seconds"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Mana_Regen_per_5_seconds += 7.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3111():
def __init__(self):
self.parent=False
self.Name="Mercury's Treads"
self.Icon="3111.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1001','1033']
self.Builds_Into=[]
self.Tags=['spell_block','movement']
self.Costs = 450
self.Total_Costs = 1200
self.Description="+25 Magic Resist UNIQUE Passive: Enhanced Movement 2 (does not stack with other Boots) UNIQUE Passive: +35 Tenacity (Tenacity reduces the duration of stuns, slows, taunts, fears, silences, blinds and immobilizes. Does not stack with other Tenacity items.)"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Magic_Resist += 25.0
self.parent.Movement_Speed += 20.0
self.parent.Tenacity=True
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3170():
def __init__(self):
self.parent=False
self.Name="Moonflair Spellblade"
self.Icon="3170.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1026']
self.Builds_Into=[]
self.Tags=['spell_damage']
self.Costs = 340
self.Total_Costs = 1200
self.Description="+50 Ability Power UNIQUE Passive: +35 Tenacity (Tenacity reduces the duration of stuns, slows, taunts, fears, silences, blinds and immobilizes. Does not stack with other Tenacity items.)"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 50.0
self.parent.Tenacity=True
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3165():
def __init__(self):
self.parent=False
self.Name="Morello's Evil Tome"
self.Icon="3165.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3098','1052','3108','1005','1052']
self.Builds_Into=[]
self.Tags=['spell_damage','mana_regen','cooldown_reduction']
self.Costs = 440
self.Total_Costs = 2330
self.Description="+75 Ability Power +12 Mana Regen per 5 seconds UNIQUE Passive: +20% Cooldown Reduction UNIQUE Active: Inflicts target enemy champion with Grievous Wound, causing 50% reduced healing and regeneration for 8 seconds (20 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 75.0
self.parent.Mana_Regen_per_5_seconds += 12.0
self.parent.Cooldown_Reduction += 20.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3115():
def __init__(self):
self.parent=False
self.Name="Nashor's Tooth"
self.Icon="3115.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3101','1042','1042','3108','1005','1052']
self.Builds_Into=[]
self.Tags=['attack_speed','spell_damage','mana_regen','cooldown_reduction']
self.Costs = 400
self.Total_Costs = 2615
self.Description="+50% Attack Speed +65 Ability Power +10 Mana Regen per 5 seconds UNIQUE Passive: +25% Cooldown Reduction"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Speed += 50.0
# above is %
self.parent.Ability_Power += 65.0
self.parent.Mana_Regen_per_5_seconds += 10.0
self.parent.Cooldown_Reduction += 25.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1058():
def __init__(self):
self.parent=False
self.Name="Needlessly Large Rod"
self.Icon="1058.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3089','3157']
self.Tags=['spell_damage']
self.Costs = 1600
self.Total_Costs = 1600
self.Description="+80 Ability Power"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 80.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1057():
def __init__(self):
self.parent=False
self.Name="Negatron Cloak"
self.Icon="1057.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3109','3102','3001','3140','3180']
self.Tags=['spell_block']
self.Costs = 740
self.Total_Costs = 740
self.Description="+48 Magic Resist"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Magic_Resist += 48.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3047():
def __init__(self):
self.parent=False
self.Name="Ninja Tabi"
self.Icon="3047.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1001','1029']
self.Builds_Into=[]
self.Tags=['armor','movement']
self.Costs = 200
self.Total_Costs = 850
self.Description="+25 Armor UNIQUE Passive: Reduces the damage taken from non-turret basic attacks by 10%. UNIQUE Passive: Enhanced Movement 2 (does not stack with other Boots)"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Armor += 25.0
self.parent.Movement_Speed += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1033():
def __init__(self):
self.parent=False
self.Name="Null-Magic Mantle"
self.Icon="1033.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3111','3028','3065','3105','3026','3091','3155']
self.Tags=['spell_block']
self.Costs = 400
self.Total_Costs = 400
self.Description="+24 Magic Resist"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Magic_Resist += 24.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3180():
def __init__(self):
self.parent=False
self.Name="Odyn's Veil"
self.Icon="3180.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1057','3010','1028','1027']
self.Builds_Into=[]
self.Tags=['health','spell_block','mana']
self.Costs = 650
self.Total_Costs = 2715
self.Description="+350 Health +350 Mana +50 Magic Resist UNIQUE Passive: Reduces and stores 10% of the magic damage dealt to your champion. UNIQUE Active: Deals 200 + (stored magic) [max: 400] magic damage to nearby enemy units (90 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 350.0
self.parent.Mana += 350.0
self.parent.Magic_Resist += 50.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_2042():
def __init__(self):
self.parent=False
self.Name="Oracle's Elixir"
self.Icon="2042.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['consumeable']
self.Costs = 400
self.Total_Costs = 400
self.Description="Click to Consume: Grants stealth detection until your champion dies."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
pass
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_2047():
def __init__(self):
self.parent=False
self.Name="Oracle's Extract"
self.Icon="2047.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['consumeable']
self.Costs = 250
self.Total_Costs = 250
self.Description="Click to Consume: Grants stealth detection for 5 minutes or until your champion dies."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
pass
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3044():
def __init__(self):
self.parent=False
self.Name="Phage"
self.Icon="3044.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1028','1036']
self.Builds_Into=['3022','3078','3184']
self.Tags=['health','damage']
self.Costs = 425
self.Total_Costs = 1315
self.Description="+225 Health +18 Attack Damage UNIQUE Passive: Your basic attacks have a 25% chance to slow your target's Movement Speed by 30% for 2.5 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 225.0
self.parent.Attack_Damage += 18.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3046():
def __init__(self):
self.parent=False
self.Name="Phantom Dancer"
self.Icon="3046.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1018','3086','1051','1042','1042']
self.Builds_Into=[]
self.Tags=['critical_strike','attack_speed','movement']
self.Costs = 400
self.Total_Costs = 2845
self.Description="+55% Attack Speed +30% Critical Strike Chance +12% Movement Speed"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Attack_Speed += 55.0
# above is %
self.parent.Critical_Strike_Chance += 30.0
# above is %
self.parent.Movement_Speed += 12.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3096():
def __init__(self):
self.parent=False
self.Name="Philosopher's Stone"
self.Icon="3096.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1004','1007']
self.Builds_Into=['3069','3173']
self.Tags=['health_regen','mana_regen']
self.Costs = 185
self.Total_Costs = 800
self.Description="+18 Health Regen per 5 seconds +8 Mana Regen per 5 seconds UNIQUE Passive: Gain an additional 5 Gold every 10 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health_Regen_per_5_seconds += 18.0
self.parent.Mana_Regen_per_5_seconds += 8.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1037():
def __init__(self):
self.parent=False
self.Name="Pickaxe"
self.Icon="1037.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3144','3035','3124','3126','3031','3156','3077']
self.Tags=['damage']
self.Costs = 975
self.Total_Costs = 975
self.Description="+25 Attack Damage"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 25.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1062():
def __init__(self):
self.parent=False
self.Name="Prospector's Blade"
self.Icon="1062.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['health','damage','life_steal','prospector']
self.Costs = 950
self.Total_Costs = 950
self.Description="+20 Attack Damage +5% Life Steal UNIQUE Passive: +200 Health (does not stack with other Prospector items)"
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 20.0
self.parent.Life_Steal += 5.0
# above is %
self.parent.Health += 200
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1063():
def __init__(self):
self.parent=False
self.Name="Prospector's Ring"
self.Icon="1063.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['spell_damage','mana_regen','health','prospector']
self.Costs = 950
self.Total_Costs = 950
self.Description="+30 Ability Power +7 Mana Regen per 5 seconds UNIQUE Passive: +200 Health (does not stack with other Prospector items)"
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 30.0
self.parent.Mana_Regen_per_5_seconds += 7.0
self.parent.Health += 200
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3140():
def __init__(self):
self.parent=False
self.Name="Quicksilver Sash"
self.Icon="3140.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1057']
self.Builds_Into=[]
self.Tags=['spell_block']
self.Costs = 700
self.Total_Costs = 1440
self.Description="+56 Magic Resist UNIQUE Active: Removes all debuffs from your champion (90 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Magic_Resist += 56.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3089():
def __init__(self):
self.parent=False
self.Name="Rabadon's Deathcap"
self.Icon="3089.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1026','1058']
self.Builds_Into=[]
self.Tags=['spell_damage']
self.Costs = 1140
self.Total_Costs = 3600
self.Description="+140 Ability Power UNIQUE Passive: Increases Ability Power by 30%"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 140.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3143():
def __init__(self):
self.parent=False
self.Name="Randuin's Omen"
self.Icon="3143.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3132','1028','3082','1031','1006','1029']
self.Builds_Into=[]
self.Tags=['health','health_regen','armor','cooldown_reduction']
self.Costs = 600
self.Total_Costs = 3075
self.Description="+350 Health +75 Armor +25 Health Regen per 5 seconds UNIQUE Passive: +5% Cooldown Reduction UNIQUE Passive: 20% chance on being hit by basic attacks to slow the attacker's Movement and Attack Speeds by 35% for 3 seconds. UNIQUE Active: Slows the Movement and Attack Speeds of surrounding enemy units by 35% for 1 second + 0.5 seconds for each 100 combined Armor and Magic Resist your champion has (60 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 350.0
self.parent.Armor += 75.0
self.parent.Health_Regen_per_5_seconds += 25.0
self.parent.Cooldown_Reduction += 5.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1043():
def __init__(self):
self.parent=False
self.Name="Recurve Bow"
self.Icon="1043.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3091','3126','3178','3185','3186']
self.Tags=['attack_speed']
self.Costs = 1050
self.Total_Costs = 1050
self.Description="+40% Attack Speed"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Attack_Speed += 40.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1007():
def __init__(self):
self.parent=False
self.Name="Regrowth Pendant"
self.Icon="1007.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3096','3083','3109']
self.Tags=['health_regen']
self.Costs = 435
self.Total_Costs = 435
self.Description="+15 Health Regen per 5 seconds"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Health_Regen_per_5_seconds += 15.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1006():
def __init__(self):
self.parent=False
self.Name="Rejuvenation Bead"
self.Icon="1006.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3082','3097','3077']
self.Tags=['health_regen']
self.Costs = 250
self.Total_Costs = 250
self.Description="+8 Health Regen per 5 seconds"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Health_Regen_per_5_seconds += 8.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3027():
def __init__(self):
self.parent=False
self.Name="Rod of Ages"
self.Icon="3027.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3010','1028','1027','1026']
self.Builds_Into=[]
self.Tags=['health','spell_damage','mana']
self.Costs = 850
self.Total_Costs = 3035
self.Description="+450 Health +525 Mana +60 Ability Power Passive: Your champion gains 18 Health, 20 Mana, and 2 Ability Power every minute (up to 10 times). UNIQUE Passive: On leveling up, restores 250 Health and 200 Mana over 8 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 450.0
self.parent.Mana += 525.0
self.parent.Ability_Power += 60.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1028():
def __init__(self):
self.parent=False
self.Name="Ruby Crystal"
self.Icon="1028.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3067','3132','3105','3044','3010','3178','3136','3083','3005','3099','3138']
self.Tags=['health']
self.Costs = 475
self.Total_Costs = 475
self.Description="+180 Health"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Health += 180.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3116():
def __init__(self):
self.parent=False
self.Name="Rylai's Crystal Scepter"
self.Icon="3116.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1026','1052','1011']
self.Builds_Into=[]
self.Tags=['health','spell_damage']
self.Costs = 700
self.Total_Costs = 3105
self.Description="+500 Health +80 Ability Power UNIQUE Passive: Dealing spell damage slows the target's Movement Speed by 35% for 1.5 seconds (15% for multi-target and damage-over-time spells)."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 500.0
self.parent.Ability_Power += 80.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3181():
def __init__(self):
self.parent=False
self.Name="Sanguine Blade"
self.Icon="3181.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1038','1053']
self.Builds_Into=[]
self.Tags=['damage','life_steal']
self.Costs = 800
self.Total_Costs = 2900
self.Description="+60 Attack Damage +15% Life Steal UNIQUE Passive: Your basic attacks grant 5 Attack Damage and 1% Life Steal for 4 seconds (effect stacks up to 7 times)."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 60.0
self.parent.Life_Steal += 15.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1027():
def __init__(self):
self.parent=False
self.Name="Sapphire Crystal"
self.Icon="1027.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3057','3070','3010','3024']
self.Tags=['mana']
self.Costs = 400
self.Total_Costs = 400
self.Description="+200 Mana"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Mana += 200.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3057():
def __init__(self):
self.parent=False
self.Name="Sheen"
self.Icon="3057.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1027','1052']
self.Builds_Into=['3100','3078']
self.Tags=['spell_damage','mana']
self.Costs = 425
self.Total_Costs = 1260
self.Description="+250 Mana +25 Ability Power UNIQUE Passive: After using an ability, your next basic attack deals bonus physical damage equal to your base Attack Damage (2 second cooldown). Does not stack with Trinity Force or Lich Bane."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Mana += 250.0
self.parent.Ability_Power += 25.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3069():
def __init__(self):
self.parent=False
self.Name="Shurelya's Reverie"
self.Icon="3069.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3067','1028','3096','1004','1007']
self.Builds_Into=[]
self.Tags=['health','health_regen','mana_regen','movement','cooldown_reduction']
self.Costs = 550
self.Total_Costs = 2200
self.Description="+330 Health +30 Health Regen per 5 seconds +15 Mana Regen per 5 seconds UNIQUE Passive: +15% Cooldown Reduction UNIQUE Active: Nearby allied champions gain 40% Movement Speed for 3 seconds (60 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 330.0
self.parent.Health_Regen_per_5_seconds += 30.0
self.parent.Mana_Regen_per_5_seconds += 15.0
self.parent.Cooldown_Reduction += 15.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_2044():
def __init__(self):
self.parent=False
self.Name="Sight Ward"
self.Icon="2044.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['consumeable']
self.Costs = 75
self.Total_Costs = 75
self.Description="Click to Consume: Places an invisible ward that reveals the surrounding area for 3 minutes."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
pass
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3020():
def __init__(self):
self.parent=False
self.Name="Sorcerer's Shoes"
self.Icon="3020.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1001']
self.Builds_Into=[]
self.Tags=['movement']
self.Costs = 750
self.Total_Costs = 1100
self.Description="+20 Magic Penetration UNIQUE Passive: Enhanced Movement 2 (does not stack with other Boots)"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Magic_Penetration += 20.0
self.parent.Movement_Speed += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3099():
def __init__(self):
self.parent=False
self.Name="Soul Shroud"
self.Icon="3099.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3067','1028','1028','3037','1004','1004']
self.Builds_Into=[]
self.Tags=['health','mana_regen','cooldown_reduction']
self.Costs = 485
self.Total_Costs = 2285
self.Description="+520 Health UNIQUE Aura: Nearby allied champions gain 10% Cooldown Reduction and 12 Mana Regen per 5 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Health += 520.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3065():
def __init__(self):
self.parent=False
self.Name="Spirit Visage"
self.Icon="3065.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3067','1028','1033']
self.Builds_Into=[]
self.Tags=['health','spell_block','cooldown_reduction']
self.Costs = 300
self.Total_Costs = 1550
self.Description="+30 Magic Resist +250 Health UNIQUE Passive: +10% Cooldown Reduction UNIQUE Passive: Increases your healing and regeneration effects on yourself by 15%."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Magic_Resist += 30.0
self.parent.Health += 250.0
self.parent.Cooldown_Reduction += 10.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3101():
def __init__(self):
self.parent=False
self.Name="Stinger"
self.Icon="3101.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1042','1042']
self.Builds_Into=['3115']
self.Tags=['attack_speed','cooldown_reduction']
self.Costs = 250
self.Total_Costs = 1090
self.Description="+40% Attack Speed UNIQUE Passive: +10% Cooldown Reduction"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Speed += 40.0
# above is %
self.parent.Cooldown_Reduction += 10.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3068():
def __init__(self):
self.parent=False
self.Name="Sunfire Cape"
self.Icon="3068.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1031','1011']
self.Builds_Into=[]
self.Tags=['health','armor']
self.Costs = 800
self.Total_Costs = 2610
self.Description="+450 Health +45 Armor UNIQUE Passive: Deals 40 magic damage per second to nearby enemies."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 450.0
self.parent.Armor += 45.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3141():
def __init__(self):
self.parent=False
self.Name="Sword of the Occult"
self.Icon="3141.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1036']
self.Builds_Into=[]
self.Tags=['damage']
self.Costs = 954
self.Total_Costs = 1369
self.Description="+10 Attack Damage UNIQUE Passive: Your champion gains 5 Attack Damage per stack, receiving 2 stacks for a kill or 1 stack for an assist (stacks up to 20). You lose a third of your stacks on death. At 20 stacks, your champion's Movement Speed is increased by 15%."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 10.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3070():
def __init__(self):
self.parent=False
self.Name="Tear of the Goddess"
self.Icon="3070.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1027','1005']
self.Builds_Into=['3003','3004']
self.Tags=['mana','mana_regen']
self.Costs = 205
self.Total_Costs = 995
self.Description="+350 Mana +7 Mana Regen per 5 seconds UNIQUE Passive: Each time you use an ability, your maximum Mana increases by 4 (3 second cooldown). Bonus caps at +1000 Mana. Does not stack with Archangel's Staff or Manamune."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Mana += 350.0
self.parent.Mana_Regen_per_5_seconds += 7.0
self.UpdateStats_Custom()
#class hurga():
def Custom(self):
self.MaxStack=250
self.Stack=250
def UpdateStats_Custom(self):
temp=self.Stack * 4
self.parent.Mana += temp
class Item_3071():
def __init__(self):
self.parent=False
self.Name="The Black Cleaver"
self.Icon="3071.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1038','1042']
self.Builds_Into=[]
self.Tags=['damage','attack_speed']
self.Costs = 795
self.Total_Costs = 2865
self.Description="+55 Attack Damage +30% Attack Speed UNIQUE Passive: Your basic attacks reduce your target's Armor by 15 for 5 seconds (effect stacks up to 3 times)."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 55.0
self.parent.Attack_Speed += 30.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3072():
def __init__(self):
self.parent=False
self.Name="The Bloodthirster"
self.Icon="3072.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1038','1053']
self.Builds_Into=[]
self.Tags=['damage','life_steal']
self.Costs = 900
self.Total_Costs = 3000
self.Description="+60 Attack Damage +12% Life Steal Passive: Gains 1 stack per kill, up to a maximum of 40. Each stack grants +1 Attack Damage and +0.2% Life Steal (max: +40 Attack Damage and +8% Life Steal). Half of the current stacks are lost upon death."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 60.0
self.parent.Life_Steal += 12.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3134():
def __init__(self):
self.parent=False
self.Name="The Brutalizer"
self.Icon="3134.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1036','1036']
self.Builds_Into=['3142']
self.Tags=['damage','cooldown_reduction']
self.Costs = 507
self.Total_Costs = 1337
self.Description="+25 Attack Damage UNIQUE Passive: +10% Cooldown Reduction UNIQUE Passive: +15 Armor Penetration"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 25.0
self.parent.Cooldown_Reduction += 10.0
# above is %
self.parent.Armor_Penetration += 15.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3200():
def __init__(self):
self.parent=False
self.Name="The Hex Core"
self.Icon="3200.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3196','3197','3198']
self.Tags=['spell_damage','viktor']
self.Costs = 0
self.Total_Costs = 0
self.Description="+3 Ability Power per level. This item can be upgraded into one of three augments that enhance Viktor's basic abilities. Click the item in the store to discover its upgrades."
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 3.0 * self.parent.Level
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3185():
def __init__(self):
self.parent=False
self.Name="The Lightbringer"
self.Icon="3185.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1043','1036']
self.Builds_Into=[]
self.Tags=['damage','attack_speed']
self.Costs = 285
self.Total_Costs = 1750
self.Description="+50% Attack Speed +20 Attack Damage UNIQUE Passive: Your basic attacks grant vision of your target for 5 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Speed += 50.0
# above is %
self.parent.Attack_Damage += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3075():
def __init__(self):
self.parent=False
self.Name="Thornmail"
self.Icon="3075.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1029','1031']
self.Builds_Into=[]
self.Tags=['armor']
self.Costs = 1000
self.Total_Costs = 2000
self.Description="+100 Armor UNIQUE Passive: On being hit by basic attacks, returns 30% of damage taken as magic damage."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Armor += 100.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3077():
def __init__(self):
self.parent=False
self.Name="Tiamat"
self.Icon="3077.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1037','1036','1004','1006']
self.Builds_Into=[]
self.Tags=['health_regen','damage','mana_regen']
self.Costs = 250
self.Total_Costs = 2070
self.Description="+50 Attack Damage +15 Health Regen per 5 seconds +5 Mana Regen per 5 seconds Passive: Your basic attacks splash, dealing 50% area damage around the target (35% for ranged attacks)."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 50.0
self.parent.Health_Regen_per_5_seconds += 15.0
self.parent.Mana_Regen_per_5_seconds += 5.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3078():
def __init__(self):
self.parent=False
self.Name="Trinity Force"
self.Icon="3078.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3086','1051','1042','3057','1027','1052','3044','1028','1036']
self.Builds_Into=[]
self.Tags=['health','damage','attack_speed','spell_damage','mana','movement','critical_strike']
self.Costs = 300
self.Total_Costs = 4070
self.Description="+30 Attack Damage +30 Ability Power +30% Attack Speed +15% Critical Strike Chance +12% Movement Speed +250 Health +250 Mana UNIQUE Passive: Your basic attacks have a 25% chance to slow your target's Movement Speed by 35% for 2.5 seconds. UNIQUE Passive: After using an ability, your next basic attack deals bonus physical damage equal to 150% of your base Attack Damage (2 second cooldown). Does not stack with Sheen or Lich Bane."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 30.0
self.parent.Ability_Power += 30.0
self.parent.Attack_Speed += 30.0
# above is %
self.parent.Critical_Strike_Chance += 15.0
# above is %
self.parent.Movement_Speed += 12.0
# above is %
self.parent.Health += 250.0
self.parent.Mana += 250.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_1053():
def __init__(self):
self.parent=False
self.Name="Vampiric Scepter"
self.Icon="1053.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=['3050','3123','3144','3181','3154','3072']
self.Tags=['life_steal']
self.Costs = 450
self.Total_Costs = 450
self.Description="+10% Life Steal"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Life_Steal += 10.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_2043():
def __init__(self):
self.parent=False
self.Name="Vision Ward"
self.Icon="2043.png"
self.Stack=0
self.MaxStack=0
self.Built_From=[]
self.Builds_Into=[]
self.Tags=['consumeable']
self.Costs = 125
self.Total_Costs = 125
self.Description="Click to Consume: Places an invisible ward that reveals the surrounding area and stealthed units in the area for 3 minutes."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
pass
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3135():
def __init__(self):
self.parent=False
self.Name="Void Staff"
self.Icon="3135.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1026','1052']
self.Builds_Into=[]
self.Tags=['spell_damage']
self.Costs = 1000
self.Total_Costs = 2295
self.Description="+70 Ability Power UNIQUE Passive: +40% Magic Penetration"
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 70.0
self.parent.Magic_Penetration += 40.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3082():
def __init__(self):
self.parent=False
self.Name="Warden's Mail"
self.Icon="3082.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1031','1006']
self.Builds_Into=['3143']
self.Tags=['health_regen','armor']
self.Costs = 400
self.Total_Costs = 1350
self.Description="+50 Armor +20 Health Regen per 5 seconds UNIQUE Passive: 20% chance on being hit by basic attacks to slow the attacker's Movement and Attack Speeds by 35% for 3 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Armor += 50.0
self.parent.Health_Regen_per_5_seconds += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3083():
def __init__(self):
self.parent=False
self.Name="Warmog's Armor"
self.Icon="3083.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1011','1028','1007']
self.Builds_Into=[]
self.Tags=['health','health_regen']
self.Costs = 980
self.Total_Costs = 3000
self.Description="+920 Health +30 Health Regen per 5 seconds Passive: Minion kills permanently grant 3.5 Health and .10 Health Regen per 5 seconds. Champion kills and assists permanently grant 35 Health and 1 Health Regen per 5 seconds. Bonuses cap at +350 Health and +10 Health Regen per 5 seconds."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 920.0
self.parent.Health_Regen_per_5_seconds += 30.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3152():
def __init__(self):
self.parent=False
self.Name="Will of the Ancients"
self.Icon="3152.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1026','3145','1052','1052']
self.Builds_Into=[]
self.Tags=['spell_damage']
self.Costs = 440
self.Total_Costs = 2500
self.Description="+50 Ability Power UNIQUE Aura: Grants nearby allied champions 30 Ability Power and 20% Spell Vamp"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 50.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3091():
def __init__(self):
self.parent=False
self.Name="Wit's End"
self.Icon="3091.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1043','1033']
self.Builds_Into=[]
self.Tags=['spell_block','attack_speed']
self.Costs = 700
self.Total_Costs = 2150
self.Description="+40% Attack Speed +30 Magic Resist UNIQUE Passive: Your basic attacks deal 42 bonus magic damage. UNIQUE Passive: Your basic attacks increase your Magic Resist by 5 for 5 seconds (effect stacks up to 4 times)."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Speed += 40.0
# above is %
self.parent.Magic_Resist += 30.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3154():
def __init__(self):
self.parent=False
self.Name="Wriggle's Lantern"
self.Icon="3154.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1053','3106','1029','1036']
self.Builds_Into=[]
self.Tags=['armor','damage','life_steal']
self.Costs = 150
self.Total_Costs = 1600
self.Description="+23 Attack Damage +30 Armor +12% Life Steal UNIQUE Passive: Your basic attacks against minions and monsters have a 20% chance to deal 425 bonus magic damage. UNIQUE Active: Places an invisible Sight Ward that reveals the surrounding area for 3 minutes (3 minute cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 23.0
self.parent.Armor += 30.0
self.parent.Life_Steal += 12.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3142():
def __init__(self):
self.parent=False
self.Name="Youmuu's Ghostblade"
self.Icon="3142.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3093','1051','3134','1036','1036']
self.Builds_Into=[]
self.Tags=['damage','critical_strike','attack_speed','cooldown_reduction','movement']
self.Costs = 600
self.Total_Costs = 2687
self.Description="+30 Attack Damage +15% Critical Strike Chance UNIQUE Passive: +15% Cooldown Reduction UNIQUE Passive: +20 Armor Penetration UNIQUE Active: You gain 20% Movement Speed and 50% Attack Speed for 4 seconds. Melee basic attacks increase the duration by 2 seconds up to a maximum duration of 8 seconds (60 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Attack_Damage += 30.0
self.parent.Critical_Strike_Chance += 15.0
# above is %
self.parent.Cooldown_Reduction += 15.0
# above is %
self.parent.Armor_Penetration += 20.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3086():
def __init__(self):
self.parent=False
self.Name="Zeal"
self.Icon="3086.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1051','1042']
self.Builds_Into=['3046','3078']
self.Tags=['critical_strike','attack_speed','movement']
self.Costs = 375
self.Total_Costs = 1195
self.Description="+20% Attack Speed +10% Critical Strike Chance +6% Movement Speed"
self.RichText_Description=""
self.has_active=False
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Attack_Speed += 20.0
# above is %
self.parent.Critical_Strike_Chance += 10.0
# above is %
self.parent.Movement_Speed += 6.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3050():
def __init__(self):
self.parent=False
self.Name="Zeke's Herald"
self.Icon="3050.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['3067','1028','1042','1053']
self.Builds_Into=[]
self.Tags=['health','attack_speed','life_steal','cooldown_reduction']
self.Costs = 425
self.Total_Costs = 2145
self.Description="+250 Health UNIQUE Passive: +15% Cooldown Reduction UNIQUE Aura: Grants nearby allied champions 12% Life Steal and 20% Attack Speed."
self.RichText_Description=""
self.has_active=False
self.has_passive=True
self.Custom()
def UpdateStats(self):
self.parent.Health += 250.0
self.parent.Cooldown_Reduction += 15.0
# above is %
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Item_3157():
def __init__(self):
self.parent=False
self.Name="Zhonya's Hourglass"
self.Icon="3157.png"
self.Stack=0
self.MaxStack=0
self.Built_From=['1031','1058']
self.Builds_Into=[]
self.Tags=['armor','spell_damage']
self.Costs = 800
self.Total_Costs = 3100
self.Description="+100 Ability Power +50 Armor UNIQUE Active: Places your champion into Stasis for 2 seconds, rendering you invulnerable and untargetable but unable to take any action (90 second cooldown)."
self.RichText_Description=""
self.has_active=True
self.has_passive=False
self.Custom()
def UpdateStats(self):
self.parent.Ability_Power += 100.0
self.parent.Armor += 50.0
self.UpdateStats_Custom()
def Custom(self):
pass
def UpdateStats_Custom(self):
pass
class Items():
def __init__(self,parent):
self.parent=parent
self.ITEMS={}
self.InitItems()
self.ItemIndex=['3001','3105','1052','3003','3174','3005','3198','3197','3196','3093','1038','3102','3006','3144','1026','3117','1001','3009','1051','3010','1031','3028','3172','1018','1029','1042','3128','1055','1056','1054','3173','2038','2039','2037','3097','3184','3123','1004','3108','3109','3110','3022','1011','3024','3026','3124','3136','2003','3132','3155','3146','3145','3187','3031','3158','3178','3098','3067','3186','3035','3138','3100','3190','1036','3126','3106','3114','3037','2004','3004','3156','3041','1005','3111','3170','3165','3115','1058','1057','3047','1033','3180','2042','2047','3044','3046','3096','1037','1062','1063','3140','3089','3143','1043','1007','1006','3027','1028','3116','3181','1027','3057','3069','2044','3020','3099','3065','3101','3068','3141','3070','3071','3072','3134','3200','3185','3075','3077','3078','1053','2043','3135','3082','3083','3152','3091','3154','3142','3086','3050','3157']
self.CreateLists()
def InitItems(self):
self.ITEMS['3001']=Item_3001()
self.ITEMS['3105']=Item_3105()
self.ITEMS['1052']=Item_1052()
self.ITEMS['3003']=Item_3003()
self.ITEMS['3174']=Item_3174()
self.ITEMS['3005']=Item_3005()
self.ITEMS['3198']=Item_3198()
self.ITEMS['3197']=Item_3197()
self.ITEMS['3196']=Item_3196()
self.ITEMS['3093']=Item_3093()
self.ITEMS['1038']=Item_1038()
self.ITEMS['3102']=Item_3102()
self.ITEMS['3006']=Item_3006()
self.ITEMS['3144']=Item_3144()
self.ITEMS['1026']=Item_1026()
self.ITEMS['3117']=Item_3117()
self.ITEMS['1001']=Item_1001()
self.ITEMS['3009']=Item_3009()
self.ITEMS['1051']=Item_1051()
self.ITEMS['3010']=Item_3010()
self.ITEMS['1031']=Item_1031()
self.ITEMS['3028']=Item_3028()
self.ITEMS['3172']=Item_3172()
self.ITEMS['1018']=Item_1018()
self.ITEMS['1029']=Item_1029()
self.ITEMS['1042']=Item_1042()
self.ITEMS['3128']=Item_3128()
self.ITEMS['1055']=Item_1055()
self.ITEMS['1056']=Item_1056()
self.ITEMS['1054']=Item_1054()
self.ITEMS['3173']=Item_3173()
self.ITEMS['2038']=Item_2038()
self.ITEMS['2039']=Item_2039()
self.ITEMS['2037']=Item_2037()
self.ITEMS['3097']=Item_3097()
self.ITEMS['3184']=Item_3184()
self.ITEMS['3123']=Item_3123()
self.ITEMS['1004']=Item_1004()
self.ITEMS['3108']=Item_3108()
self.ITEMS['3109']=Item_3109()
self.ITEMS['3110']=Item_3110()
self.ITEMS['3022']=Item_3022()
self.ITEMS['1011']=Item_1011()
self.ITEMS['3024']=Item_3024()
self.ITEMS['3026']=Item_3026()
self.ITEMS['3124']=Item_3124()
self.ITEMS['3136']=Item_3136()
self.ITEMS['2003']=Item_2003()
self.ITEMS['3132']=Item_3132()
self.ITEMS['3155']=Item_3155()
self.ITEMS['3146']=Item_3146()
self.ITEMS['3145']=Item_3145()
self.ITEMS['3187']=Item_3187()
self.ITEMS['3031']=Item_3031()
self.ITEMS['3158']=Item_3158()
self.ITEMS['3178']=Item_3178()
self.ITEMS['3098']=Item_3098()
self.ITEMS['3067']=Item_3067()
self.ITEMS['3186']=Item_3186()
self.ITEMS['3035']=Item_3035()
self.ITEMS['3138']=Item_3138()
self.ITEMS['3100']=Item_3100()
self.ITEMS['3190']=Item_3190()
self.ITEMS['1036']=Item_1036()
self.ITEMS['3126']=Item_3126()
self.ITEMS['3106']=Item_3106()
self.ITEMS['3114']=Item_3114()
self.ITEMS['3037']=Item_3037()
self.ITEMS['2004']=Item_2004()
self.ITEMS['3004']=Item_3004()
self.ITEMS['3156']=Item_3156()
self.ITEMS['3041']=Item_3041()
self.ITEMS['1005']=Item_1005()
self.ITEMS['3111']=Item_3111()
self.ITEMS['3170']=Item_3170()
self.ITEMS['3165']=Item_3165()
self.ITEMS['3115']=Item_3115()
self.ITEMS['1058']=Item_1058()
self.ITEMS['1057']=Item_1057()
self.ITEMS['3047']=Item_3047()
self.ITEMS['1033']=Item_1033()
self.ITEMS['3180']=Item_3180()
self.ITEMS['2042']=Item_2042()
self.ITEMS['2047']=Item_2047()
self.ITEMS['3044']=Item_3044()
self.ITEMS['3046']=Item_3046()
self.ITEMS['3096']=Item_3096()
self.ITEMS['1037']=Item_1037()
self.ITEMS['1062']=Item_1062()
self.ITEMS['1063']=Item_1063()
self.ITEMS['3140']=Item_3140()
self.ITEMS['3089']=Item_3089()
self.ITEMS['3143']=Item_3143()
self.ITEMS['1043']=Item_1043()
self.ITEMS['1007']=Item_1007()
self.ITEMS['1006']=Item_1006()
self.ITEMS['3027']=Item_3027()
self.ITEMS['1028']=Item_1028()
self.ITEMS['3116']=Item_3116()
self.ITEMS['3181']=Item_3181()
self.ITEMS['1027']=Item_1027()
self.ITEMS['3057']=Item_3057()
self.ITEMS['3069']=Item_3069()
self.ITEMS['2044']=Item_2044()
self.ITEMS['3020']=Item_3020()
self.ITEMS['3099']=Item_3099()
self.ITEMS['3065']=Item_3065()
self.ITEMS['3101']=Item_3101()
self.ITEMS['3068']=Item_3068()
self.ITEMS['3141']=Item_3141()
self.ITEMS['3070']=Item_3070()
self.ITEMS['3071']=Item_3071()
self.ITEMS['3072']=Item_3072()
self.ITEMS['3134']=Item_3134()
self.ITEMS['3200']=Item_3200()
self.ITEMS['3185']=Item_3185()
self.ITEMS['3075']=Item_3075()
self.ITEMS['3077']=Item_3077()
self.ITEMS['3078']=Item_3078()
self.ITEMS['1053']=Item_1053()
self.ITEMS['2043']=Item_2043()
self.ITEMS['3135']=Item_3135()
self.ITEMS['3082']=Item_3082()
self.ITEMS['3083']=Item_3083()
self.ITEMS['3152']=Item_3152()
self.ITEMS['3091']=Item_3091()
self.ITEMS['3154']=Item_3154()
self.ITEMS['3142']=Item_3142()
self.ITEMS['3086']=Item_3086()
self.ITEMS['3050']=Item_3050()
self.ITEMS['3157']=Item_3157()
def GetItem(self,itemid):
return self.ITEMS[itemid]
def CreateLists(self):
self.SortedLists={}
for ItemID in self.ItemIndex:
for i in self.ITEMS[ItemID].Tags:
if not self.SortedLists.has_key(i):
self.SortedLists[i]=[]
self.SortedLists[i].append(ItemID)
else:
self.SortedLists[i].append(ItemID)
for i in self.SortedLists:
costs = {}
count = 0
for j in self.SortedLists[i]:
costs["%s_%s" % (self.ITEMS[j].Total_Costs,count)] = j
self.SortedLists[i] = []
count +=1
for j in sorted(costs.keys()):
self.SortedLists[i].append(costs[j])
# for i in self.SortedLists.iterkeys():
# print i
# print self.SortedLists[i]
# print ".............."
def GetList(self,string):
#attack_speed
#doran
#life_steal
#spell_damage
#viktor
#armor
#spell_block
#damage
#health_regen
#mana
#health
#consumeable
#movement
#mana_regen
#critical_strike
#prospector
#cooldown_reduction
return self.SortedLists[string]
| Python |
#! /usr/bin/env python
from bs4 import BeautifulSoup
import re
import sys
import os
#passive_error_list = ['3174','3005','3028','3186','3126','3004','3089','3141','3072','3134','3077','3142']
filename=sys.argv[1]
soup = BeautifulSoup(open(filename))
#print soup.prettify()
tagtags = soup.find_all('table',{ 'class':'champion_item'})
blipp = sys.argv[2]
ITEMIDS=[]
print "import operator"
print "import copy"
print ""
#for tag in soup.find_all('div',{ 'id':re.compile('tooltip_item_detail_%s' % (blipp))}):
for tag in soup.find_all('div',{ 'id':re.compile('tooltip_item_detail_\d+')}):
# print tag.prettify()
itemid=tag['id'][-4:]
ITEMIDS.append(itemid)
name=tag.h1.string
itemname = name
desc=tag.p.string
# print "[%s]" % (itemid)
# print "name = %s" %(name)
# print "!desc!%s!" % (desc)
# desc processing
desc_stats = ""
#desc_type = ""
active_stats = ""
passive_stats = ""
chunks = []
rx = re.search('(Active|Passive|Aura)',desc) #regex 0
if rx:
# print "regex 0 match" # debug
# desc_type = rx.group(1)
m = re.match('([a-zA-Z0-9+% \.]+)(UNIQUE|Active|Passive|Aura)',desc) #regex 1
if not m:
# print "regex NOT match #1" #debug
if re.match('(UNIQUE|Active|Passive|Aura)',desc): #regex 2
# print "yeah"
desc_stats = desc
desc_stats = re.sub('UNIQUE','',desc_stats)
chunks = re.split('(Active|Passive|Aura)',desc_stats)
desc_stats = ""
# print chunks #debug
else:
# print "regex match #2" # debug
desc_stats = desc
print "ERROR_1 = True"
else:
# print "regex 1 match" # debug
desc_stats = m.group(1)
# print "!!!",desc_stats,"!" # debug
desc_stats = re.sub('UNIQUE','',desc_stats)
chunks = re.split('(Active|Passive|Aura)',desc)
chunks.pop(0)
for i in range(0,len(chunks)):
chunk = re.sub('UNIQUE','',chunks[i])
chunk = re.sub('^:\s?','',chunk)
if chunk == "Active":
temp = re.sub('UNIQUE','',chunks[i+1])
temp = re.sub('^:\s?','',temp)
active_stats += temp.rstrip(' ') +";"
i += 2
continue
if chunk == "Passive":
temp = re.sub('UNIQUE','',chunks[i+1])
temp = re.sub('^:\s?','',temp)
temp = temp.rstrip(' ')
# print "!temp!%s!" % (temp) # debug
if "Enhanced Movement 2" in temp:
# passive_stats += temp.rstrip(' ') +";"
# print "!!!!!!!!!!!",temp
# print "Movement Speed = 20"
desc_stats += "+70 Movement Speed "
passive_stats += "+70 Movement Speed;"
i += 2
if "Enhanced Movement 1" in temp:
# passive_stats += temp.rstrip(' ') +";"
# print "!!!!!!!!!!!",temp
# print "Movement Speed = 20"
desc_stats += "+50 Movement Speed "
passive_stats += "+50 Movement Speed;"
i += 2
if "Enhanced Movement 3" in temp:
# passive_stats += temp.rstrip(' ') +";"
# print "!!!!!!!!!!!",temp
# print "Movement Speed = 20"
desc_stats += "+90 Movement Speed "
passive_stats += "+90 Movement Speed;"
i += 2
else:
if re.match('\+([0-9.]+?%?)\s+?(.+)$',temp):
desc_stats += temp.rstrip(' ')
passive_stats += temp.rstrip(' ') +";"
elif re.match('([0-9.]+?%)\s+?Cooldown Reduction',temp):
desc_stats += "+%s" %(temp.rstrip(' '))
passive_stats += "+%s" %(temp.rstrip(' ')) +";"
else:
passive_stats += temp.rstrip(' ') +";"
i += 2
continue
elif re.search('Click to Consume',desc):
# print "ERROR = True"
pass
else:
desc_stats = desc
# print desc_stats
# print "!!!!!!!",desc_stats,"!!"
class_string = ""
chunks = desc_stats.split('+')
for chunk in chunks:
chunk = chunk.rstrip(' ')
# print "!chunk!",chunk,"" #debug
if chunk == "" or re.search('^\s+$',chunk):
continue
# print "!chunk!",chunk,"!!"
m = re.match('([0-9.]+?%?)\s+?(.+)$',chunk)
if m:
# print m.group(2) + " = " + m.group(1)
class_string += "%s,%s;" %(m.group(2),m.group(1))
else:
print "Regex Error"
print "RegexError-desc_stats!",desc_stats,"!"
#create_class(itemid,class_string.rstrip(';'),itemname)
print "class Item_%s():" % (itemid)
print " def __init__(self):"
print " self.parent=False"
print " self.Name=\"%s\"" % (itemname)
print " self.Icon=\"%s.png\"" % (itemid)
print " self.ID=%s" % (itemid)
print " self.Stack=0"
print " self.MaxStack=0"
if tag.table == None:
print " self.Built_From=[]"
else:
imgs = tag.table.find_all('img')
imgs.pop(0)
builtfrom = ""
for i in imgs:
builtfrom += i['src'][-8:-4] + ","
tempstring=builtfrom.rstrip(',')
tempstring=re.sub(',',"','",tempstring)
print " self.Built_From=['%s']" %(tempstring)
buildsintodiv = tag.find('div',{'class':'item_parents'})
if buildsintodiv == None:
print " self.Builds_Into=[]"
else:
buildsinto = ""
for i in buildsintodiv.find_all('img'):
buildsinto += i['src'][-8:-4] + ","
tempstring=buildsinto.rstrip(',')
tempstring=re.sub(',',"','",tempstring)
print " self.Builds_Into=['%s']" %(tempstring)
#tags
#<a class="lol_item" href="/items#3172" style="text-decoration: none;">
#<span class="highlight">Cloak and Dagger</span><br/>
#</a>
#<p>+20% Attack Speed +20% Critical Strike Chance UNIQUE Passive: +35 Tenacity (Tenacity reduces the duration of stuns, slows, taunts, fears, silences, blinds and immobilizes. Does not stack with other Tenacity items.)</p>
# <div class="item_geneology left filter_tag_critical_strike filter_tag_attack_speed"
#
for xx in tagtags:
for td in xx.find_all('td'):
if td['class'][0] == "item_icon":
if itemid in td.a.attrs['href']:
# print xx.prettify()
string = ""
for x in xx.find_all('div',{'class':'item_geneology'}):
if x.attrs['class'][1] == 'left':
#string = ""
for i in x.attrs['class']:
if 'filter' in i:
string += i[11:] + ","
if len(string) == 0:
if itemid == "3200":
print " self.Tags=['spell_damage','viktor']"
elif itemid == "3198":
print " self.Tags=['spell_damage','viktor']"
elif itemid == "3197":
print " self.Tags=['spell_damage','mana','cooldown_reduction','viktor']"
elif itemid == "3196":
print " self.Tags=['spell_damage','health','health_regen','movement','viktor']"
elif itemid == "1055":
print " self.Tags=['health','attack_speed','life_steal','doran']"
elif itemid == "1056":
print " self.Tags=['health','spell_damage','mana_regen','doran']"
elif itemid == "1054":
print " self.Tags=['health','armor','health_regen','doran']"
elif itemid == "1055":
print " self.Tags=['health','attack_speed','life_steal','doran']"
elif itemid == "2003":
print " self.Tags=['health','consumeable']"
active_stats = "yes"
elif itemid == "2004":
print " self.Tags=['mana','consumeable']"
active_stats = "yes"
elif itemid == "2038":
print " self.Tags=['attack_speed','critical_strike','consumeable']"
active_stats = "yes"
elif itemid == "2039":
print " self.Tags=['spell_damage','cooldown_reduction','consumeable']"
active_stats = "yes"
elif itemid == "2037":
print " self.Tags=['health','damage','consumeable']"
active_stats = "yes"
elif itemid == "2042":
print " self.Tags=['consumeable']"
active_stats = "yes"
elif itemid == "2043":
print " self.Tags=['consumeable']"
active_stats = "yes"
elif itemid == "2047":
print " self.Tags=['consumeable']"
active_stats = "yes"
elif itemid == "1062":
print " self.Tags=['health','damage','life_steal','prospector']"
active_stats = "yes"
elif itemid == "1063":
print " self.Tags=['spell_damage','mana_regen','health','prospector']"
active_stats = "yes"
elif itemid == "2044":
print " self.Tags=['consumeable']"
active_stats = "yes"
else:
print " self.Tags=[]"
print "ERROR_TAGS = True"
else:
string = string.rstrip(',')
string=re.sub(',',"','",string)
print " self.Tags=['%s']" % (string)
yy = xx.find('td',{'class':'cost'})
if yy:
m = re.search('>(\d+)<br',str(yy.span))
print " self.Costs =",m.group(1)
m = re.search('br/>(\d+)</spa',str(yy.span))
print " self.Total_Costs =",m.group(1)
#Builds from
# <table class="item_tree item_tree_root" style="width: 184px;">
# Built into
#<div class="item_parents">""
#output
#print "default_description = %s" % (desc)
print " self.Description=\"%s\"" % (desc)
print " self.RichText_Description=\"\""
if active_stats == "":
print " self.has_active=False"
else:
print " self.has_active=True"
if passive_stats == "":
print " self.has_passive=False"
else:
print " self.has_passive=True"
print " self.Custom()"
print ""
print " def UpdateStats(self):"
string = class_string.rstrip(';')
if len(string) == 0:
print " pass"
else:
for i in string.split(';'):
if "Augment" in i:
i="Augment,666"
if "Tenacity (" in i:
i="Tenacity,True"
name,value = i.split(',')
name = re.sub('\s+?',"_",name)
if itemid == "3200":
print " self.parent.Ability_Power += 3.0 * self.parent.Level"
elif itemid == "3156":
print " self.parent.Attack_Damage += 55.0"
print " self.parent.Magic_Resist += 36.0"
print " #self.parent.Attack_Damage += maxhealth - health = temp (maxhelth/temp)*100 = temp abs(temp/2.5) _for_every_2.5%_of_your_Maximum_Health_that_is_missing.=1.0"
elif "Pros" in name:
print " self.parent.Health += 200"
elif "True" in value:
print " self.parent.%s=True" % (name)
elif "." in value:
print " self.parent.%s += %s" % (name,value.rstrip('%'))
else:
print " self.parent.%s += %s.0" % (name,value.rstrip('%'))
if "%" in value:
print " # above is %"
print " self.UpdateStats_Custom()"
print ""
if os.path.isfile("Custom/%s.py" % (itemid)):
FILE=open("Custom/%s.py" % (itemid),'r')
for i in FILE.readlines():
print i.rstrip()
print ""
print ""
else:
print ""
print " def Custom(self):"
print " pass"
print ""
print " def UpdateStats_Custom(self):"
print " pass"
print ""
print ""
print """
class Items():
def __init__(self,parent):
self.parent=parent
self.ITEMS={}
self.InitItems()"""
string = "['"
for i in ITEMIDS:
string += i + "','"
string=string[:-2] + "]"
print " self.ItemIndex=%s" % (string)
print " self.CreateLists()"
print """
def InitItems(self):"""
for i in ITEMIDS:
print " self.ITEMS['%s']=Item_%s()" % (i,i)
print """
def GetItem(self,itemid):
return self.ITEMS[str(itemid)]
def GetItemCopy(self,itemid):
return copy.deepcopy(self.ITEMS[str(itemid)])
def CreateLists(self):
self.SortedLists={}
for ItemID in self.ItemIndex:
for i in self.ITEMS[ItemID].Tags:
if not self.SortedLists.has_key(i):
self.SortedLists[i]=[]
self.SortedLists[i].append(ItemID)
else:
self.SortedLists[i].append(ItemID)
for i in self.SortedLists:
costs = {}
for j in self.SortedLists[i]:
costs[j] = self.ITEMS[j].Total_Costs
self.SortedLists[i] = []
for k,l in sorted(costs.iteritems(), key=operator.itemgetter(1)):
self.SortedLists[i].append(k)
def GetList(self,string):
#attack_speed
#doran
#life_steal
#spell_damage
#viktor
#armor
#spell_block
#damage
#health_regen
#mana
#health
#consumeable
#movement
#mana_regen
#critical_strike
#prospector
#cooldown_reduction
return self.SortedLists[string]
"""
| Python |
#class hurga():
def Custom(self):
self.MaxStack=250
self.Stack=250
def UpdateStats_Custom(self):
temp=self.Stack * 4
self.parent.Mana += temp | Python |
#! /usr/bin/env python
from bs4 import BeautifulSoup
import re
import sys
import os
#passive_error_list = ['3174','3005','3028','3186','3126','3004','3089','3141','3072','3134','3077','3142']
filename=sys.argv[1]
soup = BeautifulSoup(open(filename))
#print soup.prettify()
tagtags = soup.find_all('table',{ 'class':'champion_item'})
blipp = sys.argv[2]
ITEMIDS=[]
print "import operator"
print "import copy"
print ""
#for tag in soup.find_all('div',{ 'id':re.compile('tooltip_item_detail_%s' % (blipp))}):
for tag in soup.find_all('div',{ 'id':re.compile('tooltip_item_detail_\d+')}):
# print tag.prettify()
itemid=tag['id'][-4:]
ITEMIDS.append(itemid)
name=tag.h1.string
itemname = name
desc=tag.p.string
# print "[%s]" % (itemid)
# print "name = %s" %(name)
# print "!desc!%s!" % (desc)
# desc processing
desc_stats = ""
#desc_type = ""
active_stats = ""
passive_stats = ""
chunks = []
rx = re.search('(Active|Passive|Aura)',desc) #regex 0
if rx:
# print "regex 0 match" # debug
# desc_type = rx.group(1)
m = re.match('([a-zA-Z0-9+% \.]+)(UNIQUE|Active|Passive|Aura)',desc) #regex 1
if not m:
# print "regex NOT match #1" #debug
if re.match('(UNIQUE|Active|Passive|Aura)',desc): #regex 2
# print "yeah"
desc_stats = desc
desc_stats = re.sub('UNIQUE','',desc_stats)
chunks = re.split('(Active|Passive|Aura)',desc_stats)
desc_stats = ""
# print chunks #debug
else:
# print "regex match #2" # debug
desc_stats = desc
print "ERROR_1 = True"
else:
# print "regex 1 match" # debug
desc_stats = m.group(1)
# print "!!!",desc_stats,"!" # debug
desc_stats = re.sub('UNIQUE','',desc_stats)
chunks = re.split('(Active|Passive|Aura)',desc)
chunks.pop(0)
for i in range(0,len(chunks)):
chunk = re.sub('UNIQUE','',chunks[i])
chunk = re.sub('^:\s?','',chunk)
if chunk == "Active":
temp = re.sub('UNIQUE','',chunks[i+1])
temp = re.sub('^:\s?','',temp)
active_stats += temp.rstrip(' ') +";"
i += 2
continue
if chunk == "Passive":
temp = re.sub('UNIQUE','',chunks[i+1])
temp = re.sub('^:\s?','',temp)
temp = temp.rstrip(' ')
# print "!temp!%s!" % (temp) # debug
if "Enhanced Movement 2" in temp:
# passive_stats += temp.rstrip(' ') +";"
# print "!!!!!!!!!!!",temp
# print "Movement Speed = 20"
desc_stats += "+70 Movement Speed "
passive_stats += "+70 Movement Speed;"
i += 2
if "Enhanced Movement 1" in temp:
# passive_stats += temp.rstrip(' ') +";"
# print "!!!!!!!!!!!",temp
# print "Movement Speed = 20"
desc_stats += "+50 Movement Speed "
passive_stats += "+50 Movement Speed;"
i += 2
if "Enhanced Movement 3" in temp:
# passive_stats += temp.rstrip(' ') +";"
# print "!!!!!!!!!!!",temp
# print "Movement Speed = 20"
desc_stats += "+90 Movement Speed "
passive_stats += "+90 Movement Speed;"
i += 2
else:
if re.match('\+([0-9.]+?%?)\s+?(.+)$',temp):
desc_stats += temp.rstrip(' ')
passive_stats += temp.rstrip(' ') +";"
elif re.match('([0-9.]+?%)\s+?Cooldown Reduction',temp):
desc_stats += "+%s" %(temp.rstrip(' '))
passive_stats += "+%s" %(temp.rstrip(' ')) +";"
else:
passive_stats += temp.rstrip(' ') +";"
i += 2
continue
elif re.search('Click to Consume',desc):
# print "ERROR = True"
pass
else:
desc_stats = desc
# print desc_stats
# print "!!!!!!!",desc_stats,"!!"
class_string = ""
chunks = desc_stats.split('+')
for chunk in chunks:
chunk = chunk.rstrip(' ')
# print "!chunk!",chunk,"" #debug
if chunk == "" or re.search('^\s+$',chunk):
continue
# print "!chunk!",chunk,"!!"
m = re.match('([0-9.]+?%?)\s+?(.+)$',chunk)
if m:
# print m.group(2) + " = " + m.group(1)
class_string += "%s,%s;" %(m.group(2),m.group(1))
else:
print "Regex Error"
print "RegexError-desc_stats!",desc_stats,"!"
#create_class(itemid,class_string.rstrip(';'),itemname)
print "class Item_%s():" % (itemid)
print " def __init__(self):"
print " self.parent=False"
print " self.Name=\"%s\"" % (itemname)
print " self.Icon=\"%s.png\"" % (itemid)
print " self.ID=%s" % (itemid)
print " self.Stack=0"
print " self.MaxStack=0"
if tag.table == None:
print " self.Built_From=[]"
else:
imgs = tag.table.find_all('img')
imgs.pop(0)
builtfrom = ""
for i in imgs:
builtfrom += i['src'][-8:-4] + ","
tempstring=builtfrom.rstrip(',')
tempstring=re.sub(',',"','",tempstring)
print " self.Built_From=['%s']" %(tempstring)
buildsintodiv = tag.find('div',{'class':'item_parents'})
if buildsintodiv == None:
print " self.Builds_Into=[]"
else:
buildsinto = ""
for i in buildsintodiv.find_all('img'):
buildsinto += i['src'][-8:-4] + ","
tempstring=buildsinto.rstrip(',')
tempstring=re.sub(',',"','",tempstring)
print " self.Builds_Into=['%s']" %(tempstring)
#tags
#<a class="lol_item" href="/items#3172" style="text-decoration: none;">
#<span class="highlight">Cloak and Dagger</span><br/>
#</a>
#<p>+20% Attack Speed +20% Critical Strike Chance UNIQUE Passive: +35 Tenacity (Tenacity reduces the duration of stuns, slows, taunts, fears, silences, blinds and immobilizes. Does not stack with other Tenacity items.)</p>
# <div class="item_geneology left filter_tag_critical_strike filter_tag_attack_speed"
#
for xx in tagtags:
for td in xx.find_all('td'):
if td['class'][0] == "item_icon":
if itemid in td.a.attrs['href']:
# print xx.prettify()
string = ""
for x in xx.find_all('div',{'class':'item_geneology'}):
if x.attrs['class'][1] == 'left':
#string = ""
for i in x.attrs['class']:
if 'filter' in i:
string += i[11:] + ","
if len(string) == 0:
if itemid == "3200":
print " self.Tags=['spell_damage','viktor']"
elif itemid == "3198":
print " self.Tags=['spell_damage','viktor']"
elif itemid == "3197":
print " self.Tags=['spell_damage','mana','cooldown_reduction','viktor']"
elif itemid == "3196":
print " self.Tags=['spell_damage','health','health_regen','movement','viktor']"
elif itemid == "1055":
print " self.Tags=['health','attack_speed','life_steal','doran']"
elif itemid == "1056":
print " self.Tags=['health','spell_damage','mana_regen','doran']"
elif itemid == "1054":
print " self.Tags=['health','armor','health_regen','doran']"
elif itemid == "1055":
print " self.Tags=['health','attack_speed','life_steal','doran']"
elif itemid == "2003":
print " self.Tags=['health','consumeable']"
active_stats = "yes"
elif itemid == "2004":
print " self.Tags=['mana','consumeable']"
active_stats = "yes"
elif itemid == "2038":
print " self.Tags=['attack_speed','critical_strike','consumeable']"
active_stats = "yes"
elif itemid == "2039":
print " self.Tags=['spell_damage','cooldown_reduction','consumeable']"
active_stats = "yes"
elif itemid == "2037":
print " self.Tags=['health','damage','consumeable']"
active_stats = "yes"
elif itemid == "2042":
print " self.Tags=['consumeable']"
active_stats = "yes"
elif itemid == "2043":
print " self.Tags=['consumeable']"
active_stats = "yes"
elif itemid == "2047":
print " self.Tags=['consumeable']"
active_stats = "yes"
elif itemid == "1062":
print " self.Tags=['health','damage','life_steal','prospector']"
active_stats = "yes"
elif itemid == "1063":
print " self.Tags=['spell_damage','mana_regen','health','prospector']"
active_stats = "yes"
elif itemid == "2044":
print " self.Tags=['consumeable']"
active_stats = "yes"
else:
print " self.Tags=[]"
print "ERROR_TAGS = True"
else:
string = string.rstrip(',')
string=re.sub(',',"','",string)
print " self.Tags=['%s']" % (string)
yy = xx.find('td',{'class':'cost'})
if yy:
m = re.search('>(\d+)<br',str(yy.span))
print " self.Costs =",m.group(1)
m = re.search('br/>(\d+)</spa',str(yy.span))
print " self.Total_Costs =",m.group(1)
#Builds from
# <table class="item_tree item_tree_root" style="width: 184px;">
# Built into
#<div class="item_parents">""
#output
#print "default_description = %s" % (desc)
print " self.Description=\"%s\"" % (desc)
print " self.RichText_Description=\"\""
if active_stats == "":
print " self.has_active=False"
else:
print " self.has_active=True"
if passive_stats == "":
print " self.has_passive=False"
else:
print " self.has_passive=True"
print " self.Custom()"
print ""
print " def UpdateStats(self):"
string = class_string.rstrip(';')
if len(string) == 0:
print " pass"
else:
for i in string.split(';'):
if "Augment" in i:
i="Augment,666"
if "Tenacity (" in i:
i="Tenacity,True"
name,value = i.split(',')
name = re.sub('\s+?',"_",name)
if itemid == "3200":
print " self.parent.Ability_Power += 3.0 * self.parent.Level"
elif itemid == "3156":
print " self.parent.Attack_Damage += 55.0"
print " self.parent.Magic_Resist += 36.0"
print " #self.parent.Attack_Damage += maxhealth - health = temp (maxhelth/temp)*100 = temp abs(temp/2.5) _for_every_2.5%_of_your_Maximum_Health_that_is_missing.=1.0"
elif "Pros" in name:
print " self.parent.Health += 200"
elif "True" in value:
print " self.parent.%s=True" % (name)
elif "." in value:
print " self.parent.%s += %s" % (name,value.rstrip('%'))
else:
print " self.parent.%s += %s.0" % (name,value.rstrip('%'))
if "%" in value:
print " # above is %"
print " self.UpdateStats_Custom()"
print ""
if os.path.isfile("Custom/%s.py" % (itemid)):
FILE=open("Custom/%s.py" % (itemid),'r')
for i in FILE.readlines():
print i.rstrip()
print ""
print ""
else:
print ""
print " def Custom(self):"
print " pass"
print ""
print " def UpdateStats_Custom(self):"
print " pass"
print ""
print ""
print """
class Items():
def __init__(self,parent):
self.parent=parent
self.ITEMS={}
self.InitItems()"""
string = "['"
for i in ITEMIDS:
string += i + "','"
string=string[:-2] + "]"
print " self.ItemIndex=%s" % (string)
print " self.CreateLists()"
print """
def InitItems(self):"""
for i in ITEMIDS:
print " self.ITEMS['%s']=Item_%s()" % (i,i)
print """
def GetItem(self,itemid):
return self.ITEMS[str(itemid)]
def GetItemCopy(self,itemid):
return copy.deepcopy(self.ITEMS[str(itemid)])
def CreateLists(self):
self.SortedLists={}
for ItemID in self.ItemIndex:
for i in self.ITEMS[ItemID].Tags:
if not self.SortedLists.has_key(i):
self.SortedLists[i]=[]
self.SortedLists[i].append(ItemID)
else:
self.SortedLists[i].append(ItemID)
for i in self.SortedLists:
costs = {}
for j in self.SortedLists[i]:
costs[j] = self.ITEMS[j].Total_Costs
self.SortedLists[i] = []
for k,l in sorted(costs.iteritems(), key=operator.itemgetter(1)):
self.SortedLists[i].append(k)
def GetList(self,string):
#attack_speed
#doran
#life_steal
#spell_damage
#viktor
#armor
#spell_block
#damage
#health_regen
#mana
#health
#consumeable
#movement
#mana_regen
#critical_strike
#prospector
#cooldown_reduction
return self.SortedLists[string]
"""
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.