code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
# -*- coding: utf-8 -*-
__author__ = 'gongqf'
from qrcode import *
qr = QRCode(version=1, error_correction=ERROR_CORRECT_H,box_size=12,border=1)
qr.add_data("HS.GDDS-DSZX/G.96/01")
qr.make(fit=True) # Generate the QRCode itself
# im contains a PIL.Image.Image object
im = qr.make_image()
# To save it
im.save("E:\\web\\flask\\gis\\filename.png") | Python |
# -*- coding: utf-8 -*-
import requests
import sys
import xlrd
# x 必须用UTF8编码格式,x内容出现 & 符号时,请用 %26 代替,
# 换行符使用 %0A
# 参数 描述 赋值例子
# bg 背景颜色 bg=颜色代码,例如:bg=ffffff
# fg 前景颜色 fg=颜色代码,例如:fg=cc0000
# gc 渐变颜色 gc=颜色代码,例如:gc=cc00000
# el 纠错等级 el可用值:h\q\m\l,例如:el=h
# w 尺寸大小 w=数值(像素),例如:w=300
# m 静区(外边距) m=数值(像素),例如:m=30
# pt 定位点颜色(外框) pt=颜色代码,例如:pt=00ff00
# inpt 定位点颜色(内点) inpt=颜色代码,例如:inpt=000000
# logo logo图片 logo=图片地址,例如:logo=http://www.liantu.com/images/2013/sample.jpg
proxies = {
"http": "http://127.0.0.1:8087",
}
api_url = 'http://qr.liantu.com/api.php?el=h&m=4&text='
def qr_code(png, text):
print '%s,%s' % (png, text)
qr_url = api_url+text
r = requests.get(qr_url, proxies=proxies)
f = open('%s.png' % png, 'wb')
f.write(path+'\\'+r.content)
f.close()
def cellint(cell):
if type(cell) in (float, int):
return int(cell)
else:
return cell
def readSheet(sheet):
sh = wb.sheet_by_name(sheet)
nrows = sh.nrows
ncols = sh.ncols
headers = dict((i, sh.cell_value(0, i)) for i in range(ncols))
return [dict((headers[j], cellint(sh.cell_value(i, j))) for j in headers) for i in range(1, nrows)]
if __name__ == '__main__':
qr_file = sys.argv[1]
if len(sys.argv) == 3:
path = sys.argv[2]
# print path
wb = xlrd.open_workbook(qr_file)
qr = readSheet('Sheet1')
for row in qr:
qr_code(row[u'序号'], row[u'光缆编码']) | Python |
# -*- coding: utf-8 -*-
__author__ = 'gongqf'
# import win32com
from win32com.client import Dispatch, constants, DispatchEx
from win32com.client.gencache import EnsureDispatch
import shutil
import qrcode
def gen_qr_pic(id,txt=''):
qr = qrcode.QRCode(version=None, error_correction=qrcode.constants.ERROR_CORRECT_H,box_size=12,border=1)
qr.add_data(txt)
qr.make(fit=True) # Generate the QRCode itself
# im contains a PIL.Image.Image object
im = qr.make_image()
# To save it
qr_file="E:\\web\\flask\\gis\\qr_%s.png"%id
im.save(qr_file)
return qr_file
def gen_card_word(qr_file,card_fibercode='',card_fibername='',card_fibercore='',card_date=''):
EnsureDispatch('Word.Application') #makepy 导入Word类库,否则constants无法使用
# w = win32com.client.Dispatch('Word.Application')
# 或者使用下面的方法,使用启动独立的进程:
# w = win32com.client.DispatchEx('Word.Application')
w = DispatchEx('Word.Application')
# 后台运行,不显示,不警告
w.Visible = True
w.DisplayAlerts = True
word_template=u'E:\\web\\flask\\gis\\光缆模板 - 副本.docx'
word_work=u'E:\\web\\flask\\gis\\temp.docx'
shutil.copy(word_template, word_work)
# 打开新的文件
doc = w.Documents.Open( FileName = word_work )
# doc = w.Documents.Add() # 创建新的文档
# card_fibercode='JD.JYYF/CHL-NCLGJ/HGC/J.48/01'
# card_fibername=u'世纪东方至交警.世纪东方25楼楼顶监控箱'
# card_fibercore='GYTS-%sB1'%6
# card_date='2014-1'
# wordSel = myRange.Select()
# expression .Execute(FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl)
# http://msdn.microsoft.com/en-us/library/office/ff193977.aspx
w.Selection.Find.Execute('card_fibercode', False, False, False, False, False, True, 1, True, card_fibercode, 2)
w.Selection.Find.Execute('card_fibername', False, False, False, False, False, True, 1, True, card_fibername, 2)
w.Selection.Find.Execute('card_fibercore', False, False, False, False, False, True, 1, True, card_fibercore, 2)
w.Selection.Find.Execute('card_date', False, False, False, False, False, True, 1, True, card_date, 2)
# dc=w.ActiveDocument.Content #取得当前活动文档的内容句柄
# ishps=w.ActiveDocument.InlineShapes #得到文中所有图片
shps=w.ActiveDocument.Shapes
# print shps.Count
for shp in shps:
print shp.Left,shp.Top,shp.Height,shp.Width,shp.Line.Visible,shp.Name
# shp.Delete()
# # shp.Select()
# shps.AddPicture(u'E:\\web\\flask\\gis\\liantu.png') # AddPicture(FileName As String, [LinkToFile], [SaveWithDocument], [Left], [Top], [Width], [Height], [Anchor])
# shps[0].Left=203
shps.AddPicture(qr_file)
shps[0].Left=155
shps[0].Top=50
shps[0].Height=75
shps[0].Width=75
# print w.Selection.InlineShapes.Count
# print w.Selection.InlineShapes[0].Name
# print ishps.Count,w.Selection.InlineShapes[0].Height
#w.ActiveDocument.InlineShapes[0].Delete()
# w.ActiveDocument.Shapes[0].Select()
# w.ActiveDocument.Shapes.AddPicture(u'E:\\web\\flask\\gis\\liantu.png') #按序号替换图片
#
#
# doc.PageSetup.PaperSize = 7 # 纸张大小, A3=6, A4=7
# doc.PageSetup.PageWidth = 8.6*28.35 # 直接设置纸张大小, 使用该设置后PaperSize设置取消
# doc.PageSetup.PageHeight = 5.49*28.35 # 直接设置纸张大小
# doc.PageSetup.Orientation = 1 # 页面方向, 竖直=0, 水平=1
# doc.PageSetup.TopMargin = 1*28.35 # 页边距上=3cm,1cm=28.35pt
# doc.PageSetup.BottomMargin = 0.3*28.35 # 页边距下=3cm
# doc.PageSetup.LeftMargin = 0.3*28.35 # 页边距左=2.5cm
# doc.PageSetup.RightMargin = 0.3*28.35 # 页边距右=2.5cm
# doc.PageSetup.TextColumns.SetCount(1) # 设置页面
#
# sel = w.Selection # 获取Selection对象
# sel.InsertBreak(8) # 插入分栏符=8, 分页符=7
# sel.Font.Name = "黑体" # 字体
# sel.Font.Size = 24 # 字大
# sel.Font.Bold = True # 粗体
# sel.Font.Italic = True # 斜体
# sel.Font.Underline = True # 下划线
# sel.ParagraphFormat.LineSpacing = 2*12 # 设置行距,1行=12磅
# sel.ParagraphFormat.Alignment = 1 # 段落对齐,0=左对齐,1=居中,2=右对齐
# sel.TypeText("XXXX") # 插入文字
# sel.TypeParagraph() # 插入空行
# # 注注注注::::ParagraphFormat属性必须使用TypeParagraph()之后才能二次生效!
#
# pic = sel.InlineShapes.AddPicture(r'c:\liantu.png') # 插入图片,缺省嵌入型
# # pic.WrapFormat.Type = 0 # 修改文字环绕方式:0=四周型,1=紧密型,3=文字上方,5=文字下方
# pic.Borders.OutsideLineStyle = constants.wdLineStyleSingleWavy # 设置图片4边线,1=实线
# pic.Borders.OutsideLineWidth = constants.wdLineWidth075pt # 设置边线宽度,对应对话框中数值依次2,4,6,8,12,18,24,36,48
# pic.Borders(-1).LineStyle = 1 # -1=上边线,-2=左边线,-3下边线,-4=右边线
# pic.Borders(-1).LineWidth = 8 # 依次2,4,6,8,12,18,24,36,48
# # 注注注注::::InlineShapes方式插入图片类似于插入字符(嵌入式),Shapes插入图片缺省是浮动的。
#
# tab=doc.Tables.Add(sel.Range, 16, 2) # 增加一个16行2列的表格
# tab.Style = "网格型" # 显示表格边框
# tab.Columns(1).SetWidth(5*28.35, 0) # 调整第1列宽度,1cm=28.35pt
# tab.Columns(2).SetWidth(9*28.35, 0) # 调整第2列宽度
# tab.Rows.Alignment = 1 # 表格对齐,0=左对齐,1=居中,2=右对齐
# tab.CellCellCellCell(1,1).Range.Text = "xxx" # 填充内容,注意Excel中使用wSheet.Cells(i,j)
# sel.MoveDown(5, 16) # 向下移动2行,5=以行为单位
# # 注注注注::::插入n行表格之后必须使用MoveDown(5,n)移动到表格之后才能进行其它操作,否则报错!
#
#
# # 插入文字
# myRange = worddoc.Range(0,0)
# myRange.InsertBefore('Hello from Python!')
#
# # 使用样式
# wordSel = myRange.Select()
# # wordSel.Style = constants.wdStyleHeading1
#
# # 正文文字替换
# w.Selection.Find.ClearFormatting()
# w.Selection.Find.Replacement.ClearFormatting()
# w.Selection.Find.Execute('ello', False, False, False, False, False, True, 1, True, '111', 2)
#
# # 页眉文字替换
# w.ActiveDocument.Sections[0].Headers[0].Range.Find.ClearFormatting()
# w.ActiveDocument.Sections[0].Headers[0].Range.Find.Replacement.ClearFormatting()
# w.ActiveDocument.Sections[0].Headers[0].Range.Find.Execute('222', False, False, False, False, False, True, 1, False, '223', 2)
#
# # 表格操作
# # worddoc.Tables[0].Rows[0].Cells[0].Range.Text ='123123'
# # worddoc.Tables[0].Rows.Add() # 增加一行
#
# # 转换为html
# wc = win32com.client.constants
# w.ActiveDocument.WebOptions.RelyOnCSS = 1
# w.ActiveDocument.WebOptions.OptimizeForBrowser = 1
# w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4
# w.ActiveDocument.WebOptions.OrganizeInFolder = 0
# w.ActiveDocument.WebOptions.UseLongFileNames = 1
# w.ActiveDocument.WebOptions.RelyOnVML = 0
# w.ActiveDocument.WebOptions.AllowPNG = 1
# # w.ActiveDocument.SaveAs( FileName = 'c:\\1.html', FileFormat = wc.wdFormatHTML )
#
# # 打印
# # worddoc.PrintOut()
word_file=r'E:\\web\\flask\\gis\\1.docx'
doc.SaveAs(word_file)
doc.Close()
# 关闭
# doc.Close()
# w.Documents.Close(wc.wdDoNotSaveChanges)
w.Quit()
return word_file
qr_pic_file=gen_qr_pic(12,u'JD.JYYF/CHL-NCLGJ/HGC/J.48/01')
print gen_card_word(qr_pic_file,'2551') | Python |
# -*- coding: utf-8 -*-
from flask.ext.login import login_required, login_user, logout_user, current_user
from login import LoginForm
__author__ = 'gongqf'
import os
import json
from flask import render_template, request, flash, url_for, redirect, jsonify, send_from_directory, make_response, g, \
session
from gis import app, login_manager, oid
from models import db, card, User, ROLE_USER
from math import ceil
from sqlalchemy import or_
from datetime import datetime
def todict(items, usenone=True, delkey=None, repkey=None):
'''
items: 是把request.form获得的ImmutableMultiDict对象用iteritems取得
usenone:是否把空值('')转换为None返回,默认转换为None
delkey: 删除指定的key,比如多余获取的input值,传入值可以是tuple或list,默认不删除
repkey: 用指定的键值新增或替换对应的键值,比如checkbox提交的时候如果uncheck则对应的name字段不会提交,需要手动控制
'''
d = {}
for k, v in items:
# print k,v
if v:
d[k] = v
elif usenone:
d[k] = None
if delkey:
if type(delkey) == tuple or type(delkey) == list:
for key in delkey:
d.pop(key, None)
else:
d.pop(delkey, None)
if repkey:
for rk in repkey:
d[rk] = repkey[rk]
return d
def sarow2dict(rows, emptystr=True):
def row2dict(row, emptystr=True):
d = {}
for column in row.__table__.columns:
d[column.name] = getattr(row, column.name)
if emptystr and d[column.name] is None:
d[column.name] = ''
return d
if not rows:
if rows is None:
return None
elif type(rows) == list:
return []
elif type(rows) == tuple:
return ()
elif type(rows) == dict:
return {}
if type(rows) == list:
# if type(rows)==tuple or type(rows)==list:
l = []
for row in rows:
l.append(row2dict(row))
return l
else:
return row2dict(rows)
def check_form_vaild(card_date, card_dept, card_fibername, card_fibercode, card_fiberlen, card_count, card_use,
card_action):
form_vaild = True
if card_date.strip() == '':
flash(u'日期错误', category='error')
form_vaild = False
if card_dept.strip() == '':
form_vaild = False
flash(u'区域/单位/部门错误', category='error')
# if card_fibername.strip() =='':
# form_vaild=False
# flash(u'标牌名称错误')
# if card_fibercode.strip() =='':
# form_vaild=False
# flash(u'标牌编码错误')
if card_count.strip() == '' or not card_count.isdigit():
form_vaild = False
flash(u'标牌数量错误', category='error')
if not card_fiberlen.isdigit():
form_vaild = False
flash(u'光缆长度错误', category='error')
# if card_use.strip() =='':
# form_vaild=False
# flash(u'领用人错误')
# if card_action.strip() =='':
# form_vaild=False
# flash(u'经办人错误')
return form_vaild
@app.route('/')
def index():
return render_template('base.html', x='hello')
@app.route('/card', methods=['GET', 'POST'])
@app.route('/card/<int:card_id>', methods=['GET', 'POST'])
def Card(card_id=None):
if request.method == 'POST':
action = request.form.get('action', None)
card_date = request.form.get('card_date', None)
card_dept = request.form.get('card_dept', None)
card_fibername = request.form.get('card_fibername', None)
card_fibercode = request.form.get('card_fibercode', None)
card_fibercore = request.form.get('card_fibercore', None)
card_fiberlen = request.form.get('card_fiberlen', None)
card_count = request.form.get('card_count', None)
card_use = request.form.get('card_use', None)
card_action = request.form.get('card_action', None)
card_gis = request.form.get('card_gis')
card_memo = request.form.get('card_memo', None)
card_source = request.form.get('card_source', None)
# print action,card_date,card_gis,request.form.iteritems()
if card_gis is None:
card_gis = False
else:
card_gis = True
if not check_form_vaild(card_date=card_date, card_dept=card_dept, card_fibername=card_fibername,
card_fibercode=card_fibercode, card_count=card_count, card_use=card_use,
card_action=card_action, card_fiberlen=card_fiberlen):
return redirect(url_for('Card', card_id=card_id))
if action == u'新增':
onecard = card(card_date=card_date, card_dept=card_dept, card_fibername=card_fibername,
card_fibercode=card_fibercode, card_count=card_count, card_use=card_use,
card_action=card_action, card_gis=card_gis, card_memo=card_memo, card_fiberlen=card_fiberlen,
card_source=card_source, card_fibercore=card_fibercore)
db.session.add(onecard)
flash(u"添加成功")
if action == u'删除':
card.query.filter_by(card_id=card_id).delete()
flash(u'删除成功')
if action == u'保存':
card.query.filter_by(card_id=card_id).update(todict(request.form.iteritems(), delkey='action',
repkey=dict(card_gis=card_gis,
card_update=datetime.strftime(
datetime.now(), '%Y-%m-%d %H:%M:%S'))))
flash(u"修改成功")
db.session.commit()
# return redirect(url_for('Card'))
onecard = card.query.filter_by(card_id=card_id).first()
todaycards = card.query.filter_by(card_date=datetime.strftime(datetime.now(), '%Y-%m-%d')).all()
return render_template('card.html', onecard=sarow2dict(onecard), cards=sarow2dict(todaycards))
@app.route('/json', methods=['GET'])
def Json():
depts = []
for item in db.session.query(card.card_dept.distinct()).order_by(card.card_dept).all():
if item[0]:
depts.append(item[0])
actions = []
for item in db.session.query(card.card_action.distinct()).order_by(card.card_action).all():
if item[0]:
actions.append(item[0])
uses = []
for item in db.session.query(card.card_use.distinct()).order_by(card.card_use).all():
if item[0]:
uses.append(item[0])
return app.response_class(
json.dumps({"depts": depts, "actions": actions, "uses": uses}, indent=None if request.is_xhr else 2),
mimetype='application/json')
@app.route('/useprint', methods=['GET', 'POST'])
def Useprint():
# ids=request.form['ids']
ids = request.values['ids']
print ids
ids = ids.split(',')
cards = card.query.filter(card.card_id.in_(ids)).all()
print ids, cards
resp = make_response(render_template('card_useprint.html', cards=sarow2dict(cards)))
resp.headers['Content-Disposition'] = 'attachment; filename=useprint.doc'
resp.headers['Content-Type'] = "application/vnd.ms-word"
return resp
@app.route('/cardprint/<id>', methods=['GET'])
def Cardprint(id):
print 'id:', id
def gen_qr_pic(id, txt=''):
import qrcode
qr = qrcode.QRCode(version=None, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=12, border=1)
qr.add_data(txt)
qr.make(fit=True) # Generate the QRCode itself
# im contains a PIL.Image.Image object
im = qr.make_image()
# To save it
print app.config['CARD_FOLDER']
qr_file = os.path.join(app.config['CARD_FOLDER'], '%s.png' % id)
im.save(qr_file)
print qr_file
return qr_file
def gen_card_word(card_id, qr_file, card_fibercode='card_fibercode', card_fibername='card_fibername',
card_fibercore='card_fibercore', card_date='card_date'):
from win32com.client import Dispatch, constants, DispatchEx
# from win32com.client.gencache import EnsureDispatch
import shutil
# EnsureDispatch('Word.Application') #makepy 导入Word类库,否则constants无法使用
# w = win32com.client.Dispatch('Word.Application')
# 或者使用下面的方法,使用启动独立的进程:
# w = win32com.client.DispatchEx('Word.Application')
w = DispatchEx('Word.Application')
# 后台运行,不显示,不警告
w.Visible = False
w.DisplayAlerts = False
word_template = os.path.join(app.config['CARD_FOLDER'], u'光缆模板.docx')
word_work = os.path.join(app.config['CARD_FOLDER'],
'%s.docx' % ''.join(map(lambda xx: (hex(ord(xx))[2:]), os.urandom(16))))
print word_work
shutil.copy(word_template, word_work)
# 打开新的文件
doc = w.Documents.Open(FileName=word_work)
# doc = w.Documents.Add() # 创建新的文档
w.Selection.Find.Execute('card_fibercode', False, False, False, False, False, True, 1, True, card_fibercode, 2)
w.Selection.Find.Execute('card_fibername', False, False, False, False, False, True, 1, True, card_fibername, 2)
w.Selection.Find.Execute('card_fibercore', False, False, False, False, False, True, 1, True,
'GYTS-%sB1' % card_fibercore, 2)
w.Selection.Find.Execute('card_date', False, False, False, False, False, True, 1, True, card_date, 2)
shps = w.ActiveDocument.Shapes
# shps.AddPicture(qr_file,Left=155,Top=50,Height=75,Width=75)
shps.AddPicture(qr_file)
for shp in shps:
print shp.Left, shp.Top, shp.Height, shp.Width, shp.Line.Visible, shp.Name
print shps.Count
shps[0].Left = 146.5
shps[0].Top = 21
shps[0].Height = 75
shps[0].Width = 75
for shp in shps:
print shp.Left, shp.Top, shp.Height, shp.Width, shp.Line.Visible, shp.Name
print shps.Count
# # 打印
# # worddoc.PrintOut()
word_file = os.path.join(app.config['CARD_FOLDER'], '%s.docx' % card_id)
doc.SaveAs(word_file)
doc.Close()
w.Quit()
print word_file
os.remove(word_work)
return word_file
onecard = card.query.filter_by(card_id=id).first()
if not onecard:
flash(u'无此标牌', 'error')
return redirect(url_for('Card'))
print onecard.card_id, onecard.card_fibercode
if not onecard.card_fibercode:
flash(u'标牌无编码', 'error')
return redirect(url_for('Card', id=onecard.card_id))
if not onecard.card_fibercore:
flash(u'标牌无芯数', 'error')
return redirect(url_for('Card', id=onecard.card_id))
if not onecard.card_date:
flash(u'标牌无日期', 'error')
return redirect(url_for('Card', id=onecard.card_id))
qr_pic_file = gen_qr_pic(onecard.card_id, onecard.card_fibercode)
card_word_file = gen_card_word(onecard.card_id, qr_pic_file, onecard.card_fibercode, onecard.card_fibername,
onecard.card_fibercore, datetime.strftime(onecard.card_date, '%Y-%m'))
resp = make_response()
resp.cache_control.no_cache = True
return send_from_directory(app.config['CARD_FOLDER'], '%s.docx' % onecard.card_id, as_attachment=True)
@app.route('/cards')
def Cards():
return render_template('cards.html')
def hj(d):
s = 0
if d:
for x in d:
s += x.card_count
return s
@app.route('/card_list', methods=['GET'])
def Card_list():
sc = request.args.get('sc', '')
inputstart = request.args.get('inputstart', '')
inputend = request.args.get('inputend', '')
page = request.args.get('page', 1, type=int)
pc = request.args.get('pc', 25, type=int)
gis = request.args.get('gis', '')
if gis == '0': card_gis = False
if gis == '1': card_gis = True
if inputstart == '': inputstart = '1970-1-1'
if inputend == '': inputend = '2070-1-1'
if gis == '':
cards = card.query.filter(or_(card.card_dept.like('%%%s%%' % sc), card.card_fibername.like('%%%s%%' % sc),
card.card_fibercode.like('%%%s%%' % sc), card.card_action.like('%%%s%%' % sc),
card.card_use.like('%%%s%%' % sc), card.card_memo.like('%%%s%%' % sc))).filter(
card.card_date >= inputstart).filter(card.card_date <= inputend).order_by(card.card_id.desc()).all()
else:
cards = card.query.filter(or_(card.card_dept.like('%%%s%%' % sc), card.card_fibername.like('%%%s%%' % sc),
card.card_fibercode.like('%%%s%%' % sc), card.card_action.like('%%%s%%' % sc),
card.card_use.like('%%%s%%' % sc), card.card_memo.like('%%%s%%' % sc))).filter(
card.card_date >= inputstart).filter(card.card_date <= inputend).filter(card.card_gis == card_gis).order_by(
card.card_id.desc()).all()
rows = len(cards)
sum_card_count = hj(cards)
if pc == 0:
pages = 1
page = 1
else:
pages = int(ceil(rows / float(pc)))
if page <= 0:
page = 1
if page > pages:
page = pages
offset = pc * (int(page) - 1)
cards = cards[offset:offset + pc]
xj_card_count = hj(cards)
# cards=card.query.order_by(card.card_id.desc()).all()
return render_template('card_list.html', cards=sarow2dict(cards), rows=rows, pages=pages, page=page, pc=pc,
xj_card_count=xj_card_count, sum_card_count=sum_card_count)
@app.before_request
def before_request():
g.user = current_user
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
@app.route("/login", methods=["GET", "POST"])
@oid.loginhandler
def login():
if g.user is not None and g.user.is_authenticated():
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
# login and validate the user...
session['remember_me'] = form.remember_me.data
return oid.try_login(form.openid.data, ask_for=['nickname', 'email'])
return render_template("login.html", title='Sign In', form=form, providers=app.config['OPENID_PROVIDERS'])
@oid.after_login
def after_login(resp):
if resp.email is None or resp.email == "":
flash('Invalid login. Please try again.')
return redirect(url_for('login'))
user = User.query.filter_by(email=resp.email).first()
if user is None:
nickname = resp.nickname
if nickname is None or nickname == "":
nickname = resp.email.split('@')[0]
user = User(nickname=nickname, email=resp.email, role=ROLE_USER)
db.session.add(user)
db.session.commit()
remember_me = False
if 'remember_me' in session:
remember_me = session['remember_me']
session.pop('remember_me', None)
login_user(user, remember=remember_me)
return redirect(request.args.get('next') or url_for('index'))
@app.route("/settings")
@login_required
def settings():
pass
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for('index'))
| Python |
# -*- coding: utf-8 -*-
__author__ = 'gongqf'
from gis import app
app.run(host='0.0.0.0',port=5001,debug=True) | Python |
# -*- coding: utf-8 -*-
__author__ = 'gongqf'
from flask.ext.wtf import Form
from wtforms import TextField, BooleanField
from wtforms.validators import Required
class LoginForm(Form):
openid = TextField('openid', validators = [Required()])
remember_me = BooleanField('remember_me', default = False) | Python |
# -*- coding: utf-8 -*-
from docx import Document
from docx.shared import Inches, Cm
document = Document()
sections=document.sections
print len(sections)
for section in sections:
print section.start_type
table = document.add_table(rows=4, cols=2)
hdr_cells = table.columns[0].cells
hdr_cells[0].text = u'光缆编码'
hdr_cells[1].text = u'光缆名称'
hdr_cells[2].text = u'光缆规格'
hdr_cells[3].text = u'施工日期'
document.add_picture('386.png', width=Cm(2.65))
section=sections[0]
print section.left_margin, section.right_margin
print section.top_margin, section.bottom_margin
print section.gutter
print section.orientation, section.page_width, section.page_height
section.page_width=Cm(8.56)
section.page_height=Cm(5.4)
section.left_margin=Cm(0.3)
section.right_margin=Cm(0.3)
section.top_margin=Cm(0.3)
section.bottom_margin=Cm(0.3)
# document.add_page_break()
document.save('386.docx')
| Python |
# This file is part of flask_tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from functools import wraps
from flask import request, current_app
from werkzeug.routing import BaseConverter
from trytond.version import VERSION as trytond_version
trytond_version = tuple(map(int, trytond_version.split('.')))
try:
from trytond.config import config
except ImportError:
from trytond.config import CONFIG as config
from trytond.pool import Pool
from trytond.transaction import Transaction
from trytond.cache import Cache
from trytond import backend
__version__ = '0.4'
__all__ = ['Tryton', 'tryton_transaction']
class Tryton(object):
"Control the Tryton integration to one or more Flask applications."
def __init__(self, app=None):
self.context_callback = None
if app is not None:
self.init_app(app)
def init_app(self, app):
"Initialize an application for the use with this Tryton setup."
database = app.config.setdefault('TRYTON_DATABASE', None)
user = app.config.setdefault('TRYTON_USER', 0)
configfile = app.config.setdefault('TRYTON_CONFIG', None)
config.update_etc(configfile)
# 3.0 compatibility
if hasattr(config, 'set_timezone'):
config.set_timezone()
self.pool = Pool(database)
with Transaction().start(database, user, readonly=True):
self.pool.init()
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['Tryton'] = self
app.url_map.converters['record'] = RecordConverter
app.url_map.converters['records'] = RecordsConverter
def default_context(self, callback):
"Set the callback for the default transaction context"
self.context_callback = callback
return callback
def _readonly(self):
return not (request
and request.method in ('PUT', 'POST', 'DELETE', 'PATCH'))
@staticmethod
def transaction(readonly=None, user=None, context=None):
"""Decorator to run inside a Tryton transaction.
The decorated method could be run multiple times in case of
database operational error.
If readonly is None then the transaction will be readonly except for
PUT, POST, DELETE and PATCH request methods.
If user is None then TRYTON_USER will be used.
readonly, user and context can also be callable.
"""
DatabaseOperationalError = backend.get('DatabaseOperationalError')
def get_value(value):
return value() if callable(value) else value
def instanciate(value):
if isinstance(value, _BaseProxy):
return value()
return value
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
tryton = current_app.extensions['Tryton']
database = current_app.config['TRYTON_DATABASE']
if trytond_version >= (3, 3):
with Transaction().start(database, 0):
Cache.clean(database)
else:
Cache.clean(database)
if user is None:
transaction_user = get_value(
int(current_app.config['TRYTON_USER']))
else:
transaction_user = get_value(user)
if readonly is None:
is_readonly = get_value(tryton._readonly)
else:
is_readonly = get_value(readonly)
transaction_context = {}
if tryton.context_callback or context:
with Transaction().start(database, transaction_user,
readonly=True):
if tryton.context_callback:
transaction_context = tryton.context_callback()
transaction_context.update(get_value(context) or {})
if trytond_version >= (3, 3):
retry = config.getint('database', 'retry')
else:
retry = int(config['retry'])
for count in range(retry, -1, -1):
with Transaction().start(database, transaction_user,
readonly=is_readonly,
context=transaction_context) as transaction:
cursor = transaction.cursor
try:
result = func(*map(instanciate, args),
**dict((n, instanciate(v))
for n, v in kwargs.iteritems()))
if not is_readonly:
cursor.commit()
except DatabaseOperationalError:
cursor.rollback()
if count and not is_readonly:
continue
raise
except Exception:
cursor.rollback()
raise
if trytond_version >= (3, 3):
Cache.resets(database)
if trytond_version < (3, 3):
Cache.resets(database)
return result
return wrapper
return decorator
tryton_transaction = Tryton.transaction
class _BaseProxy(object):
pass
class _RecordsProxy(_BaseProxy):
def __init__(self, model, ids):
self.model = model
self.ids = ids
def __iter__(self):
return iter(self.ids)
def __call__(self):
tryton = current_app.extensions['Tryton']
Model = tryton.pool.get(self.model)
return Model.browse(self.ids)
class _RecordProxy(_RecordsProxy):
def __init__(self, model, id):
super(_RecordProxy, self).__init__(model, [id])
def __int__(self):
return self.ids[0]
def __call__(self):
return super(_RecordProxy, self).__call__()[0]
class RecordConverter(BaseConverter):
"""This converter accepts record id of model::
Rule('/page/<record("res.user"):user>')"""
regex = r'\d+'
def __init__(self, map, model):
super(RecordConverter, self).__init__(map)
self.model = model
def to_python(self, value):
return _RecordProxy(self.model, int(value))
def to_url(self, value):
return str(int(value))
class RecordsConverter(BaseConverter):
"""This converter accepts record ids of model::
Rule('/page/<records("res.user"):users>')"""
regex = r'\d+(,\d+)*'
def __init__(self, map, model):
super(RecordsConverter, self).__init__(map)
self.model = model
def to_python(self, value):
return _RecordsProxy(self.model, map(int, value.split(',')))
def to_url(self, value):
return ','.join(map(int, value))
| Python |
# This file is part of flask_tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='flask_tryton',
version='0.4',
author='B2CK',
author_email='info@b2ck.com',
url='http://code.google.com/p/flask-tryton/',
description='Adds Tryton support to Flask application',
long_description=read('README'),
py_modules=['flask_tryton'],
zip_safe=False,
platforms='any',
keywords='flask tryton web',
classifiers=[
'Environment :: Web Environment',
'Framework :: Tryton',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
license='GPL-3',
install_requires=[
'Flask>=0.8',
'Werkzeug',
'trytond>=3.0',
],
)
| Python |
#!/usr/bin/env python
#
# Copyright 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.
#
# Alternatively, this software may be distributed under the terms of the
# GNU General Public License ("GPL") version 2 as published by the Free
# Software Foundation.
"""
This module provides basic encode and decode functionality to the flashrom
memory map (FMAP) structure.
Usage:
(decode)
obj = fmap_decode(blob)
print obj
(encode)
blob = fmap_encode(obj)
open('output.bin', 'w').write(blob)
The object returned by fmap_decode is a dictionary with names defined in
fmap.h. A special property 'FLAGS' is provided as a readable and read-only
tuple of decoded area flags.
"""
import struct
import sys
# constants imported from lib/fmap.h
FMAP_SIGNATURE = "__FMAP__"
FMAP_VER_MAJOR = 1
FMAP_VER_MINOR = 0
FMAP_STRLEN = 32
FMAP_FLAGS = {
'FMAP_AREA_STATIC': 1 << 0,
'FMAP_AREA_COMPRESSED': 1 << 1,
}
FMAP_HEADER_NAMES = (
'signature',
'ver_major',
'ver_minor',
'base',
'size',
'name',
'nareas',
)
FMAP_AREA_NAMES = (
'offset',
'size',
'name',
'flags',
)
# format string
FMAP_HEADER_FORMAT = "<8sBBQI%dsH" % (FMAP_STRLEN)
FMAP_AREA_FORMAT = "<II%dsH" % (FMAP_STRLEN)
def _fmap_decode_header(blob, offset):
""" (internal) Decodes a FMAP header from blob by offset"""
header = {}
for (name, value) in zip(FMAP_HEADER_NAMES,
struct.unpack_from(FMAP_HEADER_FORMAT,
blob,
offset)):
header[name] = value
if header['signature'] != FMAP_SIGNATURE:
raise struct.error('Invalid signature')
if header['ver_major'] != FMAP_VER_MAJOR or \
header['ver_minor'] != FMAP_VER_MINOR:
raise struct.error('Incompatible version')
# convert null-terminated names
header['name'] = header['name'].strip(chr(0))
return (header, struct.calcsize(FMAP_HEADER_FORMAT))
def _fmap_decode_area(blob, offset):
""" (internal) Decodes a FMAP area record from blob by offset """
area = {}
for (name, value) in zip(FMAP_AREA_NAMES,
struct.unpack_from(FMAP_AREA_FORMAT, blob, offset)):
area[name] = value
# convert null-terminated names
area['name'] = area['name'].strip(chr(0))
# add a (readonly) readable FLAGS
area['FLAGS'] = _fmap_decode_area_flags(area['flags'])
return (area, struct.calcsize(FMAP_AREA_FORMAT))
def _fmap_decode_area_flags(area_flags):
""" (internal) Decodes a FMAP flags property """
return tuple([name for name in FMAP_FLAGS if area_flags & FMAP_FLAGS[name]])
def fmap_decode(blob, offset=None):
""" Decodes a blob to FMAP dictionary object.
Arguments:
blob: a binary data containing FMAP structure.
offset: starting offset of FMAP. When omitted, fmap_decode will search in
the blob.
"""
fmap = {}
if offset == None:
# try search magic in fmap
offset = blob.find(FMAP_SIGNATURE)
(fmap, size) = _fmap_decode_header(blob, offset)
fmap['areas'] = []
offset = offset + size
for i in range(fmap['nareas']):
(area, size) = _fmap_decode_area(blob, offset)
offset = offset + size
fmap['areas'].append(area)
return fmap
def _fmap_encode_header(obj):
""" (internal) Encodes a FMAP header """
values = [obj[name] for name in FMAP_HEADER_NAMES]
return struct.pack(FMAP_HEADER_FORMAT, *values)
def _fmap_encode_area(obj):
""" (internal) Encodes a FMAP area entry """
values = [obj[name] for name in FMAP_AREA_NAMES]
return struct.pack(FMAP_AREA_FORMAT, *values)
def fmap_encode(obj):
""" Encodes a FMAP dictionary object to blob.
Arguments
obj: a FMAP dictionary object.
"""
# fix up values
obj['nareas'] = len(obj['areas'])
# TODO(hungte) re-assign signature / version?
blob = _fmap_encode_header(obj)
for area in obj['areas']:
blob = blob + _fmap_encode_area(area)
return blob
if __name__ == '__main__':
# main entry, do a unit test
blob = open('bin/example.bin').read()
obj = fmap_decode(blob)
print obj
blob2 = fmap_encode(obj)
obj2 = fmap_decode(blob2)
print obj2
assert obj == obj2
| Python |
"""
Flash Selenium - Python Client
Date: 30 March 2008
Paulo Caroli, Sachin Sudheendra
http://code.google.com/p/flash-selenium
-----------------------------------------
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.
"""
class BrowserConstants (object):
def firefox2(self):
return "Firefox/2."
def firefox3(self):
return "Firefox/3."
def msie(self):
return "MSIE"; | Python |
"""
Copyright 2006 ThoughtWorks, 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.
"""
__docformat__ = "restructuredtext en"
# This file has been automatically generated via XSL
import httplib
import urllib
import re
class selenium:
"""
Defines an object that runs Selenium commands.
Element Locators
~~~~~~~~~~~~~~~~
Element Locators tell Selenium which HTML element a command refers to.
The format of a locator is:
\ *locatorType*\ **=**\ \ *argument*
We support the following strategies for locating elements:
* \ **identifier**\ =\ *id*:
Select the element with the specified @id attribute. If no match is
found, select the first element whose @name attribute is \ *id*.
(This is normally the default; see below.)
* \ **id**\ =\ *id*:
Select the element with the specified @id attribute.
* \ **name**\ =\ *name*:
Select the first element with the specified @name attribute.
* username
* name=username
The name may optionally be followed by one or more \ *element-filters*, separated from the name by whitespace. If the \ *filterType* is not specified, \ **value**\ is assumed.
* name=flavour value=chocolate
* \ **dom**\ =\ *javascriptExpression*:
Find an element by evaluating the specified string. This allows you to traverse the HTML Document Object
Model using JavaScript. Note that you must not return a value in this string; simply make it the last expression in the block.
* dom=document.forms['myForm'].myDropdown
* dom=document.images[56]
* dom=function foo() { return document.links[1]; }; foo();
* \ **xpath**\ =\ *xpathExpression*:
Locate an element using an XPath expression.
* xpath=//img[@alt='The image alt text']
* xpath=//table[@id='table1']//tr[4]/td[2]
* xpath=//a[contains(@href,'#id1')]
* xpath=//a[contains(@href,'#id1')]/@class
* xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
* xpath=//input[@name='name2' and @value='yes']
* xpath=//\*[text()="right"]
* \ **link**\ =\ *textPattern*:
Select the link (anchor) element which contains text matching the
specified \ *pattern*.
* link=The link text
* \ **css**\ =\ *cssSelectorSyntax*:
Select the element using css selectors. Please refer to CSS2 selectors, CSS3 selectors for more information. You can also check the TestCssLocators test in the selenium test suite for an example of usage, which is included in the downloaded selenium core package.
* css=a[href="#id3"]
* css=span#firstChild + span
Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after).
* \ **ui**\ =\ *uiSpecifierString*:
Locate an element by resolving the UI specifier string to another locator, and evaluating it. See the Selenium UI-Element Reference for more details.
* ui=loginPages::loginButton()
* ui=settingsPages::toggle(label=Hide Email)
* ui=forumPages::postBody(index=2)//a[2]
Without an explicit locator prefix, Selenium uses the following default
strategies:
* \ **dom**\ , for locators starting with "document."
* \ **xpath**\ , for locators starting with "//"
* \ **identifier**\ , otherwise
Element Filters
~~~~~~~~~~~~~~~
Element filters can be used with a locator to refine a list of candidate elements. They are currently used only in the 'name' element-locator.
Filters look much like locators, ie.
\ *filterType*\ **=**\ \ *argument*
Supported element-filters are:
\ **value=**\ \ *valuePattern*
Matches elements based on their values. This is particularly useful for refining a list of similarly-named toggle-buttons.
\ **index=**\ \ *index*
Selects a single element based on its position in the list (offset from zero).
String-match Patterns
~~~~~~~~~~~~~~~~~~~~~
Various Pattern syntaxes are available for matching string values:
* \ **glob:**\ \ *pattern*:
Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a
kind of limited regular-expression syntax typically used in command-line
shells. In a glob pattern, "\*" represents any sequence of characters, and "?"
represents any single character. Glob patterns match against the entire
string.
* \ **regexp:**\ \ *regexp*:
Match a string using a regular-expression. The full power of JavaScript
regular-expressions is available.
* \ **regexpi:**\ \ *regexpi*:
Match a string using a case-insensitive regular-expression.
* \ **exact:**\ \ *string*:
Match a string exactly, verbatim, without any of that fancy wildcard
stuff.
If no pattern prefix is specified, Selenium assumes that it's a "glob"
pattern.
For commands that return multiple values (such as verifySelectOptions),
the string being matched is a comma-separated list of the return values,
where both commas and backslashes in the values are backslash-escaped.
When providing a pattern, the optional matching syntax (i.e. glob,
regexp, etc.) is specified once, as usual, at the beginning of the
pattern.
"""
### This part is hard-coded in the XSL
def __init__(self, host, port, browserStartCommand, browserURL):
self.host = host
self.port = port
self.browserStartCommand = browserStartCommand
self.browserURL = browserURL
self.sessionId = None
self.extensionJs = ""
def setExtensionJs(self, extensionJs):
self.extensionJs = extensionJs
def start(self):
result = self.get_string("getNewBrowserSession", [self.browserStartCommand, self.browserURL, self.extensionJs])
try:
self.sessionId = result
except ValueError:
raise Exception, result
def stop(self):
self.do_command("testComplete", [])
self.sessionId = None
def do_command(self, verb, args):
conn = httplib.HTTPConnection(self.host, self.port)
body = u'cmd=' + urllib.quote_plus(unicode(verb).encode('utf-8'))
for i in range(len(args)):
body += '&' + unicode(i+1) + '=' + urllib.quote_plus(unicode(args[i]).encode('utf-8'))
if (None != self.sessionId):
body += "&sessionId=" + unicode(self.sessionId)
headers = {"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"}
conn.request("POST", "/selenium-server/driver/", body, headers)
response = conn.getresponse()
#print response.status, response.reason
data = unicode(response.read(), "UTF-8")
result = response.reason
#print "Selenium Result: " + repr(data) + "\n\n"
if (not data.startswith('OK')):
raise Exception, data
return data
def get_string(self, verb, args):
result = self.do_command(verb, args)
return result[3:]
def get_string_array(self, verb, args):
csv = self.get_string(verb, args)
token = ""
tokens = []
escape = False
for i in range(len(csv)):
letter = csv[i]
if (escape):
token = token + letter
escape = False
continue
if (letter == '\\'):
escape = True
elif (letter == ','):
tokens.append(token)
token = ""
else:
token = token + letter
tokens.append(token)
return tokens
def get_number(self, verb, args):
# Is there something I need to do here?
return self.get_string(verb, args)
def get_number_array(self, verb, args):
# Is there something I need to do here?
return self.get_string_array(verb, args)
def get_boolean(self, verb, args):
boolstr = self.get_string(verb, args)
if ("true" == boolstr):
return True
if ("false" == boolstr):
return False
raise ValueError, "result is neither 'true' nor 'false': " + boolstr
def get_boolean_array(self, verb, args):
boolarr = self.get_string_array(verb, args)
for i in range(len(boolarr)):
if ("true" == boolstr):
boolarr[i] = True
continue
if ("false" == boolstr):
boolarr[i] = False
continue
raise ValueError, "result is neither 'true' nor 'false': " + boolarr[i]
return boolarr
### From here on, everything's auto-generated from XML
def click(self,locator):
"""
Clicks on a link, button, checkbox or radio button. If the click action
causes a new page to load (like a link usually does), call
waitForPageToLoad.
'locator' is an element locator
"""
self.do_command("click", [locator,])
def double_click(self,locator):
"""
Double clicks on a link, button, checkbox or radio button. If the double click action
causes a new page to load (like a link usually does), call
waitForPageToLoad.
'locator' is an element locator
"""
self.do_command("doubleClick", [locator,])
def context_menu(self,locator):
"""
Simulates opening the context menu for the specified element (as might happen if the user "right-clicked" on the element).
'locator' is an element locator
"""
self.do_command("contextMenu", [locator,])
def click_at(self,locator,coordString):
"""
Clicks on a link, button, checkbox or radio button. If the click action
causes a new page to load (like a link usually does), call
waitForPageToLoad.
'locator' is an element locator
'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
"""
self.do_command("clickAt", [locator,coordString,])
def double_click_at(self,locator,coordString):
"""
Doubleclicks on a link, button, checkbox or radio button. If the action
causes a new page to load (like a link usually does), call
waitForPageToLoad.
'locator' is an element locator
'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
"""
self.do_command("doubleClickAt", [locator,coordString,])
def context_menu_at(self,locator,coordString):
"""
Simulates opening the context menu for the specified element (as might happen if the user "right-clicked" on the element).
'locator' is an element locator
'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
"""
self.do_command("contextMenuAt", [locator,coordString,])
def fire_event(self,locator,eventName):
"""
Explicitly simulate an event, to trigger the corresponding "on\ *event*"
handler.
'locator' is an element locator
'eventName' is the event name, e.g. "focus" or "blur"
"""
self.do_command("fireEvent", [locator,eventName,])
def focus(self,locator):
"""
Move the focus to the specified element; for example, if the element is an input field, move the cursor to that field.
'locator' is an element locator
"""
self.do_command("focus", [locator,])
def key_press(self,locator,keySequence):
"""
Simulates a user pressing and releasing a key.
'locator' is an element locator
'keySequence' is Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119".
"""
self.do_command("keyPress", [locator,keySequence,])
def shift_key_down(self):
"""
Press the shift key and hold it down until doShiftUp() is called or a new page is loaded.
"""
self.do_command("shiftKeyDown", [])
def shift_key_up(self):
"""
Release the shift key.
"""
self.do_command("shiftKeyUp", [])
def meta_key_down(self):
"""
Press the meta key and hold it down until doMetaUp() is called or a new page is loaded.
"""
self.do_command("metaKeyDown", [])
def meta_key_up(self):
"""
Release the meta key.
"""
self.do_command("metaKeyUp", [])
def alt_key_down(self):
"""
Press the alt key and hold it down until doAltUp() is called or a new page is loaded.
"""
self.do_command("altKeyDown", [])
def alt_key_up(self):
"""
Release the alt key.
"""
self.do_command("altKeyUp", [])
def control_key_down(self):
"""
Press the control key and hold it down until doControlUp() is called or a new page is loaded.
"""
self.do_command("controlKeyDown", [])
def control_key_up(self):
"""
Release the control key.
"""
self.do_command("controlKeyUp", [])
def key_down(self,locator,keySequence):
"""
Simulates a user pressing a key (without releasing it yet).
'locator' is an element locator
'keySequence' is Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119".
"""
self.do_command("keyDown", [locator,keySequence,])
def key_up(self,locator,keySequence):
"""
Simulates a user releasing a key.
'locator' is an element locator
'keySequence' is Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119".
"""
self.do_command("keyUp", [locator,keySequence,])
def mouse_over(self,locator):
"""
Simulates a user hovering a mouse over the specified element.
'locator' is an element locator
"""
self.do_command("mouseOver", [locator,])
def mouse_out(self,locator):
"""
Simulates a user moving the mouse pointer away from the specified element.
'locator' is an element locator
"""
self.do_command("mouseOut", [locator,])
def mouse_down(self,locator):
"""
Simulates a user pressing the left mouse button (without releasing it yet) on
the specified element.
'locator' is an element locator
"""
self.do_command("mouseDown", [locator,])
def mouse_down_right(self,locator):
"""
Simulates a user pressing the right mouse button (without releasing it yet) on
the specified element.
'locator' is an element locator
"""
self.do_command("mouseDownRight", [locator,])
def mouse_down_at(self,locator,coordString):
"""
Simulates a user pressing the left mouse button (without releasing it yet) at
the specified location.
'locator' is an element locator
'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
"""
self.do_command("mouseDownAt", [locator,coordString,])
def mouse_down_right_at(self,locator,coordString):
"""
Simulates a user pressing the right mouse button (without releasing it yet) at
the specified location.
'locator' is an element locator
'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
"""
self.do_command("mouseDownRightAt", [locator,coordString,])
def mouse_up(self,locator):
"""
Simulates the event that occurs when the user releases the mouse button (i.e., stops
holding the button down) on the specified element.
'locator' is an element locator
"""
self.do_command("mouseUp", [locator,])
def mouse_up_right(self,locator):
"""
Simulates the event that occurs when the user releases the right mouse button (i.e., stops
holding the button down) on the specified element.
'locator' is an element locator
"""
self.do_command("mouseUpRight", [locator,])
def mouse_up_at(self,locator,coordString):
"""
Simulates the event that occurs when the user releases the mouse button (i.e., stops
holding the button down) at the specified location.
'locator' is an element locator
'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
"""
self.do_command("mouseUpAt", [locator,coordString,])
def mouse_up_right_at(self,locator,coordString):
"""
Simulates the event that occurs when the user releases the right mouse button (i.e., stops
holding the button down) at the specified location.
'locator' is an element locator
'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
"""
self.do_command("mouseUpRightAt", [locator,coordString,])
def mouse_move(self,locator):
"""
Simulates a user pressing the mouse button (without releasing it yet) on
the specified element.
'locator' is an element locator
"""
self.do_command("mouseMove", [locator,])
def mouse_move_at(self,locator,coordString):
"""
Simulates a user pressing the mouse button (without releasing it yet) on
the specified element.
'locator' is an element locator
'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
"""
self.do_command("mouseMoveAt", [locator,coordString,])
def type(self,locator,value):
"""
Sets the value of an input field, as though you typed it in.
Can also be used to set the value of combo boxes, check boxes, etc. In these cases,
value should be the value of the option selected, not the visible text.
'locator' is an element locator
'value' is the value to type
"""
self.do_command("type", [locator,value,])
def type_keys(self,locator,value):
"""
Simulates keystroke events on the specified element, as though you typed the value key-by-key.
This is a convenience method for calling keyDown, keyUp, keyPress for every character in the specified string;
this is useful for dynamic UI widgets (like auto-completing combo boxes) that require explicit key events.
Unlike the simple "type" command, which forces the specified value into the page directly, this command
may or may not have any visible effect, even in cases where typing keys would normally have a visible effect.
For example, if you use "typeKeys" on a form element, you may or may not see the results of what you typed in
the field.
In some cases, you may need to use the simple "type" command to set the value of the field and then the "typeKeys" command to
send the keystroke events corresponding to what you just typed.
'locator' is an element locator
'value' is the value to type
"""
self.do_command("typeKeys", [locator,value,])
def set_speed(self,value):
"""
Set execution speed (i.e., set the millisecond length of a delay which will follow each selenium operation). By default, there is no such delay, i.e.,
the delay is 0 milliseconds.
'value' is the number of milliseconds to pause after operation
"""
self.do_command("setSpeed", [value,])
def get_speed(self):
"""
Get execution speed (i.e., get the millisecond length of the delay following each selenium operation). By default, there is no such delay, i.e.,
the delay is 0 milliseconds.
See also setSpeed.
"""
return self.get_string("getSpeed", [])
def check(self,locator):
"""
Check a toggle-button (checkbox/radio)
'locator' is an element locator
"""
self.do_command("check", [locator,])
def uncheck(self,locator):
"""
Uncheck a toggle-button (checkbox/radio)
'locator' is an element locator
"""
self.do_command("uncheck", [locator,])
def select(self,selectLocator,optionLocator):
"""
Select an option from a drop-down using an option locator.
Option locators provide different ways of specifying options of an HTML
Select element (e.g. for selecting a specific option, or for asserting
that the selected option satisfies a specification). There are several
forms of Select Option Locator.
* \ **label**\ =\ *labelPattern*:
matches options based on their labels, i.e. the visible text. (This
is the default.)
* label=regexp:^[Oo]ther
* \ **value**\ =\ *valuePattern*:
matches options based on their values.
* value=other
* \ **id**\ =\ *id*:
matches options based on their ids.
* id=option1
* \ **index**\ =\ *index*:
matches an option based on its index (offset from zero).
* index=2
If no option locator prefix is provided, the default behaviour is to match on \ **label**\ .
'selectLocator' is an element locator identifying a drop-down menu
'optionLocator' is an option locator (a label by default)
"""
self.do_command("select", [selectLocator,optionLocator,])
def add_selection(self,locator,optionLocator):
"""
Add a selection to the set of selected options in a multi-select element using an option locator.
@see #doSelect for details of option locators
'locator' is an element locator identifying a multi-select box
'optionLocator' is an option locator (a label by default)
"""
self.do_command("addSelection", [locator,optionLocator,])
def remove_selection(self,locator,optionLocator):
"""
Remove a selection from the set of selected options in a multi-select element using an option locator.
@see #doSelect for details of option locators
'locator' is an element locator identifying a multi-select box
'optionLocator' is an option locator (a label by default)
"""
self.do_command("removeSelection", [locator,optionLocator,])
def remove_all_selections(self,locator):
"""
Unselects all of the selected options in a multi-select element.
'locator' is an element locator identifying a multi-select box
"""
self.do_command("removeAllSelections", [locator,])
def submit(self,formLocator):
"""
Submit the specified form. This is particularly useful for forms without
submit buttons, e.g. single-input "Search" forms.
'formLocator' is an element locator for the form you want to submit
"""
self.do_command("submit", [formLocator,])
def open(self,url):
"""
Opens an URL in the test frame. This accepts both relative and absolute
URLs.
The "open" command waits for the page to load before proceeding,
ie. the "AndWait" suffix is implicit.
\ *Note*: The URL must be on the same domain as the runner HTML
due to security restrictions in the browser (Same Origin Policy). If you
need to open an URL on another domain, use the Selenium Server to start a
new browser session on that domain.
'url' is the URL to open; may be relative or absolute
"""
self.do_command("open", [url,])
def open_window(self,url,windowID):
"""
Opens a popup window (if a window with that ID isn't already open).
After opening the window, you'll need to select it using the selectWindow
command.
This command can also be a useful workaround for bug SEL-339. In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before the "onLoad" event, for example).
In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using
an empty (blank) url, like this: openWindow("", "myFunnyWindow").
'url' is the URL to open, which can be blank
'windowID' is the JavaScript window ID of the window to select
"""
self.do_command("openWindow", [url,windowID,])
def select_window(self,windowID):
"""
Selects a popup window using a window locator; once a popup window has been selected, all
commands go to that window. To select the main window again, use null
as the target.
Window locators provide different ways of specifying the window object:
by title, by internal JavaScript "name," or by JavaScript variable.
* \ **title**\ =\ *My Special Window*:
Finds the window using the text that appears in the title bar. Be careful;
two windows can share the same title. If that happens, this locator will
just pick one.
* \ **name**\ =\ *myWindow*:
Finds the window using its internal JavaScript "name" property. This is the second
parameter "windowName" passed to the JavaScript method window.open(url, windowName, windowFeatures, replaceFlag)
(which Selenium intercepts).
* \ **var**\ =\ *variableName*:
Some pop-up windows are unnamed (anonymous), but are associated with a JavaScript variable name in the current
application window, e.g. "window.foo = window.open(url);". In those cases, you can open the window using
"var=foo".
If no window locator prefix is provided, we'll try to guess what you mean like this:
1.) if windowID is null, (or the string "null") then it is assumed the user is referring to the original window instantiated by the browser).
2.) if the value of the "windowID" parameter is a JavaScript variable name in the current application window, then it is assumed
that this variable contains the return value from a call to the JavaScript window.open() method.
3.) Otherwise, selenium looks in a hash it maintains that maps string names to window "names".
4.) If \ *that* fails, we'll try looping over all of the known windows to try to find the appropriate "title".
Since "title" is not necessarily unique, this may have unexpected behavior.
If you're having trouble figuring out the name of a window that you want to manipulate, look at the Selenium log messages
which identify the names of windows created via window.open (and therefore intercepted by Selenium). You will see messages
like the following for each window as it is opened:
``debug: window.open call intercepted; window ID (which you can use with selectWindow()) is "myNewWindow"``
In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before the "onLoad" event, for example).
(This is bug SEL-339.) In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using
an empty (blank) url, like this: openWindow("", "myFunnyWindow").
'windowID' is the JavaScript window ID of the window to select
"""
self.do_command("selectWindow", [windowID,])
def select_pop_up(self,windowID):
"""
Simplifies the process of selecting a popup window (and does not offer
functionality beyond what ``selectWindow()`` already provides).
* If ``windowID`` is either not specified, or specified as
"null", the first non-top window is selected. The top window is the one
that would be selected by ``selectWindow()`` without providing a
``windowID`` . This should not be used when more than one popup
window is in play.
* Otherwise, the window will be looked up considering
``windowID`` as the following in order: 1) the "name" of the
window, as specified to ``window.open()``; 2) a javascript
variable which is a reference to a window; and 3) the title of the
window. This is the same ordered lookup performed by
``selectWindow`` .
'windowID' is an identifier for the popup window, which can take on a number of different meanings
"""
self.do_command("selectPopUp", [windowID,])
def deselect_pop_up(self):
"""
Selects the main window. Functionally equivalent to using
``selectWindow()`` and specifying no value for
``windowID``.
"""
self.do_command("deselectPopUp", [])
def select_frame(self,locator):
"""
Selects a frame within the current window. (You may invoke this command
multiple times to select nested frames.) To select the parent frame, use
"relative=parent" as a locator; to select the top frame, use "relative=top".
You can also select a frame by its 0-based index number; select the first frame with
"index=0", or the third frame with "index=2".
You may also use a DOM expression to identify the frame you want directly,
like this: ``dom=frames["main"].frames["subframe"]``
'locator' is an element locator identifying a frame or iframe
"""
self.do_command("selectFrame", [locator,])
def get_whether_this_frame_match_frame_expression(self,currentFrameString,target):
"""
Determine whether current/locator identify the frame containing this running code.
This is useful in proxy injection mode, where this code runs in every
browser frame and window, and sometimes the selenium server needs to identify
the "current" frame. In this case, when the test calls selectFrame, this
routine is called for each frame to figure out which one has been selected.
The selected frame will return true, while all others will return false.
'currentFrameString' is starting frame
'target' is new frame (which might be relative to the current one)
"""
return self.get_boolean("getWhetherThisFrameMatchFrameExpression", [currentFrameString,target,])
def get_whether_this_window_match_window_expression(self,currentWindowString,target):
"""
Determine whether currentWindowString plus target identify the window containing this running code.
This is useful in proxy injection mode, where this code runs in every
browser frame and window, and sometimes the selenium server needs to identify
the "current" window. In this case, when the test calls selectWindow, this
routine is called for each window to figure out which one has been selected.
The selected window will return true, while all others will return false.
'currentWindowString' is starting window
'target' is new window (which might be relative to the current one, e.g., "_parent")
"""
return self.get_boolean("getWhetherThisWindowMatchWindowExpression", [currentWindowString,target,])
def wait_for_pop_up(self,windowID,timeout):
"""
Waits for a popup window to appear and load up.
'windowID' is the JavaScript window "name" of the window that will appear (not the text of the title bar) If unspecified, or specified as "null", this command will wait for the first non-top window to appear (don't rely on this if you are working with multiple popups simultaneously).
'timeout' is a timeout in milliseconds, after which the action will return with an error. If this value is not specified, the default Selenium timeout will be used. See the setTimeout() command.
"""
self.do_command("waitForPopUp", [windowID,timeout,])
def choose_cancel_on_next_confirmation(self):
"""
By default, Selenium's overridden window.confirm() function will
return true, as if the user had manually clicked OK; after running
this command, the next call to confirm() will return false, as if
the user had clicked Cancel. Selenium will then resume using the
default behavior for future confirmations, automatically returning
true (OK) unless/until you explicitly call this command for each
confirmation.
Take note - every time a confirmation comes up, you must
consume it with a corresponding getConfirmation, or else
the next selenium operation will fail.
"""
self.do_command("chooseCancelOnNextConfirmation", [])
def choose_ok_on_next_confirmation(self):
"""
Undo the effect of calling chooseCancelOnNextConfirmation. Note
that Selenium's overridden window.confirm() function will normally automatically
return true, as if the user had manually clicked OK, so you shouldn't
need to use this command unless for some reason you need to change
your mind prior to the next confirmation. After any confirmation, Selenium will resume using the
default behavior for future confirmations, automatically returning
true (OK) unless/until you explicitly call chooseCancelOnNextConfirmation for each
confirmation.
Take note - every time a confirmation comes up, you must
consume it with a corresponding getConfirmation, or else
the next selenium operation will fail.
"""
self.do_command("chooseOkOnNextConfirmation", [])
def answer_on_next_prompt(self,answer):
"""
Instructs Selenium to return the specified answer string in response to
the next JavaScript prompt [window.prompt()].
'answer' is the answer to give in response to the prompt pop-up
"""
self.do_command("answerOnNextPrompt", [answer,])
def go_back(self):
"""
Simulates the user clicking the "back" button on their browser.
"""
self.do_command("goBack", [])
def refresh(self):
"""
Simulates the user clicking the "Refresh" button on their browser.
"""
self.do_command("refresh", [])
def close(self):
"""
Simulates the user clicking the "close" button in the titlebar of a popup
window or tab.
"""
self.do_command("close", [])
def is_alert_present(self):
"""
Has an alert occurred?
This function never throws an exception
"""
return self.get_boolean("isAlertPresent", [])
def is_prompt_present(self):
"""
Has a prompt occurred?
This function never throws an exception
"""
return self.get_boolean("isPromptPresent", [])
def is_confirmation_present(self):
"""
Has confirm() been called?
This function never throws an exception
"""
return self.get_boolean("isConfirmationPresent", [])
def get_alert(self):
"""
Retrieves the message of a JavaScript alert generated during the previous action, or fail if there were no alerts.
Getting an alert has the same effect as manually clicking OK. If an
alert is generated but you do not consume it with getAlert, the next Selenium action
will fail.
Under Selenium, JavaScript alerts will NOT pop up a visible alert
dialog.
Selenium does NOT support JavaScript alerts that are generated in a
page's onload() event handler. In this case a visible dialog WILL be
generated and Selenium will hang until someone manually clicks OK.
"""
return self.get_string("getAlert", [])
def get_confirmation(self):
"""
Retrieves the message of a JavaScript confirmation dialog generated during
the previous action.
By default, the confirm function will return true, having the same effect
as manually clicking OK. This can be changed by prior execution of the
chooseCancelOnNextConfirmation command.
If an confirmation is generated but you do not consume it with getConfirmation,
the next Selenium action will fail.
NOTE: under Selenium, JavaScript confirmations will NOT pop up a visible
dialog.
NOTE: Selenium does NOT support JavaScript confirmations that are
generated in a page's onload() event handler. In this case a visible
dialog WILL be generated and Selenium will hang until you manually click
OK.
"""
return self.get_string("getConfirmation", [])
def get_prompt(self):
"""
Retrieves the message of a JavaScript question prompt dialog generated during
the previous action.
Successful handling of the prompt requires prior execution of the
answerOnNextPrompt command. If a prompt is generated but you
do not get/verify it, the next Selenium action will fail.
NOTE: under Selenium, JavaScript prompts will NOT pop up a visible
dialog.
NOTE: Selenium does NOT support JavaScript prompts that are generated in a
page's onload() event handler. In this case a visible dialog WILL be
generated and Selenium will hang until someone manually clicks OK.
"""
return self.get_string("getPrompt", [])
def get_location(self):
"""
Gets the absolute URL of the current page.
"""
return self.get_string("getLocation", [])
def get_title(self):
"""
Gets the title of the current page.
"""
return self.get_string("getTitle", [])
def get_body_text(self):
"""
Gets the entire text of the page.
"""
return self.get_string("getBodyText", [])
def get_value(self,locator):
"""
Gets the (whitespace-trimmed) value of an input field (or anything else with a value parameter).
For checkbox/radio elements, the value will be "on" or "off" depending on
whether the element is checked or not.
'locator' is an element locator
"""
return self.get_string("getValue", [locator,])
def get_text(self,locator):
"""
Gets the text of an element. This works for any element that contains
text. This command uses either the textContent (Mozilla-like browsers) or
the innerText (IE-like browsers) of the element, which is the rendered
text shown to the user.
'locator' is an element locator
"""
return self.get_string("getText", [locator,])
def highlight(self,locator):
"""
Briefly changes the backgroundColor of the specified element yellow. Useful for debugging.
'locator' is an element locator
"""
self.do_command("highlight", [locator,])
def get_eval(self,script):
"""
Gets the result of evaluating the specified JavaScript snippet. The snippet may
have multiple lines, but only the result of the last line will be returned.
Note that, by default, the snippet will run in the context of the "selenium"
object itself, so ``this`` will refer to the Selenium object. Use ``window`` to
refer to the window of your application, e.g. ``window.document.getElementById('foo')``
If you need to use
a locator to refer to a single element in your application page, you can
use ``this.browserbot.findElement("id=foo")`` where "id=foo" is your locator.
'script' is the JavaScript snippet to run
"""
return self.get_string("getEval", [script,])
def is_checked(self,locator):
"""
Gets whether a toggle-button (checkbox/radio) is checked. Fails if the specified element doesn't exist or isn't a toggle-button.
'locator' is an element locator pointing to a checkbox or radio button
"""
return self.get_boolean("isChecked", [locator,])
def get_table(self,tableCellAddress):
"""
Gets the text from a cell of a table. The cellAddress syntax
tableLocator.row.column, where row and column start at 0.
'tableCellAddress' is a cell address, e.g. "foo.1.4"
"""
return self.get_string("getTable", [tableCellAddress,])
def get_selected_labels(self,selectLocator):
"""
Gets all option labels (visible text) for selected options in the specified select or multi-select element.
'selectLocator' is an element locator identifying a drop-down menu
"""
return self.get_string_array("getSelectedLabels", [selectLocator,])
def get_selected_label(self,selectLocator):
"""
Gets option label (visible text) for selected option in the specified select element.
'selectLocator' is an element locator identifying a drop-down menu
"""
return self.get_string("getSelectedLabel", [selectLocator,])
def get_selected_values(self,selectLocator):
"""
Gets all option values (value attributes) for selected options in the specified select or multi-select element.
'selectLocator' is an element locator identifying a drop-down menu
"""
return self.get_string_array("getSelectedValues", [selectLocator,])
def get_selected_value(self,selectLocator):
"""
Gets option value (value attribute) for selected option in the specified select element.
'selectLocator' is an element locator identifying a drop-down menu
"""
return self.get_string("getSelectedValue", [selectLocator,])
def get_selected_indexes(self,selectLocator):
"""
Gets all option indexes (option number, starting at 0) for selected options in the specified select or multi-select element.
'selectLocator' is an element locator identifying a drop-down menu
"""
return self.get_string_array("getSelectedIndexes", [selectLocator,])
def get_selected_index(self,selectLocator):
"""
Gets option index (option number, starting at 0) for selected option in the specified select element.
'selectLocator' is an element locator identifying a drop-down menu
"""
return self.get_string("getSelectedIndex", [selectLocator,])
def get_selected_ids(self,selectLocator):
"""
Gets all option element IDs for selected options in the specified select or multi-select element.
'selectLocator' is an element locator identifying a drop-down menu
"""
return self.get_string_array("getSelectedIds", [selectLocator,])
def get_selected_id(self,selectLocator):
"""
Gets option element ID for selected option in the specified select element.
'selectLocator' is an element locator identifying a drop-down menu
"""
return self.get_string("getSelectedId", [selectLocator,])
def is_something_selected(self,selectLocator):
"""
Determines whether some option in a drop-down menu is selected.
'selectLocator' is an element locator identifying a drop-down menu
"""
return self.get_boolean("isSomethingSelected", [selectLocator,])
def get_select_options(self,selectLocator):
"""
Gets all option labels in the specified select drop-down.
'selectLocator' is an element locator identifying a drop-down menu
"""
return self.get_string_array("getSelectOptions", [selectLocator,])
def get_attribute(self,attributeLocator):
"""
Gets the value of an element attribute. The value of the attribute may
differ across browsers (this is the case for the "style" attribute, for
example).
'attributeLocator' is an element locator followed by an @ sign and then the name of the attribute, e.g. "foo@bar"
"""
return self.get_string("getAttribute", [attributeLocator,])
def is_text_present(self,pattern):
"""
Verifies that the specified text pattern appears somewhere on the rendered page shown to the user.
'pattern' is a pattern to match with the text of the page
"""
return self.get_boolean("isTextPresent", [pattern,])
def is_element_present(self,locator):
"""
Verifies that the specified element is somewhere on the page.
'locator' is an element locator
"""
return self.get_boolean("isElementPresent", [locator,])
def is_visible(self,locator):
"""
Determines if the specified element is visible. An
element can be rendered invisible by setting the CSS "visibility"
property to "hidden", or the "display" property to "none", either for the
element itself or one if its ancestors. This method will fail if
the element is not present.
'locator' is an element locator
"""
return self.get_boolean("isVisible", [locator,])
def is_editable(self,locator):
"""
Determines whether the specified input element is editable, ie hasn't been disabled.
This method will fail if the specified element isn't an input element.
'locator' is an element locator
"""
return self.get_boolean("isEditable", [locator,])
def get_all_buttons(self):
"""
Returns the IDs of all buttons on the page.
If a given button has no ID, it will appear as "" in this array.
"""
return self.get_string_array("getAllButtons", [])
def get_all_links(self):
"""
Returns the IDs of all links on the page.
If a given link has no ID, it will appear as "" in this array.
"""
return self.get_string_array("getAllLinks", [])
def get_all_fields(self):
"""
Returns the IDs of all input fields on the page.
If a given field has no ID, it will appear as "" in this array.
"""
return self.get_string_array("getAllFields", [])
def get_attribute_from_all_windows(self,attributeName):
"""
Returns every instance of some attribute from all known windows.
'attributeName' is name of an attribute on the windows
"""
return self.get_string_array("getAttributeFromAllWindows", [attributeName,])
def dragdrop(self,locator,movementsString):
"""
deprecated - use dragAndDrop instead
'locator' is an element locator
'movementsString' is offset in pixels from the current location to which the element should be moved, e.g., "+70,-300"
"""
self.do_command("dragdrop", [locator,movementsString,])
def set_mouse_speed(self,pixels):
"""
Configure the number of pixels between "mousemove" events during dragAndDrop commands (default=10).
Setting this value to 0 means that we'll send a "mousemove" event to every single pixel
in between the start location and the end location; that can be very slow, and may
cause some browsers to force the JavaScript to timeout.
If the mouse speed is greater than the distance between the two dragged objects, we'll
just send one "mousemove" at the start location and then one final one at the end location.
'pixels' is the number of pixels between "mousemove" events
"""
self.do_command("setMouseSpeed", [pixels,])
def get_mouse_speed(self):
"""
Returns the number of pixels between "mousemove" events during dragAndDrop commands (default=10).
"""
return self.get_number("getMouseSpeed", [])
def drag_and_drop(self,locator,movementsString):
"""
Drags an element a certain distance and then drops it
'locator' is an element locator
'movementsString' is offset in pixels from the current location to which the element should be moved, e.g., "+70,-300"
"""
self.do_command("dragAndDrop", [locator,movementsString,])
def drag_and_drop_to_object(self,locatorOfObjectToBeDragged,locatorOfDragDestinationObject):
"""
Drags an element and drops it on another element
'locatorOfObjectToBeDragged' is an element to be dragged
'locatorOfDragDestinationObject' is an element whose location (i.e., whose center-most pixel) will be the point where locatorOfObjectToBeDragged is dropped
"""
self.do_command("dragAndDropToObject", [locatorOfObjectToBeDragged,locatorOfDragDestinationObject,])
def window_focus(self):
"""
Gives focus to the currently selected window
"""
self.do_command("windowFocus", [])
def window_maximize(self):
"""
Resize currently selected window to take up the entire screen
"""
self.do_command("windowMaximize", [])
def get_all_window_ids(self):
"""
Returns the IDs of all windows that the browser knows about.
"""
return self.get_string_array("getAllWindowIds", [])
def get_all_window_names(self):
"""
Returns the names of all windows that the browser knows about.
"""
return self.get_string_array("getAllWindowNames", [])
def get_all_window_titles(self):
"""
Returns the titles of all windows that the browser knows about.
"""
return self.get_string_array("getAllWindowTitles", [])
def get_html_source(self):
"""
Returns the entire HTML source between the opening and
closing "html" tags.
"""
return self.get_string("getHtmlSource", [])
def set_cursor_position(self,locator,position):
"""
Moves the text cursor to the specified position in the given input element or textarea.
This method will fail if the specified element isn't an input element or textarea.
'locator' is an element locator pointing to an input element or textarea
'position' is the numerical position of the cursor in the field; position should be 0 to move the position to the beginning of the field. You can also set the cursor to -1 to move it to the end of the field.
"""
self.do_command("setCursorPosition", [locator,position,])
def get_element_index(self,locator):
"""
Get the relative index of an element to its parent (starting from 0). The comment node and empty text node
will be ignored.
'locator' is an element locator pointing to an element
"""
return self.get_number("getElementIndex", [locator,])
def is_ordered(self,locator1,locator2):
"""
Check if these two elements have same parent and are ordered siblings in the DOM. Two same elements will
not be considered ordered.
'locator1' is an element locator pointing to the first element
'locator2' is an element locator pointing to the second element
"""
return self.get_boolean("isOrdered", [locator1,locator2,])
def get_element_position_left(self,locator):
"""
Retrieves the horizontal position of an element
'locator' is an element locator pointing to an element OR an element itself
"""
return self.get_number("getElementPositionLeft", [locator,])
def get_element_position_top(self,locator):
"""
Retrieves the vertical position of an element
'locator' is an element locator pointing to an element OR an element itself
"""
return self.get_number("getElementPositionTop", [locator,])
def get_element_width(self,locator):
"""
Retrieves the width of an element
'locator' is an element locator pointing to an element
"""
return self.get_number("getElementWidth", [locator,])
def get_element_height(self,locator):
"""
Retrieves the height of an element
'locator' is an element locator pointing to an element
"""
return self.get_number("getElementHeight", [locator,])
def get_cursor_position(self,locator):
"""
Retrieves the text cursor position in the given input element or textarea; beware, this may not work perfectly on all browsers.
Specifically, if the cursor/selection has been cleared by JavaScript, this command will tend to
return the position of the last location of the cursor, even though the cursor is now gone from the page. This is filed as SEL-243.
This method will fail if the specified element isn't an input element or textarea, or there is no cursor in the element.
'locator' is an element locator pointing to an input element or textarea
"""
return self.get_number("getCursorPosition", [locator,])
def get_expression(self,expression):
"""
Returns the specified expression.
This is useful because of JavaScript preprocessing.
It is used to generate commands like assertExpression and waitForExpression.
'expression' is the value to return
"""
return self.get_string("getExpression", [expression,])
def get_xpath_count(self,xpath):
"""
Returns the number of nodes that match the specified xpath, eg. "//table" would give
the number of tables.
'xpath' is the xpath expression to evaluate. do NOT wrap this expression in a 'count()' function; we will do that for you.
"""
return self.get_number("getXpathCount", [xpath,])
def assign_id(self,locator,identifier):
"""
Temporarily sets the "id" attribute of the specified element, so you can locate it in the future
using its ID rather than a slow/complicated XPath. This ID will disappear once the page is
reloaded.
'locator' is an element locator pointing to an element
'identifier' is a string to be used as the ID of the specified element
"""
self.do_command("assignId", [locator,identifier,])
def allow_native_xpath(self,allow):
"""
Specifies whether Selenium should use the native in-browser implementation
of XPath (if any native version is available); if you pass "false" to
this function, we will always use our pure-JavaScript xpath library.
Using the pure-JS xpath library can improve the consistency of xpath
element locators between different browser vendors, but the pure-JS
version is much slower than the native implementations.
'allow' is boolean, true means we'll prefer to use native XPath; false means we'll only use JS XPath
"""
self.do_command("allowNativeXpath", [allow,])
def ignore_attributes_without_value(self,ignore):
"""
Specifies whether Selenium will ignore xpath attributes that have no
value, i.e. are the empty string, when using the non-native xpath
evaluation engine. You'd want to do this for performance reasons in IE.
However, this could break certain xpaths, for example an xpath that looks
for an attribute whose value is NOT the empty string.
The hope is that such xpaths are relatively rare, but the user should
have the option of using them. Note that this only influences xpath
evaluation when using the ajaxslt engine (i.e. not "javascript-xpath").
'ignore' is boolean, true means we'll ignore attributes without value at the expense of xpath "correctness"; false means we'll sacrifice speed for correctness.
"""
self.do_command("ignoreAttributesWithoutValue", [ignore,])
def wait_for_condition(self,script,timeout):
"""
Runs the specified JavaScript snippet repeatedly until it evaluates to "true".
The snippet may have multiple lines, but only the result of the last line
will be considered.
Note that, by default, the snippet will be run in the runner's test window, not in the window
of your application. To get the window of your application, you can use
the JavaScript snippet ``selenium.browserbot.getCurrentWindow()``, and then
run your JavaScript in there
'script' is the JavaScript snippet to run
'timeout' is a timeout in milliseconds, after which this command will return with an error
"""
self.do_command("waitForCondition", [script,timeout,])
def set_timeout(self,timeout):
"""
Specifies the amount of time that Selenium will wait for actions to complete.
Actions that require waiting include "open" and the "waitFor\*" actions.
The default timeout is 30 seconds.
'timeout' is a timeout in milliseconds, after which the action will return with an error
"""
self.do_command("setTimeout", [timeout,])
def wait_for_page_to_load(self,timeout):
"""
Waits for a new page to load.
You can use this command instead of the "AndWait" suffixes, "clickAndWait", "selectAndWait", "typeAndWait" etc.
(which are only available in the JS API).
Selenium constantly keeps track of new pages loading, and sets a "newPageLoaded"
flag when it first notices a page load. Running any other Selenium command after
turns the flag to false. Hence, if you want to wait for a page to load, you must
wait immediately after a Selenium command that caused a page-load.
'timeout' is a timeout in milliseconds, after which this command will return with an error
"""
self.do_command("waitForPageToLoad", [timeout,])
def wait_for_frame_to_load(self,frameAddress,timeout):
"""
Waits for a new frame to load.
Selenium constantly keeps track of new pages and frames loading,
and sets a "newPageLoaded" flag when it first notices a page load.
See waitForPageToLoad for more information.
'frameAddress' is FrameAddress from the server side
'timeout' is a timeout in milliseconds, after which this command will return with an error
"""
self.do_command("waitForFrameToLoad", [frameAddress,timeout,])
def get_cookie(self):
"""
Return all cookies of the current page under test.
"""
return self.get_string("getCookie", [])
def get_cookie_by_name(self,name):
"""
Returns the value of the cookie with the specified name, or throws an error if the cookie is not present.
'name' is the name of the cookie
"""
return self.get_string("getCookieByName", [name,])
def is_cookie_present(self,name):
"""
Returns true if a cookie with the specified name is present, or false otherwise.
'name' is the name of the cookie
"""
return self.get_boolean("isCookiePresent", [name,])
def create_cookie(self,nameValuePair,optionsString):
"""
Create a new cookie whose path and domain are same with those of current page
under test, unless you specified a path for this cookie explicitly.
'nameValuePair' is name and value of the cookie in a format "name=value"
'optionsString' is options for the cookie. Currently supported options include 'path', 'max_age' and 'domain'. the optionsString's format is "path=/path/, max_age=60, domain=.foo.com". The order of options are irrelevant, the unit of the value of 'max_age' is second. Note that specifying a domain that isn't a subset of the current domain will usually fail.
"""
self.do_command("createCookie", [nameValuePair,optionsString,])
def delete_cookie(self,name,optionsString):
"""
Delete a named cookie with specified path and domain. Be careful; to delete a cookie, you
need to delete it using the exact same path and domain that were used to create the cookie.
If the path is wrong, or the domain is wrong, the cookie simply won't be deleted. Also
note that specifying a domain that isn't a subset of the current domain will usually fail.
Since there's no way to discover at runtime the original path and domain of a given cookie,
we've added an option called 'recurse' to try all sub-domains of the current domain with
all paths that are a subset of the current path. Beware; this option can be slow. In
big-O notation, it operates in O(n\*m) time, where n is the number of dots in the domain
name and m is the number of slashes in the path.
'name' is the name of the cookie to be deleted
'optionsString' is options for the cookie. Currently supported options include 'path', 'domain' and 'recurse.' The optionsString's format is "path=/path/, domain=.foo.com, recurse=true". The order of options are irrelevant. Note that specifying a domain that isn't a subset of the current domain will usually fail.
"""
self.do_command("deleteCookie", [name,optionsString,])
def delete_all_visible_cookies(self):
"""
Calls deleteCookie with recurse=true on all cookies visible to the current page.
As noted on the documentation for deleteCookie, recurse=true can be much slower
than simply deleting the cookies using a known domain/path.
"""
self.do_command("deleteAllVisibleCookies", [])
def set_browser_log_level(self,logLevel):
"""
Sets the threshold for browser-side logging messages; log messages beneath this threshold will be discarded.
Valid logLevel strings are: "debug", "info", "warn", "error" or "off".
To see the browser logs, you need to
either show the log window in GUI mode, or enable browser-side logging in Selenium RC.
'logLevel' is one of the following: "debug", "info", "warn", "error" or "off"
"""
self.do_command("setBrowserLogLevel", [logLevel,])
def run_script(self,script):
"""
Creates a new "script" tag in the body of the current test window, and
adds the specified text into the body of the command. Scripts run in
this way can often be debugged more easily than scripts executed using
Selenium's "getEval" command. Beware that JS exceptions thrown in these script
tags aren't managed by Selenium, so you should probably wrap your script
in try/catch blocks if there is any chance that the script will throw
an exception.
'script' is the JavaScript snippet to run
"""
self.do_command("runScript", [script,])
def add_location_strategy(self,strategyName,functionDefinition):
"""
Defines a new function for Selenium to locate elements on the page.
For example,
if you define the strategy "foo", and someone runs click("foo=blah"), we'll
run your function, passing you the string "blah", and click on the element
that your function
returns, or throw an "Element not found" error if your function returns null.
We'll pass three arguments to your function:
* locator: the string the user passed in
* inWindow: the currently selected window
* inDocument: the currently selected document
The function must return null if the element can't be found.
'strategyName' is the name of the strategy to define; this should use only letters [a-zA-Z] with no spaces or other punctuation.
'functionDefinition' is a string defining the body of a function in JavaScript. For example: ``return inDocument.getElementById(locator);``
"""
self.do_command("addLocationStrategy", [strategyName,functionDefinition,])
def capture_entire_page_screenshot(self,filename,kwargs):
"""
Saves the entire contents of the current window canvas to a PNG file.
Contrast this with the captureScreenshot command, which captures the
contents of the OS viewport (i.e. whatever is currently being displayed
on the monitor), and is implemented in the RC only. Currently this only
works in Firefox when running in chrome mode, and in IE non-HTA using
the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly
borrowed from the Screengrab! Firefox extension. Please see
http://www.screengrab.org and http://snapsie.sourceforge.net/ for
details.
'filename' is the path to the file to persist the screenshot as. No filename extension will be appended by default. Directories will not be created if they do not exist, and an exception will be thrown, possibly by native code.
'kwargs' is a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD" . Currently valid options:
* background
the background CSS for the HTML document. This may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension to fail and a black background is exposed (possibly obscuring black text).
"""
self.do_command("captureEntirePageScreenshot", [filename,kwargs,])
def rollup(self,rollupName,kwargs):
"""
Executes a command rollup, which is a series of commands with a unique
name, and optionally arguments that control the generation of the set of
commands. If any one of the rolled-up commands fails, the rollup is
considered to have failed. Rollups may also contain nested rollups.
'rollupName' is the name of the rollup command
'kwargs' is keyword arguments string that influences how the rollup expands into commands
"""
self.do_command("rollup", [rollupName,kwargs,])
def add_script(self,scriptContent,scriptTagId):
"""
Loads script content into a new script tag in the Selenium document. This
differs from the runScript command in that runScript adds the script tag
to the document of the AUT, not the Selenium document. The following
entities in the script content are replaced by the characters they
represent:
<
>
&
The corresponding remove command is removeScript.
'scriptContent' is the Javascript content of the script to add
'scriptTagId' is (optional) the id of the new script tag. If specified, and an element with this id already exists, this operation will fail.
"""
self.do_command("addScript", [scriptContent,scriptTagId,])
def remove_script(self,scriptTagId):
"""
Removes a script tag from the Selenium document identified by the given
id. Does nothing if the referenced tag doesn't exist.
'scriptTagId' is the id of the script element to remove.
"""
self.do_command("removeScript", [scriptTagId,])
def use_xpath_library(self,libraryName):
"""
Allows choice of one of the available libraries.
'libraryName' is name of the desired library Only the following three can be chosen:
* "ajaxslt" - Google's library
* "javascript-xpath" - Cybozu Labs' faster library
* "default" - The default library. Currently the default library is "ajaxslt" .
If libraryName isn't one of these three, then no change will be made.
"""
self.do_command("useXpathLibrary", [libraryName,])
def set_context(self,context):
"""
Writes a message to the status bar and adds a note to the browser-side
log.
'context' is the message to be sent to the browser
"""
self.do_command("setContext", [context,])
def attach_file(self,fieldLocator,fileLocator):
"""
Sets a file input (upload) field to the file listed in fileLocator
'fieldLocator' is an element locator
'fileLocator' is a URL pointing to the specified file. Before the file can be set in the input field (fieldLocator), Selenium RC may need to transfer the file to the local machine before attaching the file in a web page form. This is common in selenium grid configurations where the RC server driving the browser is not the same machine that started the test. Supported Browsers: Firefox ("\*chrome") only.
"""
self.do_command("attachFile", [fieldLocator,fileLocator,])
def capture_screenshot(self,filename):
"""
Captures a PNG screenshot to the specified file.
'filename' is the absolute path to the file to be written, e.g. "c:\blah\screenshot.png"
"""
self.do_command("captureScreenshot", [filename,])
def capture_screenshot_to_string(self):
"""
Capture a PNG screenshot. It then returns the file as a base 64 encoded string.
"""
return self.get_string("captureScreenshotToString", [])
def captureNetworkTraffic(self, type):
"""
Returns the network traffic seen by the browser, including headers, AJAX requests, status codes, and timings. When this function is called, the traffic log is cleared, so the returned content is only the traffic seen since the last call.
'type' is The type of data to return the network traffic as. Valid values are: json, xml, or plain.
"""
return self.get_string("captureNetworkTraffic", [type,])
def addCustomRequestHeader(self, key, value):
"""
Tells the Selenium server to add the specificed key and value as a custom outgoing request header. This only works if the browser is configured to use the built in Selenium proxy.
'key' the header name.
'value' the header value.
"""
return self.do_command("addCustomRequestHeader", [key,value,])
def capture_entire_page_screenshot_to_string(self,kwargs):
"""
Downloads a screenshot of the browser current window canvas to a
based 64 encoded PNG file. The \ *entire* windows canvas is captured,
including parts rendered outside of the current view port.
Currently this only works in Mozilla and when running in chrome mode.
'kwargs' is A kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD". This may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension to fail and a black background is exposed (possibly obscuring black text).
"""
return self.get_string("captureEntirePageScreenshotToString", [kwargs,])
def shut_down_selenium_server(self):
"""
Kills the running Selenium Server and all browser sessions. After you run this command, you will no longer be able to send
commands to the server; you can't remotely start the server once it has been stopped. Normally
you should prefer to run the "stop" command, which terminates the current browser session, rather than
shutting down the entire server.
"""
self.do_command("shutDownSeleniumServer", [])
def retrieve_last_remote_control_logs(self):
"""
Retrieve the last messages logged on a specific remote control. Useful for error reports, especially
when running multiple remote controls in a distributed environment. The maximum number of log messages
that can be retrieve is configured on remote control startup.
"""
return self.get_string("retrieveLastRemoteControlLogs", [])
def key_down_native(self,keycode):
"""
Simulates a user pressing a key (without releasing it yet) by sending a native operating system keystroke.
This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing
a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and
metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular
element, focus on the element first before running this command.
'keycode' is an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes!
"""
self.do_command("keyDownNative", [keycode,])
def key_up_native(self,keycode):
"""
Simulates a user releasing a key by sending a native operating system keystroke.
This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing
a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and
metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular
element, focus on the element first before running this command.
'keycode' is an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes!
"""
self.do_command("keyUpNative", [keycode,])
def key_press_native(self,keycode):
"""
Simulates a user pressing and releasing a key by sending a native operating system keystroke.
This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing
a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and
metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular
element, focus on the element first before running this command.
'keycode' is an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes!
"""
self.do_command("keyPressNative", [keycode,])
| Python |
"""
Flash Selenium - Python Client
Date: 30 March 2008
Paulo Caroli, Sachin Sudheendra
http://code.google.com/p/flash-selenium
-----------------------------------------
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.
"""
from selenium import selenium
import unittest
from FlashSelenium import FlashSelenium
class FlashSeleniumTest(unittest.TestCase):
URL = "http://flashselenium.t35.com/colors.html"
def setUp(self):
self.seleniumObj = selenium("localhost", 4444, "*firefoxproxy", self.URL)
self.seleniumObj.set_speed(1000)
self.flashSeleniumObj = FlashSelenium(self.seleniumObj, "coloredSquare")
self.flashSeleniumObj.start()
def tearDown(self):
self.flashSeleniumObj.stop()
def _testShouldOpenGoogleHomePage(self):
seleniumObj = selenium("localhost", 4444, "*firefox", "http://www.google.co.in")
seleniumObj.start()
seleniumObj.open("http://www.google.co.in")
self.assertEquals("Google", seleniumObj.get_title())
seleniumObj.stop()
def _testShouldCreateFlashSeleniumObject(self):
self.assertTrue(self.flashSeleniumObj is not None)
self.assertEquals(FlashSelenium(None, "").__class__, self.flashSeleniumObj.__class__)
def testShouldLoadMovie100Percent(self):
self.flashSeleniumObj.open(self.URL)
self.assertEquals('100', self.flashSeleniumObj.percent_loaded());
def testShouldCheckIfMovieIsPlaying(self):
self.flashSeleniumObj.open(self.URL)
self.assertTrue(self.flashSeleniumObj.is_playing())
def testShouldReturnVariableValueFromMovie(self):
self.flashSeleniumObj.open(self.URL)
self.assertEquals('GREEN', self.flashSeleniumObj.call('getColor'))
self.flashSeleniumObj.call("click")
self.assertEquals('BLUE', self.flashSeleniumObj.call('getColor'))
def testShouldGetVariable(self):
self.flashSeleniumObj.open(self.URL)
self.flashSeleniumObj.set_variable("FooBar", "42")
self.assertEquals("42", self.flashSeleniumObj.get_variable("FooBar"))
def testShouldClickAndProceedToNextFrame(self):
self.flashSeleniumObj.open(self.URL)
self.flashSeleniumObj.call("click")
self.assertEquals('BLUE', self.flashSeleniumObj.call('getColor'))
self.flashSeleniumObj.call("click")
self.assertEquals('RED', self.flashSeleniumObj.call('getColor'))
def testShouldPanMovie(self):
self.flashSeleniumObj.open(self.URL)
try:
self.flashSeleniumObj.zoom(10)
self.flashSeleniumObj.pan(20, 20, 1)
except:
self.fail("Should not fail")
def testShouldFailWhenInvalidArgumentsAreSentToPanMethod(self):
self.flashSeleniumObj.open(self.URL)
try:
self.flashSeleniumObj.pan("Invalid", "Arguments", "And Strings")
self.fail("Should have thrown exception")
except:
self.assertTrue(True)
def testShouldZoomMovieBy10Percent(self):
self.flashSeleniumObj.open(self.URL)
self.flashSeleniumObj.zoom(10)
def testShouldReturnTotalNumberOfFramesInMovie(self):
self.flashSeleniumObj.open(self.URL)
while (self.flashSeleniumObj.percent_loaded() < 100):
pass
self.assertEquals('1', self.flashSeleniumObj.total_frames())
def testShouldGetNavigatorName(self):
self.flashSeleniumObj.open(self.URL)
retVal = self.flashSeleniumObj.checkBrowserAndReturnJSPrefix()
self.assertEquals("window.document['coloredSquare'].", retVal);
if __name__ == '__main__':
unittest.main()
| Python |
"""
Flash Selenium - Python Client
Date: 30 March 2008
Paulo Caroli, Sachin Sudheendra
http://code.google.com/p/flash-selenium
-----------------------------------------
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.
"""
from selenium import selenium
from BrowserConstants import BrowserConstants
class FlashSelenium(object):
def __init__(self, seleniumObj, flashObjectId):
self.seleniumObj = seleniumObj
self.flashObjectId = flashObjectId
self.browserConstants = BrowserConstants();
self.flashJSStringPrefix = self.createJSPrefix_document(self.flashObjectId)
def start(self):
self.seleniumObj.start()
def stop(self):
self.seleniumObj.stop()
def open(self, Url):
self.seleniumObj.open(Url)
def call(self, functionName, *parameter):
self.flashJSStringPrefix = self.checkBrowserAndReturnJSPrefix()
return self.seleniumObj.get_eval(self.jsForFunction(functionName, list(parameter)))
#### Standard Methods ####
def percent_loaded(self):
return self.call("PercentLoaded")
def is_playing(self):
return self.call("IsPlaying")
def get_variable(self, varName):
return self.call("GetVariable", varName)
def goto_frame(self, value):
return self.call("GotoFrame", value)
def load_movie(self, layerNumber, Url):
return self.call("LoadMovie", layerNumber, Url)
def pan(self, x, y, mode):
return self.call("Pan", x, y, mode)
def play(self):
return self.call("Play")
def rewind(self):
return self.call("Rewind")
def set_variable(self, name, value):
return self.call("SetVariable", name, value)
def set_zoom_rect(self, left, top, right, bottom):
return self.call("SetZoomRect", left, top, right, bottom)
def stop_play(self):
return self.call("StopPlay")
def total_frames(self):
return self.call("TotalFrames")
def zoom(self, percent):
return self.call("Zoom", percent)
#### TellTarget Methods ####
def t_call_frame(self, target, frameNumber):
return self.call("TCallFrame", target, frameNumber)
def t_call_label(self, target, label):
return self.call("TCallLabel", target, label)
def t_current_frame(self, target):
return self.call("TCurrentFrame", target)
def t_current_label(self, target):
return self.call("TCurrentLabel", target)
def t_get_property(self, target, property):
return self.call("TGetProperty", target, property)
def t_get_property_as_number(self, target, property):
return self.call("TGetPropertyAsNumber", target, property)
def t_goto_frame(self, target, frameNumber):
return self.call("TGotoFrame", target, frameNumber)
def t_goto_label(self, target, label):
return self.call("TGotoLabel", target, label)
def t_play(self, target):
return self.call("TPlay", target)
def t_set_property(self, property, value):
return self.call("TSetProperty", property, value)
def t_stop_play(self, target):
return self.call("TStopPlay", target)
#### Standard Events ####
def on_progress(self, percent):
return self.call("OnProgress", percent)
def on_ready_state_change(self, state):
return self.call("OnReadyStateChange", state)
#### Custom Code ####
def checkBrowserAndReturnJSPrefix(self):
return self.createJSPrefix_browserbot(self.flashObjectId);
#appName = self.seleniumObj.get_eval("navigator.userAgent")
#if (appName.find(self.browserConstants.firefox3()) is not -1) or (appName.find(self.browserConstants.msie()) is not -1):
# return self.createJSPrefix_window_document(self.flashObjectId)
#else:
# return self.createJSPrefix_document(self.flashObjectId)
def createJSPrefix_window_document(self, flashObjectId):
return "window.document['" + flashObjectId + "'].";
def createJSPrefix_document(self, flashObjectId):
return "document['" + flashObjectId + "'].";
def jsForFunction(self, functionName, *args):
functionArgs = ""
if len(args) > 0 and args != None :
for arg in args[0]:
functionArgs = functionArgs + "'" + str(arg) + "',"
functionArgs = functionArgs[0:len(functionArgs)-1]
return self.flashJSStringPrefix + functionName + "(" + functionArgs + ");"
def createJSPrefix_browserbot(self, flashObjectId):
return "this.browserbot.findElement(\"" + flashObjectId + "\").";
| Python |
# -*- coding: utf-8 -*-
'''
Created on 2013-4-3
@author: chenkaode@baidu.com
'''
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import uic
from PyQt4 import QtCore, QtGui
import os,sys
import ui_main
from PathSelectDlg import *
import subprocess
class MainDlg(QDialog,ui_main.Ui_Dialog):
def __init__(self,parent=None):
super(MainDlg,self).__init__(parent)
self.setupUi(self)
self.child = None
self.child = PathSelectDlg();
self.connect(self.selectVersionButton,SIGNAL("clicked()"),self.slotChild)
self.connect(self.flashbutton, SIGNAL("clicked()"),self.flashRom)
def slotChild(self):
self.child.show();
def flashRom(self):
print self.child.imgPath
bootImg = self.child.imgPath + os.sep + "boot.img"
systemImg = self.child.imgPath + os.sep + "system.img"
userdataImg = self.child.imgPath + os.sep + "userdata.img"
if not os.path.exists(bootImg) or not os.path.exists(systemImg) or not os.path.exists(userdataImg):
print "not exists"
sys.exit()
self.flashProgressBar.setMinimum(0)
self.flashProgressBar.setMaximum(10)
# subp = subprocess.Popen("adb reboot-bootloader")
os.system("adb reboot-bootloader")
# subp.wait()
QThread.msleep(1000)
# subp = subprocess.Popen("fastboot devices",stdout=subprocess.PIPE)
# out = subp.stdout.read()
# if out == '':
# sys.exit
# else:
# print out
# subp.wait()
QThread.msleep(1000)
self.flashProgressBar.setValue(1)
bootImg = str(bootImg)
bootImg = bootImg.replace("\\", "\\\\")
cmd = "fastboot flash boot " + bootImg
print cmd
# subp = subprocess.Popen(cmd)
# subp.wait()
os.system(cmd)
self.flashProgressBar.setValue(3)
QThread.msleep(2000)
systemImg = str(systemImg)
systemImg = systemImg.replace("\\", "\\\\")
cmd = "fastboot flash system " + systemImg
print cmd
os.system(cmd)
# subp = subprocess.Popen(cmd)
# subp.wait()
self.flashProgressBar.setValue(7)
QThread.msleep(2000)
userdataImg = str(userdataImg)
userdataImg = userdataImg.replace("\\", "\\\\")
cmd = "fastboot flash userdata " + userdataImg
print cmd
os.system(cmd)
# subp = subprocess.Popen(cmd)
# subp.wait()
QThread.msleep(2000)
self.flashProgressBar.setValue(10) | Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'D:\eclipse\eclipseWorkspace\FlashTool\src\main.ui'
#
# Created: Sat Apr 06 23:04:08 2013
# by: PyQt4 UI code generator 4.10
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.setWindowModality(QtCore.Qt.NonModal)
Dialog.resize(371, 252)
Dialog.setSizeIncrement(QtCore.QSize(0, 0))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
Dialog.setPalette(palette)
Dialog.setFocusPolicy(QtCore.Qt.NoFocus)
Dialog.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
Dialog.setWindowOpacity(1.0)
Dialog.setSizeGripEnabled(False)
Dialog.setModal(False)
self.selectVersionButton = QtGui.QPushButton(Dialog)
self.selectVersionButton.setGeometry(QtCore.QRect(110, 110, 141, 51))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(85, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(85, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(85, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
self.selectVersionButton.setPalette(palette)
self.selectVersionButton.setObjectName(_fromUtf8("selectVersionButton"))
self.flashbutton = QtGui.QPushButton(Dialog)
self.flashbutton.setGeometry(QtCore.QRect(110, 180, 141, 51))
self.flashbutton.setObjectName(_fromUtf8("flashbutton"))
self.flashProgressBar = QtGui.QProgressBar(Dialog)
self.flashProgressBar.setGeometry(QtCore.QRect(0, 230, 371, 23))
self.flashProgressBar.setProperty("value", 0)
self.flashProgressBar.setObjectName(_fromUtf8("flashProgressBar"))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "ProductFlash", None))
self.selectVersionButton.setText(_translate("Dialog", "选择版本", None))
self.flashbutton.setText(_translate("Dialog", "刷机", None))
| Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'D:\eclipse\eclipseWorkspace\FlashTool\src\pathSelectDlg.ui'
#
# Created: Wed Apr 03 11:43:41 2013
# by: PyQt4 UI code generator 4.10
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_selectPathDialog(object):
def setupUi(self, selectPathDialog):
selectPathDialog.setObjectName(_fromUtf8("selectPathDialog"))
selectPathDialog.resize(400, 32)
self.acceptButton = QtGui.QPushButton(selectPathDialog)
self.acceptButton.setGeometry(QtCore.QRect(0, 0, 75, 31))
self.acceptButton.setObjectName(_fromUtf8("acceptButton"))
self.selectPathButton = QtGui.QPushButton(selectPathDialog)
self.selectPathButton.setGeometry(QtCore.QRect(80, 0, 81, 31))
self.selectPathButton.setObjectName(_fromUtf8("selectPathButton"))
self.pathEdit = QtGui.QLineEdit(selectPathDialog)
self.pathEdit.setGeometry(QtCore.QRect(170, 0, 231, 31))
self.pathEdit.setObjectName(_fromUtf8("pathEdit"))
self.retranslateUi(selectPathDialog)
QtCore.QMetaObject.connectSlotsByName(selectPathDialog)
def retranslateUi(self, selectPathDialog):
selectPathDialog.setWindowTitle(_translate("selectPathDialog", "选择路径", None))
self.acceptButton.setText(_translate("selectPathDialog", "确定", None))
self.selectPathButton.setText(_translate("selectPathDialog", "选择版本路径", None))
| Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'D:\eclipse\eclipseWorkspace\FlashTool\src\pathSelectWidget.ui'
#
# Created: Wed Apr 03 11:28:40 2013
# by: PyQt4 UI code generator 4.10
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_pathSelectWidget(object):
def setupUi(self, pathSelectWidget):
pathSelectWidget.setObjectName(_fromUtf8("pathSelectWidget"))
pathSelectWidget.resize(383, 32)
self.acceptButton = QtGui.QPushButton(pathSelectWidget)
self.acceptButton.setGeometry(QtCore.QRect(0, 0, 75, 31))
self.acceptButton.setObjectName(_fromUtf8("acceptButton"))
self.selectPathButton = QtGui.QPushButton(pathSelectWidget)
self.selectPathButton.setGeometry(QtCore.QRect(80, 0, 75, 31))
self.selectPathButton.setObjectName(_fromUtf8("selectPathButton"))
self.pathLineEdit = QtGui.QLineEdit(pathSelectWidget)
self.pathLineEdit.setGeometry(QtCore.QRect(160, 0, 221, 31))
self.pathLineEdit.setObjectName(_fromUtf8("pathLineEdit"))
self.retranslateUi(pathSelectWidget)
QtCore.QMetaObject.connectSlotsByName(pathSelectWidget)
def retranslateUi(self, pathSelectWidget):
pathSelectWidget.setWindowTitle(_translate("pathSelectWidget", "选择版本路径", None))
self.acceptButton.setText(_translate("pathSelectWidget", "确定", None))
self.selectPathButton.setText(_translate("pathSelectWidget", "选定路径", None))
| Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'D:\eclipse\eclipseWorkspace\FlashTool\src\main.ui'
#
# Created: Wed Apr 03 11:32:15 2013
# by: PyQt4 UI code generator 4.10
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.setWindowModality(QtCore.Qt.NonModal)
Dialog.resize(371, 233)
Dialog.setSizeIncrement(QtCore.QSize(0, 0))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
Dialog.setPalette(palette)
Dialog.setFocusPolicy(QtCore.Qt.NoFocus)
Dialog.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
Dialog.setWindowOpacity(1.0)
Dialog.setSizeGripEnabled(False)
Dialog.setModal(False)
self.selectVersionButton = QtGui.QPushButton(Dialog)
self.selectVersionButton.setGeometry(QtCore.QRect(110, 110, 141, 51))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(85, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(85, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(85, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
self.selectVersionButton.setPalette(palette)
self.selectVersionButton.setObjectName(_fromUtf8("selectVersionButton"))
self.flashbutton = QtGui.QPushButton(Dialog)
self.flashbutton.setGeometry(QtCore.QRect(110, 180, 141, 51))
self.flashbutton.setObjectName(_fromUtf8("flashbutton"))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "ProductFlash", None))
self.selectVersionButton.setText(_translate("Dialog", "选择版本", None))
self.flashbutton.setText(_translate("Dialog", "刷机", None))
| Python |
# -*- coding: utf-8 -*-
'''
Created on 2013-4-3
@author: chenkaode@baidu.com
'''
from PyQt4.QtGui import *
import sys
from MainDlg import *
if __name__ == "__main__":
app=QApplication(sys.argv)
dialog=MainDlg()
dialog.show()
app.exec_()
| Python |
# -*- coding: utf-8 -*-
'''
Created on 2013-4-3
@author: chenkaode@baidu.com
'''
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import uic
from PyQt4 import QtCore, QtGui
import sys
import ui_pathSelect
class PathSelectDlg(QDialog,ui_pathSelect.Ui_selectPathDialog):
def __init__(self,parent=None):
super(PathSelectDlg,self).__init__(parent)
self.setupUi(self)
self.native = QtGui.QCheckBox()
self.native.setText("Use native file dialog.")
self.native.setChecked(True)
if sys.platform not in ("win32", "darwin"):
self.native.hide()
self.imgPath = ''
self.path = ''
self.connect(self.selectPathButton,SIGNAL("clicked()"),self.selectImgPath)
self.connect(self.acceptButton,SIGNAL("clicked()"),self.acceptPath)
def selectImgPath(self):
options = QtGui.QFileDialog.Options()
if not self.native.isChecked():
options |= QtGui.QFileDialog.DontUseNativeDialog
self.path = QtGui.QFileDialog.getExistingDirectory(self, caption=QString())
def acceptPath(self):
self.imgPath = self.path
self.close()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
from fabric import Fabric
class UI:
def __init__(self, fabric):
self.fabric = fabric
def start(self):
while True:
print "\n\n"
print "### Que désirez-vous faire ? \n"
print "### 1. Maj intervalle \t 2. Maj lien \t 3. Chater \n"
print "### 4. Pinger \t\t 5. Traceroute \t\t 6. Afficher contenu FIB \n"
print "### 7. Afficher vecteur voisins \t\t 0. Quitter \n"
choice = raw_input("### Votre choix: ")
if choice == "1":
interval = raw_input(" > Nouvelle valeur (en secondes):" )
if interval >= 0:
self.fabric.setInterval(interval)
#methode de Actions qui modifie l'interval.
print "\n ~ Intervalle mis à jour.\n"
else:
print "\n ~ Intervalle négatif - non mis à jour.\n"
elif choice == "2":
print " > Liste des interfaces :"
print self.fabric.configuration
dest = raw_input(" > Couple d'interface: ")
cost = raw_input("\n > Nouveau coût du lien: ")
#methode de Actions qui verifie et modifie le cout du lien
if self.fabric.setCost(dest, cost):
print "\n ~ Nouveau coût =", cost, "\n"
else:
print "\n ~ Une erreur a du se produire.\n"
elif choice == "3":
dest = raw_input(" > Destination: ")
ttl = raw_input(" > TTL: ")
if ttl > 0:
content = raw_input("\n > Tapez votre message: ")
#methode de Actions qui verifie et envoit le message.
msg = self.fabric.generateMsg('CHAT', dest, ttl, content)
self.fabric.deliver(msg)
print "\n ~ Message envoyé. \n"
else:
print "\n ~ Erreur de TTL. \n"
elif choice == "4":
dest = raw_input(" > Destination: ")
ttl = raw_input(" > TTL: ")
if ttl > 0:
#methode de Actions qui envoit un ping
content = str(random.randint(1, 100))
msg = self.fabric.generateMsg('PING', dest, ttl, content)
self.fabric.deliver(msg)
print "\n ~ Ping envoyé. \n"
else:
print "\n ~ Erreur de TTL. \n"
elif choice == "5":
dest = raw_input(" > Destination: ")
#methode de Actions qui envoit un traceroute
self.fabric.traceRoute(dest)
print "\n ~ Traceroute effectué. \n"
elif choice == "6":
print " > FIB: "
print self.fabric.fib
#methode de Actions qui affiche la FIB
elif choice == "7":
pass
#methode de Actions qui affiche les vecteurs voisins
elif choice == "0":
exit(0)
else:
print "\n ! Cette option ne figure pas dans la liste. \n"
| Python |
#!/usr/bin/python
# -*- coding: UTF-8 -
class Message:
def __init__(self, packet):
self.unpack(packet)
def unpack(self, packet):
#header, value = packet.splitlines()
header, value = packet.split("\r\n", 1)
#print "---"
#print value
#print "---"
#value = value.rsplit("\r\n", 1)
#print value
#print "---"
#header, value = self.splitLines(packet)
header = header.split(" ")
self.sourceAddr = header[0]
self.destAddr = header[1]
self.ttl = header[2]
self.cat = header[3]
self.length = header[4]
self.content = value
def repack(self):
packet = (self.sourceAddr + " " + self.destAddr + " " + self.ttl +
" " + self.cat + " " + self.length + "\r\n" + self.content)
return packet
def isValid(self):
alphanum = self.isAlNum(self.sourceAddr) and self.isAlNum(self.destAddr)
alpha = self.isAlpha(self.cat)
digit = self.ttl.isdigit() and self.length.isdigit()
#print "length : " + self.length
#print "len : " + str(len(self.content))
#print "content : " + self.content
length = self.length == (str(len(self.content)-2))
#length = True
if not (alphanum and alpha and digit and length):
return False, 3
self.ttl = str(int(self.ttl) - 1)
if self.ttl == "0":
return False, 1
categories = ["CHAT", "ERREUR", "PING", "PONG", "VECTEUR-DISTANCE"]
if not self.cat in categories:
return False, 4
result = False
if self.cat == "CHAT":
result = self.isAlNum(self.content)
elif self.cat == "ERREUR":
s1, s2 = self.content.split(" ", 1)
result = s1.isdigit() and self.isAlNum(s2)
elif self.cat == "PING" or self.cat == "PONG":
result = self.content.isdigit()
else:
s1, s2 = self.content.rsplit(" ", 1)
result = self.isAlNum(s1) and s2.isdigit()
return True, 5
def isAlpha(self, element):
for character in element:
if (character != "_"
and character != "-"
and not character.isalpha()):
return False
return True
def isAlNum(self, element):
for character in element:
if (character != "_"
and character != "-"
and not character.isalnum()):
return False
return True
def splitLines(self, element):
elements = element.split("\r\n", 1)
elements[1] = elements[1].rsplit("\r\n", 1)[0]
#print "ELEMENT TOT : " + element
#print "ELEMENT 0 : " + elements[0]
#print "ELEMENT 1 : " + elements[1]
return elements[0], elements[1]
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
INFINITY = 100
MODIFIED = False
class Fib:
"""
Cette classe représente la table de forwarding d'un routeur.
Chaque entrée de la table de forwarding contient:
- La destination.
- Le coût pour joindre cette destination.
- Le premier routeur sur le chemin.
"""
def __init__(self, rname):
"""
Cette fonction initialise la table de forwarding.
Elle crée un dictionnaire (vide) et connait le
nom de son routeur.
"""
self.fib = dict()
self.rname = rname
def insert(self, dest, cost, by, infos):
"""
Cette fonction insère une destination, le coût pour
joindre cette destination et le premier routeur
sur le chemin vers cette destination, dans la FIB.
@param dest - str - destination.
@param cost - int - coût pour joindre la destination.
@param by - str - premier routeur sur le chemin.
"""
self.fib[dest] = [str(cost), by, infos]
def remove(self, dest):
"""
Cette fonction retire une destination de la table
de forwarding.
@param dest - str - destination.
"""
del self.fib[dest]
def modify(self, dest, new_cost):
"""
Cette fonction permet de notifier un routeur du changement
de coût d'un lien. Les changements nécessaires sont apportés
à la table de forwarding.
"""
if self.fib.has_key(dest) and self.fib[dest][1] == dest:
self.fib[dest][0] = new_cost
def receive(self, other, link_cost, by, infos):
"""
Cette fonction permet à la fib de recevoir la table
de forwarding d'un autre routeur. Elle se charge alors
d'intégrer celle-ci dans une stucture de donnée (ici
une matrice).
@param other - str - fib d'un autre routeur.
@param link_cost - int - coût du lien vers ce routeur.
@param by - str - routeur de qui on reçoit la fib.
"""
lines = other.splitlines()
size = len(lines)
matrix = [""] * size
for i in range(0, size):
matrix[i] = lines[i].split(' ')
self.compute(matrix, link_cost, by, infos)
def compute(self, matrix, link_cost, by, infos):
"""
Cette fonction permet à la FIB de recalculer ses plus
courts chemins sur base des vecteurs de distances
envoyés par les routeurs voisins.
@param matrix - array of array - la fib sous forme matricielle.
@param link_cost - int - coût du lien vers le routeur.
@param by - str - routeur de qui on reçoit la fib.
"""
MODIFIED = False
for vector in matrix:
dest = vector[0]
cost = int(vector[1])
link_cost = int(link_cost)
if self.fib.has_key(dest):
mycost = int(self.fib[dest][0])
rnext = self.fib[dest][1]
if by == rnext:
MODIFIED = True
self.fib[dest][0] = str(cost + link_cost)
elif mycost > cost + link_cost:
MODIFIED = True
self.fib[dest][0] = str(cost + link_cost)
self.fib[dest][1] = by
self.fib[dest][2] = infos
else:
if cost < INFINITY and dest != self.rname:
MODIFIED = True
self.insert(dest, cost + link_cost, by, infos)
def getFibFor(self, dest):
"""
Cette fonction retourne la table de forwarding à envoyer
à dest. Sur base de cette destination, on peut appliquer
le poison reverse.
@param dest - str - destination.
"""
result = self.rname + " 0"
for router in self.fib:
cost = self.fib[router][0]
rnext = self.fib[router][1]
if dest == rnext:
result = result + "\r\n" + router + " " + str(INFINITY)
else:
result = result + "\r\n" + router + " " + cost
return result
def getInterfaceFor(self, dest):
"""
Cette fonction retourne l'interface de sortie a utiliser
pour joindre une destination précise.
"""
if self.fib.has_key(dest):
return self.fib[dest][2]
return None
def wasModified(self):
"""
Cette fonction retourne True si la fib a été modifiée
lors de la dernière mise à jour, False sinon.
"""
return MODIFIED
def __str__(self):
def dictToMatrix(dictionnary):
matrix = list()
for key in dictionnary:
line = [key] + dictionnary[key]
matrix.append(line)
return matrix
def getColumnsSize(matrix):
result = [0] * 4
for line in matrix:
index = 0
for item in line:
result[index] = max(result[index], len(str(item)))
index = index + 1
return result
def fillWith(item, char, size):
n = len(str(item))
return str(item) + (size + 2 - n) * char
def fillLine(sizes, char, line):
result = " "
index = 0
for item in line:
result = result + fillWith(item, char, sizes[index]) + " "
index = index + 1
return result + "\n"
def makeStringArray(dictionnary):
matrix = dictToMatrix(dictionnary)
sizes = getColumnsSize(matrix)
result = fillLine(sizes, " ", ["DEST", "COST", "BY", "INTERFACE"])
if len(matrix) != 0:
result = result + fillLine(sizes, "-", ["", "", "", ""])
for line in matrix:
result = result + fillLine(sizes, " ", line)
result = result + fillLine(sizes, "-", ["", "", "", ""])
return result
return makeStringArray(self.fib)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
MODIFIED = False
class Fib:
"""
Cette classe représente la table de forwarding d'un routeur.
Chaque entrée de la table de forwarding contient:
- La destination.
- Le coût pour joindre cette destination.
- Le premier routeur sur le chemin.
"""
def __init__(self, rname):
"""
Cette fonction initialise la table de forwarding.
Elle crée un dictionnaire (vide) et connait le
nom de son routeur.
"""
self.fib = dict()
self.rname = rname
self.modified = False
def insert(self, dest, cost, by, infos):
"""
Cette fonction insère une destination, le coût pour
joindre cette destination et le premier routeur
sur le chemin vers cette destination, dans la FIB.
@param dest - str - destination.
@param cost - int - coût pour joindre la destination.
@param by - str - premier routeur sur le chemin.
"""
self.fib[dest] = [str(cost), by, infos]
def remove(self, dest):
"""
Cette fonction retire une destination de la table
de forwarding.
@param dest - str - destination.
"""
del self.fib[dest]
def modify(self, dest, new_cost):
"""
Cette fonction permet de notifier un routeur du changement
de coût d'un lien. Les changements nécessaires sont apportés
à la table de forwarding.
"""
if self.fib.has_key(dest) and self.fib[dest][1] == dest:
self.fib[dest][0] = new_cost
def receive(self, other, link_cost, by, infos):
"""
Cette fonction permet à la fib de recevoir la table
de forwarding d'un autre routeur. Elle se charge alors
d'intégrer celle-ci dans une stucture de donnée (ici
une matrice).
@param other - str - fib d'un autre routeur.
@param link_cost - int - coût du lien vers ce routeur.
@param by - str - routeur de qui on reçoit la fib.
"""
lines = other.splitlines()
size = len(lines)
matrix = [""] * size
for i in range(0, size):
matrix[i] = lines[i].split(' ')
self.compute(matrix, link_cost, by, infos)
def compute(self, matrix, link_cost, by, infos):
"""
Cette fonction permet à la FIB de recalculer ses plus
courts chemins sur base des vecteurs de distances
envoyés par les routeurs voisins.
@param matrix - array of array - la fib sous forme matricielle.
@param link_cost - int - coût du lien vers le routeur.
@param by - str - routeur de qui on reçoit la fib.
"""
self.modified = False
for vector in matrix:
dest = vector[0] #destination en cours de traitement
cost = int(vector[1]) #distance à partir du routeur qui envoit la fib
link_cost = int(link_cost)
if self.fib.has_key(dest):
mycost = int(self.fib[dest][0]) #cout present actuellement dans MA fib
rnext = self.fib[dest][1] #le routeur emprunté pour le moment
if by == rnext:
if cost < 0:
self.modified = True
self.fib[dest][0] = "-1"
else:
self.modified = True
self.fib[dest][0] = str(cost + link_cost)
elif cost >= 0 and mycost > cost + link_cost:
self.modified = True
self.fib[dest][0] = str(cost + link_cost)
self.fib[dest][1] = by
self.fib[dest][2] = infos
else:
if cost >= 0 and dest != self.rname:
self.modified = True
self.insert(dest, cost + link_cost, by, infos)
def flush(self):
"""
Cette fonction permet, une fois que la fib a été broadcastée,
de retirer les vecteurs dont la distance est infinie, car une
fois que ces informations ont été propagées elles n'ont plus
d'utilité dans la fib.
"""
keys = list(self.fib)
for key in keys:
if int(self.fib[key][0]) < 0:
self.remove(key)
def upperCost(self, neighborInterface):
"""
Quand le cout vers une interface augmente, il faut répercuter
ce changement dans la fib en allant placer une métrique infinie
à toutes les destinations passant par cette interface. Si on ne
le fait pas, les couts ne seraient pas mis à jour.
"""
for key in self.fib:
if self.fib[key][2] == neighborInterface:
self.modified = True
self.fib[key][0] = "-1"
def getFibFor(self, dest):
"""
Cette fonction retourne la table de forwarding à envoyer
à dest. Sur base de cette destination, on peut appliquer
le poison reverse.
@param dest - str - destination.
"""
result = self.rname + " 0"
for router in self.fib:
cost = self.fib[router][0]
rnext = self.fib[router][1]
if dest == rnext:
result = result + "\r\n" + router + " -1"
else:
result = result + "\r\n" + router + " " + cost
return result
def getInterfaceFor(self, dest):
"""
Cette fonction retourne l'interface de sortie a utiliser
pour joindre une destination précise.
"""
if self.fib.has_key(dest):
return self.fib[dest][2]
return None
def wasModified(self):
"""
Cette fonction retourne True si la fib a été modifiée
lors de la dernière mise à jour, False sinon.
"""
return self.modified
def __str__(self):
def dictToMatrix(dictionnary):
matrix = list()
for key in dictionnary:
line = [key] + dictionnary[key]
matrix.append(line)
return matrix
def getColumnsSize(matrix):
result = [0] * 4
for line in matrix:
index = 0
for item in line:
result[index] = max(result[index], len(str(item)))
index = index + 1
return result
def fillWith(item, char, size):
n = len(str(item))
return str(item) + (size + 2 - n) * char
def fillLine(sizes, char, line):
result = " "
index = 0
for item in line:
result = result + fillWith(item, char, sizes[index]) + " "
index = index + 1
return result + "\n"
def makeStringArray(dictionnary):
matrix = dictToMatrix(dictionnary)
sizes = getColumnsSize(matrix)
result = fillLine(sizes, " ", ["DEST", "COST", "BY", "INTERFACE"])
if len(matrix) != 0:
result = result + fillLine(sizes, "-", ["", "", "", ""])
for line in matrix:
result = result + fillLine(sizes, " ", line)
result = result + fillLine(sizes, "-", ["", "", "", ""])
return result
return makeStringArray(self.fib)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from threading import Thread
class Spooler(Thread):
def __init__(self, fabric, data, infos):
Thread.__init__(self)
self.fabric = fabric
self.data = data
self.infos = infos
self.lock = fabric.getLock()
def run(self):
self.lock.acquire()
self.fabric.receive(self.data, self.infos)
self.lock.release()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
from spooler import Spooler
from threading import Thread
BUFF_SIZE = 1024
class Link(Thread):
def __init__(self, linkConfig, UDPsock, fabric):
"""
Cette fonction crée un lien. Un lien est caractérisé par:
- Une adresse IP (celle du routeur)
- Un port (celui sur lequel les données sont reçues)
- L'adresse IP du routeur de l'autre côté du lien.
- Le port sur lequel joindre ce voisin.
- Le coût pour emprunter ce lien.
"""
Thread.__init__(self)
self.continu = True
self.fabric = fabric
self.routerIP = linkConfig[0]
self.routerPort = linkConfig[1]
self.neighborIP = linkConfig[2]
self.neighborPort = linkConfig[3]
self.linkCost = linkConfig[4]
if self.linkCost > 0:
self.isActive = True
else:
self.isActive = False
self.UDPsock = UDPsock
description = (self.routerIP, self.routerPort,
self.neighborIP, self.neighborPort)
self.fabric.addLink(description, self)
def modifyLinkCost(self, newCost):
"""
Cette fonction permet de changer le coût du lien.
"""
self.linkCost = newCost
if self.linkCost > 0 and not self.isActive:
self.isActive = True
else:
self.isActive = False
def getSocket(self):
return self.UDPsock
def stop(self):
self.continu = False
def run(self):
"""
Cette fonction démarre l'activité du lien. C'est-à-dire
que l'interface attend désormais l'arrivée des paquets.
"""
while self.continu:
data, adress = self.UDPsock.recvfrom(BUFF_SIZE)
if adress == (self.neighborIP, int(self.neighborPort)) and self.isActive:
infos = (self.neighborIP, self.neighborPort, self.linkCost)
spooler = Spooler(self.fabric, data, infos)
spooler.start()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import random
from fibv2 import Fib
from message import Message
from threading import Lock
from threading import Timer
class Fabric:
def __init__(self, routerName, configuration, interval):
self.routerName = routerName
self.configuration = configuration
self.defaultTTL = "64"
self.interval = interval
self.inTraceRoute = False
self.trLock = Lock()
self.lock = Lock()
self.fib = Fib(routerName)
self.links = dict()
def autoTime(self):
"""
Cette fonction sert de timer au routeur pour savoir quand il doit
envoyer la FIB a ses voisins.
"""
t = Timer(int(self.interval), self.autoTime)
self.sendFIB()
t.start()
def sendFIB(self):
"""
Cette fonction permet de demander l'acces a la FIB, ensuite envoyer
la FIB a ses voisins et relache ensuite le verrou de la FIB.
"""
self.lock.acquire()
self.broadcast()
self.lock.release()
def getLock(self):
"""
Cette fonction retourne le verrou de la fabrique.
En effet, un et un seul paquet peut accéder à la fabrique
à la fois.
"""
return self.lock
def addLink(self, description, link):
"""
Cette fonction permet à la fabrique de connaitre
l'ensemble des liens et de pouvoir intéragir directement
avec ceux-ci.
"""
self.links[description] = link
def receive(self, packet, infos):
"""
Cette fonction permet de recevoir un message, verifier
sa validité, et selon cette dernière, traiter ou non le
paquet.
"""
msg = Message(packet)
valid, code = msg.isValid()
if valid:
if self.routerName == msg.destAddr or msg.destAddr == "UNKNOWN":
self.extract(msg, infos)
else:
self.deliver(msg)
else:
error = self.generateError(msg.sourceAddr, code)
self.deliver(error)
def extract(self, msg, infos):
"""
Cette fonction se charge d'effectuer l'opération liée
au type du message reçu.
"""
if msg.cat == "CHAT":
self.chat(msg)
elif msg.cat == "ERREUR":
self.error(msg)
elif msg.cat == "PING":
self.ping(msg)
elif msg.cat == "PONG":
self.pong(msg)
elif msg.cat == "VECTEUR-DISTANCE":
self.vector(msg, infos)
def chat(self, msg):
"""
Cette fonction permet d'afficher un message CHAT.
"""
print "Message: ", msg.content
def error(self, msg):
"""
Cette fonction permet d'afficher un message
d'erreur lorsque l'on en réceptionne un.
"""
error, reason = msg.content.split(" ", 1)
if self.inTraceRoute:
if error == "1":
print " ", msg.sourceAddr
else:
print " Une erreur s'est produite."
self.inTraceRoute = False
self.trLock.release()
else:
print "Erreur: ", error, "\n", "Raison: ", reason
def ping(self, msg):
"""
Cette fonction permet d'afficher un PING et de transmettre
le PONG associé à la source du PING.
"""
print "Ping: ", msg.content
msg.cat = "PONG"
dest = msg.destAddr
msg.destAddr = msg.sourceAddr
msg.sourceAddr = dest
msg.ttl = self.defaultTTL
self.deliver(msg)
def pong(self, msg):
"""
Cette fonction permet d'afficher un PONG.
"""
if self.inTraceRoute:
self.inTraceRoute = False
self.trLock.release()
print "PONG: " + msg.content
def traceRoute(self, dest):
"""
Cette fonction permet d'effectuer un traceroute via des ping successifs
et une incrementation du TTL.
"""
if self.fib.getInterfaceFor(dest) != None:
ttl = 1
self.inTraceRoute = True
while self.trLock.acquire() and self.inTraceRoute:
content = str(random.randint(1, 100))
msg = self.generateMsg("PING", dest, ttl, content)
self.deliver(msg)
ttl = ttl + 1
else:
print " Destination inconnue"
def vector(self, msg, infos):
"""
Cette fonction permet, lorsque l'on reçoit un vecteur
de distance, de le transmettre à la table de forwarding
afin qu'elle puisse recalculer ses plus court chemins.
"""
ineighbor = (str(infos[0]), str(infos[1]))
cost = str(infos[2])
self.fib.receive(msg.content, cost, msg.sourceAddr, ineighbor)
for config in self.configuration:
if ineighbor == (config[2], config[3]):
config[5] = msg.sourceAddr
break
def broadcast(self):
"""
Cette fonction est celle qui effectue l'envoie de la FIB, mais aussi,
qui cree un message pour chaque destinataire, etant donne que le
contenu d'un vecteur-distance est variable en fonction du destinataire.
"""
for conf in self.configuration:
link = self.links[(conf[0], conf[1], conf[2], conf[3])]
neighborName = conf[5]
sender = link.getSocket()
content = self.fib.getFibFor(neighborName)
msg = self.generateMsg("VECTEUR-DISTANCE", neighborName, '2', content)
sender.sendto(msg.repack(), (conf[2], int(conf[3])))
self.fib.flush()
def deliver(self, msg, retry=True):
"""
Cette fonction permet de délivrer un message.
"""
neighbor = self.fib.getInterfaceFor(msg.destAddr)
if neighbor != None:
routerIP, routerPort = self.getOutput(neighbor)
link = self.links[(routerIP,routerPort,neighbor[0],neighbor[1])]
sender = link.getSocket()
sender.sendto(msg.repack(), (neighbor[0], int(neighbor[1])))
elif retry:
error = self.generateError(msg.sourceAddr, 2)
self.deliver(msg, False)
def getOutput(self, interface):
"""
Cette fonction sur base de l'interface d'entrée d'un voisin,
retourne l'interface de sortie par laquelle on doit envoyer
un paquet
"""
for element in self.configuration:
if interface[0] == element[2] and interface[1] == element[3]:
return element[0], element[1]
return None, None
def generateMsg(self, cat, destName, ttl, content):
"""
Cette fonction permet de générer simplement un message.
"""
msg = Message(self.routerName + " " + destName + " " + str(ttl) + " "
+ cat + " " + str(len(content)) + "\r\n" + content + "\r\n")
return msg
def generateError(self, destName, code):
"""
Cette fonction permet de générer simplement une erreur.
"""
msg = Message(self.routerName + " " + destName
+ " " + self.defaultTTL + " ERREUR 8 \r\n" + str(code)
+ " Erreur\r\n")
return msg
def setCost(self, interface, cost):
"""
Cette fonction permet d'informer un lien d'un changement
de coût ainsi que la FIB.
"""
temp = interface.split(" ")
key = (temp[0], temp[1], temp[2], temp[3])
if self.links.has_key(key):
for config in self.configuration:
iconfig = (config[0] + " " + config[1] + " " + config[2] + " " +
config[3])
if interface == iconfig:
if int(cost) < 0 or int(cost) > int(self.links[key].linkCost):
self.fib.upperCost((config[2], config[3]))
self.links[key].modifyLinkCost(cost)
return True
return False
def setInterval(self, interval):
"""
Cette fonction permet de changer l'interval a l'interieur du routeur,
ce changement est effectue via l'interface utilisateur.
"""
self.interval = interval
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from threading import Thread
class Spooler(Thread):
def __init__(self, fabric, data, infos):
Thread.__init__(self)
self.fabric = fabric
self.data = data
self.infos = infos
self.lock = fabric.getLock()
def run(self):
self.lock.acquire()
self.fabric.receive(self.data, self.infos)
self.lock.release()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
from fabric import Fabric
class UI:
def __init__(self, fabric):
self.fabric = fabric
def start(self):
while True:
print "\n\n"
print "### Que désirez-vous faire ? \n"
print "### 1. Maj intervalle \t 2. Maj lien \t 3. Chater \n"
print "### 4. Pinger \t\t 5. Traceroute \t\t 6. Afficher contenu FIB \n"
print "### 7. Afficher vecteur voisins \t\t 0. Quitter \n"
choice = raw_input("### Votre choix: ")
if choice == "1":
interval = raw_input(" > Nouvelle valeur (en secondes):" )
if interval >= 0:
self.fabric.setInterval(interval)
#methode de Actions qui modifie l'interval.
print "\n ~ Intervalle mis à jour.\n"
else:
print "\n ~ Intervalle négatif - non mis à jour.\n"
elif choice == "2":
print " > Liste des interfaces :"
print self.fabric.configuration
dest = raw_input(" > Couple d'interface: ")
cost = raw_input("\n > Nouveau coût du lien: ")
#methode de Actions qui verifie et modifie le cout du lien
if self.fabric.setCost(dest, cost):
print "\n ~ Nouveau coût =", cost, "\n"
else:
print "\n ~ Une erreur a du se produire.\n"
elif choice == "3":
dest = raw_input(" > Destination: ")
ttl = raw_input(" > TTL: ")
if ttl > 0:
content = raw_input("\n > Tapez votre message: ")
#methode de Actions qui verifie et envoit le message.
msg = self.fabric.generateMsg('CHAT', dest, ttl, content)
self.fabric.deliver(msg)
print "\n ~ Message envoyé. \n"
else:
print "\n ~ Erreur de TTL. \n"
elif choice == "4":
dest = raw_input(" > Destination: ")
ttl = raw_input(" > TTL: ")
if ttl > 0:
#methode de Actions qui envoit un ping
content = str(random.randint(1, 100))
msg = self.fabric.generateMsg('PING', dest, ttl, content)
self.fabric.deliver(msg)
print "\n ~ Ping envoyé. \n"
else:
print "\n ~ Erreur de TTL. \n"
elif choice == "5":
dest = raw_input(" > Destination: ")
#methode de Actions qui envoit un traceroute
self.fabric.traceRoute(dest)
print "\n ~ Traceroute effectué. \n"
elif choice == "6":
print " > FIB: "
print self.fabric.fib
#methode de Actions qui affiche la FIB
elif choice == "7":
pass
#methode de Actions qui affiche les vecteurs voisins
elif choice == "0":
exit(0)
else:
print "\n ! Cette option ne figure pas dans la liste. \n"
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fabric import Fabric
from link import Link
from threading import Timer
from UI import UI
import sys
import socket
class Router:
def extractConfiguration(self, cfile):
"""
Cette fonction extrait les différentes informations
présentent dans le fichier de configuration.
"""
f = open(cfile, "r")
routerName = f.readline().splitlines()[0]
interval = f.readline().splitlines()[0]
nlinks = int(f.readline())
configuration = [""] * nlinks
for i in range(0, nlinks):
link = f.readline().splitlines()
configuration[i] = link[0].split(" ")
configuration[i].append("UNKNOWN")
return routerName, interval, configuration
def initLinks(self, fabric, configuration):
"""
Cette fonction se charge de créer les différentes interfaces
du routeur.
"""
sockets = dict()
nlinks = len(configuration)
for i in range(0, nlinks):
routerIP = configuration[i][0]
routerPort = configuration[i][1]
if sockets.has_key((routerIP, routerPort)):
UDPsock = sockets[(routerIP, routerPort)]
link = Link(configuration[i], UDPsock, fabric)
link.start()
else:
UDPsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
UDPsock.bind((routerIP, int(routerPort)))
sockets[(routerIP, routerPort)] = UDPsock
link = Link(configuration[i], UDPsock, fabric)
link.start()
if __name__ == "__main__":
try:
router = Router()
cfile = sys.argv[1]
rname, interval, config = router.extractConfiguration(cfile)
fabric = Fabric(rname, config, interval)
router.initLinks(fabric, config)
fabric.autoTime()
ui = UI(fabric)
ui.start()
except KeyboardInterrupt:
print "\b\b Goodbye !!!"
exit(0)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
from spooler import Spooler
from threading import Thread
BUFF_SIZE = 1024
class Link(Thread):
def __init__(self, linkConfig, UDPsock, fabric):
"""
Cette fonction crée un lien. Un lien est caractérisé par:
- Une adresse IP (celle du routeur)
- Un port (celui sur lequel les données sont reçues)
- L'adresse IP du routeur de l'autre côté du lien.
- Le port sur lequel joindre ce voisin.
- Le coût pour emprunter ce lien.
"""
Thread.__init__(self)
self.continu = True
self.fabric = fabric
self.routerIP = linkConfig[0]
self.routerPort = linkConfig[1]
self.neighborIP = linkConfig[2]
self.neighborPort = linkConfig[3]
self.linkCost = linkConfig[4]
if self.linkCost > 0:
self.isActive = True
else:
self.isActive = False
self.UDPsock = UDPsock
description = (self.routerIP, self.routerPort,
self.neighborIP, self.neighborPort)
self.fabric.addLink(description, self)
def modifyLinkCost(self, newCost):
"""
Cette fonction permet de changer le coût du lien.
"""
self.linkCost = newCost
if self.linkCost > 0 and not self.isActive:
self.isActive = True
else:
self.isActive = False
def getSocket(self):
return self.UDPsock
def stop(self):
self.continu = False
def run(self):
"""
Cette fonction démarre l'activité du lien. C'est-à-dire
que l'interface attend désormais l'arrivée des paquets.
"""
while self.continu:
data, adress = self.UDPsock.recvfrom(BUFF_SIZE)
if adress == (self.neighborIP, int(self.neighborPort)) and self.isActive:
infos = (self.neighborIP, self.neighborPort, self.linkCost)
spooler = Spooler(self.fabric, data, infos)
spooler.start()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
MODIFIED = False
class Fib:
"""
Cette classe représente la table de forwarding d'un routeur.
Chaque entrée de la table de forwarding contient:
- La destination.
- Le coût pour joindre cette destination.
- Le premier routeur sur le chemin.
"""
def __init__(self, rname):
"""
Cette fonction initialise la table de forwarding.
Elle crée un dictionnaire (vide) et connait le
nom de son routeur.
"""
self.fib = dict()
self.rname = rname
self.modified = False
def insert(self, dest, cost, by, infos):
"""
Cette fonction insère une destination, le coût pour
joindre cette destination et le premier routeur
sur le chemin vers cette destination, dans la FIB.
@param dest - str - destination.
@param cost - int - coût pour joindre la destination.
@param by - str - premier routeur sur le chemin.
"""
self.fib[dest] = [str(cost), by, infos]
def remove(self, dest):
"""
Cette fonction retire une destination de la table
de forwarding.
@param dest - str - destination.
"""
del self.fib[dest]
def modify(self, dest, new_cost):
"""
Cette fonction permet de notifier un routeur du changement
de coût d'un lien. Les changements nécessaires sont apportés
à la table de forwarding.
"""
if self.fib.has_key(dest) and self.fib[dest][1] == dest:
self.fib[dest][0] = new_cost
def receive(self, other, link_cost, by, infos):
"""
Cette fonction permet à la fib de recevoir la table
de forwarding d'un autre routeur. Elle se charge alors
d'intégrer celle-ci dans une stucture de donnée (ici
une matrice).
@param other - str - fib d'un autre routeur.
@param link_cost - int - coût du lien vers ce routeur.
@param by - str - routeur de qui on reçoit la fib.
"""
lines = other.splitlines()
size = len(lines)
matrix = [""] * size
for i in range(0, size):
matrix[i] = lines[i].split(' ')
self.compute(matrix, link_cost, by, infos)
def compute(self, matrix, link_cost, by, infos):
"""
Cette fonction permet à la FIB de recalculer ses plus
courts chemins sur base des vecteurs de distances
envoyés par les routeurs voisins.
@param matrix - array of array - la fib sous forme matricielle.
@param link_cost - int - coût du lien vers le routeur.
@param by - str - routeur de qui on reçoit la fib.
"""
self.modified = False
for vector in matrix:
dest = vector[0] #destination en cours de traitement
cost = int(vector[1]) #distance à partir du routeur qui envoit la fib
link_cost = int(link_cost)
if self.fib.has_key(dest):
mycost = int(self.fib[dest][0]) #cout present actuellement dans MA fib
rnext = self.fib[dest][1] #le routeur emprunté pour le moment
if by == rnext:
if cost < 0:
self.modified = True
self.fib[dest][0] = "-1"
else:
self.modified = True
self.fib[dest][0] = str(cost + link_cost)
elif cost >= 0 and mycost > cost + link_cost:
self.modified = True
self.fib[dest][0] = str(cost + link_cost)
self.fib[dest][1] = by
self.fib[dest][2] = infos
else:
if cost >= 0 and dest != self.rname:
self.modified = True
self.insert(dest, cost + link_cost, by, infos)
def flush(self):
"""
Cette fonction permet, une fois que la fib a été broadcastée,
de retirer les vecteurs dont la distance est infinie, car une
fois que ces informations ont été propagées elles n'ont plus
d'utilité dans la fib.
"""
keys = list(self.fib)
for key in keys:
if int(self.fib[key][0]) < 0:
self.remove(key)
def upperCost(self, neighborInterface):
"""
Quand le cout vers une interface augmente, il faut répercuter
ce changement dans la fib en allant placer une métrique infinie
à toutes les destinations passant par cette interface. Si on ne
le fait pas, les couts ne seraient pas mis à jour.
"""
for key in self.fib:
if self.fib[key][2] == neighborInterface:
self.modified = True
self.fib[key][0] = "-1"
def getFibFor(self, dest):
"""
Cette fonction retourne la table de forwarding à envoyer
à dest. Sur base de cette destination, on peut appliquer
le poison reverse.
@param dest - str - destination.
"""
result = self.rname + " 0"
for router in self.fib:
cost = self.fib[router][0]
rnext = self.fib[router][1]
if dest == rnext:
result = result + "\r\n" + router + " -1"
else:
result = result + "\r\n" + router + " " + cost
return result
def getInterfaceFor(self, dest):
"""
Cette fonction retourne l'interface de sortie a utiliser
pour joindre une destination précise.
"""
if self.fib.has_key(dest):
return self.fib[dest][2]
return None
def wasModified(self):
"""
Cette fonction retourne True si la fib a été modifiée
lors de la dernière mise à jour, False sinon.
"""
return self.modified
def __str__(self):
def dictToMatrix(dictionnary):
matrix = list()
for key in dictionnary:
line = [key] + dictionnary[key]
matrix.append(line)
return matrix
def getColumnsSize(matrix):
result = [0] * 4
for line in matrix:
index = 0
for item in line:
result[index] = max(result[index], len(str(item)))
index = index + 1
return result
def fillWith(item, char, size):
n = len(str(item))
return str(item) + (size + 2 - n) * char
def fillLine(sizes, char, line):
result = " "
index = 0
for item in line:
result = result + fillWith(item, char, sizes[index]) + " "
index = index + 1
return result + "\n"
def makeStringArray(dictionnary):
matrix = dictToMatrix(dictionnary)
sizes = getColumnsSize(matrix)
result = fillLine(sizes, " ", ["DEST", "COST", "BY", "INTERFACE"])
if len(matrix) != 0:
result = result + fillLine(sizes, "-", ["", "", "", ""])
for line in matrix:
result = result + fillLine(sizes, " ", line)
result = result + fillLine(sizes, "-", ["", "", "", ""])
return result
return makeStringArray(self.fib)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
INFINITY = 100
MODIFIED = False
class Fib:
"""
Cette classe représente la table de forwarding d'un routeur.
Chaque entrée de la table de forwarding contient:
- La destination.
- Le coût pour joindre cette destination.
- Le premier routeur sur le chemin.
"""
def __init__(self, rname):
"""
Cette fonction initialise la table de forwarding.
Elle crée un dictionnaire (vide) et connait le
nom de son routeur.
"""
self.fib = dict()
self.rname = rname
def insert(self, dest, cost, by, infos):
"""
Cette fonction insère une destination, le coût pour
joindre cette destination et le premier routeur
sur le chemin vers cette destination, dans la FIB.
@param dest - str - destination.
@param cost - int - coût pour joindre la destination.
@param by - str - premier routeur sur le chemin.
"""
self.fib[dest] = [str(cost), by, infos]
def remove(self, dest):
"""
Cette fonction retire une destination de la table
de forwarding.
@param dest - str - destination.
"""
del self.fib[dest]
def modify(self, dest, new_cost):
"""
Cette fonction permet de notifier un routeur du changement
de coût d'un lien. Les changements nécessaires sont apportés
à la table de forwarding.
"""
if self.fib.has_key(dest) and self.fib[dest][1] == dest:
self.fib[dest][0] = new_cost
def receive(self, other, link_cost, by, infos):
"""
Cette fonction permet à la fib de recevoir la table
de forwarding d'un autre routeur. Elle se charge alors
d'intégrer celle-ci dans une stucture de donnée (ici
une matrice).
@param other - str - fib d'un autre routeur.
@param link_cost - int - coût du lien vers ce routeur.
@param by - str - routeur de qui on reçoit la fib.
"""
lines = other.splitlines()
size = len(lines)
matrix = [""] * size
for i in range(0, size):
matrix[i] = lines[i].split(' ')
self.compute(matrix, link_cost, by, infos)
def compute(self, matrix, link_cost, by, infos):
"""
Cette fonction permet à la FIB de recalculer ses plus
courts chemins sur base des vecteurs de distances
envoyés par les routeurs voisins.
@param matrix - array of array - la fib sous forme matricielle.
@param link_cost - int - coût du lien vers le routeur.
@param by - str - routeur de qui on reçoit la fib.
"""
MODIFIED = False
for vector in matrix:
dest = vector[0]
cost = int(vector[1])
link_cost = int(link_cost)
if self.fib.has_key(dest):
mycost = int(self.fib[dest][0])
rnext = self.fib[dest][1]
if by == rnext:
MODIFIED = True
self.fib[dest][0] = str(cost + link_cost)
elif mycost > cost + link_cost:
MODIFIED = True
self.fib[dest][0] = str(cost + link_cost)
self.fib[dest][1] = by
self.fib[dest][2] = infos
else:
if cost < INFINITY and dest != self.rname:
MODIFIED = True
self.insert(dest, cost + link_cost, by, infos)
def getFibFor(self, dest):
"""
Cette fonction retourne la table de forwarding à envoyer
à dest. Sur base de cette destination, on peut appliquer
le poison reverse.
@param dest - str - destination.
"""
result = self.rname + " 0"
for router in self.fib:
cost = self.fib[router][0]
rnext = self.fib[router][1]
if dest == rnext:
result = result + "\r\n" + router + " " + str(INFINITY)
else:
result = result + "\r\n" + router + " " + cost
return result
def getInterfaceFor(self, dest):
"""
Cette fonction retourne l'interface de sortie a utiliser
pour joindre une destination précise.
"""
if self.fib.has_key(dest):
return self.fib[dest][2]
return None
def wasModified(self):
"""
Cette fonction retourne True si la fib a été modifiée
lors de la dernière mise à jour, False sinon.
"""
return MODIFIED
def __str__(self):
def dictToMatrix(dictionnary):
matrix = list()
for key in dictionnary:
line = [key] + dictionnary[key]
matrix.append(line)
return matrix
def getColumnsSize(matrix):
result = [0] * 4
for line in matrix:
index = 0
for item in line:
result[index] = max(result[index], len(str(item)))
index = index + 1
return result
def fillWith(item, char, size):
n = len(str(item))
return str(item) + (size + 2 - n) * char
def fillLine(sizes, char, line):
result = " "
index = 0
for item in line:
result = result + fillWith(item, char, sizes[index]) + " "
index = index + 1
return result + "\n"
def makeStringArray(dictionnary):
matrix = dictToMatrix(dictionnary)
sizes = getColumnsSize(matrix)
result = fillLine(sizes, " ", ["DEST", "COST", "BY", "INTERFACE"])
if len(matrix) != 0:
result = result + fillLine(sizes, "-", ["", "", "", ""])
for line in matrix:
result = result + fillLine(sizes, " ", line)
result = result + fillLine(sizes, "-", ["", "", "", ""])
return result
return makeStringArray(self.fib)
| Python |
#!/usr/bin/python
# -*- coding: UTF-8 -
class Message:
def __init__(self, packet):
self.unpack(packet)
def unpack(self, packet):
#header, value = packet.splitlines()
header, value = packet.split("\r\n", 1)
#print "---"
#print value
#print "---"
#value = value.rsplit("\r\n", 1)
#print value
#print "---"
#header, value = self.splitLines(packet)
header = header.split(" ")
self.sourceAddr = header[0]
self.destAddr = header[1]
self.ttl = header[2]
self.cat = header[3]
self.length = header[4]
self.content = value
def repack(self):
packet = (self.sourceAddr + " " + self.destAddr + " " + self.ttl +
" " + self.cat + " " + self.length + "\r\n" + self.content)
return packet
def isValid(self):
alphanum = self.isAlNum(self.sourceAddr) and self.isAlNum(self.destAddr)
alpha = self.isAlpha(self.cat)
digit = self.ttl.isdigit() and self.length.isdigit()
#print "length : " + self.length
#print "len : " + str(len(self.content))
#print "content : " + self.content
length = self.length == (str(len(self.content)-2))
#length = True
if not (alphanum and alpha and digit and length):
return False, 3
self.ttl = str(int(self.ttl) - 1)
if self.ttl == "0":
return False, 1
categories = ["CHAT", "ERREUR", "PING", "PONG", "VECTEUR-DISTANCE"]
if not self.cat in categories:
return False, 4
result = False
if self.cat == "CHAT":
result = self.isAlNum(self.content)
elif self.cat == "ERREUR":
s1, s2 = self.content.split(" ", 1)
result = s1.isdigit() and self.isAlNum(s2)
elif self.cat == "PING" or self.cat == "PONG":
result = self.content.isdigit()
else:
s1, s2 = self.content.rsplit(" ", 1)
result = self.isAlNum(s1) and s2.isdigit()
return True, 5
def isAlpha(self, element):
for character in element:
if (character != "_"
and character != "-"
and not character.isalpha()):
return False
return True
def isAlNum(self, element):
for character in element:
if (character != "_"
and character != "-"
and not character.isalnum()):
return False
return True
def splitLines(self, element):
elements = element.split("\r\n", 1)
elements[1] = elements[1].rsplit("\r\n", 1)[0]
#print "ELEMENT TOT : " + element
#print "ELEMENT 0 : " + elements[0]
#print "ELEMENT 1 : " + elements[1]
return elements[0], elements[1]
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fabric import Fabric
from link import Link
from threading import Timer
from UI import UI
import sys
import socket
class Router:
def extractConfiguration(self, cfile):
"""
Cette fonction extrait les différentes informations
présentent dans le fichier de configuration.
"""
f = open(cfile, "r")
routerName = f.readline().splitlines()[0]
interval = f.readline().splitlines()[0]
nlinks = int(f.readline())
configuration = [""] * nlinks
for i in range(0, nlinks):
link = f.readline().splitlines()
configuration[i] = link[0].split(" ")
configuration[i].append("UNKNOWN")
return routerName, interval, configuration
def initLinks(self, fabric, configuration):
"""
Cette fonction se charge de créer les différentes interfaces
du routeur.
"""
sockets = dict()
nlinks = len(configuration)
for i in range(0, nlinks):
routerIP = configuration[i][0]
routerPort = configuration[i][1]
if sockets.has_key((routerIP, routerPort)):
UDPsock = sockets[(routerIP, routerPort)]
link = Link(configuration[i], UDPsock, fabric)
link.start()
else:
UDPsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
UDPsock.bind((routerIP, int(routerPort)))
sockets[(routerIP, routerPort)] = UDPsock
link = Link(configuration[i], UDPsock, fabric)
link.start()
if __name__ == "__main__":
try:
router = Router()
cfile = sys.argv[1]
rname, interval, config = router.extractConfiguration(cfile)
fabric = Fabric(rname, config, interval)
router.initLinks(fabric, config)
fabric.autoTime()
ui = UI(fabric)
ui.start()
except KeyboardInterrupt:
print "\b\b Goodbye !!!"
exit(0)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import random
from fibv2 import Fib
from message import Message
from threading import Lock
from threading import Timer
class Fabric:
def __init__(self, routerName, configuration, interval):
self.routerName = routerName
self.configuration = configuration
self.defaultTTL = "64"
self.interval = interval
self.inTraceRoute = False
self.trLock = Lock()
self.lock = Lock()
self.fib = Fib(routerName)
self.links = dict()
def autoTime(self):
"""
Cette fonction sert de timer au routeur pour savoir quand il doit
envoyer la FIB a ses voisins.
"""
t = Timer(int(self.interval), self.autoTime)
self.sendFIB()
t.start()
def sendFIB(self):
"""
Cette fonction permet de demander l'acces a la FIB, ensuite envoyer
la FIB a ses voisins et relache ensuite le verrou de la FIB.
"""
self.lock.acquire()
self.broadcast()
self.lock.release()
def getLock(self):
"""
Cette fonction retourne le verrou de la fabrique.
En effet, un et un seul paquet peut accéder à la fabrique
à la fois.
"""
return self.lock
def addLink(self, description, link):
"""
Cette fonction permet à la fabrique de connaitre
l'ensemble des liens et de pouvoir intéragir directement
avec ceux-ci.
"""
self.links[description] = link
def receive(self, packet, infos):
"""
Cette fonction permet de recevoir un message, verifier
sa validité, et selon cette dernière, traiter ou non le
paquet.
"""
msg = Message(packet)
valid, code = msg.isValid()
if valid:
if self.routerName == msg.destAddr or msg.destAddr == "UNKNOWN":
self.extract(msg, infos)
else:
self.deliver(msg)
else:
error = self.generateError(msg.sourceAddr, code)
self.deliver(error)
def extract(self, msg, infos):
"""
Cette fonction se charge d'effectuer l'opération liée
au type du message reçu.
"""
if msg.cat == "CHAT":
self.chat(msg)
elif msg.cat == "ERREUR":
self.error(msg)
elif msg.cat == "PING":
self.ping(msg)
elif msg.cat == "PONG":
self.pong(msg)
elif msg.cat == "VECTEUR-DISTANCE":
self.vector(msg, infos)
def chat(self, msg):
"""
Cette fonction permet d'afficher un message CHAT.
"""
print "Message: ", msg.content
def error(self, msg):
"""
Cette fonction permet d'afficher un message
d'erreur lorsque l'on en réceptionne un.
"""
error, reason = msg.content.split(" ", 1)
if self.inTraceRoute:
if error == "1":
print " ", msg.sourceAddr
else:
print " Une erreur s'est produite."
self.inTraceRoute = False
self.trLock.release()
else:
print "Erreur: ", error, "\n", "Raison: ", reason
def ping(self, msg):
"""
Cette fonction permet d'afficher un PING et de transmettre
le PONG associé à la source du PING.
"""
print "Ping: ", msg.content
msg.cat = "PONG"
dest = msg.destAddr
msg.destAddr = msg.sourceAddr
msg.sourceAddr = dest
msg.ttl = self.defaultTTL
self.deliver(msg)
def pong(self, msg):
"""
Cette fonction permet d'afficher un PONG.
"""
if self.inTraceRoute:
self.inTraceRoute = False
self.trLock.release()
print "PONG: " + msg.content
def traceRoute(self, dest):
"""
Cette fonction permet d'effectuer un traceroute via des ping successifs
et une incrementation du TTL.
"""
if self.fib.getInterfaceFor(dest) != None:
ttl = 1
self.inTraceRoute = True
while self.trLock.acquire() and self.inTraceRoute:
content = str(random.randint(1, 100))
msg = self.generateMsg("PING", dest, ttl, content)
self.deliver(msg)
ttl = ttl + 1
else:
print " Destination inconnue"
def vector(self, msg, infos):
"""
Cette fonction permet, lorsque l'on reçoit un vecteur
de distance, de le transmettre à la table de forwarding
afin qu'elle puisse recalculer ses plus court chemins.
"""
ineighbor = (str(infos[0]), str(infos[1]))
cost = str(infos[2])
self.fib.receive(msg.content, cost, msg.sourceAddr, ineighbor)
for config in self.configuration:
if ineighbor == (config[2], config[3]):
config[5] = msg.sourceAddr
break
def broadcast(self):
"""
Cette fonction est celle qui effectue l'envoie de la FIB, mais aussi,
qui cree un message pour chaque destinataire, etant donne que le
contenu d'un vecteur-distance est variable en fonction du destinataire.
"""
for conf in self.configuration:
link = self.links[(conf[0], conf[1], conf[2], conf[3])]
neighborName = conf[5]
sender = link.getSocket()
content = self.fib.getFibFor(neighborName)
msg = self.generateMsg("VECTEUR-DISTANCE", neighborName, '2', content)
sender.sendto(msg.repack(), (conf[2], int(conf[3])))
self.fib.flush()
def deliver(self, msg, retry=True):
"""
Cette fonction permet de délivrer un message.
"""
neighbor = self.fib.getInterfaceFor(msg.destAddr)
if neighbor != None:
routerIP, routerPort = self.getOutput(neighbor)
link = self.links[(routerIP,routerPort,neighbor[0],neighbor[1])]
sender = link.getSocket()
sender.sendto(msg.repack(), (neighbor[0], int(neighbor[1])))
elif retry:
error = self.generateError(msg.sourceAddr, 2)
self.deliver(msg, False)
def getOutput(self, interface):
"""
Cette fonction sur base de l'interface d'entrée d'un voisin,
retourne l'interface de sortie par laquelle on doit envoyer
un paquet
"""
for element in self.configuration:
if interface[0] == element[2] and interface[1] == element[3]:
return element[0], element[1]
return None, None
def generateMsg(self, cat, destName, ttl, content):
"""
Cette fonction permet de générer simplement un message.
"""
msg = Message(self.routerName + " " + destName + " " + str(ttl) + " "
+ cat + " " + str(len(content)) + "\r\n" + content + "\r\n")
return msg
def generateError(self, destName, code):
"""
Cette fonction permet de générer simplement une erreur.
"""
msg = Message(self.routerName + " " + destName
+ " " + self.defaultTTL + " ERREUR 8 \r\n" + str(code)
+ " Erreur\r\n")
return msg
def setCost(self, interface, cost):
"""
Cette fonction permet d'informer un lien d'un changement
de coût ainsi que la FIB.
"""
temp = interface.split(" ")
key = (temp[0], temp[1], temp[2], temp[3])
if self.links.has_key(key):
for config in self.configuration:
iconfig = (config[0] + " " + config[1] + " " + config[2] + " " +
config[3])
if interface == iconfig:
if int(cost) < 0 or int(cost) > int(self.links[key].linkCost):
self.fib.upperCost((config[2], config[3]))
self.links[key].modifyLinkCost(cost)
return True
return False
def setInterval(self, interval):
"""
Cette fonction permet de changer l'interval a l'interieur du routeur,
ce changement est effectue via l'interface utilisateur.
"""
self.interval = interval
| Python |
# Testloader for setuptools unittest.
# Copyright (C) 2009 Manuel Hermann <manuel-hermann@gmx.net>
#
# This file is part of tinydav.
#
# tinydav 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 of the License, 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
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Testloader for setuptools unittest."""
from os import path
import sys
import unittest
try:
import coverage
except ImportError:
coverage = None
else:
cov = coverage.coverage(cover_pylib=False)
cov.start()
import Mock
TESTDIR = path.dirname(Mock.__file__)
TINYDAV = path.join(TESTDIR, "..")
sys.path.insert(0, TINYDAV)
from tinydav import creator, exception, util
import tinydav
import TestTinyDAV
import TestCreator
import TestUtil
import TestException
MODULES = [tinydav, creator, exception, util]
def run():
suite = unittest.TestSuite()
for testclass in (TestTinyDAV, TestCreator, TestUtil, TestException):
suite.addTests(unittest.findTestCases(testclass))
unittest.TextTestRunner(verbosity=2).run(suite)
if coverage:
cov.stop()
print "\nTest coverage report:"
print "====================="
cov.report(MODULES)
if __name__ == "__main__":
run()
| Python |
# Unittests for util module.
# coding: utf-8
# Copyright (C) 2009 Manuel Hermann <manuel-hermann@gmx.net>
#
# This file is part of tinydav.
#
# tinydav 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 of the License, 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
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Unittests for util module."""
from __future__ import with_statement
from StringIO import StringIO
import unittest
from tinydav import HTTPClient, HTTPError
from tinydav import util
from Mock import injected
import Mock
MULTI = """\
--foobar
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
Content-Disposition: form-data; name="a"
foo
--foobar
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
Content-Disposition: form-data; name="b"
bar
--foobar--"""
MULTI_ISO = """\
--foobar
Content-Type: text/plain; charset="iso-8859-1"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Content-Disposition: form-data; name="a"
foo
--foobar
Content-Type: text/plain; charset="iso-8859-1"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Content-Disposition: form-data; name="b"
=C3=A4=C3=B6=C3=BC=C3=9F
--foobar--"""
MIME_ISO_EXPLICIT = """\
--foobar
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
Content-Disposition: form-data; name="a"
foo
--foobar
Content-Type: text/plain; charset="iso-8859-1"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Content-Disposition: form-data; name="b"
=C3=A4=C3=B6=C3=BC=C3=9F
--foobar--"""
MIME_FILE = """\
--foobar
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
Content-Disposition: form-data; name="a"
foo
--foobar
Content-Type: application/octet-stream
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: form-data; name="b"
VGhpcyBpcyBhIHRlc3QgZmlsZS4=
--foobar--"""
MIME_FILE_EXPLICIT = """\
--foobar
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
Content-Disposition: form-data; name="a"
foo
--foobar
Content-Type: text/plain
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: form-data; name="b"
VGhpcyBpcyBhIHRlc3QgZmlsZS4=
--foobar--"""
MIME_FILE_NAME = """\
--foobar
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
Content-Disposition: form-data; name="a"
foo
--foobar
Content-Type: application/octet-stream
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: form-data; name="b"; filename="test.txt"
VGhpcyBpcyBhIHRlc3QgZmlsZS4=
--foobar--"""
MIME_FILES = """\
--foobar
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
Content-Disposition: form-data; name="a"
foo
--foobar
Content-Type: multipart/mixed; boundary="foobar-mixed"
MIME-Version: 1.0
--foobar-mixed
Content-Type: application/octet-stream
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: file; name="c"; filename="test2.txt"
VGhpcyBpcyBhbm90aGVyIHRlc3QgZmlsZS4=
--foobar-mixed
Content-Type: application/octet-stream
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: file; name="b"
VGhpcyBpcyBhIHRlc3QgZmlsZS4=
--foobar-mixed--
--foobar--"""
class UtilTestCase(unittest.TestCase):
"""Test util module."""
def test_fake_http_request(self):
"""Test util.FakeHTTPReqest."""
client = HTTPClient("localhost")
headers = dict(a="1", b="2")
fake = util.FakeHTTPRequest(client, "/foo/bar", headers)
self.assertEqual(fake.get_full_url(), "http://localhost:80/foo/bar")
self.assertEqual(fake.get_host(), "localhost")
self.assertFalse(fake.is_unverifiable())
self.assertEqual(fake.get_origin_req_host(), "localhost")
self.assertEqual(fake.get_type(), "http")
self.assertTrue(fake.has_header("a"))
self.assertFalse(fake.has_header("foobar"))
fake.add_unredirected_header("foobar", "baz")
self.assertTrue(fake.has_header("foobar"))
def test_make_absolute(self):
"""Test util.make_absolute function."""
mockclient = Mock.Omnivore()
mockclient.protocol = "http"
mockclient.host = "localhost"
mockclient.port = 80
expect = "http://localhost:80/foo/bar"
self.assertEqual(util.make_absolute(mockclient, "/foo/bar"), expect)
def test_extract_namespace(self):
"""Test util.extrace_namespace."""
self.assertEqual(util.extract_namespace("{foo}bar"), "foo")
self.assertEqual(util.extract_namespace("bar"), None)
def test_get_depth(self):
"""Test util.get_depth."""
# test unrestricted
self.assertEqual(util.get_depth("0"), "0")
self.assertEqual(util.get_depth(0), "0")
self.assertEqual(util.get_depth("1"), "1")
self.assertEqual(util.get_depth(1), "1")
self.assertEqual(util.get_depth("InFiNiTy"), "infinity")
self.assertRaises(ValueError, util.get_depth, "illegal")
# test restricted
restricted = ("0", "infinity")
self.assertEqual(util.get_depth("0", restricted), "0")
self.assertEqual(util.get_depth(0, restricted), "0")
self.assertRaises(ValueError, util.get_depth, "1", restricted)
self.assertRaises(ValueError, util.get_depth, 1, restricted)
self.assertEqual(util.get_depth("InFiNiTy", restricted), "infinity")
def test_get_cookie_response(self):
"""Test util.get_cookie_response."""
response = Mock.Omnivore()
response.response = Mock.Omnivore()
response.response.msg = "The message"
self.assertEqual(util.get_cookie_response(response), response.response)
# must extract response object from HTTPError
error = HTTPError(response)
self.assertEqual(util.get_cookie_response(error), response.response)
def test_parse_authenticate(self):
"""Test util.parse_authenticate."""
# basic auth
basic = 'Basic realm="restricted"'
authdata = util.parse_authenticate(basic)
self.assertEqual(authdata.get("schema"), "Basic")
self.assertEqual(authdata.get("realm"), "restricted")
self.assertEqual(authdata.get("domain"), None)
self.assertEqual(authdata.get("nonce"), None)
self.assertEqual(authdata.get("opaque"), None)
self.assertEqual(authdata.get("stale"), None)
self.assertEqual(authdata.get("algorithm"), None)
# digest auth
digest = 'Digest realm="restricted" domain="foo.de" nonce="abcd1234"'\
'opaque="qwer4321" stale=false algorithm="MD5"'
authdata = util.parse_authenticate(digest)
self.assertEqual(authdata.get("schema"), "Digest")
self.assertEqual(authdata.get("realm"), "restricted")
self.assertEqual(authdata.get("domain"), "foo.de")
self.assertEqual(authdata.get("nonce"), "abcd1234")
self.assertEqual(authdata.get("opaque"), "qwer4321")
self.assertEqual(authdata.get("stale"), "false")
self.assertEqual(authdata.get("algorithm"), "MD5")
# digest auth missing something
digest = 'Digest realm="restricted" domain="foo.de" nonce="abcd1234"'\
'opaque="qwer4321" algorithm="MD5"'
authdata = util.parse_authenticate(digest)
self.assertEqual(authdata.get("schema"), "Digest")
self.assertEqual(authdata.get("realm"), "restricted")
self.assertEqual(authdata.get("domain"), "foo.de")
self.assertEqual(authdata.get("nonce"), "abcd1234")
self.assertEqual(authdata.get("opaque"), "qwer4321")
self.assertEqual(authdata.get("stale"), None)
self.assertEqual(authdata.get("algorithm"), "MD5")
# broken authenticate header
authdata = util.parse_authenticate("Nothing")
self.assertEqual(authdata, dict())
def test_make_multipart(self):
"""Test util.make_multipart."""
# form-data
context = dict(MIMEMultipart=Mock.FakeMIMEMultipart())
with injected(util.make_multipart, **context):
content = dict(a="foo", b="bar")
(headers, multi) = util.make_multipart(content)
self.assertEqual(
headers["Content-Type"],
'multipart/form-data; boundary="foobar"'
)
self.assertEqual(multi, MULTI)
# form-data with iso-8859-1
context = dict(MIMEMultipart=Mock.FakeMIMEMultipart())
with injected(util.make_multipart, **context):
content = dict(a="foo", b="äöüß")
(headers, multi) = util.make_multipart(content, "iso-8859-1")
self.assertEqual(
headers["Content-Type"],
'multipart/form-data; boundary="foobar"'
)
self.assertEqual(multi, MULTI_ISO)
# form-data with explicit iso-8859-1
context = dict(MIMEMultipart=Mock.FakeMIMEMultipart())
with injected(util.make_multipart, **context):
content = dict(a="foo", b=("äöüß", "iso-8859-1"))
(headers, multi) = util.make_multipart(content)
self.assertEqual(
headers["Content-Type"],
'multipart/form-data; boundary="foobar"'
)
self.assertEqual(multi, MIME_ISO_EXPLICIT)
# post one file
sio = StringIO("This is a test file.")
context = dict(MIMEMultipart=Mock.FakeMIMEMultipart())
with injected(util.make_multipart, **context):
content = dict(a="foo", b=sio)
(headers, multi) = util.make_multipart(content)
self.assertEqual(
headers["Content-Type"],
'multipart/form-data; boundary="foobar"'
)
self.assertEqual(multi, MIME_FILE)
# post one file with filename
sio = StringIO("This is a test file.")
sio.name = "test.txt"
context = dict(MIMEMultipart=Mock.FakeMIMEMultipart())
with injected(util.make_multipart, **context):
content = dict(a="foo", b=sio)
(headers, multi) = util.make_multipart(content, with_filenames=True)
self.assertEqual(
headers["Content-Type"],
'multipart/form-data; boundary="foobar"'
)
self.assertEqual(multi, MIME_FILE_NAME)
# post one file with explicit content-type
sio = StringIO("This is a test file.")
context = dict(MIMEMultipart=Mock.FakeMIMEMultipart())
with injected(util.make_multipart, **context):
content = dict(a="foo", b=(sio, "text/plain"))
(headers, multi) = util.make_multipart(content)
self.assertEqual(
headers["Content-Type"],
'multipart/form-data; boundary="foobar"'
)
self.assertEqual(multi, MIME_FILE_EXPLICIT)
# post two files, one with filename
sio = StringIO("This is a test file.")
sio2 = StringIO("This is another test file.")
sio2.name = "test2.txt"
context = dict(MIMEMultipart=Mock.FakeMIMEMultipart())
with injected(util.make_multipart, **context):
content = dict(a="foo", b=sio, c=sio2)
(headers, multi) = util.make_multipart(content, with_filenames=True)
self.assertEqual(
headers["Content-Type"],
'multipart/form-data; boundary="foobar"'
)
self.assertEqual(multi, MIME_FILES)
| Python |
# Unittests for tinydav lib.
# coding: utf-8
# Copyright (C) 2009 Manuel Hermann <manuel-hermann@gmx.net>
#
# This file is part of tinydav.
#
# tinydav 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 of the License, 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
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Unittests for tinydav lib."""
from __future__ import with_statement
from cookielib import CookieJar
from StringIO import StringIO
from xml.etree.ElementTree import ElementTree
import hashlib
import httplib
import urllib
import socket
import sys
import tinydav
import unittest
from tinydav import HTTPError, HTTPUserError, HTTPServerError
from tinydav import HTTPClient
from tinydav import HTTPResponse
from tinydav import CoreWebDAVClient
from tinydav import ExtendedWebDAVClient
from tinydav import WebDAVResponse
from tinydav import WebDAVLockResponse
from tinydav import MultiStatusResponse
from Mock import injected, replaced
import Mock
PYTHONVERSION = sys.version_info[:2] # (2, 5) or (2, 6)
if PYTHONVERSION >= (2, 7):
from xml.etree.ElementTree import ParseError
else:
from xml.parsers.expat import ExpatError as ParseError
MULTISTATUS = """\
<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:" xmlns:dc="DC:">
<D:response>
<D:href>/3/38/38f/38fa476aa97a4b2baeb41a481fdca00b</D:href>
<D:propstat>
<D:prop>
<D:getetag>6ca7-364-475e65375ce80</D:getetag>
<dc:created/>
<dc:resource/>
<dc:author/>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
"""
# unbound prefix
MULTISTATUS_BROKEN = """\
<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:">
<D:response>
<D:href>/3/38/38f/38fa476aa97a4b2baeb41a481fdca00b</D:href>
<D:propstat>
<D:prop>
<D:getetag>6ca7-364-475e65375ce80</D:getetag>
<dc:created/>
<dc:resource/>
<dc:author/>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
"""
REPORT = """\
<?xml version="1.0" encoding="utf-8" ?>
<D:multistatus xmlns:D="DAV:">
<D:response>
<D:href>/his/23/ver/V1</D:href>
<D:propstat>
<D:prop>
<D:version-name>V1</D:version-name>
<D:creator-displayname>Fred</D:creator-displayname>
<D:successor-set>
<D:href>/his/23/ver/V2</D:href>
</D:successor-set>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
<D:response>
<D:href>/his/23/ver/V2</D:href>
<D:propstat>
<D:prop>
<D:version-name>V2</D:version-name>
<D:creator-displayname>Fred</D:creator-displayname>
<D:successor-set/>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
"""
RESPONSE = """\
<?xml version="1.0" encoding="utf-8"?>
<D:response xmlns:D="DAV:" xmlns:dc="DC:">
<D:href>/3/38/38f/38fa476aa97a4b2baeb41a481fdca00b</D:href>
<D:propstat>
<D:prop>
<D:getetag>6ca7-364-475e65375ce80</D:getetag>
<dc:created/>
<dc:resource/>
<dc:author>Me</dc:author>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
"""
LOCKDISCOVERY = """\
<?xml version="1.0" encoding="utf-8" ?>
<D:prop xmlns:D="DAV:">
<D:lockdiscovery>
<D:activelock>
<D:locktype><D:write/></D:locktype>
<D:lockscope><D:exclusive/></D:lockscope>
<D:depth>Infinity</D:depth>
<D:owner>
<D:href>
http://localhost/me.html
</D:href>
</D:owner>
<D:timeout>Second-604800</D:timeout>
<D:locktoken>
<D:href>
opaquelocktoken:e71d4fae-5dec-22d6-fea5-00a0c91e6be4
</D:href>
</D:locktoken>
</D:activelock>
</D:lockdiscovery>
</D:prop>
"""
class HTTPClientTestCase(unittest.TestCase):
"""Test the HTTPClient class."""
def setUp(self):
"""Setup the client."""
self.http = HTTPClient("127.0.0.1", 80)
self.con = Mock.HTTPConnection()
self.http._getconnection = lambda: self.con
def test_init(self):
"""Test initializing the HTTPClient."""
self.assertEqual(self.http.host, "127.0.0.1")
self.assertEqual(self.http.port, 80)
def test_getconnection(self):
"""Test HTTPClient._getconnection."""
# http
http = HTTPClient("127.0.0.1", 80)
con = http._getconnection()
self.assertTrue(isinstance(con, httplib.HTTPConnection))
# https
http = HTTPClient("127.0.0.1", 80, protocol="https")
con = http._getconnection()
self.assertTrue(isinstance(con, httplib.HTTPSConnection))
http = HTTPClient("127.0.0.1", timeout=300, source_address="here.loc")
# Python2.5
mockhttplib = Mock.Omnivore(HTTPConnection=[None])
context = dict(
PYTHON2_6=False,
PYTHON2_7=False,
httplib=mockhttplib,
)
with injected(http._getconnection, **context):
http._getconnection()
call_log = mockhttplib.called["HTTPConnection"][0][1]
self.assertFalse(call_log["strict"])
self.assertEqual(call_log.get("timeout"), None)
self.assertEqual(call_log.get("source_address"), None)
# Python2.6
mockhttplib = Mock.Omnivore(HTTPConnection=[None])
context = dict(
PYTHON2_6=True,
PYTHON2_7=False,
httplib=mockhttplib,
)
with injected(http._getconnection, **context):
http._getconnection()
call_log = mockhttplib.called["HTTPConnection"][0][1]
self.assertFalse(call_log["strict"])
self.assertEqual(call_log["timeout"], 300)
self.assertEqual(call_log.get("source_address"), None)
# Python2.7
mockhttplib = Mock.Omnivore(HTTPConnection=[None])
context = dict(
PYTHON2_6=True,
PYTHON2_7=True,
httplib=mockhttplib,
)
with injected(http._getconnection, **context):
http._getconnection()
call_log = mockhttplib.called["HTTPConnection"][0][1]
self.assertFalse(call_log["strict"])
self.assertEqual(call_log["timeout"], 300)
self.assertEqual(call_log.get("source_address"), "here.loc")
def test_request(self):
"""Test HTTPClient._request."""
headers = {"X-Test": "Hello"}
resp = self.http._request("POST", "/foo", "my content", headers)
self.assertEqual(resp, 200)
# relative path to absolute path
resp = self.http._request("POST", "foo", "my content", headers)
self.assertTrue(self.con.path.startswith("/"))
self.assertEqual(resp, 200)
# cookies
self.http.cookie = Mock.Omnivore()
resp = self.http._request("POST", "/foo", "my content", headers)
self.assertTrue("add_cookie_header" in self.http.cookie.called)
# errors
self.con.response.status = 400
self.assertRaises(HTTPUserError, self.http._request, "POST", "/foo")
self.con.response.status = 500
self.assertRaises(HTTPServerError, self.http._request, "POST", "/foo")
def test_setcookie(self):
"""Test HTTPClient.setcookie."""
self.http.setcookie(CookieJar())
self.assertTrue(isinstance(self.http.cookie, CookieJar))
def test_setssl(self):
"""Test HTTPClient.setssl."""
# set nothing
self.http.setssl(None, None)
self.assertEqual(self.http.protocol, "http")
self.assertEqual(self.http.key_file, None)
self.assertEqual(self.http.cert_file, None)
# set key file only
self.http.setssl("Foo", None)
self.assertEqual(self.http.protocol, "https")
self.assertEqual(self.http.key_file, "Foo")
self.assertEqual(self.http.cert_file, None)
self.http.protocol = "http"
self.http.key_file = None
# set cert file only
self.http.setssl(None, "Foo")
self.assertEqual(self.http.protocol, "https")
self.assertEqual(self.http.key_file, None)
self.assertEqual(self.http.cert_file, "Foo")
self.http.protocol = "http"
self.http.key_file = None
# set key file and cert file
self.http.setssl("Foo", "Bar")
self.assertEqual(self.http.protocol, "https")
self.assertEqual(self.http.key_file, "Foo")
self.assertEqual(self.http.cert_file, "Bar")
def test_prepare(self):
"""Test HTTPClient._prepare."""
headers = {"X-Test": "Hello", "X-Test-2": "Umlaut ä"}
query = {"foo": "bär"}
http = HTTPClient("127.0.0.1", 80)
http.setbasicauth("me", "secret")
(uri, headers) = http._prepare("/foo bar/baz", headers, query)
self.assertEqual(uri, "/foo%20bar/baz?foo=b%C3%A4r")
expect = {
'Authorization': 'Basic bWU6c2VjcmV0',
'X-Test': 'Hello',
'X-Test-2': '=?utf-8?b?VW1sYXV0IMOk?=',
}
self.assertEqual(headers, expect)
def test_get(self):
"""Test HTTPClient.get."""
# prepare mock connection
self.con.response.status = 200
query = {"path": "/foo/bar"}
self.assertEqual(self.http.get("/index", None, query=query), 200)
self.assertEqual(self.con.method, "GET")
self.assertEqual(self.con.path, "/index?path=%2Ffoo%2Fbar")
self.assertTrue(self.con.closed)
def test_post(self):
"""Test HTTPClient.post."""
data = StringIO("Test data")
# prepare mock connection
self.con.response.status = 200
query = {"path": "/foo/bar"}
self.assertEqual(self.http.post("/index", None, query=query), 200)
self.assertEqual(self.con.method, "POST")
self.assertEqual(self.con.path, "/index?path=%2Ffoo%2Fbar")
self.assertTrue(self.con.closed)
def test_post_py25(self):
"""Test HTTPClient.post with Python 2.5."""
data = StringIO("Test data")
# prepare mock connection
self.con.response.status = 200
query = {"path": "/foo/bar"}
with injected(self.http.post, PYTHON2_6=False):
self.assertEqual(self.http.post("/index", data), 200)
self.assertEqual(self.con.method, "POST")
self.assertEqual(self.con.path, "/index")
self.assertTrue(self.con.closed)
def test_post_content_none(self):
"""Test HTTPClient.post with None as content."""
# prepare mock connection
self.con.response.status = 200
query = {"path": "/foo/bar"}
self.assertEqual(self.http.post("/index", None, query=query), 200)
self.assertEqual(self.con.method, "POST")
self.assertEqual(self.con.path, "/index?path=%2Ffoo%2Fbar")
self.assertTrue(self.con.closed)
def test_post_no_query(self):
"""Test HTTPClient.post without query string."""
data = StringIO("Test data")
# prepare mock connection
self.con.response.status = 200
self.assertEqual(self.http.post("/index", data), 200)
self.assertEqual(self.con.method, "POST")
self.assertEqual(self.con.path, "/index")
self.assertTrue(self.con.closed)
def test_post_form_data(self):
"""Test HTTPClient.post form-data."""
data = dict(a="foo", b="bar")
def urlencode(data):
urlencode.count += 1
return urllib.urlencode(data)
urlencode.count = 0
# prepare mock connection
mockurllib = Mock.Omnivore()
mockurllib.quote = urllib.quote
mockurllib.urlencode = urlencode
context = dict(
urllib_quote=mockurllib.quote,
urllib_urlencode=mockurllib.urlencode,
)
with injected(self.http.post, **context):
resp = self.http.post("/index", data)
self.assertEqual(urlencode.count, 1)
self.assertEqual(resp, 200)
def test_post_multipart(self):
"""Test HTTPClient.post multipart/form-data."""
data = dict(a="foo", b="bar")
resp = self.http.post("/index", data, as_multipart=True)
self.assertEqual(resp, 200)
self.assertEqual(self.con.method, "POST")
self.assertEqual(self.con.path, "/index")
self.assertTrue(self.con.closed)
def test_options(self):
"""Test HTTPClient.options."""
self.con.response.status = 200
self.assertEqual(self.http.options("/index"), 200)
self.assertEqual(self.con.method, "OPTIONS")
self.assertEqual(self.con.path, "/index")
self.assertTrue(self.con.closed)
def test_head(self):
"""Test HTTPClient.head."""
self.con.response.status = 200
self.assertEqual(self.http.head("/index"), 200)
self.assertEqual(self.con.method, "HEAD")
self.assertEqual(self.con.path, "/index")
self.assertTrue(self.con.closed)
def test_delete(self):
"""Test HTTPClient.delete."""
self.con.response.status = 200
self.assertEqual(self.http.delete("/index"), 200)
self.assertEqual(self.con.method, "DELETE")
self.assertEqual(self.con.path, "/index")
self.assertTrue(self.con.closed)
def test_trace(self):
"""Test HTTPClient.trace."""
self.con.response.status = 200
self.assertEqual(self.http.trace("/index"), 200)
self.assertEqual(self.con.method, "TRACE")
self.assertEqual(self.con.path, "/index")
self.assertTrue(self.con.closed)
def test_trace_maxforwards_via(self):
"""Test HTTPClient.trace with given maxforwards and via."""
self.con.response.status = 200
self.assertEqual(self.http.trace("/index", 5, ["a", "b"]), 200)
self.assertEqual(self.con.method, "TRACE")
self.assertEqual(self.con.path, "/index")
self.assertEqual(self.con.headers.get("Max-Forwards"), "5")
self.assertEqual(self.con.headers.get("Via"), "a, b")
self.assertTrue(self.con.closed)
def test_connect(self):
"""Test HTTPClient.connect."""
self.con.response.status = 200
self.assertEqual(self.http.connect("/"), 200)
self.assertEqual(self.con.method, "CONNECT")
self.assertEqual(self.con.path, "/")
self.assertTrue(self.con.closed)
class CoreWebDAVClientTestCase(unittest.TestCase):
"""Test the CoreWebDAVClient class."""
def setUp(self):
"""Setup the client."""
self.dav = CoreWebDAVClient("127.0.0.1", 80)
self.dav.setbasicauth("test", "passwd")
self.con = Mock.HTTPConnection()
self.dav._getconnection = lambda: self.con
response = Mock.Response()
response.content = LOCKDISCOVERY
response.status = 200
self.lock = WebDAVLockResponse(self.dav, "/", response)
def test_preparecopymove(self):
"""Test CoreWebDAVClient._preparecopymove."""
source = "/foo bar/baz"
dest = "/dest/in/ation"
headers = {"X-Test": "Hello", "X-Test-2": "Umlaut ä"}
query = {"foo": "bär"}
http = CoreWebDAVClient("127.0.0.1", 80)
http.setbasicauth("me", "secret")
(source, headers) = http._preparecopymove(source, dest, 0,
False, headers)
self.assertEqual(source, "/foo%20bar/baz")
exp_headers = {
"Destination": "http://127.0.0.1:80/dest/in/ation",
"Overwrite": "F",
"Authorization": "Basic bWU6c2VjcmV0",
"X-Test": "Hello",
"X-Test-2": "=?utf-8?b?VW1sYXV0IMOk?=",
}
self.assertEqual(headers, exp_headers)
def test_preparecopymove_col(self):
"""Test CoreWebDAVClient._preparecopymove with collection as source."""
source = "/foo bar/baz/"
dest = "/dest/in/ation"
headers = {"X-Test": "Hello", "X-Test-2": "Umlaut ä"}
query = {"foo": "bär"}
http = CoreWebDAVClient("127.0.0.1", 80)
http.setbasicauth("me", "secret")
(source, headers) = http._preparecopymove(source, dest, 0,
True, headers)
self.assertEqual(source, "/foo%20bar/baz/")
exp_headers = {
"Destination": "http://127.0.0.1:80/dest/in/ation",
"Depth": "0",
"Overwrite": "T",
"Authorization": "Basic bWU6c2VjcmV0",
"X-Test": "Hello",
"X-Test-2": "=?utf-8?b?VW1sYXV0IMOk?=",
}
self.assertEqual(headers, exp_headers)
def test_preparecopymove_illegal_depth(self):
"""Test CoreWebDAVClient._preparecopymove with illegal depth value."""
source = "/foo bar/baz"
dest = "/dest/in/ation"
headers = {"X-Test": "Hello"}
query = {"foo": "bär"}
http = CoreWebDAVClient("127.0.0.1", 80)
http.setbasicauth("me", "secret")
self.assertRaises(
ValueError,
http._preparecopymove,
source, dest, "1", False, headers
)
def test_mkcol(self):
"""Test CoreWebDAVClient.mkcol."""
# prepare mock connection
self.con.response.status = 201
self.assertEqual(self.dav.mkcol("/foobar"), 201)
self.assertEqual(self.con.method, "MKCOL")
self.assertEqual(self.con.path, "/foobar")
self.assertTrue(self.con.closed)
self.assertTrue("Authorization" in self.con.headers)
def test_propfind(self):
"""Test CoreWebDAVClient.propfind."""
# prepare mock connection
self.con.response.status = 207
self.con.response.content = MULTISTATUS
self.assertEqual(self.dav.propfind("/foobar"), 207)
self.assertEqual(self.con.method, "PROPFIND")
self.assertEqual(self.con.path, "/foobar")
self.assertEqual(self.con.headers["Depth"], "0")
self.assertTrue(self.con.closed)
self.assertTrue("Authorization" in self.con.headers)
def test_propfind_depth_1(self):
"""Test CoreWebDAVClient.propfind with depth 1."""
# prepare mock connection
self.con.response.status = 207
self.con.response.content = MULTISTATUS
self.assertEqual(self.dav.propfind("/foobar", "1"), 207)
self.assertEqual(self.con.method, "PROPFIND")
self.assertEqual(self.con.path, "/foobar")
self.assertEqual(self.con.headers["Depth"], "1")
self.assertTrue(self.con.closed)
self.assertTrue("Authorization" in self.con.headers)
def test_propfind_illegal_depth(self):
"""Test CoreWebDAVClient.propfind with illegal depth."""
# prepare mock connection
self.assertRaises(ValueError, self.dav.propfind, "/foobar", "ABC")
def test_propfind_illegal_args(self):
"""Test CoreWebDAVClient.propfind with illegal args."""
# prepare mock connection
self.assertRaises(ValueError,
self.dav.propfind, "/foobar", 1,
properties=["foo"], include=["bar"])
def test_put(self):
"""Test CoreWebDAVClient.put."""
# prepare mock connection
self.con.response.status = 201
self.con.response.content = "Test content."
self.assertEqual(self.dav.put("/foobar", self.con.response), 201)
self.assertEqual(self.con.method, "PUT")
self.assertEqual(self.con.path, "/foobar")
if PYTHONVERSION == (2, 5):
self.assertEqual(self.con.body, "Test content.")
else:
self.assertEqual(self.con.body, self.con.response)
self.assertTrue(self.con.closed)
self.assertTrue("Authorization" in self.con.headers)
def test_proppatch(self):
"""Test CoreWebDAVClient.proppatch."""
self.con.response.status = 207
self.con.response.content = MULTISTATUS
props = {"CADN:author": "me", "CADN:created": "2009-09-09 13:31"}
ns = {"CADN": "CADN:"}
self.assertEqual(207, self.dav.proppatch("/foobar", props, None, ns))
def test_proppatch_noprops(self):
"""Test CoreWebDAVClient.proppatch with no defined properties."""
ns = {"CADN": "CADN:"}
self.assertRaises(ValueError,
self.dav.proppatch, "/foobar", None, None, ns)
def test_delete(self):
"""Test CoreWebDAVClient.delete."""
self.con.response.status = 200
self.assertEqual(200, self.dav.delete("/foobar", None))
def test_delete_collection(self):
"""Test CoreWebDAVClient.delete on collection."""
self.con.response.status = 200
self.assertEqual(200, self.dav.delete("/foobar/", None))
def test_copy(self):
"""Test CoreWebDAVClient.copy."""
self.con.response.status = 200
source = "/foo bar/baz"
dest = "/dest/in/ation"
headers = {"X-Test": "Hello"}
resp = self.dav.copy(source, dest, 0, False, headers)
self.assertEqual(resp, 200)
def test_move(self):
"""Test CoreWebDAVClient.move."""
self.con.response.status = 200
source = "/foo bar/baz"
dest = "/dest/in/ation"
headers = {"X-Test": "Hello"}
resp = self.dav.move(source, dest, 0, False, headers)
self.assertEqual(resp, 200)
def test_move_collection_illegal_depth(self):
"""Test CoreWebDAVClient.move on collections with illegal depth."""
self.con.response.status = 200
source = "/foo bar/baz/"
dest = "/dest/in/ation"
headers = {"X-Test": "Hello"}
self.assertRaises(
ValueError,
self.dav.move,
source, dest, 0
)
def test_lock(self):
"""Test CoreWebDAVClient.lock."""
self.con.response.status = 200
resp = self.dav.lock("/foo")
self.assertTrue(isinstance(resp, WebDAVLockResponse))
self.assertEqual(resp, 200)
def test_lock_timeout(self):
"""Test CoreWebDAVClient.lock with timeout."""
self.con.response.status = 200
resp = self.dav.lock("/foo", timeout=12345)
self.assertEqual(resp, 200)
def test_lock_timeout_inf(self):
"""Test CoreWebDAVClient.lock with infinite timeout."""
self.con.response.status = 200
resp = self.dav.lock("/foo", timeout="infinite")
self.assertEqual(resp, 200)
def test_lock_timeout_toolong(self):
"""Test CoreWebDAVClient.lock with too long timeout."""
self.assertRaises(
ValueError,
self.dav.lock,
"/foo",
timeout=4294967296
)
def test_lock_timeout_err(self):
"""Test CoreWebDAVClient.lock with wrong timeout."""
self.assertRaises(
ValueError,
self.dav.lock,
"/foo",
timeout="abc"
)
def test_lock_depth(self):
"""Test CoreWebDAVClient.lock with given depth."""
self.con.response.status = 200
resp = self.dav.lock("/foo", depth=0)
self.assertEqual(resp, 200)
self.assertEqual(self.con.headers["Depth"], "0")
def test_lock_illegaldepth(self):
"""Test CoreWebDAVClient.lock with given illegal depth."""
self.assertRaises(
ValueError,
self.dav.lock,
"/foo",
depth=1
)
def test_unlock_lock(self):
"""Test CoreWebDAVClient.unlock with lock object."""
self.dav.locks[self.lock._tag] = self.lock
self.con.response.status = 204
resp = self.dav.unlock(self.lock)
self.assertEqual(self.con.method, "UNLOCK")
self.assertEqual(self.con.headers["Lock-Token"],
"<%s>" % self.lock.locktokens[0])
self.assertTrue(self.lock._tag not in self.dav.locks)
def test_unlock_uri(self):
"""Test CoreWebDAVClient.unlock with uri."""
self.dav.locks[self.lock._tag] = self.lock
self.con.response.status = 204
resp = self.dav.unlock("/")
self.assertEqual(self.con.method, "UNLOCK")
self.assertEqual(self.con.headers["Lock-Token"],
"<%s>" % self.lock.locktokens[0])
self.assertTrue(self.lock._tag not in self.dav.locks)
def test_unlock_uri_no_token(self):
"""Test CoreWebDAVClient.unlock with uri."""
self.con.response.status = 204
self.assertRaises(ValueError, self.dav.unlock, "/")
def test_unlock_lock_no_token(self):
"""Test CoreWebDAVClient.unlock with lock object and no token."""
self.con.response.status = 204
resp = self.dav.unlock(self.lock)
self.assertEqual(self.con.method, "UNLOCK")
self.assertEqual(self.con.headers["Lock-Token"],
"<%s>" % self.lock.locktokens[0])
self.assertTrue(self.lock._tag not in self.dav.locks)
class ExtendedWebDAVClientTestCase(unittest.TestCase):
"""Test the ExtendedWebDAVClient class."""
def setUp(self):
"""Setup the client."""
self.dav = ExtendedWebDAVClient("127.0.0.1", 80)
self.dav.setbasicauth("test", "passwd")
self.con = Mock.HTTPConnection()
self.dav._getconnection = lambda: self.con
def test_report(self):
"""Test ExtendedWebDAVClient.report."""
self.con.response.status = 207
self.con.response.content = REPORT
props = ["version-name", "creator-displayname", "successor-set"]
response = self.dav.report("/foo.html", properties=props)
self.assertEqual(response, 207)
self.assertEqual(self.con.method, "REPORT")
self.assertEqual(self.con.path, "/foo.html")
self.assertEqual(self.con.headers["Depth"], "0")
self.assertTrue(self.con.closed)
self.assertTrue("Authorization" in self.con.headers)
def test_report_depth_1(self):
"""Test ExtendedWebDAVClient.report with depth 1."""
self.con.response.status = 207
self.con.response.content = REPORT
props = ["version-name", "creator-displayname", "successor-set"]
response = self.dav.report("/foo.html", "1", props)
self.assertEqual(response, 207)
self.assertEqual(self.con.method, "REPORT")
self.assertEqual(self.con.path, "/foo.html")
self.assertEqual(self.con.headers["Depth"], "1")
self.assertTrue(self.con.closed)
self.assertTrue("Authorization" in self.con.headers)
def test_report_illegal_depth(self):
"""Test ExtendedWebDAVClient.report with illegal depth."""
# prepare mock connection
self.assertRaises(ValueError, self.dav.report, "/foo.html", "ABC")
class HTTPResponseTestCase(unittest.TestCase):
"""Test HTTPResponse class."""
def setUp(self):
"""Initialize the tests."""
self.response = Mock.Response()
self.response.status = 207
self.response.content = MULTISTATUS
self.httpresponse = HTTPResponse(self.response)
# 401
self.response = Mock.Response()
digest = 'Digest realm="restricted" domain="foo.de" nonce="abcd1234"'\
'opaque="qwer4321" stale=false algorithm="MD5"'
self.response.headers["www-authenticate"] = digest
self.response.status = 401
self.response.content = ""
self.httpresponse401 = HTTPResponse(self.response)
def test_init(self):
"""Test Initializing the HTTPResponse."""
self.assertEqual(self.httpresponse.content, MULTISTATUS)
self.assertEqual(self.httpresponse.statusline,
"HTTP/1.1 207 The reason")
self.assertEqual(self.httpresponse401.content, "")
self.assertEqual(self.httpresponse401.statusline,
"HTTP/1.1 401 The reason")
self.assertEqual(self.httpresponse401.schema, "Digest")
self.assertEqual(self.httpresponse401.realm, "restricted")
self.assertEqual(self.httpresponse401.domain, "foo.de")
self.assertEqual(self.httpresponse401.nonce, "abcd1234")
self.assertEqual(self.httpresponse401.opaque, "qwer4321")
self.assertFalse(self.httpresponse401.stale)
self.assertEqual(self.httpresponse401.algorithm, hashlib.md5)
def test_str(self):
"""Test HTTPResponse.__str__."""
self.assertEqual(str(self.httpresponse), "HTTP/1.1 207 The reason")
self.assertEqual(str(self.httpresponse401), "HTTP/1.1 401 The reason")
def test_repr(self):
"""Test HTTPResponse.__repr__."""
self.assertEqual(repr(self.httpresponse), "<HTTPResponse: 207>")
self.assertEqual(repr(self.httpresponse401), "<HTTPResponse: 401>")
def test_status(self):
"""Test HTTPResponse.status property."""
self.assertEqual(self.httpresponse, 207)
self.assertEqual(self.httpresponse401, 401)
class WebDAVResponseTestCase(unittest.TestCase):
"""Test the WebDAVResponse class."""
def test_init(self):
"""Test initializing the WebDAVResponse."""
response = Mock.Response()
response.content = MULTISTATUS
# no parsing
response.status = 200
davresponse = WebDAVResponse(response)
self.assertFalse(bool(davresponse._etree.getroot()))
# parsing
response.status = 207
davresponse = WebDAVResponse(response)
self.assertTrue(bool(davresponse._etree.getroot()))
# broken xml
response.status = 207
response.content = MULTISTATUS_BROKEN
davresponse = WebDAVResponse(response)
self.assertTrue(bool(davresponse._etree.getroot()))
self.assertTrue(isinstance(davresponse.parse_error, ParseError))
def test_len(self):
"""Test WebDAVResponse.__len__."""
response = Mock.Response()
response.content = MULTISTATUS
response.status = 200
davresponse = WebDAVResponse(response)
self.assertEqual(len(davresponse), 1)
def test_len_207(self):
"""Test WebDAVResponse.__len__ in Multi-Status."""
response = Mock.Response()
response.content = MULTISTATUS
response.status = 207
davresponse = WebDAVResponse(response)
self.assertEqual(len(davresponse), 1)
def test_iter(self):
"""Test WebDAVResponse.__iter__."""
response = Mock.Response()
response.content = MULTISTATUS
response.status = 200
davresponse = WebDAVResponse(response)
self.assertTrue(isinstance(list(davresponse)[0], WebDAVResponse))
def test_iter_207(self):
"""Test WebDAVResponse.__iter__ in Multi-Status."""
response = Mock.Response()
response.content = MULTISTATUS
response.status = 207
davresponse = WebDAVResponse(response)
self.assertEqual(list(davresponse)[0], 200)
def test_parse_xml_content(self):
"""Test WebDAVResponse._parse_xml_content."""
response = Mock.Response()
response.content = MULTISTATUS
response.status = 207
with replaced(WebDAVResponse, _parse_xml_content=Mock.omnivore_func()):
davresponse = WebDAVResponse(response)
davresponse._parse_xml_content()
href = davresponse._etree.findtext("/{DAV:}response/{DAV:}href")
self.assertEquals(href, "/3/38/38f/38fa476aa97a4b2baeb41a481fdca00b")
def test_parse_xml_content_broken(self):
"""Test WebDAVResponse._parse_xml_content with broken XML."""
response = Mock.Response()
response.content = MULTISTATUS_BROKEN
response.status = 207
with replaced(WebDAVResponse, _parse_xml_content=Mock.omnivore_func()):
davresponse = WebDAVResponse(response)
davresponse._parse_xml_content()
empty = davresponse._etree.getroot().getchildren()[0]
self.assertEquals(empty.tag, "empty")
def test_set_multistatus(self):
"""Test WebDAVResponse._set_multistatus."""
response = Mock.Response()
response.content = MULTISTATUS
response.status = 200
davresponse = WebDAVResponse(response)
mockparser = Mock.Omnivore()
with replaced(davresponse, _parse_xml_content=mockparser):
self.assertFalse(davresponse.is_multistatus)
self.assertEquals(len(mockparser.called["__call__"]), 0)
davresponse._set_multistatus()
self.assertTrue(davresponse.is_multistatus)
self.assertEquals(len(mockparser.called["__call__"]), 1)
class WebDAVLockResponseTestCase(unittest.TestCase):
"""Test the WebDAVLockResponse class."""
def setUp(self):
"""Setup the tests"""
self.client = CoreWebDAVClient("localhost")
response = Mock.Response()
response.content = LOCKDISCOVERY
response.status = 200
self.lock = WebDAVLockResponse(self.client, "/", response)
def test_init_200(self):
"""Test WebDAVLockResponse.__init__ with 200 status."""
lock = self.lock
self.assertEqual(lock.lockscope.tag, "{DAV:}exclusive")
self.assertEqual(lock.locktype.tag, "{DAV:}write")
self.assertEqual(lock.depth, "Infinity")
href = "http://localhost/me.html"
self.assertEqual(lock.owner.findtext("{DAV:}href").strip(), href)
self.assertEqual(lock.timeout, "Second-604800")
token = "opaquelocktoken:e71d4fae-5dec-22d6-fea5-00a0c91e6be4"
self.assertEqual(lock.locktokens[0], token)
def test_init_409(self):
"""Test WebDAVLockResponse.__init__ with 409 status."""
client = CoreWebDAVClient("localhost")
response = Mock.Response()
response.content = MULTISTATUS
response.status = 409
lock = WebDAVLockResponse(client, "/", response)
self.assertTrue(lock._etree.find("/{DAV:}response") is not None)
self.assertTrue(lock.is_multistatus)
def test_repr(self):
"""Test WebDAVLockResponse.__repr__."""
lrepr = "<WebDAVLockResponse: <%s> 200>" % self.lock._tag
self.assertEqual(repr(self.lock), lrepr)
def test_call(self):
"""Test WebDAVLockResponse.__call__."""
self.assertTrue(self.lock._tagged)
self.lock(False)
self.assertFalse(self.lock._tagged)
self.lock()
self.assertTrue(self.lock._tagged)
self.lock(False)
self.lock(True)
self.assertTrue(self.lock._tagged)
def test_contextmanager(self):
"""Test contextmanager on WebDAVLockResponse."""
self.client.headers["If"] = "My previous if"
# tagged
with self.lock:
expect = "<http://localhost:80/> "\
"(<opaquelocktoken:e71d4fae-5dec-22d6-fea5-00a0c91e6be4>)"
if_header = self.client.headers["If"]
self.assertEqual(expect, if_header)
self.assertEqual("My previous if", self.client.headers["If"])
# untagged
with self.lock(False):
expect = "(<opaquelocktoken:e71d4fae-5dec-22d6-fea5-00a0c91e6be4>)"
if_header = self.client.headers["If"]
self.assertEqual(expect, if_header)
self.assertEqual("My previous if", self.client.headers["If"])
# untagged, no previous if header
del self.client.headers["If"]
with self.lock(False):
expect = "(<opaquelocktoken:e71d4fae-5dec-22d6-fea5-00a0c91e6be4>)"
if_header = self.client.headers["If"]
self.assertEqual(expect, if_header)
self.assertTrue("If" not in self.client.headers)
class MultiStatusResponseTestCase(unittest.TestCase):
"""Test the MultiStatusResponse class."""
def setUp(self):
self.etree = ElementTree()
self.etree.parse(StringIO(RESPONSE))
self.msr = MultiStatusResponse(self.etree.getroot())
def test_init(self):
"""Test initializing the MultiStatusResponse."""
self.assertEqual(self.msr, 200)
def test_repr(self):
"""Test MultiStatusResponse.__repr__."""
self.assertEqual(repr(self.msr), "<MultiStatusResponse: 200>")
def test_getitem(self):
"""Test MultiStatusResponse.__getitem__."""
self.assertEqual(self.msr["getetag"].text, "6ca7-364-475e65375ce80")
self.assertEqual(self.msr["{DC:}author"].text, "Me")
self.assertRaises(KeyError, lambda: self.msr['non-existant'])
def test_keys(self):
"""Test MultiStatusResponse.keys."""
expect = ['getetag', '{DC:}created', '{DC:}resource', '{DC:}author']
expect.sort()
keys = self.msr.keys()
keys.sort()
self.assertEqual(keys, expect)
def test_iter(self):
"""Test MultiStatusResponse.__iter__."""
expect = ['getetag', '{DC:}created', '{DC:}resource', '{DC:}author']
expect.sort()
keys = list(self.msr)
keys.sort()
self.assertEqual(keys, expect)
def test_iterkeys(self):
"""Test MultiStatusResponse.iterkeys."""
expect = ['getetag', '{DC:}created', '{DC:}resource', '{DC:}author']
expect.sort()
keys = list(self.msr.iterkeys())
keys.sort()
self.assertEqual(keys, expect)
def test_items(self):
"""Test MultiStatusResponse.items."""
expect = [('getetag', '6ca7-364-475e65375ce80'),
('{DC:}created', None),
('{DC:}resource', None),
('{DC:}author', 'Me')]
expect.sort()
items = list((k, v.text) for (k, v) in self.msr.items())
items.sort()
self.assertEqual(items, expect)
def test_iteritems(self):
"""Test MultiStatusResponse.iteritems."""
expect = [('getetag', '6ca7-364-475e65375ce80'),
('{DC:}created', None),
('{DC:}resource', None),
('{DC:}author', 'Me')]
expect.sort()
items = list((k, v.text) for (k, v) in self.msr.iteritems())
items.sort()
self.assertEqual(items, expect)
def test_get(self):
"""Test MultiStatusResponse.get."""
self.assertEqual(self.msr.get("{DC:}author").text, "Me")
self.assertEqual(self.msr.get("author", namespace="DC:").text, "Me")
self.assertEqual(self.msr.get("non-existant", "You"), "You")
def test_statusline(self):
"""Test MultiStatusResponse.statusline property."""
self.assertEqual(self.msr.statusline, "HTTP/1.1 200 OK")
def test_href(self):
"""Test MultiStatusResponse.href property."""
self.assertEqual(self.msr.href,
"/3/38/38f/38fa476aa97a4b2baeb41a481fdca00b")
def test_namespaces(self):
"""Test MultiStatusResponse.namespaces property."""
expect = set(["DC:", "DAV:"])
self.msr.iterkeys = lambda b: ["foo", "bar", "{DC:}x", "{DAV:}y"]
self.assertEqual(self.msr.namespaces, expect)
| Python |
# Unittests for creator module.
# Copyright (C) 2009 Manuel Hermann <manuel-hermann@gmx.net>
#
# This file is part of tinydav.
#
# tinydav 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 of the License, 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
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Unittests for creator module."""
from xml.etree.ElementTree import Element
import sys
import unittest
from tinydav import creator
PYTHONVERSION = sys.version_info[:2] # (2, 5) or (2, 6)
class TestAddNamespaces(unittest.TestCase):
"""Test creator._addnamespaces."""
def test_addnamespaces(self):
"""Test creator._addnamespaces."""
namespaces = {"a": "ABC:", "b": "XXX:"}
element = Element("foo")
creator._addnamespaces(element, namespaces)
expect = {"xmlns:b": "XXX:", "xmlns:a": "ABC:"}
self.assertEqual(element.attrib, expect)
class TestCreatePropFind(unittest.TestCase):
"""Test creator.create_propfind function."""
def test_create_propfind(self):
"""Test WebDAVClient._create_propfind."""
# allprops
xml = creator.create_propfind(False, None, None, None)
self.assertEqual(xml, "<?xml version='1.0' encoding='UTF-8'?>\n"
'<propfind xmlns="DAV:"><allprop /></propfind>')
# names only
xml = creator.create_propfind(True, None, None, None)
self.assertEqual(xml, "<?xml version='1.0' encoding='UTF-8'?>\n"
'<propfind xmlns="DAV:"><propname /></propfind>')
# properties
xml = creator.create_propfind(False, ["{DC:}author"], None, None)
if PYTHONVERSION >= (2, 7):
self.assertEqual(xml, "<?xml version='1.0' encoding='UTF-8'?>\n"
'<propfind xmlns:ns0="DC:" '
'xmlns="DAV:"><prop>'
'<ns0:author /></prop>'
'</propfind>')
else:
self.assertEqual(xml, "<?xml version='1.0' encoding='UTF-8'?>\n"
'<propfind xmlns="DAV:"><prop>'
'<ns0:author xmlns:ns0="DC:" /></prop>'
'</propfind>')
# include
xml = creator.create_propfind(False, None,
["supported-report-set"], None)
self.assertEqual(xml, "<?xml version='1.0' encoding='UTF-8'?>\n"
'<propfind xmlns="DAV:"><allprop />'
'<include><supported-report-set /></include>'
'</propfind>')
class TestCreatePropPatch(unittest.TestCase):
"""Test creator.create_proppatch function."""
def test_create_proppatch_set(self):
"""Test WebDAVClient._create_proppatch: set property"""
# set only
setprops = {"CADN:author": "me", "CADN:created": "2009-09-09 13:31"}
ns = {"CADN": "CADN:"}
xml = creator.create_proppatch(setprops, None, ns)
self.assertEqual(xml, "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n"
'<propertyupdate xmlns="DAV:" xmlns:CADN="CADN:">'
'<set>'
'<prop>'
'<CADN:created>2009-09-09 13:31'
'<CADN:author>me</CADN:author>'
'</CADN:created>'
'</prop>'
'</set>'
'</propertyupdate>')
def test_create_proppatch_remove(self):
"""Test WebDAVClient._create_proppatch: remove property"""
# remove only
delprops = ["DEL:xxx"]
ns = {"DEL": "DEL:"}
xml = creator.create_proppatch(None, delprops, ns)
self.assertEqual(xml, "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n"
'<propertyupdate xmlns="DAV:" xmlns:DEL="DEL:">'
'<remove>'
'<prop><DEL:xxx /></prop>'
'</remove>'
'</propertyupdate>')
def test_create_proppatch_setremove(self):
"""Test WebDAVClient._create_proppatch: set and remove property"""
# set and del
setprops = {"CADN:author": "me", "CADN:created": "2009-09-09 13:31"}
delprops = ["DEL:xxx"]
ns = {"CADN": "CADN:", "DEL": "DEL:"}
xml = creator.create_proppatch(setprops, delprops, ns)
self.assertEqual(xml, "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n"
'<propertyupdate xmlns="DAV:" xmlns:CADN="CADN:"'
' xmlns:DEL="DEL:">'
'<set>'
'<prop>'
'<CADN:created>2009-09-09 13:31'
'<CADN:author>me</CADN:author>'
'</CADN:created>'
'</prop>'
'</set>'
'<remove>'
'<prop><DEL:xxx /></prop>'
'</remove>'
'</propertyupdate>')
class TestCreateLock(unittest.TestCase):
"""Test creator.create_lock function."""
def test_create_lock(self):
"""Test creator.create_lock."""
xml = creator.create_lock()
self.assertEqual(xml, '<lockinfo xmlns="DAV:"><lockscope>'
'<exclusive /></lockscope><locktype><write />'
'</locktype></lockinfo>')
def test_create_illegal_scope(self):
"""Test creator.create_lock with illegal scope."""
self.assertRaises(
ValueError,
creator.create_lock,
scope="everything"
)
def test_create_lock_owner(self):
"""Test creator.create_lock with given owner."""
xml = creator.create_lock(owner="me")
self.assertEqual(xml, '<lockinfo xmlns="DAV:"><lockscope><exclusive />'
'</lockscope><locktype><write /></locktype>'
'<owner>me</owner></lockinfo>')
def test_create_lock_owner_element(self):
"""Test creator.create_lock with given owner element."""
owner = Element("name")
owner.text = "me"
xml = creator.create_lock(owner=owner)
self.assertEqual(xml, '<lockinfo xmlns="DAV:"><lockscope><exclusive />'
'</lockscope><locktype><write /></locktype>'
'<owner><name>me</name></owner></lockinfo>')
class TestCreateReport(unittest.TestCase):
"""Test creator.create_report function."""
def test_create_report(self):
"""Test creator.create_report."""
# default report
xml = creator.create_report()
self.assertEqual(xml, "<?xml version='1.0' encoding='UTF-8'?>\n"
'<version-tree xmlns="DAV:" />')
# properties
xml = creator.create_report(["creator-displayname"])
self.assertEqual(xml, "<?xml version='1.0' encoding='UTF-8'?>\n"
'<version-tree xmlns="DAV:"><prop>'
'<creator-displayname />'
'</prop></version-tree>')
# additional xml
xml = creator.create_report(elements=[Element("foo", {"bar": "1"})])
self.assertEqual(xml, "<?xml version='1.0' encoding='UTF-8'?>\n"
'<version-tree xmlns="DAV:">'
'<foo bar="1" /></version-tree>')
| Python |
# Mock object for unittests.
# Copyright (C) 2009 Manuel Hermann <manuel-hermann@gmx.net>
#
# This file is part of tinydav.
#
# tinydav 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 of the License, 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
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Mock object for unittests."""
from collections import defaultdict
from contextlib import contextmanager
from email.mime.multipart import MIMEMultipart
from functools import partial
from StringIO import StringIO
import urllib2
@contextmanager
def injected(func, **kwargs):
"""Inject vars into a function or method while in context mode."""
# recognize methods
if hasattr(func, "im_func"):
func = func.im_func
# save and replace current function globals as to kwargs
func_globals = func.func_globals
saved = dict((k, func_globals[k]) for k in kwargs if k in func_globals)
func_globals.update(kwargs)
# context is now ready to be used
yield
# restore previous state
func_globals.update(saved)
@contextmanager
def replaced(obj, **attrs):
"""Replace attribute in object while in context mode."""
# save and replace current attributes
saved = dict((k, getattr(obj, k)) for k in attrs)
for (name, attr) in attrs.iteritems():
setattr(obj, name, attr)
# context is ready
yield
# restore previous state
for (name, attr) in saved.iteritems():
setattr(obj, name, attr)
def omnivore_func(retval=None, exception=None):
"""Return a function accepting any number of args and act accordingly.
retval -- Returned function returns this value on call.
exception -- If not None, this will be raised by the returned function.
"""
def omnivore(*args, **kwargs):
omnivore.callcount += 1
if exception is not None:
raise exception
return retval
omnivore.callcount = 0
return omnivore
class Omnivore(object):
"""Omnivore class.
Return pre-defined values or raise predefined exceptions an any method
that may be called, including __call__.
"""
def __init__(self, **kwargs):
"""Initialize with return values.
**kwargs -- Key is the method name, value is the returned value. If
the value is an instance of Exception, it will be raised.
"""
self.__name__ = "Omnivore"
self.retvals = dict()
for (key, value) in kwargs.iteritems():
self.retvals[key] = iter(value)
self.called = defaultdict(list)
def __enter__(self):
self.called["__enter__"] = True
return self
def __exit__(exctype, excvalue, exctb):
self.called["__exit__"] = (exctype, excvalue, exctb)
def method(self, methodname, *args, **kwargs):
self.called[methodname].append((args, kwargs))
generator = self.retvals.get(methodname)
if generator is None:
return None
value = generator.next()
if isinstance(value, Exception):
raise value
return value
def __getattr__(self, name):
return partial(self.method, name)
def __call__(self, *args, **kwargs):
return self.method("__call__", *args, **kwargs)
class FakeMIMEMultipart(object):
"""Subclass of MIMEMultipart."""
def __init__(self, boundary="foobar"):
self.boundary = boundary
def __call__(self, subtype):
boundary = self.boundary
if subtype == "mixed":
boundary += "-mixed"
return MIMEMultipart(subtype, boundary)
class HTTPConnection(object):
"""Mock httplib.HTTPConnection object."""
def __init__(self):
# input
self.method = None
self.path = None
self.body = None
self.headers = None
# output
self.response = Response()
self.closed = False
def request(self, method, path, body=None, headers=None):
self.method = method
self.path = path
self.body = body
self.headers = headers
def __enter__(self):
pass
def __exit__(self, *args):
pass
def getresponse(self):
return self.response
def close(self):
self.closed = True
class ModuleProxy(object):
"""Mock module. Must be instantiated."""
def __init__(self, module):
self.__module = module
def __getattr__(self, name):
return getattr(self.__module, name)
class Response(urllib2.HTTPError):
"""Mock urllib2 response object."""
def __init__(self):
self.code = None
self.content = ""
self.version = 11
self.reason = "The reason"
self.headers = dict()
self.status = 200
def getheaders(self):
return self.headers
def read(self):
return self.content
| Python |
# Unittests for exception module.
# Copyright (C) 2009 Manuel Hermann <manuel-hermann@gmx.net>
#
# This file is part of tinydav.
#
# tinydav 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 of the License, 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
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Unittests for exception module."""
import unittest
from tinydav.exception import HTTPError
import Mock
class HTTTPErrorTestCase(unittest.TestCase):
"""Test HTTPErrro exception class."""
def setUp(self):
"""Setup the tests."""
self.response = 400
self.err = HTTPError(self.response)
def test_init(self):
"""Test initializing the HTTPError class."""
self.assertEqual(self.err.response, self.response)
def test_repr(self):
"""Test HTTPError.__repr__."""
self.assertEqual(repr(self.err), "<HTTPError: 400>")
def test_str(self):
"""Test HTTPError.__str__."""
response = Mock.Response()
response.statusline = "HTTP/1.1 400 Some error"
err = HTTPError(response)
self.assertEqual(str(err), "HTTP/1.1 400 Some error")
| Python |
# Exceptions for the tinydav WebDAV client.
# Copyright (C) 2009 Manuel Hermann <manuel-hermann@gmx.net>
#
# This file is part of tinydav.
#
# tinydav 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 of the License, 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
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Exceptions for the tinydav WebDAV client."""
class HTTPError(Exception):
"""Base exception class for HTTP errors.
response -- httplib.Response object.
method -- String with uppercase method name.
This object has the following attributes:
response -- The HTTPResponse object.
"""
def __init__(self, response):
"""Initialize the HTTPError.
response -- HTTPClient or one of its subclasses.
method -- The uppercase method name where the error occured.
This instance has the following attributes:
response -- Given HTTPClient.
"""
Exception.__init__(self)
self.response = response
def __repr__(self):
"""Return representation of an HTTPError."""
return "<%s: %d>" % (self.__class__.__name__, self.response)
def __str__(self):
"""Return string representation of an HTTPError."""
return self.response.statusline
class HTTPUserError(HTTPError):
"""Exception class for 4xx HTTP errors."""
class HTTPServerError(HTTPError):
"""Exception class for 5xx HTTP errors."""
| Python |
# Utility function for tinydav WebDAV client.
# Copyright (C) 2009 Manuel Hermann <manuel-hermann@gmx.net>
#
# This file is part of tinydav.
#
# tinydav 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 of the License, 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
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Utility functions and classes for tinydav WebDAV client."""
import sys
PYTHON2 = ((2, 5) <= sys.version_info <= (3, 0))
from email.encoders import encode_base64
from email.mime.application import MIMEApplication
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from os import path
import re
if PYTHON2:
from urlparse import urlunsplit
else:
from urllib.parse import urlunsplit
from tinydav.exception import HTTPError
__all__ = (
"FakeHTTPRequest", "make_absolute", "make_multipart",
"extract_namespace", "get_depth"
)
authparser = re.compile("""
(?P<schema>Basic|Digest)
(
\s+
(?:realm="(?P<realm>[^"]*)")?
(?:domain="(?P<domain>[^"]*)")?
(?:nonce="(?P<nonce>[^"]*)")?
(?:opaque="(?P<opaque>[^"]*)")?
(?:stale=(?P<stale>(true|false|TRUE|FALSE)))?
(?:algorithm="(?P<algorithm>\w+)")?
)+
""", re.VERBOSE)
DEFAULT_CONTENT_TYPE = "application/octet-stream"
class FakeHTTPRequest(object):
"""Fake HTTP request object needed for cookies.
See http://docs.python.org/library/cookielib.html#cookiejar-and-filecookiejar-objects
"""
def __init__(self, client, uri, headers):
"""Initialize the fake HTTP request object.
client -- HTTPClient object or one of its subclasses.
uri -- The URI to call.
headers -- Headers dict to add cookie stuff to.
"""
self._client = client
self._uri = uri
self._headers = headers
def get_full_url(self):
return make_absolute(self._client, self._uri)
def get_host(self):
return self._client.host
def is_unverifiable(self):
return False
def get_origin_req_host(self):
return self.get_host()
def get_type(self):
return self._client.protocol
def has_header(self, name):
return (name in self._headers)
def add_unredirected_header(self, key, header):
self._headers[key] = header
def make_absolute(httpclient, uri):
"""Return correct absolute URI.
httpclient -- HTTPClient instance with protocol, host and port attribute.
uri -- The destination path.
"""
netloc = "%s:%d" % (httpclient.host, httpclient.port)
parts = (httpclient.protocol, netloc, uri, None, None)
return urlunsplit(parts)
class Multipart(object):
def __init__(self, data, default_encoding="ascii", with_filenames=False):
self.data = data
self.default_encoding = default_encoding
self.with_filenames = with_filenames
self._mp = MIMEMultipart("form-data")
self._files = list()
def _create_non_file_parts(self):
items_iterator = self.data.iteritems() if PYTHON2 else self.data.items()
for (key, data) in items_iterator:
# Are there explicit encodings/content-types given?
# Note: Cannot do a (value, encoding) = value here as fileobjects
# then would get iterated, which is not what we want.
if isinstance(data, tuple) and (len(data) == 2):
(value, encoding) = data
else:
(value, encoding) = (data, None)
# collect file-like objects
if hasattr(value, "read"):
self._files.append((key, value, encoding))
# no file-like object
else:
if isinstance(value, MIMEBase):
part = value
else:
encoding = encoding if encoding else default_encoding
part = MIMEText(value, "plain", encoding)
add_disposition(part, key)
self._mp.attach(part)
def _add_disposition(self, part, name, filename=None,
disposition="form-data"):
"""Add a Content-Disposition header to the part.
part -- Part to add header to.
name -- Name of the part.
filename -- Add this filename as parameter, if given.
disposition -- Value of the content-disposition header.
"""
# RFC 2388 Returning Values from Forms: multipart/form-data
# Each part is expected to contain a content-disposition header
# [RFC 2183] where the disposition type is "form-data", and where the
# disposition contains an (additional) parameter of "name", where the
# value of that parameter is the original field name in the form.
params = dict(name=name)
if self.with_filenames and (filename is not None):
# RFC 2388 Returning Values from Forms: multipart/form-data
# The original local file name may be supplied as well, either as
# a "filename" parameter either of the "content-disposition:
# form-data" header or, in the case of multiple files, in a
# "content-disposition: file" header of the subpart.
params["filename"] = path.basename(filename)
part.add_header("Content-Disposition", disposition, **params)
def make_multipart(content, default_encoding="ascii", with_filenames=False):
"""Return the headers and content for multipart/form-data.
content -- Dict with content to POST. The dict values are expected to
be unicode or decodable with us-ascii.
default_encoding -- Send multipart with this encoding, if no special
encoding was given with the content. Default is ascii.
with_filenames -- If True, a multipart's files will be sent with the
filename paramenter set. Default is False.
"""
def add_disposition(part, name, filename=None, disposition="form-data"):
"""Add a Content-Disposition header to the part.
part -- Part to add header to.
name -- Name of the part.
filename -- Add this filename as parameter, if given.
disposition -- Value of the content-disposition header.
"""
# RFC 2388 Returning Values from Forms: multipart/form-data
# Each part is expected to contain a content-disposition header
# [RFC 2183] where the disposition type is "form-data", and where the
# disposition contains an (additional) parameter of "name", where the
# value of that parameter is the original field name in the form.
params = dict(name=name)
if with_filenames and (filename is not None):
# RFC 2388 Returning Values from Forms: multipart/form-data
# The original local file name may be supplied as well, either as
# a "filename" parameter either of the "content-disposition:
# form-data" header or, in the case of multiple files, in a
# "content-disposition: file" header of the subpart.
params["filename"] = path.basename(filename)
part.add_header("Content-Disposition", disposition, **params)
def create_part(key, fileobject, content_type, multiple=False):
"""Create and return a multipart part as to given file data.
key -- Field name.
fileobject -- The file-like object to add to the part.
content_type -- Content-type of the file. If None, use default.
multiple -- If true, use Content-Disposition: file.
"""
if not content_type:
content_type = DEFAULT_CONTENT_TYPE
(maintype, subtype) = content_type.split("/")
part = MIMEBase(maintype, subtype)
part.set_payload(fileobject.read())
encode_base64(part)
filename = getattr(fileobject, "name", None)
kwargs = dict()
if multiple:
# RFC 2388 Returning Values from Forms: multipart/form-data
# The original local file name may be supplied as well, either as
# a "filename" parameter either of the "content-disposition:
# form-data" header or, in the case of multiple files, in a
# "content-disposition: file" header of the subpart.
kwargs["disposition"] = "file"
add_disposition(part, key, filename, **kwargs)
return part
# RFC 2388 Returning Values from Forms: multipart/form-data
mime = MIMEMultipart("form-data")
files = list()
items_iterator = content.iteritems() if PYTHON2 else content.items()
for (key, data) in items_iterator:
# Are there explicit encodings/content-types given?
# Note: Cannot do a (value, encoding) = value here as fileobjects then
# would get iterated, which is not what we want.
if isinstance(data, tuple) and (len(data) == 2):
(value, encoding) = data
else:
(value, encoding) = (data, None)
# collect file-like objects
if hasattr(value, "read"):
files.append((key, value, encoding))
# no file-like object
else:
if isinstance(value, MIMEBase):
part = value
else:
encoding = encoding if encoding else default_encoding
part = MIMEText(value, "plain", encoding)
add_disposition(part, key)
mime.attach(part)
filecount = len(files)
if filecount == 1:
filedata = files[0]
part = create_part(*filedata)
mime.attach(part)
elif filecount > 1:
# RFC 2388 Returning Values from Forms: multipart/form-data
# 4.2 Sets of files
# If the value of a form field is a set of files rather than a single
# file, that value can be transferred together using the
# "multipart/mixed" format.
mixed = MIMEMultipart("mixed")
for filedata in files:
part = create_part(multiple=True, *filedata)
mixed.attach(part)
mime.attach(mixed)
# mime.items must be called after mime.as_string when the headers shall
# contain the boundary
complete_mime = mime.as_string()
headers = dict(mime.items())
# trim headers from create mime as these will later be added by httplib.
payload_start = complete_mime.index("\n\n") + 2
payload = complete_mime[payload_start:]
return (headers, payload)
def extract_namespace(key):
"""Return the namespace in key or None, when no namespace is in key.
key -- String to get namespace from
"""
if not key.startswith("{"):
return None
return key[1:].split("}")[0]
def get_depth(depth, allowed=("0", "1", "infinity")):
"""Return string with depth.
depth -- Depth value to check.
allowed -- Iterable with allowed depth header values.
Raise ValueError, if an illegal depth was given.
"""
depth = str(depth).lower()
if depth not in allowed:
raise ValueError("illegal depth %s" % depth)
return depth
def get_cookie_response(tiny_response):
"""Return response object suitable with cookielib.
This makes the httplib.HTTPResponse compatible with cookielib.
"""
if isinstance(tiny_response, HTTPError):
tiny_response = tiny_response.response
tiny_response.response.info = lambda: tiny_response.response.msg
return tiny_response.response
def parse_authenticate(value):
"""Parse www-authenticate header and return dict with values.
Return empty dict when value doesn't match a www-authenticate header value.
value -- String value of www-authenticate header.
"""
sre = authparser.match(value)
if sre:
return sre.groupdict()
return dict()
| Python |
# The tinydav WebDAV client.
# Copyright (C) 2009 Manuel Hermann <manuel-hermann@gmx.net>
#
# This file is part of tinydav.
#
# tinydav 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 of the License, 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
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""The tinydav WebDAV client."""
from __future__ import with_statement
import sys
PYTHON2_6 = (sys.version_info >= (2, 6))
PYTHON2_7 = (sys.version_info >= (2, 7))
PYTHON2 = ((2, 5) <= sys.version_info <= (3, 0))
PYTHON3 = (sys.version_info >= (3, 0))
from contextlib import closing
from email.header import Header
from functools import wraps, partial
if PYTHON2:
from httplib import MULTI_STATUS, OK, CONFLICT, NO_CONTENT, UNAUTHORIZED
from urllib import quote as urllib_quote
from urllib import urlencode as urllib_urlencode
from StringIO import StringIO
import httplib
else:
from http.client import MULTI_STATUS, OK, CONFLICT, NO_CONTENT
from http.client import UNAUTHORIZED
from io import BytesIO
from io import StringIO
from urllib.parse import quote as urllib_quote
from urllib.parse import urlencode as urllib_urlencode
import base64
import http.client as httplib
from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring
if PYTHON2_7 or PYTHON3:
from xml.etree.ElementTree import ParseError
else:
from xml.parsers.expat import ExpatError as ParseError
import hashlib
from tinydav import creator, util
from tinydav.exception import HTTPError, HTTPUserError, HTTPServerError
__author__ = "Manuel Hermann <manuel-hermann@gmx.net>"
__license__ = "LGPL"
__version__ = "0.7.1"
__all__ = (
"HTTPError", "HTTPUserError", "HTTPServerError",
"HTTPClient", "WebDAVClient",
)
# RFC 2518, 9.8 Timeout Request Header
# The timeout value for TimeType "Second" MUST NOT be greater than 2^32-1.
MAX_TIMEOUT = 2**32-1
ACTIVELOCK = "./{DAV:}lockdiscovery/{DAV:}activelock"
# map with default ports mapped to http protocol
PROTOCOL = {
80: "http",
443: "https",
8080: "http",
8081: "http",
}
default_header_encoding = "utf-8"
separate_query_sequences = True
# Responses
class HTTPResponse(int):
"""Result from HTTP request.
An HTTPResponse object is a subclass of int. The int value of such an
object is the HTTP status number from the response.
This object has the following attributes:
response -- The original httplib.HTTPResponse object.
headers -- A dictionary with the received headers.
content -- The content of the response as string.
statusline -- The received HTTP status line. E.g. "HTTP/1.1 200 OK".
"""
def __new__(cls, response):
"""Construct HTTPResponse.
response -- The original httplib.HTTPResponse object.
"""
return int.__new__(cls, response.status)
def __init__(self, response):
"""Initialize the HTTPResponse.
response -- The original httplib.HTTPResponse object.
"""
self.response = response
self.headers = dict(response.getheaders())
self.content = response.read()
version = "HTTP/%s.%s" % tuple(str(response.version))
self.statusline = "%s %d %s"\
% (version, response.status, response.reason)
if self == UNAUTHORIZED:
self._setauth()
def __repr__(self):
"""Return representation."""
if PYTHON2:
return "<%s: %d>" % (self.__class__.__name__, self)
else:
return "<{0}: {1}>".format(self.__class__.__name__, self)
def __str__(self):
"""Return string representation."""
return self.statusline
def _setauth(self):
value = self.headers.get("www-authenticate", "")
auth = util.parse_authenticate(value)
for attrname in ("schema", "realm", "domain", "nonce", "opaque"):
setattr(self, attrname, auth.get(attrname))
stale = auth.get("stale")
if stale is None:
stale = "false"
self.stale = (stale.lower() == "true")
algorithm = auth.get("algorithm")
if algorithm is None:
algorithm = "MD5"
self.algorithm = getattr(hashlib, algorithm.lower())
class WebDAVResponse(HTTPResponse):
"""Result from WebDAV request.
A WebDAVResponse object is a subclass of int. The int value of such an
object is the HTTP status number from the response.
This object has the following attributes:
response -- The original httplib.HTTPResponse object.
headers -- A dictionary with the received headers.
content -- The content of the response as string.
statusline -- The received HTTP status line. E.g. "HTTP/1.1 200 OK".
is_multistatus -- True, if the response's content is a multi-status
response.
You can iterate over a WebDAVResponse object. If the received data was
a multi-status response, the iterator will yield a MultiStatusResponse
object per result. If it was no multi-status response, the iterator will
just yield this WebDAVResponse object.
The length of a WebDAVResponse object is 1, except for multi-status
responses. The length will then be the number of results in the
multi-status.
"""
def __init__(self, response):
"""Initialize the WebDAVResponse.
response -- The original httplib.HTTPResponse object.
"""
super(WebDAVResponse, self).__init__(response)
self._etree = ElementTree()
# on XML parsing error set this to the raised exception
self.parse_error = None
self.is_multistatus = False
if (self == MULTI_STATUS):
self._set_multistatus()
def __len__(self):
"""Return the number of responses in a multistatus response.
When the response was no multistatus the return value is 1.
"""
if self.is_multistatus:
# RFC 2518, 12.9 multistatus XML Element
# <!ELEMENT multistatus (response+, responsedescription?) >
return len(self._etree.findall("./{DAV:}response"))
return 1
def __iter__(self):
"""Iterator over the response.
Yield MultiStatusResponse instances for each response in a 207
response.
Yield self otherwise.
"""
if self.is_multistatus:
# RFC 2518, 12.9 multistatus XML Element
# <!ELEMENT multistatus (response+, responsedescription?) >
for response in self._etree.findall("./{DAV:}response"):
yield MultiStatusResponse(response)
else:
yield self
def _parse_xml_content(self):
"""Parse the XML content.
If the response content cannot be parsed as XML content,
<root><empty/></root> will be taken as content instead.
"""
try:
if PYTHON2:
parse_me = StringIO(self.content)
else:
parse_me = BytesIO(self.content)
self._etree.parse(parse_me)
except ParseError:
# get the exception object this way to be compatible with Python
# versions 2.5 up to 3.x
self.parse_error = sys.exc_info()[1]
# don't fail on further processing
self._etree.parse(StringIO("<root><empty/></root>"))
def _set_multistatus(self):
"""Set this response to a multistatus response."""
self.is_multistatus = True
self._parse_xml_content()
class WebDAVLockResponse(WebDAVResponse):
"""Result from WebDAV LOCK request.
A WebDAVLockResponse object is a subclass of WebDAVResponse which is a
subclass of int. The int value of such an object is the HTTP status number
from the response.
This object has the following attributes:
response -- The original httplib.HTTPResponse object.
headers -- A dictionary with the received headers.
content -- The content of the response as string.
statusline -- The received HTTP status line. E.g. "HTTP/1.1 200 OK".
is_multistatus -- True, if the response's content is a multi-status
response.
lockscope -- Specifies whether a lock is an exclusive lock, or a
shared lock.
locktype -- Specifies the access type of a lock (which is always write).
depth -- The value of the Depth header.
owner -- The principal taking out this lock.
timeout -- The timeout associated with this lock
locktoken -- The lock token associated with this lock.
You can iterate over a WebDAVLockResponse object. If the received data was
a multi-status response, the iterator will yield a MultiStatusResponse
object per result. If it was no multi-status response, the iterator will
just yield this WebDAVLockResponse object.
The length of a WebDAVLockResponse object is 1, except for multi-status
responses. The length will then be the number of results in the
multi-status.
You can use this object to make conditional requests. For this, the context
manager protocol is implemented:
>>> lock = dav.lock("somewhere")
>>> with lock:
>>> dav.put("somwhere", <something>)
The above example will make a tagged PUT request. For untagged requests do:
>>> lock = dav.lock("somewhere")
>>> with lock(False):
>>> dav.put("somwhere", <something>)
"""
def __new__(cls, client, uri, response):
"""Construct WebDAVLockResponse.
client -- HTTPClient instance or one of its subclasses.
uri -- The called uri.
response --The original httplib.HTTPResponse object.
"""
return WebDAVResponse.__new__(cls, response)
def __init__(self, client, uri, response):
"""Initialize the WebDAVLockResponse.
client -- HTTPClient instance or one of its subclasses.
uri -- The called uri.
response -- The original httplib.HTTPResponse object.
"""
super(WebDAVLockResponse, self).__init__(response)
self._client = None
self._uri = None
self._locktype = None
self._lockscope = None
self._depth = None
self._owner = None
self._timeout = None
self._locktokens = None
self._previous_if = None
self._tagged = True
self._tag = None
# RFC 2518, 8.10.7 Status Codes
# 200 (OK) - The lock request succeeded and the value of the
# lockdiscovery property is included in the body.
if self == OK:
self._parse_xml_content()
self._client = client
self._uri = uri
self._tag = util.make_absolute(self._client, uri)
# RFC 2518, 8.10.4 Depth and Locking
# If the lock cannot be granted to all resources, a 409 (Conflict)
# status code MUST be returned with a response entity body
# containing a multistatus XML element describing which resource(s)
# prevented the lock from being granted.
elif self == CONFLICT:
self._set_multistatus()
def __repr__(self):
"""Return representation."""
return "<%s: <%s> %d>" % (self.__class__.__name__, self._tag, self)
def __call__(self, tagged=True):
"""Configure this lock to use tagged header or not.
tagged -- True, if the If header should contain a tagged list.
False, if the If header should contain a no-tag-list.
Default is True.
"""
self._tagged = tagged
return self
def __enter__(self):
"""Use the lock on requests on the returned prepare WebDAVClient."""
if self.locktokens:
# RFC 2518, 9.4 If Header
# If = "If" ":" ( 1*No-tag-list | 1*Tagged-list)
# No-tag-list = List
# Tagged-list = Resource 1*List
# Resource = Coded-URL
# List = "(" 1*(["Not"](State-token | "[" entity-tag "]")) ")"
# State-token = Coded-URL
# Coded-URL = "<" absoluteURI ">"
self._previous_if = self._client.headers.get("If")
tokens = "".join("<%s>" % token for token in self.locktokens)
if self._tagged:
if_value = "<%s> (%s)" % (self._tag, tokens)
else:
if_value = "(%s)" % tokens
self._tagged = True
self._client.headers["If"] = if_value
return self._client
def __exit__(self, exc, exctype, exctb):
"""Remove If statement in WebDAVClient."""
if "If" in self._client.headers:
if self._previous_if is not None:
self._client.headers["If"] = self._previous_if
self._previous_if = None
else:
del self._client.headers["If"]
@property
def lockscope(self):
"""Return the lockscope as ElementTree element."""
if self._lockscope is None:
# RFC 2518, 12.7 lockscope XML Element
# <!ELEMENT lockscope (exclusive | shared) >
# RFC 2518, 12.7.1 exclusive XML Element
# <!ELEMENT exclusive EMPTY >
# RFC 2518, 12.7.2 shared XML Element
# <!ELEMENT shared EMPTY >
scope = ACTIVELOCK + "/{DAV:}lockscope/*"
self._lockscope = self._etree.find(scope)
return self._lockscope
@property
def locktype(self):
"""Return the type of this lock."""
if self._locktype is None:
# RFC 2518, 12.8 locktype XML Element
# <!ELEMENT locktype (write) >
locktype = ACTIVELOCK + "/{DAV:}locktype/*"
self._locktype = self._etree.find(locktype)
return self._locktype
@property
def depth(self):
"""Return the applied depth."""
if self._depth is None:
# RFC 2518, 12.1.1 depth XML Element
# <!ELEMENT depth (#PCDATA) >
depth = ACTIVELOCK + "/{DAV:}depth"
self._depth = self._etree.findtext(depth)
return self._depth
@property
def owner(self):
"""Return the owner ElementTree element or None, if there's no owner."""
if self._owner is None:
# RFC 2518, 12.10 owner XML Element
# <!ELEMENT owner ANY>
owner = ACTIVELOCK + "/{DAV:}owner"
self._owner = self._etree.find(owner)
return self._owner
@property
def timeout(self):
"""Return the timeout of this lock or None, if not available."""
if self._timeout is None:
# RFC 2518, 12.1.3 timeout XML Element
# <!ELEMENT timeout (#PCDATA) >
timeout = ACTIVELOCK + "/{DAV:}timeout"
self._timeout = self._etree.findtext(timeout).strip()
return self._timeout
@property
def locktokens(self):
"""Return the locktokens for this lock."""
if self._locktokens is None:
# RFC 2518, 12.1.2 locktoken XML Element
# <!ELEMENT locktoken (href+) >
token = ACTIVELOCK + "/{DAV:}locktoken/{DAV:}href"
self._locktokens = [t.text.strip()
for t in self._etree.findall(token)]
return self._locktokens
class MultiStatusResponse(int):
"""Wrapper for multistatus responses.
A MultiStatusResponse object is a subclass of int. The int value of such an
object is the HTTP status number from the response.
Furthermore this object implements the dictionary interface. Through it
you can access all properties that the resource has.
This object has the following attributes:
statusline -- The received HTTP status line. E.g. "HTTP/1.1 200 OK".
href -- The HREF of the resource this status is for.
namespaces -- A frozenset with all the XML namespaces that the underlying
XML structure had.
"""
def __new__(cls, response):
"""Create instance with status code as int value."""
# RFC 2518, 12.9.1 response XML Element
# <!ELEMENT response (href, ((href*, status)|(propstat+)),
# responsedescription?) >
statusline = response.findtext("{DAV:}propstat/{DAV:}status")
status = int(statusline.split()[1])
return int.__new__(cls, status)
def __init__(self, response):
"""Initialize the MultiStatusResponse.
response -- ElementTree element: response-tag.
"""
self.response = response
self._href = None
self._statusline = None
self._namespaces = None
def __repr__(self):
"""Return representation string."""
return "<%s: %d>" % (self.__class__.__name__, self)
def __getitem__(self, name):
"""Return requested property as ElementTree element.
name -- Name of the property with namespace. No namespace needed for
DAV properties.
"""
# check, whether it's a default DAV property name
if not name.startswith("{"):
name = "{DAV:}%s" % name
# RFC 2518, 12.9.1.1 propstat XML Element
# <!ELEMENT propstat (prop, status, responsedescription?) >
prop = self.response.find("{DAV:}propstat/{DAV:}prop/%s" % name)
if prop is None:
raise KeyError(name)
return prop
if PYTHON2:
def __iter__(self):
"""Iterator over propertynames with their namespaces."""
return self.iterkeys()
else:
def __iter__(self):
"""Iterator over propertynames with their namespaces."""
return self.keys()
if PYTHON2:
def keys(self):
"""Return list of propertynames with their namespaces.
No namespaces for DAV properties.
"""
return list(self.iterkeys())
def iterkeys(self, cut_dav_ns=True):
"""Iterate over propertynames with their namespaces.
cut_dav_ns -- No namespaces for DAV properties when this is True.
"""
for (tagname, value) in self.iteritems(cut_dav_ns):
yield tagname
else:
def keys(self, cut_dav_ns=True):
"""Iterate over propertynames with their namespaces.
cut_dav_ns -- No namespaces for DAV properties when this is True.
"""
for (tagname, value) in self.items(cut_dav_ns):
yield tagname
def items(self):
"""Return list of 2-tuples with propertyname and ElementTree element."""
return list(self.iteritems())
def iteritems(self, cut_dav_ns=True):
"""Iterate list of 2-tuples with propertyname and ElementTree element.
cut_dav_ns -- No namespaces for DAV properties when this is True.
"""
# RFC 2518, 12.11 prop XML element
# <!ELEMENT prop ANY>
props = self.response.findall("{DAV:}propstat/{DAV:}prop/*")
for prop in props:
tagname = prop.tag
if cut_dav_ns and tagname.startswith("{DAV:}"):
tagname = tagname[6:]
yield (tagname, prop)
if PYTHON3:
items = iteritems
del iteritems
def get(self, key, default=None, namespace=None):
"""Return value for requested property.
key -- Property name with namespace. Namespace may be omitted, when
namespace-argument is given, or Namespace is DAV:
default -- Return this value when key does not exist.
namespace -- The namespace in which the property lives in. Must be
given, when the key value has no namespace defined and
the namespace ist not DAV:.
"""
if namespace:
key = "{%s}%s" % (namespace, key)
try:
return self[key]
except KeyError:
return default
@property
def statusline(self):
"""Return the status line for this response."""
if self._statusline is None:
# RFC 2518, 12.9.1.2 status XML Element
# <!ELEMENT status (#PCDATA) >
statustag = self.response.findtext("{DAV:}propstat/{DAV:}status")
self._statusline = statustag
return self._statusline
@property
def href(self):
"""Return the href for this response."""
if self._href is None:
# RFC 2518, 12.3 href XML Element
# <!ELEMENT href (#PCDATA)>
self._href = self.response.findtext("{DAV:}href")
return self._href
if PYTHON2:
@property
def namespaces(self):
"""Return frozenset of namespaces."""
if self._namespaces is None:
self._namespaces = frozenset(util.extract_namespace(key)
for key in self.iterkeys(False)
if util.extract_namespace(key))
return self._namespaces
else:
@property
def namespaces(self):
"""Return frozenset of namespaces."""
if self._namespaces is None:
self._namespaces = frozenset(util.extract_namespace(key)
for key in self.keys(False)
if util.extract_namespace(key))
return self._namespaces
# Clients
class HTTPClient(object):
"""Mini HTTP client.
This object has the following attributes:
host -- Given host on initialization.
port -- Given port on initialization.
protocol -- Used protocol. Either chosen by the port number or taken
from given value in initialization.
headers -- Dictionary with headers to send with every request.
cookie -- If set with setcookie: the given object.
locks -- Mapping with locks.
"""
ResponseType = HTTPResponse
def __init__(self, host, port=80, protocol=None, strict=False,
timeout=None, source_address=None):
"""Initialize the WebDAV client.
host -- WebDAV server host.
port -- WebDAV server port.
protocol -- Override protocol name. Is either 'http' or 'https'. If
not given, the protocol will be chosen by the port number
automatically:
80 -> http
443 -> https
8080 -> http
8081 -> http
Default port is 'http'.
strict -- When True, raise BadStatusLine if the status line can't be
parsed as a valid HTTP/1.0 or 1.1 status line (see Python
doc for httplib).
timeout -- Operations will timeout after that many seconds. Else the
global default timeout setting is used (see Python doc for
httplib). This argument is available since Python 2.6. It
won't have any effect in previous version.
source_address -- A tuple of (host, port) to use as the source address
the HTTP connection is made from (see Python doc for
httplib). This argument is available since
Python 2.7. It won't have any effect in previous
versions.
"""
assert isinstance(port, int)
assert protocol in (None, "http", "https")
self.host = host
self.port = port
if protocol is None:
self.protocol = PROTOCOL.get(port, "http")
else:
self.protocol = protocol
self.strict = strict
self.timeout = timeout
self.source_address = source_address
if PYTHON2:
self.key_file = None
self.cert_file = None
else:
self.context = None
self.headers = dict()
self.cookie = None
self._do_digest_auth = False
def _getconnection(self):
"""Return HTTP(S)Connection object depending on set protocol."""
args = (self.host, self.port,)
kwargs = dict(strict=self.strict)
if PYTHON2_6:
kwargs["timeout"] = self.timeout
if PYTHON2_7:
kwargs["source_address"] = self.source_address
if self.protocol == "http":
return httplib.HTTPConnection(*args, **kwargs)
# setup HTTPS
if PYTHON2:
kwargs["key_file"] = self.key_file
kwargs["cert_file"] = self.cert_file
else:
kwargs["context"] = self.context
return httplib.HTTPSConnection(*args, **kwargs)
def _request(self, method, uri, content=None, headers=None):
"""Make request and return response.
method -- Request method.
uri -- URI the request is for.
content -- The content of the request. May be None.
headers -- If given, a mapping with additonal headers to send.
"""
if not uri.startswith("/"):
uri = "/%s" % uri
headers = dict() if (headers is None) else headers
# handle cookies, if necessary
if self.cookie is not None:
fake_request = util.FakeHTTPRequest(self, uri, headers)
self.cookie.add_cookie_header(fake_request)
con = self._getconnection()
with closing(con):
con.request(method, uri, content, headers)
response = self.ResponseType(con.getresponse())
if 400 <= response < 500:
response = HTTPUserError(response)
elif 500 <= response < 600:
response = HTTPServerError(response)
if self.cookie is not None:
# Get response object suitable for cookielib
cookie_response = util.get_cookie_response(response)
self.cookie.extract_cookies(cookie_response, fake_request)
if isinstance(response, HTTPError):
raise response
return response
def _prepare(self, uri, headers, query=None):
"""Return 2-tuple with prepared version of uri and headers.
The headers will contain the authorization headers, if given.
uri -- URI the request is for.
headers -- Mapping with additional headers to send. Unicode values that
are no ASCII will be MIME-encoded with UTF-8. Set
tinydav.default_header_encoding to another encoding, if
UTF-8 doesn't suit you.
query -- Mapping with key/value-pairs to be added as query to the URI.
"""
uri = urllib_quote(uri)
# collect headers
sendheaders = dict(self.headers)
if headers:
sendheaders.update(headers)
for (key, value) in sendheaders.items():
try:
unicode(value).encode("ascii")
except UnicodeError:
value = str(Header(value, default_header_encoding))
sendheaders[key] = value
# construct query string
if query:
querystr = urllib_urlencode(query, doseq=separate_query_sequences)
uri = "%s?%s" % (uri, querystr)
return (uri, sendheaders)
if PYTHON2:
def setbasicauth(self, user, password):
"""Set authorization header for basic auth.
user -- Username
password -- Password for user.
"""
# RFC 2068, 11.1 Basic Authentication Scheme
# basic-credentials = "Basic" SP basic-cookie
# basic-cookie = <base64 [7] encoding of user-pass,
# except not limited to 76 char/line>
# user-pass = userid ":" password
# userid = *<TEXT excluding ":">
# password = *TEXT
userpw = "%s:%s" % (user, password)
auth = userpw.encode("base64").rstrip()
self.headers["Authorization"] = "Basic %s" % auth
else:
def setbasicauth(self, user, password,
b64encoder=base64.standard_b64encode):
"""Set authorization header for basic auth.
user -- Username as bytes string.
password -- Password for user as bytes.
encoder -- Base64 encoder function. Default is the standard
encoder. Should not be changed.
"""
# RFC 2068, 11.1 Basic Authentication Scheme
# basic-credentials = "Basic" SP basic-cookie
# basic-cookie = <base64 [7] encoding of user-pass,
# except not limited to 76 char/line>
# user-pass = userid ":" password
# userid = *<TEXT excluding ":">
# password = *TEXT
userpw = user + bytes(":", "ascii") + password
auth = b64encoder(userpw).decode("ascii")
self.headers["Authorization"] = "Basic {0}".format(auth)
def setcookie(self, cookie):
"""Set cookie class to be used in requests.
cookie -- Cookie class from cookielib.
"""
self.cookie = cookie
if PYTHON2:
def setssl(self, key_file=None, cert_file=None):
"""Set SSL key file and/or certificate chain file for HTTPS.
Calling this method has the side effect of setting the protocol to
https.
key_file -- The name of a PEM formatted file that contains your
private key.
cert_file -- PEM formatted certificate chain file (see Python doc
for httplib).
"""
self.key_file = key_file
self.cert_file = cert_file
if any((key_file, cert_file)):
self.protocol = "https"
else:
def setssl(self, context):
"""Set SSLContext for this connection.
Calling this method has the side effect of setting the protocol to
https.
context -- ssl.SSLContext instance describing the various SSL
options.
"""
self.protocol = "https"
self.context = context
def options(self, uri, headers=None):
"""Make OPTIONS request and return status.
uri -- URI of the request.
headers -- Optional mapping with headers to send.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
(uri, headers) = self._prepare(uri, headers)
return self._request("OPTIONS", uri, None, headers)
def get(self, uri, headers=None, query=None):
"""Make GET request and return status.
uri -- URI of the request.
headers -- Optional mapping with headers to send.
query -- Mapping with key/value-pairs to be added as query to the URI.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
(uri, headers) = self._prepare(uri, headers, query)
return self._request("GET", uri, None, headers)
def head(self, uri, headers=None, query=None):
"""Make HEAD request and return status.
uri -- URI of the request.
headers -- Optional mapping with headers to send.
query -- Mapping with key/value-pairs to be added as query to the URI.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
(uri, headers) = self._prepare(uri, headers, query)
return self._request("HEAD", uri, None, headers)
def post(self, uri, content="", headers=None, query=None,
as_multipart=False, encoding="ascii", with_filenames=False):
"""Make POST request and return HTTPResponse.
uri -- Path to post data to.
content -- File descriptor, string or dict with content to POST. If it
is a dict, the dict contents will be posted as content type
application/x-www-form-urlencoded.
headers -- If given, must be a mapping with headers to set.
query -- Mapping with key/value-pairs to be added as query to the URI.
as_multipart -- Send post data as multipart/form-data. content must be
a dict, then. If content is not a dict, then this
argument will be ignored. The values of the dict may be
a subclass of email.mime.base.MIMEBase, which will be
attached to the multipart as is, a 2-tuple containing
the actual value (or file-like object) and an encoding
for this value (or the content-type in case of a
file-like object).
encoding -- Send multipart content with this encoding. Default is
ASCII.
with_filenames -- If True, a multipart's files will be sent with the
filename paramenter set. Default is False.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
(uri, headers) = self._prepare(uri, headers, query)
if isinstance(content, dict):
if as_multipart:
(multihead, content) = util.make_multipart(content,
encoding,
with_filenames)
headers.update(multihead)
else:
headers["content-type"] = "application/x-www-form-urlencoded"
content = urllib_urlencode(content)
if hasattr(content, "read") and not PYTHON2_6:
# python 2.5 httlib cannot handle file-like objects
content = content.read()
return self._request("POST", uri, content, headers)
def put(self, uri, fileobject, content_type="application/octet-stream",
headers=None):
"""Make PUT request and return status.
uri -- Path for PUT.
fileobject -- File-like object or string with content to PUT.
content_type -- The content-type of the file. Default value is
application/octet-stream.
headers -- If given, must be a dict with headers to send.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
(uri, headers) = self._prepare(uri, headers)
headers["content-type"] = content_type
# use 2.6 feature, if running under this version
data = fileobject if PYTHON2_6 else fileobject.read()
return self._request("PUT", uri, data, headers)
def delete(self, uri, content="", headers=None):
"""Make DELETE request and return HTTPResponse.
uri -- Path to post data to.
content -- File descriptor or string with content.
headers -- If given, must be a mapping with headers to set.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
(uri, headers) = self._prepare(uri, headers)
return self._request("DELETE", uri, content, headers)
def trace(self, uri, maxforwards=None, via=None, headers=None):
"""Make TRACE request and return HTTPResponse.
uri -- Path to post data to.
maxforwards -- Number of maximum forwards. May be None.
via -- If given, an iterable containing each station in the form
stated in RFC2616, section 14.45.
headers -- If given, must be a mapping with headers to set.
Raise ValueError, if maxforward is not an int or convertable to
an int.
Raise TypeError, if via is not an iterable of string.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
(uri, headers) = self._prepare(uri, headers)
if maxforwards is not None:
# RFC 2068, 14.31 Max-Forwards
# Max-Forwards = "Max-Forwards" ":" 1*DIGIT
int(maxforwards)
headers["Max-Forwards"] = str(maxforwards)
# RFC 2068, 14.44 Via
if via:
headers["Via"] = ", ".join(via)
return self._request("TRACE", uri, None, headers)
def connect(self, uri, headers=None):
"""Make CONNECT request and return HTTPResponse.
uri -- Path to post data to.
headers -- If given, must be a mapping with headers to set.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
(uri, headers) = self._prepare(uri, headers)
return self._request("CONNECT", uri, None, headers)
class CoreWebDAVClient(HTTPClient):
"""Basic WebDAVClient specified in RFC 2518.
This object has the following attributes:
host -- Given host on initialization.
port -- Given port on initialization.
protocol -- Used protocol. Either chosen by the port number or taken
from given value in initialization.
headers -- Dictionary with headers to send with every request.
cookie -- If set with setcookie: the given object.
locks -- Dictionary containing all active locks, mapped by tag -> Lock.
"""
ResponseType = WebDAVResponse
def __init__(self, host, port=80, protocol=None):
"""Initialize the WebDAV client.
host -- WebDAV server host.
port -- WebDAV server port.
protocol -- Override protocol name. Is either 'http' or 'https'. If
not given, the protocol will be chosen by the port number
automatically:
80 -> http
443 -> https
8080 -> http
8081 -> http
Default port is 'http'.
"""
super(CoreWebDAVClient, self).__init__(host, port, protocol)
self.locks = dict()
def _preparecopymove(self, source, destination, depth, overwrite, headers):
"""Return prepared for copy/move request version of uri and headers."""
# RFC 2518, 8.8.3 COPY for Collections
# A client may submit a Depth header on a COPY on a collection with a
# value of "0" or "infinity".
depth = util.get_depth(depth, ("0", "infinity"))
headers = dict() if (headers is None) else headers
(source, headers) = self._prepare(source, headers)
# RFC 2518, 8.8 COPY Method
# The Destination header MUST be present.
# RFC 2518, 8.9 MOVE Method
# Consequently, the Destination header MUST be present on all MOVE
# methods and MUST follow all COPY requirements for the COPY part of
# the MOVE method.
# RFC 2518, 9.3 Destination Header
# Destination = "Destination" ":" absoluteURI
headers["Destination"] = util.make_absolute(self, destination)
# RFC 2518, 8.8.3 COPY for Collections
# A client may submit a Depth header on a COPY on a collection with
# a value of "0" or "infinity".
# RFC 2518, 8.9.2 MOVE for Collections
if source.endswith("/"):
headers["Depth"] = depth
# RFC 2518, 8.8.4 COPY and the Overwrite Header
# 8.9.3 MOVE and the Overwrite Header
# If a resource exists at the destination and the Overwrite header is
# "T" then prior to performing the copy the server MUST perform a
# DELETE with "Depth: infinity" on the destination resource. If the
# Overwrite header is set to "F" then the operation will fail.
if overwrite is not None:
headers["Overwrite"] = "T" if overwrite else "F"
return (source, headers)
def mkcol(self, uri, headers=None):
"""Make MKCOL request and return status.
uri -- Path to create.
headers -- If given, must be a dict with headers to send.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
(uri, headers) = self._prepare(uri, headers)
return self._request("MKCOL", uri, None, headers)
def propfind(self, uri, depth=0, names=False,
properties=None, include=None, namespaces=None,
headers=None):
"""Make PROPFIND request and return status.
uri -- Path for PROPFIND.
depth -- Depth for PROFIND request. Default is zero.
names -- If True, only the available namespace names are returned.
properties -- If given, an iterable with all requested properties is
expected.
include -- If properties is not given, then additional properties can
be requested with this argument.
namespaces -- Mapping with namespaces for given properties, if needed.
headers -- If given, must be a dict with headers to send.
Raise ValueError, if illegal depth was given or if properties and
include arguments were given.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
namespaces = dict() if (namespaces is None) else namespaces
# RFC 2518, 8.1 PROPFIND
# A client may submit a Depth header with a value of "0", "1", or
# "infinity" with a PROPFIND on a collection resource with internal
# member URIs.
depth = util.get_depth(depth)
# check mutually exclusive arguments
if all([properties, include]):
raise ValueError("properties and include are mutually exclusive")
(uri, headers) = self._prepare(uri, headers)
# additional headers needed for PROPFIND
headers["Depth"] = depth
headers["Content-Type"] = "application/xml"
content = creator.create_propfind(names, properties,
include, namespaces)
return self._request("PROPFIND", uri, content, headers)
def search(self, uri, query, namespaces=None, headers=None):
"""Make SEARCHREQUEST request and return status.
uri -- Path for SEARCHREQUEST.
query -- SQL like DASL/DAVSearch string
namespaces -- Mapping with namespaces for given properties, if needed.
headers -- If given, must be a dict with headers to send.
Raise ValueError, if illegal depth was given or if properties and
include arguments were given.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
namespaces = dict() if (namespaces is None) else namespaces
(uri, headers) = self._prepare(uri, headers)
headers["Content-Type"] = "application/xml"
#headers["Translate"] = "f"
headers["Accept"] = "application/xml"
content = creator.create_search(query, namespaces)
print content
return self._request("SEARCH", uri, content, headers)
def proppatch(self, uri, setprops=None, delprops=None,
namespaces=None, headers=None):
"""Make PROPPATCH request and return status.
uri -- Path to resource to set properties.
setprops -- Mapping with properties to set.
delprops -- Iterable with properties to remove.
namespaces -- dict with namespaces: name -> URI.
headers -- If given, must be a dict with headers to send.
Either setprops or delprops or both of them must be given, else
ValueError will be risen.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
# RFC 2518, 12.13 propertyupdate XML element
# <!ELEMENT propertyupdate (remove | set)+ >
if not any((setprops, delprops)):
raise ValueError("setprops and/or delprops must be given")
(uri, headers) = self._prepare(uri, headers)
# additional header for proppatch
headers["Content-Type"] = "application/xml"
content = creator.create_proppatch(setprops, delprops, namespaces)
return self._request("PROPPATCH", uri, content, headers)
def delete(self, uri, headers=None):
"""Make DELETE request and return WebDAVResponse.
uri -- Path of resource or collection to delete.
headers -- If given, must be a mapping with headers to set.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
headers = dict() if (headers is None) else headers
if uri.endswith("/"):
# RFC 2518, 8.6.2 DELETE for Collections
# A client MUST NOT submit a Depth header with a DELETE on a
# collection with any value but infinity.
headers["Depth"] = "infinity"
return super(CoreWebDAVClient, self).delete(uri, headers)
def copy(self, source, destination, depth="infinity",
overwrite=None, headers=None):
"""Make COPY request and return WebDAVResponse.
source -- Path of resource to copy.
destination -- Path of destination to copy source to.
depth -- Either 0 or "infinity". Default is the latter.
overwrite -- If not None, then a boolean indicating whether the
Overwrite header ist set to "T" (True) or "F" (False).
headers -- If given, must be a mapping with headers to set.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
(source, headers) = self._preparecopymove(source, destination, depth,
overwrite, headers)
return self._request("COPY", source, None, headers)
def move(self, source, destination, depth="infinity",
overwrite=None, headers=None):
"""Make MOVE request and return WebDAVResponse.
source -- Path of resource to move.
destination -- Path of destination to move source to.
depth -- Either 0 or "infinity". Default is the latter.
overwrite -- If not None, then a boolean indicating whether the
Overwrite header ist set to "T" (True) or "F" (False).
headers -- If given, must be a mapping with headers to set.
Raise ValueError, if an illegal depth was given.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
# RFC 2518, 8.9.2 MOVE for Collections
# A client MUST NOT submit a Depth header on a MOVE on a collection
# with any value but "infinity".
if source.endswith("/") and (depth != "infinity"):
raise ValueError("depth must be infinity when moving collections")
(source, headers) = self._preparecopymove(source, destination, depth,
overwrite, headers)
return self._request("MOVE", source, None, headers)
def lock(self, uri, scope="exclusive", type_="write", owner=None,
timeout=None, depth=None, headers=None):
"""Make LOCK request and return DAVLock instance.
uri -- Resource to get lock on.
scope -- Lock scope: One of "exclusive" (default) or "shared".
type_ -- Lock type: "write" (default) only. Any other value allowed by
this library.
owner -- Content of owner element. May be None, a string or an
ElementTree element.
timeout -- Value for the timeout header. Either "infinite" or a number
representing the seconds (not greater than 2^32 - 1).
headers -- If given, must be a mapping with headers to set.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
(uri, headers) = self._prepare(uri, headers)
# RFC 2518, 9.8 Timeout Request Header
# TimeOut = "Timeout" ":" 1#TimeType
# TimeType = ("Second-" DAVTimeOutVal | "Infinite" | Other)
# DAVTimeOutVal = 1*digit
# Other = "Extend" field-value ; See section 4.2 of [RFC2068]
if timeout is not None:
try:
timeout = int(timeout)
except ValueError: # no number
if timeout.lower() == "infinite":
value = "Infinite"
else:
raise ValueError("either number of seconds or 'infinite'")
else:
if timeout > MAX_TIMEOUT:
raise ValueError("timeout too big")
value = "Second-%d" % timeout
headers["Timeout"] = value
# RFC 2518, 8.10.4 Depth and Locking
# Values other than
# 0 or infinity MUST NOT be used with the Depth header on a LOCK
# method.
if depth is not None:
headers["Depth"] = util.get_depth(depth, ("0", "infinity"))
content = creator.create_lock(scope, type_, owner)
# set a specialized ResponseType as instance var
self.ResponseType = partial(WebDAVLockResponse, self, uri)
try:
lock_response = self._request("LOCK", uri, content, headers)
if lock_response == OK:
self.locks[lock_response._tag] = lock_response
return lock_response
finally:
# remove the formerly set ResponseType from the instance
del self.ResponseType
def unlock(self, uri_or_lock, locktoken=None, headers=None):
"""Make UNLOCK request and return WebDAVResponse.
uri_or_lock -- Resource URI to unlock or WebDAVLockResponse.
locktoken -- Use this lock token for unlocking. If not given, the
registered locks (self.locks) will be referenced.
headers -- If given, must be a mapping with headers to set.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
if isinstance(uri_or_lock, WebDAVLockResponse):
uri = uri_or_lock._uri
tag = uri_or_lock._tag
locktoken = uri_or_lock.locktokens[0]
# uri is already prepared in WebDAVLockResponse
(_, headers) = self._prepare("", headers)
else:
tag = util.make_absolute(self, uri_or_lock)
if locktoken is None:
try:
lock = self.locks[tag]
except KeyError:
raise ValueError("no lock token")
tag = lock._tag
locktoken = lock.locktokens[0]
(uri, headers) = self._prepare(uri_or_lock, headers)
# RFC 2518, 9.5 Lock-Token Header
# Lock-Token = "Lock-Token" ":" Coded-URL
headers["Lock-Token"] = "<%s>" % locktoken
response = self._request("UNLOCK", uri, None, headers)
# RFC 2518, 8.11 UNLOCK Method
# The 204 (No Content) status code is used instead of 200 (OK) because
# there is no response entity body.
if response == NO_CONTENT:
try:
del self.locks[tag]
except KeyError:
pass
return response
class ExtendedWebDAVClient(CoreWebDAVClient):
"""WebDAV client with versioning extensions (RFC 3253)."""
def report(self, uri, depth=0, properties=None,
elements=None, namespaces=None, headers=None):
"""Make a REPORT request and return status.
uri -- Resource or collection to get report for.
depth -- Either 0 or 1 or "infinity". Default is zero.
properties -- If given, an iterable with all requested properties is
expected.
elements -- An iterable with additional XML (ElementTree) elements to
append to the version-tree.
namespaces -- Mapping with namespaces for given properties, if needed.
headers -- If given, must be a mapping with headers to set.
Raise ValueError, if an illegal depth value was given.
Raise HTTPUserError on 4xx HTTP status codes.
Raise HTTPServerError on 5xx HTTP status codes.
"""
depth = util.get_depth(depth)
(uri, headers) = self._prepare(uri, headers)
content = creator.create_report(properties, elements, namespaces)
# RFC 3253, 3.6 REPORT Method
# The request MAY include a Depth header. If no Depth header is
# included, Depth:0 is assumed.
headers["Depth"] = depth
headers["Content-Type"] = "application/xml"
return self._request("REPORT", uri, content, headers)
class WebDAVClient(ExtendedWebDAVClient):
"""Mini WebDAV client.
This object has the following attributes:
host -- Given host on initialization.
port -- Given port on initialization.
protocol -- Used protocol. Either chosen by the port number or taken
from given value in initialization.
headers -- Dictionary with headers to send with every request.
cookie -- If set with setcookie: the given object.
"""
| Python |
# Request creator function for tinydav WebDAV client.
# Copyright (C) 2009 Manuel Hermann <manuel-hermann@gmx.net>
#
# This file is part of tinydav.
#
# tinydav 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 of the License, 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
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Module with helper functions that generate XML requests."""
from xml.etree.ElementTree import Element, SubElement, tostring
import sys
PYTHON2 = ((2, 5) <= sys.version_info <= (3, 0))
STRING_TYPE = basestring if PYTHON2 else str
_NS = {"xmlns": "DAV:"}
def _addnamespaces(elem, namespaces):
"""Add namespace definitions to a given XML element.
elem -- ElementTree element to add namespaces to.
namespaces -- Mapping (prefix->namespace) with additional namespaces,
if necessary.
"""
for nsname in namespaces:
attrname = "xmlns:%s" % nsname
elem.attrib[attrname] = namespaces[nsname]
def create_propfind(names=False, properties=None,
include=None, namespaces=None):
"""Construct and return XML string for PROPFIND.
names -- Boolean whether the profind is requesting property names only.
properties -- An iterable containing property names to request. Will only
by considered when names is False.
include -- An Iterable containing properties that shall be returned by the
WebDAV server in addition to the properties returned by an
allprop request.
namespaces -- Mapping (prefix->namespace) with additional namespaces,
if necessary.
If names is False, properties is considered False, an allprop-PROPFIND
request is created.
"""
namespaces = dict() if (namespaces is None) else namespaces
# RFC 2518, 12.14 propfind XML Element
# <!ELEMENT propfind (allprop | propname | prop) >
propfind = Element("propfind", _NS)
_addnamespaces(propfind, namespaces)
if names:
# RFC 2518, 12.14.2 propname XML Element
# <!ELEMENT propname EMPTY >
names_element = SubElement(propfind, "propname")
elif properties:
# RFC 2518, 12.11 prop XML Element
# <!ELEMENT prop ANY >
prop = SubElement(propfind, "prop")
for propname in properties:
propelement = SubElement(prop, propname)
else:
# RFC 2518, 12.14.2 allprop XML Element
# <!ELEMENT allprop EMPTY >
allprop = SubElement(propfind, "allprop")
# draft-reschke-webdav-allprop-include-00
# <!ELEMENT propfind ((allprop, include+) | propname | prop) >
# <!ELEMENT include ANY >
if include:
include_element = SubElement(propfind, "include")
for propname in include:
inclprop = SubElement(include_element, propname)
return tostring(propfind, "UTF-8")
def create_search(query=None, namespaces=None):
"""Construct and return XML string for SEARCHREQUEST.
query -- SQL like DASL/DAVSearch query
namespaces -- Mapping (prefix->namespace) with additional namespaces,
if necessary.
"""
namespaces = dict() if (namespaces is None) else namespaces
searchrequest = Element("searchrequest",_NS)
_addnamespaces(searchrequest, namespaces)
if query:
sql = SubElement(searchrequest, "sql")
sql.text = query
return tostring(searchrequest, "UTF-8")
def create_proppatch(setprops, delprops, namespaces=None):
"""Construct and return XML string for PROPPATCH.
setprops -- Mapping with properties to set.
delprops -- Iterable with element names to remove.
namespaces -- Mapping (prefix->namespace) with additional namespaces,
if necessary.
"""
# RFC 2518, 12.13 propertyupdate XML element
# <!ELEMENT propertyupdate (remove | set)+ >
propertyupdate = Element("propertyupdate", _NS)
if namespaces:
_addnamespaces(propertyupdate, namespaces)
# RFC 2518, 12.13.2 set XML element
# <!ELEMENT set (prop) >
if setprops:
set_ = SubElement(propertyupdate, "set")
prop = SubElement(set_, "prop")
items_iterator = setprops.iteritems() if PYTHON2 else setprops.items()
for (propname, propvalue) in items_iterator:
prop = SubElement(prop, propname)
prop.text = propvalue
# RFC 2518, 12.13.1 set XML element
# <!ELEMENT remove (prop) >
if delprops:
remove = SubElement(propertyupdate, "remove")
prop = SubElement(remove, "prop")
for propname in delprops:
prop = SubElement(prop, propname)
return tostring(propertyupdate, "UTF-8")
def create_lock(scope="exclusive", type_="write", owner=None):
"""Construct and return XML string for LOCK.
scope -- One of "exclusive" or "shared".
type_ -- Only "write" in defined in RFC.
owner -- Optional owner information for lock. Can be any string.
Raise ValueError, if illegal scope was given.
"""
# RFC 2518, 12.7 lockscope XML Element
# <!ELEMENT lockscope (exclusive | shared) >
# RFC 2518, 12.7.1 exclusive XML Element
# <!ELEMENT exclusive EMPTY >
# RFC 2518, 12.7.2 shared XML Element
# <!ELEMENT shared EMPTY >
if scope not in ("exclusive", "shared"):
raise ValueError("scope must be either exclusive or shared")
# RFC 2518, 12.6 lockinfo XML Element
# <!ELEMENT lockinfo (lockscope, locktype, owner?) >
lockinfo = Element("lockinfo", _NS)
# set lockscope
lockscope = SubElement(lockinfo, "lockscope")
scope = SubElement(lockscope, scope)
# RFC 2518, 12.8 locktype XML Element
# <!ELEMENT locktype (write) >
# RFC 2518, 12.8.1 write XML Element
# <!ELEMENT write EMPTY >
locktype = SubElement(lockinfo, "locktype")
typ_ = SubElement(locktype, type_)
if owner is not None:
# RFC 2518, 12.10 owner XML Element
# <!ELEMENT owner ANY>
owner_elem = SubElement(lockinfo, "owner")
if isinstance(owner, STRING_TYPE):
owner_elem.text = owner
else:
owner_elem.append(owner)
return tostring(lockinfo)
def create_report(properties=None, elements=None, namespaces=None):
"""Construct and return XML for REPORT."""
namespaces = dict() if (namespaces is None) else namespaces
ns = {"xmlns": "DAV:"}
# RFC 3253, 3.7 DAV:version-tree Report
# <!ELEMENT version-tree ANY>
# ANY value: a sequence of zero or more elements, with at most one
# DAV:prop element.
report = Element("version-tree", ns)
_addnamespaces(report, namespaces)
if properties:
prop = SubElement(report, "prop")
for propname in properties:
propelement = SubElement(prop, propname)
if elements:
for element in elements:
report.append(element)
return tostring(report, "UTF-8")
| Python |
#!/usr/bin/python
# coding: utf-8
#
# Copyright (C) 2009 Manuel Hermann <manuel-hermann@gmx.net>
from distutils.core import setup
import tinydav
VERSION = tinydav.__version__
DOWNLOAD = "http://tinydav.googlecode.com/files/tinydav-%s.tar.gz" % VERSION
DESCRIPTION = "An easy-to-use HTTP and WebDAV client library."
LONG_DESCRIPTION = """\
An easy-to-use HTML and WebDAV client library for Python
--------------------------------------------------------
This is a small library for contacting HTTP and WebDAV servers. Goal of this project until version 1.0 is supporting all WebDAV methods including the versioning extensions from RFC 3253).
Features:
- HTTP methods OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT.
- WebDAV methods MKCOL, PROPFIND, PROPPATCH, DELETE, COPY, MOVE, LOCK, UNLOCK
- Support for REPORT method (report-tree requests only, RFC 3253)
- Cookies
- SSL
- Multipart/form-data and application/x-www-form-urlencoded POST requests
This version requires Python 2.5 or later (including Python 3.)
"""
CLASSIFIERS = [
"Programming Language :: Python",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: "\
"GNU Library or Lesser General Public License (LGPL)",
"Operating System :: OS Independent",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Software Development :: Libraries :: Python Modules",
]
if __name__ == "__main__":
setup(
name="tinydav",
packages=["tinydav"],
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
author="Manuel Hermann",
author_email="manuel-hermann@gmx.net",
url="http://code.google.com/p/tinydav/",
download_url=DOWNLOAD,
keywords = ["webdav", "https", "http", "library", "client", "lgpl",
"rfc2518", "rfc2068", "rfc3253"],
license="LGPL",
classifiers=CLASSIFIERS,
)
| Python |
from sqlalchemy.ext.declarative import declarative_base
BaseModel = declarative_base()
| Python |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import myproject.config as config
engine = create_engine(config.db_url, echo=config.debug)
Session = sessionmaker(bind=engine, expire_on_commit=False)
| Python |
from flask import Flask
import myproject.config as config
from myproject.pbin.views import blueprint as blueprint_pbin
app = Flask("myproject")
app.config.update(config.flask_config)
app.register_blueprint(blueprint_pbin, url_prefix="/pbin")
def main():
app.run(config.web_ip, config.web_port)
if __name__ == "__main__":
main()
| Python |
import os
import yaml
def load_config(cfg_path):
with open(cfg_path, "r") as f:
params = yaml.load(f)
globals().update(params)
cfg_path = os.path.join(os.path.dirname(__file__), "config.yaml")
load_config(cfg_path)
| Python |
'''
Module which prompts the user for translations and saves them.
TODO: implement
@author: Rodrigo Damazio
'''
class Translator(object):
'''
classdocs
'''
def __init__(self, language):
'''
Constructor
'''
self._language = language
def Translate(self, string_names):
print string_names | Python |
'''
Module which brings history information about files from Mercurial.
@author: Rodrigo Damazio
'''
import re
import subprocess
REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*')
def _GetOutputLines(args):
'''
Runs an external process and returns its output as a list of lines.
@param args: the arguments to run
'''
process = subprocess.Popen(args,
stdout=subprocess.PIPE,
universal_newlines = True,
shell = False)
output = process.communicate()[0]
return output.splitlines()
def FillMercurialRevisions(filename, parsed_file):
'''
Fills the revs attribute of all strings in the given parsed file with
a list of revisions that touched the lines corresponding to that string.
@param filename: the name of the file to get history for
@param parsed_file: the parsed file to modify
'''
# Take output of hg annotate to get revision of each line
output_lines = _GetOutputLines(['hg', 'annotate', '-c', filename])
# Create a map of line -> revision (key is list index, line 0 doesn't exist)
line_revs = ['dummy']
for line in output_lines:
rev_match = REVISION_REGEX.match(line)
if not rev_match:
raise 'Unexpected line of output from hg: %s' % line
rev_hash = rev_match.group('hash')
line_revs.append(rev_hash)
for str in parsed_file.itervalues():
# Get the lines that correspond to each string
start_line = str['startLine']
end_line = str['endLine']
# Get the revisions that touched those lines
revs = []
for line_number in range(start_line, end_line + 1):
revs.append(line_revs[line_number])
# Merge with any revisions that were already there
# (for explict revision specification)
if 'revs' in str:
revs += str['revs']
# Assign the revisions to the string
str['revs'] = frozenset(revs)
def DoesRevisionSuperceed(filename, rev1, rev2):
'''
Tells whether a revision superceeds another.
This essentially means that the older revision is an ancestor of the newer
one.
This also returns True if the two revisions are the same.
@param rev1: the revision that may be superceeding the other
@param rev2: the revision that may be superceeded
@return: True if rev1 superceeds rev2 or they're the same
'''
if rev1 == rev2:
return True
# TODO: Add filename
args = ['hg', 'log', '-r', 'ancestors(%s)' % rev1, '--template', '{node|short}\n', filename]
output_lines = _GetOutputLines(args)
return rev2 in output_lines
def NewestRevision(filename, rev1, rev2):
'''
Returns which of two revisions is closest to the head of the repository.
If none of them is the ancestor of the other, then we return either one.
@param rev1: the first revision
@param rev2: the second revision
'''
if DoesRevisionSuperceed(filename, rev1, rev2):
return rev1
return rev2 | Python |
'''
Module which parses a string XML file.
@author: Rodrigo Damazio
'''
from xml.parsers.expat import ParserCreate
import re
#import xml.etree.ElementTree as ET
class StringsParser(object):
'''
Parser for string XML files.
This object is not thread-safe and should be used for parsing a single file at
a time, only.
'''
def Parse(self, file):
'''
Parses the given file and returns a dictionary mapping keys to an object
with attributes for that key, such as the value, start/end line and explicit
revisions.
In addition to the standard XML format of the strings file, this parser
supports an annotation inside comments, in one of these formats:
<!-- KEEP_PARENT name="bla" -->
<!-- KEEP_PARENT name="bla" rev="123456789012" -->
Such an annotation indicates that we're explicitly inheriting form the
master file (and the optional revision says that this decision is compatible
with the master file up to that revision).
@param file: the name of the file to parse
'''
self._Reset()
# Unfortunately expat is the only parser that will give us line numbers
self._xml_parser = ParserCreate()
self._xml_parser.StartElementHandler = self._StartElementHandler
self._xml_parser.EndElementHandler = self._EndElementHandler
self._xml_parser.CharacterDataHandler = self._CharacterDataHandler
self._xml_parser.CommentHandler = self._CommentHandler
file_obj = open(file)
self._xml_parser.ParseFile(file_obj)
file_obj.close()
return self._all_strings
def _Reset(self):
self._currentString = None
self._currentStringName = None
self._currentStringValue = None
self._all_strings = {}
def _StartElementHandler(self, name, attrs):
if name != 'string':
return
if 'name' not in attrs:
return
assert not self._currentString
assert not self._currentStringName
self._currentString = {
'startLine' : self._xml_parser.CurrentLineNumber,
}
if 'rev' in attrs:
self._currentString['revs'] = [attrs['rev']]
self._currentStringName = attrs['name']
self._currentStringValue = ''
def _EndElementHandler(self, name):
if name != 'string':
return
assert self._currentString
assert self._currentStringName
self._currentString['value'] = self._currentStringValue
self._currentString['endLine'] = self._xml_parser.CurrentLineNumber
self._all_strings[self._currentStringName] = self._currentString
self._currentString = None
self._currentStringName = None
self._currentStringValue = None
def _CharacterDataHandler(self, data):
if not self._currentString:
return
self._currentStringValue += data
_KEEP_PARENT_REGEX = re.compile(r'\s*KEEP_PARENT\s+'
r'name\s*=\s*[\'"]?(?P<name>[a-z0-9_]+)[\'"]?'
r'(?:\s+rev=[\'"]?(?P<rev>[0-9a-f]{12})[\'"]?)?\s*',
re.MULTILINE | re.DOTALL)
def _CommentHandler(self, data):
keep_parent_match = self._KEEP_PARENT_REGEX.match(data)
if not keep_parent_match:
return
name = keep_parent_match.group('name')
self._all_strings[name] = {
'keepParent' : True,
'startLine' : self._xml_parser.CurrentLineNumber,
'endLine' : self._xml_parser.CurrentLineNumber
}
rev = keep_parent_match.group('rev')
if rev:
self._all_strings[name]['revs'] = [rev] | Python |
#!/usr/bin/python
'''
Entry point for My Tracks i18n tool.
@author: Rodrigo Damazio
'''
import mytracks.files
import mytracks.translate
import mytracks.validate
import sys
def Usage():
print 'Usage: %s <command> [<language> ...]\n' % sys.argv[0]
print 'Commands are:'
print ' cleanup'
print ' translate'
print ' validate'
sys.exit(1)
def Translate(languages):
'''
Asks the user to interactively translate any missing or oudated strings from
the files for the given languages.
@param languages: the languages to translate
'''
validator = mytracks.validate.Validator(languages)
validator.Validate()
missing = validator.missing_in_lang()
outdated = validator.outdated_in_lang()
for lang in languages:
untranslated = missing[lang] + outdated[lang]
if len(untranslated) == 0:
continue
translator = mytracks.translate.Translator(lang)
translator.Translate(untranslated)
def Validate(languages):
'''
Computes and displays errors in the string files for the given languages.
@param languages: the languages to compute for
'''
validator = mytracks.validate.Validator(languages)
validator.Validate()
error_count = 0
if (validator.valid()):
print 'All files OK'
else:
for lang, missing in validator.missing_in_master().iteritems():
print 'Missing in master, present in %s: %s:' % (lang, str(missing))
error_count = error_count + len(missing)
for lang, missing in validator.missing_in_lang().iteritems():
print 'Missing in %s, present in master: %s:' % (lang, str(missing))
error_count = error_count + len(missing)
for lang, outdated in validator.outdated_in_lang().iteritems():
print 'Outdated in %s: %s:' % (lang, str(outdated))
error_count = error_count + len(outdated)
return error_count
if __name__ == '__main__':
argv = sys.argv
argc = len(argv)
if argc < 2:
Usage()
languages = mytracks.files.GetAllLanguageFiles()
if argc == 3:
langs = set(argv[2:])
if not langs.issubset(languages):
raise 'Language(s) not found'
# Filter just to the languages specified
languages = dict((lang, lang_file)
for lang, lang_file in languages.iteritems()
if lang in langs or lang == 'en' )
cmd = argv[1]
if cmd == 'translate':
Translate(languages)
elif cmd == 'validate':
error_count = Validate(languages)
else:
Usage()
error_count = 0
print '%d errors found.' % error_count
| Python |
'''
Module which compares languague files to the master file and detects
issues.
@author: Rodrigo Damazio
'''
import os
from mytracks.parser import StringsParser
import mytracks.history
class Validator(object):
def __init__(self, languages):
'''
Builds a strings file validator.
Params:
@param languages: a dictionary mapping each language to its corresponding directory
'''
self._langs = {}
self._master = None
self._language_paths = languages
parser = StringsParser()
for lang, lang_dir in languages.iteritems():
filename = os.path.join(lang_dir, 'strings.xml')
parsed_file = parser.Parse(filename)
mytracks.history.FillMercurialRevisions(filename, parsed_file)
if lang == 'en':
self._master = parsed_file
else:
self._langs[lang] = parsed_file
self._Reset()
def Validate(self):
'''
Computes whether all the data in the files for the given languages is valid.
'''
self._Reset()
self._ValidateMissingKeys()
self._ValidateOutdatedKeys()
def valid(self):
return (len(self._missing_in_master) == 0 and
len(self._missing_in_lang) == 0 and
len(self._outdated_in_lang) == 0)
def missing_in_master(self):
return self._missing_in_master
def missing_in_lang(self):
return self._missing_in_lang
def outdated_in_lang(self):
return self._outdated_in_lang
def _Reset(self):
# These are maps from language to string name list
self._missing_in_master = {}
self._missing_in_lang = {}
self._outdated_in_lang = {}
def _ValidateMissingKeys(self):
'''
Computes whether there are missing keys on either side.
'''
master_keys = frozenset(self._master.iterkeys())
for lang, file in self._langs.iteritems():
keys = frozenset(file.iterkeys())
missing_in_master = keys - master_keys
missing_in_lang = master_keys - keys
if len(missing_in_master) > 0:
self._missing_in_master[lang] = missing_in_master
if len(missing_in_lang) > 0:
self._missing_in_lang[lang] = missing_in_lang
def _ValidateOutdatedKeys(self):
'''
Computers whether any of the language keys are outdated with relation to the
master keys.
'''
for lang, file in self._langs.iteritems():
outdated = []
for key, str in file.iteritems():
# Get all revisions that touched master and language files for this
# string.
master_str = self._master[key]
master_revs = master_str['revs']
lang_revs = str['revs']
if not master_revs or not lang_revs:
print 'WARNING: No revision for %s in %s' % (key, lang)
continue
master_file = os.path.join(self._language_paths['en'], 'strings.xml')
lang_file = os.path.join(self._language_paths[lang], 'strings.xml')
# Assume that the repository has a single head (TODO: check that),
# and as such there is always one revision which superceeds all others.
master_rev = reduce(
lambda r1, r2: mytracks.history.NewestRevision(master_file, r1, r2),
master_revs)
lang_rev = reduce(
lambda r1, r2: mytracks.history.NewestRevision(lang_file, r1, r2),
lang_revs)
# If the master version is newer than the lang version
if mytracks.history.DoesRevisionSuperceed(lang_file, master_rev, lang_rev):
outdated.append(key)
if len(outdated) > 0:
self._outdated_in_lang[lang] = outdated
| Python |
'''
Module for dealing with resource files (but not their contents).
@author: Rodrigo Damazio
'''
import os.path
from glob import glob
import re
MYTRACKS_RES_DIR = 'MyTracks/res'
ANDROID_MASTER_VALUES = 'values'
ANDROID_VALUES_MASK = 'values-*'
def GetMyTracksDir():
'''
Returns the directory in which the MyTracks directory is located.
'''
path = os.getcwd()
while not os.path.isdir(os.path.join(path, MYTRACKS_RES_DIR)):
if path == '/':
raise 'Not in My Tracks project'
# Go up one level
path = os.path.split(path)[0]
return path
def GetAllLanguageFiles():
'''
Returns a mapping from all found languages to their respective directories.
'''
mytracks_path = GetMyTracksDir()
res_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_VALUES_MASK)
language_dirs = glob(res_dir)
master_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_MASTER_VALUES)
if len(language_dirs) == 0:
raise 'No languages found!'
if not os.path.isdir(master_dir):
raise 'Couldn\'t find master file'
language_tuples = [(re.findall(r'.*values-([A-Za-z-]+)', dir)[0],dir) for dir in language_dirs]
language_tuples.append(('en', master_dir))
return dict(language_tuples)
| Python |
import pyglet
import random
import time
from pyglet.window import Window
win = Window(width=640, height=480)
win.set_fullscreen(True)
win.set_mouse_visible(False)
a=True
@win.event
def on_key_press(symbol, modifiers):
win.set_fullscreen(False)
@win.event
def on_draw():
global a
if a==False:
pyglet.gl.glClearColor(random.random(),random.random(),random.random(),random.random())
a=True
else:
pyglet.gl.glClearColor(0,0,0,0)
a=False
win.clear()
def update(dt):
time.sleep(0.05)
pyglet.clock.schedule(update)
from pyglet import app
app.run() | Python |
# coding:utf8
import unittest
from unittest import TestCase
from hgwebcommit.actions import Action, ActionManager
class ActionTestCase(TestCase):
"""
Actionのテスト
"""
def test_call(self):
action = Action('test', 'test', lambda :'ok')
self.assertEqual(action(), 'ok')
class ActionManagerTestCase(TestCase):
"""
ActionManagerのテスト
"""
def setUp(self):
self.action = Action('test', 'test', lambda :'ok')
self.manager = ActionManager()
def test_add(self):
self.manager.add(self.action)
self.assertEqual(len(self.manager.actions), 1)
def test_call(self):
self.manager.add(self.action)
self.assertEqual(self.manager.call('test'), 'ok')
if __name__ == '__main__':
unittest.main()
| Python |
# app
from hgwebcommit import app
# config
SECRET_KEY = '(secret key)'
HGWEBCOMMIT_REPOSITORY = '/path/to/repository'
HGWEBCOMMIT_ENCODING = 'utf-8'
HGWEBCOMMIT_ALLOW_COMMIT = True
# actions
HGWEBCOMMIT_ACTIONS = (
# 'hgwebcommit.actions.hello',
)
if __name__ == '__main__':
app.debug = True
app.config.from_object(__name__)
app.run(host='0.0.0.0')
| Python |
from flaskext.wtf import Form
from flaskext.wtf import SelectMultipleField, IntegerField, HiddenField, TextField, SelectField
from flaskext.wtf import HiddenInput, Required
from flaskext.babel import lazy_gettext as _
class SelectFileForm(Form):
files = SelectMultipleField('Files', validators=[Required()])
class SelectFileConfirmForm(SelectFileForm):
confirm = IntegerField(widget=HiddenInput())
class SelectFileSubmitConfirmForm(SelectFileConfirmForm):
operation = HiddenField(validators=[Required()])
commit_message = TextField(_('Commit message'))
class SelectActionForm(Form):
action = SelectField('Action', validators=[Required()])
| Python |
import os
from mercurial import cmdutil
from mercurial import commands
from mercurial.util import datestr
from mercurial.hg import repository
from mercurial.ui import ui
from mercurial.match import match
from mercurial.node import short
class MercurialWrapper(object):
def __init__(self, path, encoding='utf-8'):
self.path = os.path.normpath(path)
self.ui = ui()
self.ui.readconfig(os.path.join(self.path, '.hg', 'hgrc'))
self.repository = repository(self.ui, self.path)
self.encoding = encoding
@property
def name(self):
return os.path.basename(self.path)
@property
def parent_node(self):
return self.repository['']
def parent_date(self):
return datestr(self.parent_node.date())
def parent_branch(self):
return self.parent_node.branch()
def parent_revision(self):
return short(self.parent_node.node())
def parent_number(self):
return self.parent_node.rev()
def branch(self):
return self.repository[None].branch()
def status_modified(self):
return self.repository.status()[0]
def status_added(self):
return self.repository.status()[1]
def status_removed(self):
return self.repository.status()[2]
def status_deleted(self):
return self.repository.status()[3]
def status_unknown(self):
return self.repository.status(unknown=True)[4]
def add(self, files):
self.repository[None].add(files)
def commit(self, files, commit_message):
self.repository.commit(
text=commit_message.encode(self.encoding),
match=match(self.repository.root, self.repository.root, None, include=files)
)
def revert(self, files, no_backup=True):
opts = {
'no_backup': no_backup,
'date': '',
'rev': '',
}
commands.revert(self.ui, self.repository, *[os.path.join(self.path, fn) for fn in files], **opts)
def remove(self, files):
self.repository[None].remove(files)
| Python |
from flask import flash
from flaskext.babel import gettext, lazy_gettext
from hgwebcommit.actions.decorators import action
@action('hello', lazy_gettext('Hello'))
def hello():
flash(gettext('Hello!'))
| Python |
from hgwebcommit.actions import Action, manager
def action(name, label, params=None):
def _wrap(func):
obj = Action(name, label, func, params)
manager.add(obj)
return func
return _wrap
| Python |
# coding:utf-8
from werkzeug import import_string
from hgwebcommit import app
class ActionLoader(object):
def load_actions(self):
action_modules = app.config.get('HGWEBCOMMIT_ACTIONS') or []
for mod_name in action_modules:
mod = import_string(mod_name)
| Python |
class InvalidAction(Exception):
pass
class Action(object):
def __init__(self, name, label, func, params=None):
self.name = name
self.label = label
self.func = func
self.params = params
def __call__(self, *args, **kwargs):
if self.params:
kwargs.update(self.params)
return self.func(*args, **kwargs)
class ActionManager(object):
def __init__(self):
self._actions = []
self.loaded = False
@property
def actions(self):
"""
proxy access to actions property
"""
if not self.loaded:
self.loaded = True
from hgwebcommit.actions import loader
loader.load_actions()
return self._actions
def add(self, action):
"""
add action
"""
self._actions.append(action)
def list(self):
"""
list actions
result: (name, label)
eg: use choices.
"""
return [(action.name, action.label) for action in self.actions]
def pick(self, name):
"""
return action by name
"""
for action in self.actions:
if action.name == name:
return action
raise InvalidAction('No such action "%s"' % name)
def call(self, name, *args, **kwargs):
"""
call action by name
"""
action = self.pick(name)
return action(*args, **kwargs)
| Python |
from hgwebcommit.actions.base import InvalidAction, Action, ActionManager
from hgwebcommit.actions.loaders import ActionLoader
manager = ActionManager()
loader = ActionLoader()
| Python |
import os
import socket
import logging
from copy import copy
from werkzeug import MultiDict
from flask import Flask, render_template, request, abort, redirect, url_for, session, flash
from flaskext.babel import gettext as _
from flaskext.babel import lazy_gettext
from hgwebcommit import app
from hgwebcommit.hgwrapper import MercurialWrapper
from hgwebcommit.forms import SelectFileForm, SelectFileConfirmForm, SelectFileSubmitConfirmForm, SelectActionForm
from hgwebcommit.actions import manager as action_manager
# const
OPERATION_MESSAGE = {
'commit': lazy_gettext('Commit'),
'revert': lazy_gettext('Revert'),
'remove': lazy_gettext('Remove'),
}
# util
def get_repo():
return MercurialWrapper(app.config['HGWEBCOMMIT_REPOSITORY'], app.config['HGWEBCOMMIT_ENCODING'])
def get_allow_commit():
return app.config.get('HGWEBCOMMIT_ALLOW_COMMIT', True)
def get_choices_ctrl(repo):
return [(val, 'M %s' % val) for val in repo.status_modified()] + \
[(val, 'A %s' % val) for val in repo.status_added()] + \
[(val, 'R %s' % val) for val in repo.status_removed()] + \
[(val, '! %s' % val) for val in repo.status_deleted()]
def get_choices_unknown(repo):
return [(val, '? %s' % val) for val in repo.status_unknown()]
def operation_repo(repo, operation, files, commit_message=None):
if operation == 'commit':
# commit
repo.commit(files, commit_message)
return _('commited.')
elif operation == 'revert':
# revert
repo.revert(files)
return _('reverted.')
elif operation == 'remove':
# remove
repo.remove(files)
return _('removed.')
else:
abort(400)
def gethostname():
return socket.gethostname()
# entry points
@app.route('/')
def index():
"""
top page
"""
repo = get_repo()
form_ctrl = SelectFileForm(request.form, prefix='ctrl-')
form_unknown = SelectFileForm(request.form)
form_ctrl.files.choices = get_choices_ctrl(repo)
form_unknown.files.choices = get_choices_unknown(repo)
form_actions = SelectActionForm(request.form, prefix='action-')
form_actions.action.choices = action_manager.list()
return render_template('index.html',
repository=repo,
form_unknown=form_unknown,
form_ctrl=form_ctrl,
form_actions=form_actions,
hostname=gethostname(),
allow_commit=get_allow_commit(),
)
@app.route('/add_unknown', methods=['POST'])
def add_unknown_confirm():
"""
Show confirm on adding untracked files
"""
if not get_allow_commit():
abort(401)
repo = get_repo()
form = SelectFileConfirmForm(request.form)
form.files.choices = get_choices_unknown(repo)
if not form.validate():
abort(400)
if form.data.get('confirm'):
# add to repos
repo.add(form.data['files'])
flash(_('added.'))
return redirect(url_for('index'))
formdata = MultiDict(request.form)
del formdata['csrf']
form = SelectFileConfirmForm(None, confirm=1, **formdata)
form.files.choices = get_choices_unknown(repo)
form.validate()
return render_template('add_unknown_confirm.html',
repository=repo,
form=form,
hostname=gethostname(),
)
@app.route('/submit', methods=['POST'])
def submit_confirm():
"""
Show confirm submitting
"""
if not get_allow_commit():
abort(401)
repo = get_repo()
form = SelectFileSubmitConfirmForm(request.form, prefix='ctrl-')
form.files.choices = get_choices_ctrl(repo)
if not form.validate():
abort(400)
if form.data.get('confirm'):
# operation
message = operation_repo(repo, form.data['operation'], form.data['files'], form.data['commit_message'])
flash(message)
return redirect(url_for('index'))
formdata = MultiDict(request.form)
del formdata['ctrl-csrf']
form = SelectFileSubmitConfirmForm(None, prefix='ctrl-', confirm=1, **formdata)
form.files.choices = get_choices_ctrl(repo)
form.validate()
return render_template('submit.html',
repository=repo,
form=form,
message=OPERATION_MESSAGE.get(form.data['operation']),
enable_commit_message=form.data['operation'] == 'commit',
hostname=gethostname(),
)
@app.route('/exec_action', methods=['POST'])
def exec_action():
"""
Run action method
"""
form = SelectActionForm(request.form, prefix='action-')
form.action.choices = action_manager.list()
if form.validate():
response = action_manager.call(form.data['action'])
if response is not None:
return response
return redirect(url_for('index'))
| Python |
from flask import Flask, g, request
from flaskext.babel import Babel
app = Flask(__name__)
babel = Babel(app)
@babel.localeselector
def get_locale():
return request.accept_languages.best_match(['en', 'ja', 'ja_JP'])
import hgwebcommit.views
| Python |
'''
Module which brings history information about files from Mercurial.
@author: Rodrigo Damazio
'''
import re
import subprocess
REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*')
def _GetOutputLines(args):
'''
Runs an external process and returns its output as a list of lines.
@param args: the arguments to run
'''
process = subprocess.Popen(args,
stdout=subprocess.PIPE,
universal_newlines = True,
shell = False)
output = process.communicate()[0]
return output.splitlines()
def FillMercurialRevisions(filename, parsed_file):
'''
Fills the revs attribute of all strings in the given parsed file with
a list of revisions that touched the lines corresponding to that string.
@param filename: the name of the file to get history for
@param parsed_file: the parsed file to modify
'''
# Take output of hg annotate to get revision of each line
output_lines = _GetOutputLines(['hg', 'annotate', '-c', filename])
# Create a map of line -> revision (key is list index, line 0 doesn't exist)
line_revs = ['dummy']
for line in output_lines:
rev_match = REVISION_REGEX.match(line)
if not rev_match:
raise 'Unexpected line of output from hg: %s' % line
rev_hash = rev_match.group('hash')
line_revs.append(rev_hash)
for str in parsed_file.itervalues():
# Get the lines that correspond to each string
start_line = str['startLine']
end_line = str['endLine']
# Get the revisions that touched those lines
revs = []
for line_number in range(start_line, end_line + 1):
revs.append(line_revs[line_number])
# Merge with any revisions that were already there
# (for explict revision specification)
if 'revs' in str:
revs += str['revs']
# Assign the revisions to the string
str['revs'] = frozenset(revs)
def DoesRevisionSuperceed(filename, rev1, rev2):
'''
Tells whether a revision superceeds another.
This essentially means that the older revision is an ancestor of the newer
one.
This also returns True if the two revisions are the same.
@param rev1: the revision that may be superceeding the other
@param rev2: the revision that may be superceeded
@return: True if rev1 superceeds rev2 or they're the same
'''
if rev1 == rev2:
return True
# TODO: Add filename
args = ['hg', 'log', '-r', 'ancestors(%s)' % rev1, '--template', '{node|short}\n', filename]
output_lines = _GetOutputLines(args)
return rev2 in output_lines
def NewestRevision(filename, rev1, rev2):
'''
Returns which of two revisions is closest to the head of the repository.
If none of them is the ancestor of the other, then we return either one.
@param rev1: the first revision
@param rev2: the second revision
'''
if DoesRevisionSuperceed(filename, rev1, rev2):
return rev1
return rev2 | Python |
#!/usr/bin/python
'''
Entry point for My Tracks i18n tool.
@author: Rodrigo Damazio
'''
import mytracks.files
import mytracks.translate
import mytracks.validate
import sys
def Usage():
print 'Usage: %s <command> [<language> ...]\n' % sys.argv[0]
print 'Commands are:'
print ' cleanup'
print ' translate'
print ' validate'
sys.exit(1)
def Translate(languages):
'''
Asks the user to interactively translate any missing or oudated strings from
the files for the given languages.
@param languages: the languages to translate
'''
validator = mytracks.validate.Validator(languages)
validator.Validate()
missing = validator.missing_in_lang()
outdated = validator.outdated_in_lang()
for lang in languages:
untranslated = missing[lang] + outdated[lang]
if len(untranslated) == 0:
continue
translator = mytracks.translate.Translator(lang)
translator.Translate(untranslated)
def Validate(languages):
'''
Computes and displays errors in the string files for the given languages.
@param languages: the languages to compute for
'''
validator = mytracks.validate.Validator(languages)
validator.Validate()
error_count = 0
if (validator.valid()):
print 'All files OK'
else:
for lang, missing in validator.missing_in_master().iteritems():
print 'Missing in master, present in %s: %s:' % (lang, str(missing))
error_count = error_count + len(missing)
for lang, missing in validator.missing_in_lang().iteritems():
print 'Missing in %s, present in master: %s:' % (lang, str(missing))
error_count = error_count + len(missing)
for lang, outdated in validator.outdated_in_lang().iteritems():
print 'Outdated in %s: %s:' % (lang, str(outdated))
error_count = error_count + len(outdated)
return error_count
if __name__ == '__main__':
argv = sys.argv
argc = len(argv)
if argc < 2:
Usage()
languages = mytracks.files.GetAllLanguageFiles()
if argc == 3:
langs = set(argv[2:])
if not langs.issubset(languages):
raise 'Language(s) not found'
# Filter just to the languages specified
languages = dict((lang, lang_file)
for lang, lang_file in languages.iteritems()
if lang in langs or lang == 'en' )
cmd = argv[1]
if cmd == 'translate':
Translate(languages)
elif cmd == 'validate':
error_count = Validate(languages)
else:
Usage()
error_count = 0
print '%d errors found.' % error_count
| Python |
'''
Module which prompts the user for translations and saves them.
TODO: implement
@author: Rodrigo Damazio
'''
class Translator(object):
'''
classdocs
'''
def __init__(self, language):
'''
Constructor
'''
self._language = language
def Translate(self, string_names):
print string_names | Python |
'''
Module which compares languague files to the master file and detects
issues.
@author: Rodrigo Damazio
'''
import os
from mytracks.parser import StringsParser
import mytracks.history
class Validator(object):
def __init__(self, languages):
'''
Builds a strings file validator.
Params:
@param languages: a dictionary mapping each language to its corresponding directory
'''
self._langs = {}
self._master = None
self._language_paths = languages
parser = StringsParser()
for lang, lang_dir in languages.iteritems():
filename = os.path.join(lang_dir, 'strings.xml')
parsed_file = parser.Parse(filename)
mytracks.history.FillMercurialRevisions(filename, parsed_file)
if lang == 'en':
self._master = parsed_file
else:
self._langs[lang] = parsed_file
self._Reset()
def Validate(self):
'''
Computes whether all the data in the files for the given languages is valid.
'''
self._Reset()
self._ValidateMissingKeys()
self._ValidateOutdatedKeys()
def valid(self):
return (len(self._missing_in_master) == 0 and
len(self._missing_in_lang) == 0 and
len(self._outdated_in_lang) == 0)
def missing_in_master(self):
return self._missing_in_master
def missing_in_lang(self):
return self._missing_in_lang
def outdated_in_lang(self):
return self._outdated_in_lang
def _Reset(self):
# These are maps from language to string name list
self._missing_in_master = {}
self._missing_in_lang = {}
self._outdated_in_lang = {}
def _ValidateMissingKeys(self):
'''
Computes whether there are missing keys on either side.
'''
master_keys = frozenset(self._master.iterkeys())
for lang, file in self._langs.iteritems():
keys = frozenset(file.iterkeys())
missing_in_master = keys - master_keys
missing_in_lang = master_keys - keys
if len(missing_in_master) > 0:
self._missing_in_master[lang] = missing_in_master
if len(missing_in_lang) > 0:
self._missing_in_lang[lang] = missing_in_lang
def _ValidateOutdatedKeys(self):
'''
Computers whether any of the language keys are outdated with relation to the
master keys.
'''
for lang, file in self._langs.iteritems():
outdated = []
for key, str in file.iteritems():
# Get all revisions that touched master and language files for this
# string.
master_str = self._master[key]
master_revs = master_str['revs']
lang_revs = str['revs']
if not master_revs or not lang_revs:
print 'WARNING: No revision for %s in %s' % (key, lang)
continue
master_file = os.path.join(self._language_paths['en'], 'strings.xml')
lang_file = os.path.join(self._language_paths[lang], 'strings.xml')
# Assume that the repository has a single head (TODO: check that),
# and as such there is always one revision which superceeds all others.
master_rev = reduce(
lambda r1, r2: mytracks.history.NewestRevision(master_file, r1, r2),
master_revs)
lang_rev = reduce(
lambda r1, r2: mytracks.history.NewestRevision(lang_file, r1, r2),
lang_revs)
# If the master version is newer than the lang version
if mytracks.history.DoesRevisionSuperceed(lang_file, master_rev, lang_rev):
outdated.append(key)
if len(outdated) > 0:
self._outdated_in_lang[lang] = outdated
| Python |
'''
Module for dealing with resource files (but not their contents).
@author: Rodrigo Damazio
'''
import os.path
from glob import glob
import re
MYTRACKS_RES_DIR = 'MyTracks/res'
ANDROID_MASTER_VALUES = 'values'
ANDROID_VALUES_MASK = 'values-*'
def GetMyTracksDir():
'''
Returns the directory in which the MyTracks directory is located.
'''
path = os.getcwd()
while not os.path.isdir(os.path.join(path, MYTRACKS_RES_DIR)):
if path == '/':
raise 'Not in My Tracks project'
# Go up one level
path = os.path.split(path)[0]
return path
def GetAllLanguageFiles():
'''
Returns a mapping from all found languages to their respective directories.
'''
mytracks_path = GetMyTracksDir()
res_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_VALUES_MASK)
language_dirs = glob(res_dir)
master_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_MASTER_VALUES)
if len(language_dirs) == 0:
raise 'No languages found!'
if not os.path.isdir(master_dir):
raise 'Couldn\'t find master file'
language_tuples = [(re.findall(r'.*values-([A-Za-z-]+)', dir)[0],dir) for dir in language_dirs]
language_tuples.append(('en', master_dir))
return dict(language_tuples)
| Python |
'''
Module which parses a string XML file.
@author: Rodrigo Damazio
'''
from xml.parsers.expat import ParserCreate
import re
#import xml.etree.ElementTree as ET
class StringsParser(object):
'''
Parser for string XML files.
This object is not thread-safe and should be used for parsing a single file at
a time, only.
'''
def Parse(self, file):
'''
Parses the given file and returns a dictionary mapping keys to an object
with attributes for that key, such as the value, start/end line and explicit
revisions.
In addition to the standard XML format of the strings file, this parser
supports an annotation inside comments, in one of these formats:
<!-- KEEP_PARENT name="bla" -->
<!-- KEEP_PARENT name="bla" rev="123456789012" -->
Such an annotation indicates that we're explicitly inheriting form the
master file (and the optional revision says that this decision is compatible
with the master file up to that revision).
@param file: the name of the file to parse
'''
self._Reset()
# Unfortunately expat is the only parser that will give us line numbers
self._xml_parser = ParserCreate()
self._xml_parser.StartElementHandler = self._StartElementHandler
self._xml_parser.EndElementHandler = self._EndElementHandler
self._xml_parser.CharacterDataHandler = self._CharacterDataHandler
self._xml_parser.CommentHandler = self._CommentHandler
file_obj = open(file)
self._xml_parser.ParseFile(file_obj)
file_obj.close()
return self._all_strings
def _Reset(self):
self._currentString = None
self._currentStringName = None
self._currentStringValue = None
self._all_strings = {}
def _StartElementHandler(self, name, attrs):
if name != 'string':
return
if 'name' not in attrs:
return
assert not self._currentString
assert not self._currentStringName
self._currentString = {
'startLine' : self._xml_parser.CurrentLineNumber,
}
if 'rev' in attrs:
self._currentString['revs'] = [attrs['rev']]
self._currentStringName = attrs['name']
self._currentStringValue = ''
def _EndElementHandler(self, name):
if name != 'string':
return
assert self._currentString
assert self._currentStringName
self._currentString['value'] = self._currentStringValue
self._currentString['endLine'] = self._xml_parser.CurrentLineNumber
self._all_strings[self._currentStringName] = self._currentString
self._currentString = None
self._currentStringName = None
self._currentStringValue = None
def _CharacterDataHandler(self, data):
if not self._currentString:
return
self._currentStringValue += data
_KEEP_PARENT_REGEX = re.compile(r'\s*KEEP_PARENT\s+'
r'name\s*=\s*[\'"]?(?P<name>[a-z0-9_]+)[\'"]?'
r'(?:\s+rev=[\'"]?(?P<rev>[0-9a-f]{12})[\'"]?)?\s*',
re.MULTILINE | re.DOTALL)
def _CommentHandler(self, data):
keep_parent_match = self._KEEP_PARENT_REGEX.match(data)
if not keep_parent_match:
return
name = keep_parent_match.group('name')
self._all_strings[name] = {
'keepParent' : True,
'startLine' : self._xml_parser.CurrentLineNumber,
'endLine' : self._xml_parser.CurrentLineNumber
}
rev = keep_parent_match.group('rev')
if rev:
self._all_strings[name]['revs'] = [rev] | Python |
# api code for the reviewboard extension, inspired/copied from reviewboard
# post-review code.
import cookielib
import getpass
import mimetools
import os
import urllib2
import simplejson
import mercurial.ui
from urlparse import urljoin, urlparse
class APIError(Exception):
pass
class ReviewBoardError(Exception):
def __init__(self, json=None):
self.msg = None
self.code = None
self.tags = {}
if isinstance(json, urllib2.URLError):
try:
json = json.read()
except:
json = ""
if isinstance(json, str) or isinstance(json, unicode):
try:
json = simplejson.loads(json)
except:
self.msg = "Unknown error - non-JSON response"
return
if json:
if json.has_key('err'):
self.msg = json['err']['msg']
self.code = json['err']['code']
for key, value in json.items():
if isinstance(value,unicode) or isinstance(value,str) or \
key == 'fields':
self.tags[key] = value
def __str__(self):
if self.msg:
return ("%s (%s)" % (self.msg, self.code)) + \
''.join([("\n%s: %s" % (k, v)) for k,v in self.tags.items()])
else:
return Exception.__str__(self)
class Repository:
"""
Represents a ReviewBoard repository
"""
def __init__(self, id, name, tool, path):
self.id = id
self.name = name
self.tool = tool
self.path = path
class ReviewBoardHTTPPasswordMgr(urllib2.HTTPPasswordMgr):
"""
Adds HTTP authentication support for URLs.
Python 2.4's password manager has a bug in http authentication when the
target server uses a non-standard port. This works around that bug on
Python 2.4 installs. This also allows post-review to prompt for passwords
in a consistent way.
See: http://bugs.python.org/issue974757
"""
def __init__(self, reviewboard_url):
self.passwd = {}
self.rb_url = reviewboard_url
self.rb_user = None
self.rb_pass = None
def set_credentials(self, username, password):
self.rb_user = username
self.rb_pass = password
def find_user_password(self, realm, uri):
if uri.startswith(self.rb_url):
if self.rb_user is None or self.rb_pass is None:
print "==> HTTP Authentication Required"
print 'Enter username and password for "%s" at %s' % \
(realm, urlparse(uri)[1])
self.rb_user = mercurial.ui.ui().prompt('Username: ')
self.rb_pass = getpass.getpass('Password: ')
return self.rb_user, self.rb_pass
else:
# If this is an auth request for some other domain (since HTTP
# handlers are global), fall back to standard password management.
return urllib2.HTTPPasswordMgr.find_user_password(self, realm, uri)
class ApiRequest(urllib2.Request):
"""
Allows HTTP methods other than GET and POST to be used
"""
def __init__(self, method, *args, **kwargs):
self._method = method
urllib2.Request.__init__(self, *args, **kwargs)
def get_method(self):
return self._method
class HttpErrorHandler(urllib2.HTTPDefaultErrorHandler):
"""
Error handler that doesn't throw an exception for any code below 400.
This is necessary because RB returns 2xx codes other than 200 to indicate
success.
"""
def http_error_default(self, req, fp, code, msg, hdrs):
if code >= 400:
return urllib2.HTTPDefaultErrorHandler.http_error_default(self,
req, fp, code, msg, hdrs)
else:
result = urllib2.HTTPError( req.get_full_url(), code, msg, hdrs, fp)
result.status = code
return result
class HttpClient:
def __init__(self, url, proxy=None):
if not url.endswith('/'):
url = url + '/'
self.url = url
if 'APPDATA' in os.environ:
homepath = os.environ["APPDATA"]
elif 'USERPROFILE' in os.environ:
homepath = os.path.join(os.environ["USERPROFILE"], "Local Settings",
"Application Data")
elif 'HOME' in os.environ:
homepath = os.environ["HOME"]
else:
homepath = ''
self.cookie_file = os.path.join(homepath, ".post-review-cookies.txt")
self._cj = cookielib.MozillaCookieJar(self.cookie_file)
self._password_mgr = ReviewBoardHTTPPasswordMgr(self.url)
self._opener = opener = urllib2.build_opener(
urllib2.ProxyHandler(proxy),
urllib2.UnknownHandler(),
urllib2.HTTPHandler(),
HttpErrorHandler(),
urllib2.HTTPErrorProcessor(),
urllib2.HTTPCookieProcessor(self._cj),
urllib2.HTTPBasicAuthHandler(self._password_mgr),
urllib2.HTTPDigestAuthHandler(self._password_mgr)
)
urllib2.install_opener(self._opener)
def set_credentials(self, username, password):
self._password_mgr.set_credentials(username, password)
def api_request(self, method, url, fields=None, files=None):
"""
Performs an API call using an HTTP request at the specified path.
"""
try:
rsp = self._http_request(method, url, fields, files)
if rsp:
return self._process_json(rsp)
else:
return None
except APIError, e:
rsp, = e.args
raise ReviewBoardError(rsp)
def has_valid_cookie(self):
"""
Load the user's cookie file and see if they have a valid
'rbsessionid' cookie for the current Review Board server. Returns
true if so and false otherwise.
"""
try:
parsed_url = urlparse(self.url)
host = parsed_url[1]
path = parsed_url[2] or '/'
# Cookie files don't store port numbers, unfortunately, so
# get rid of the port number if it's present.
host = host.split(":")[0]
print("Looking for '%s %s' cookie in %s" % \
(host, path, self.cookie_file))
self._cj.load(self.cookie_file, ignore_expires=True)
try:
cookie = self._cj._cookies[host][path]['rbsessionid']
if not cookie.is_expired():
print("Loaded valid cookie -- no login required")
return True
print("Cookie file loaded, but cookie has expired")
except KeyError:
print("Cookie file loaded, but no cookie for this server")
except IOError, error:
print("Couldn't load cookie file: %s" % error)
return False
def _http_request(self, method, path, fields, files):
"""
Performs an HTTP request on the specified path.
"""
if path.startswith('/'):
path = path[1:]
url = urljoin(self.url, path)
body = None
headers = {}
if fields or files:
content_type, body = self._encode_multipart_formdata(fields, files)
headers = {
'Content-Type': content_type,
'Content-Length': str(len(body))
}
try:
r = ApiRequest(method, str(url), body, headers)
data = urllib2.urlopen(r).read()
self._cj.save(self.cookie_file)
return data
except urllib2.URLError, e:
if not hasattr(e, 'code'):
raise
if e.code >= 400:
raise ReviewBoardError(e)
else:
return ""
def _process_json(self, data):
"""
Loads in a JSON file and returns the data if successful. On failure,
APIError is raised.
"""
rsp = simplejson.loads(data)
if rsp['stat'] == 'fail':
raise APIError, rsp
return rsp
def _encode_multipart_formdata(self, fields, files):
"""
Encodes data for use in an HTTP POST.
"""
BOUNDARY = mimetools.choose_boundary()
content = ""
fields = fields or {}
files = files or {}
for key in fields:
content += "--" + BOUNDARY + "\r\n"
content += "Content-Disposition: form-data; name=\"%s\"\r\n" % key
content += "\r\n"
content += str(fields[key]) + "\r\n"
for key in files:
filename = files[key]['filename']
value = files[key]['content']
content += "--" + BOUNDARY + "\r\n"
content += "Content-Disposition: form-data; name=\"%s\"; " % key
content += "filename=\"%s\"\r\n" % filename
content += "\r\n"
content += value + "\r\n"
content += "--" + BOUNDARY + "--\r\n"
content += "\r\n"
content_type = "multipart/form-data; boundary=%s" % BOUNDARY
return content_type, content
class ApiClient:
def __init__(self, httpclient):
self._httpclient = httpclient
def _api_request(self, method, url, fields=None, files=None):
return self._httpclient.api_request(method, url, fields, files)
class Api20Client(ApiClient):
"""
Implements the 2.0 version of the API
"""
def __init__(self, httpclient):
ApiClient.__init__(self, httpclient)
self._repositories = None
self._requestcache = {}
def login(self, username=None, password=None):
self._httpclient.set_credentials(username, password)
return
def repositories(self):
if not self._repositories:
rsp = self._api_request('GET', '/api/repositories/?max-results=500')
self._repositories = [Repository(r['id'], r['name'], r['tool'],
r['path'])
for r in rsp['repositories']]
return self._repositories
def new_request(self, repo_id, fields={}, diff='', parentdiff=''):
req = self._create_request(repo_id)
self._set_request_details(req, fields, diff, parentdiff)
self._requestcache[req['id']] = req
return req['id']
def update_request(self, id, fields={}, diff='', parentdiff='', publish=True):
req = self._get_request(id)
self._set_request_details(req, fields, diff, parentdiff)
if publish:
self.publish(id)
def publish(self, id):
req = self._get_request(id)
drafturl = req['links']['draft']['href']
self._api_request('PUT', drafturl, {'public':'1'})
def _create_request(self, repo_id):
data = { 'repository': repo_id }
result = self._api_request('POST', '/api/review-requests/', data)
return result['review_request']
def _get_request(self, id):
if self._requestcache.has_key(id):
return self._requestcache[id]
else:
result = self._api_request('GET', '/api/review-requests/%s/' % id)
self._requestcache[id] = result['review_request']
return result['review_request']
def _set_request_details(self, req, fields, diff, parentdiff):
if fields:
drafturl = req['links']['draft']['href']
self._api_request('PUT', drafturl, fields)
if diff:
diffurl = req['links']['diffs']['href']
data = {'path': {'filename': 'diff', 'content': diff}}
if parentdiff:
data['parent_diff_path'] = \
{'filename': 'parent_diff', 'content': parentdiff}
self._api_request('POST', diffurl, {}, data)
class Api10Client(ApiClient):
"""
Implements the 1.0 version of the API
"""
def __init__(self, httpclient):
ApiClient.__init__(self, httpclient)
self._repositories = None
self._requests = None
def _api_post(self, url, fields=None, files=None):
return self._api_request('POST', url, fields, files)
def login(self, username=None, password=None):
if not username and not password and self._httpclient.has_valid_cookie():
return
if not username:
username = mercurial.ui.ui().prompt('Username: ')
if not password:
password = getpass.getpass('Password: ')
self._api_post('/api/json/accounts/login/', {
'username': username,
'password': password,
})
def repositories(self):
if not self._repositories:
rsp = self._api_post('/api/json/repositories/')
self._repositories = [Repository(r['id'], r['name'], r['tool'],
r['path'])
for r in rsp['repositories']]
return self._repositories
def requests(self):
if not self._requests:
rsp = self._api_post('/api/json/reviewrequests/all/')
self._requests = rsp['review_requests']
return self._requests
def new_request(self, repo_id, fields={}, diff='', parentdiff=''):
repository_path = None
for r in self.repositories():
if r.id == int(repo_id):
repository_path = r.path
break
if not repository_path:
raise ReviewBoardError, ("can't find repository with id: %s" % \
repo_id)
id = self._create_request(repository_path)
self._set_request_details(id, fields, diff, parentdiff)
return id
def update_request(self, id, fields={}, diff='', parentdiff='', publish=True):
request_id = None
for r in self.requests():
if r['id'] == int(id):
request_id = int(id)
break
if not request_id:
raise ReviewBoardError, ("can't find request with id: %s" % id)
self._set_request_details(request_id, fields, diff, parentdiff)
return request_id
def publish(self, id):
self._api_post('api/json/reviewrequests/%s/publish/' % id)
def _create_request(self, repository_path):
data = { 'repository_path': repository_path }
rsp = self._api_post('/api/json/reviewrequests/new/', data)
return rsp['review_request']['id']
def _set_request_field(self, id, field, value):
self._api_post('/api/json/reviewrequests/%s/draft/set/' %
id, { field: value })
def _upload_diff(self, id, diff, parentdiff=""):
data = {'path': {'filename': 'diff', 'content': diff}}
if parentdiff:
data['parent_diff_path'] = \
{'filename': 'parent_diff', 'content': parentdiff}
rsp = self._api_post('/api/json/reviewrequests/%s/diff/new/' % \
id, {}, data)
def _set_fields(self, id, fields={}):
for field in fields:
self._set_request_field(id, field, fields[field])
def _set_request_details(self, id, fields, diff, parentdiff):
self._set_fields(id, fields)
if diff:
self._upload_diff(id, diff, parentdiff)
if fields or diff:
self._save_draft(id)
def _save_draft(self, id):
self._api_post("/api/json/reviewrequests/%s/draft/save/" % id )
def make_rbclient(url, username, password, proxy=None, apiver=''):
httpclient = HttpClient(url, proxy)
if not httpclient.has_valid_cookie():
if not username:
username = mercurial.ui.ui().prompt('Username: ')
if not password:
password = getpass.getpass('Password: ')
httpclient.set_credentials(username, password)
if not apiver:
# Figure out whether the server supports API version 2.0
try:
httpclient.api_request('GET', '/api/')
apiver = '2.0'
except:
apiver = '1.0'
if apiver == '2.0':
return Api20Client(httpclient)
elif apiver == '1.0':
cli = Api10Client(httpclient)
cli.login(username, password)
return cli
else:
raise Exception("Unknown API version: %s" % apiver)
| Python |
"""Implementation of JSONDecoder
"""
import re
import sys
import struct
from scanner import make_scanner
c_scanstring = None
__all__ = ['JSONDecoder']
FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
def _floatconstants():
_BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
if sys.byteorder != 'big':
_BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
nan, inf = struct.unpack('dd', _BYTES)
return nan, inf, -inf
NaN, PosInf, NegInf = _floatconstants()
def linecol(doc, pos):
lineno = doc.count('\n', 0, pos) + 1
if lineno == 1:
colno = pos
else:
colno = pos - doc.rindex('\n', 0, pos)
return lineno, colno
def errmsg(msg, doc, pos, end=None):
# Note that this function is called from _speedups
lineno, colno = linecol(doc, pos)
if end is None:
#fmt = '{0}: line {1} column {2} (char {3})'
#return fmt.format(msg, lineno, colno, pos)
fmt = '%s: line %d column %d (char %d)'
return fmt % (msg, lineno, colno, pos)
endlineno, endcolno = linecol(doc, end)
#fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})'
#return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end)
fmt = '%s: line %d column %d - line %d column %d (char %d - %d)'
return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end)
_CONSTANTS = {
'-Infinity': NegInf,
'Infinity': PosInf,
'NaN': NaN,
}
STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
BACKSLASH = {
'"': u'"', '\\': u'\\', '/': u'/',
'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t',
}
DEFAULT_ENCODING = "utf-8"
def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match):
"""Scan the string s for a JSON string. End is the index of the
character in s after the quote that started the JSON string.
Unescapes all valid JSON string escape sequences and raises ValueError
on attempt to decode an invalid string. If strict is False then literal
control characters are allowed in the string.
Returns a tuple of the decoded string and the index of the character in s
after the end quote."""
if encoding is None:
encoding = DEFAULT_ENCODING
chunks = []
_append = chunks.append
begin = end - 1
while 1:
chunk = _m(s, end)
if chunk is None:
raise ValueError(
errmsg("Unterminated string starting at", s, begin))
end = chunk.end()
content, terminator = chunk.groups()
# Content is contains zero or more unescaped string characters
if content:
if not isinstance(content, unicode):
content = unicode(content, encoding)
_append(content)
# Terminator is the end of string, a literal control character,
# or a backslash denoting that an escape sequence follows
if terminator == '"':
break
elif terminator != '\\':
if strict:
msg = "Invalid control character %r at" % (terminator,)
#msg = "Invalid control character {0!r} at".format(terminator)
raise ValueError(errmsg(msg, s, end))
else:
_append(terminator)
continue
try:
esc = s[end]
except IndexError:
raise ValueError(
errmsg("Unterminated string starting at", s, begin))
# If not a unicode escape sequence, must be in the lookup table
if esc != 'u':
try:
char = _b[esc]
except KeyError:
msg = "Invalid \\escape: " + repr(esc)
raise ValueError(errmsg(msg, s, end))
end += 1
else:
# Unicode escape sequence
esc = s[end + 1:end + 5]
next_end = end + 5
if len(esc) != 4:
msg = "Invalid \\uXXXX escape"
raise ValueError(errmsg(msg, s, end))
uni = int(esc, 16)
# Check for surrogate pair on UCS-4 systems
if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535:
msg = "Invalid \\uXXXX\\uXXXX surrogate pair"
if not s[end + 5:end + 7] == '\\u':
raise ValueError(errmsg(msg, s, end))
esc2 = s[end + 7:end + 11]
if len(esc2) != 4:
raise ValueError(errmsg(msg, s, end))
uni2 = int(esc2, 16)
uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
next_end += 6
char = unichr(uni)
end = next_end
# Append the unescaped character
_append(char)
return u''.join(chunks), end
# Use speedup if available
scanstring = c_scanstring or py_scanstring
WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)
WHITESPACE_STR = ' \t\n\r'
def JSONObject((s, end), encoding, strict, scan_once, object_hook, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
pairs = {}
# Use a slice to prevent IndexError from being raised, the following
# check will raise a more specific ValueError if the string is empty
nextchar = s[end:end + 1]
# Normally we expect nextchar == '"'
if nextchar != '"':
if nextchar in _ws:
end = _w(s, end).end()
nextchar = s[end:end + 1]
# Trivial empty object
if nextchar == '}':
return pairs, end + 1
elif nextchar != '"':
raise ValueError(errmsg("Expecting property name", s, end))
end += 1
while True:
key, end = scanstring(s, end, encoding, strict)
# To skip some function call overhead we optimize the fast paths where
# the JSON key separator is ": " or just ":".
if s[end:end + 1] != ':':
end = _w(s, end).end()
if s[end:end + 1] != ':':
raise ValueError(errmsg("Expecting : delimiter", s, end))
end += 1
try:
if s[end] in _ws:
end += 1
if s[end] in _ws:
end = _w(s, end + 1).end()
except IndexError:
pass
try:
value, end = scan_once(s, end)
except StopIteration:
raise ValueError(errmsg("Expecting object", s, end))
pairs[key] = value
try:
nextchar = s[end]
if nextchar in _ws:
end = _w(s, end + 1).end()
nextchar = s[end]
except IndexError:
nextchar = ''
end += 1
if nextchar == '}':
break
elif nextchar != ',':
raise ValueError(errmsg("Expecting , delimiter", s, end - 1))
try:
nextchar = s[end]
if nextchar in _ws:
end += 1
nextchar = s[end]
if nextchar in _ws:
end = _w(s, end + 1).end()
nextchar = s[end]
except IndexError:
nextchar = ''
end += 1
if nextchar != '"':
raise ValueError(errmsg("Expecting property name", s, end - 1))
if object_hook is not None:
pairs = object_hook(pairs)
return pairs, end
def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
values = []
nextchar = s[end:end + 1]
if nextchar in _ws:
end = _w(s, end + 1).end()
nextchar = s[end:end + 1]
# Look-ahead for trivial empty array
if nextchar == ']':
return values, end + 1
_append = values.append
while True:
try:
value, end = scan_once(s, end)
except StopIteration:
raise ValueError(errmsg("Expecting object", s, end))
_append(value)
nextchar = s[end:end + 1]
if nextchar in _ws:
end = _w(s, end + 1).end()
nextchar = s[end:end + 1]
end += 1
if nextchar == ']':
break
elif nextchar != ',':
raise ValueError(errmsg("Expecting , delimiter", s, end))
try:
if s[end] in _ws:
end += 1
if s[end] in _ws:
end = _w(s, end + 1).end()
except IndexError:
pass
return values, end
class JSONDecoder(object):
"""Simple JSON <http://json.org> decoder
Performs the following translations in decoding by default:
+---------------+-------------------+
| JSON | Python |
+===============+===================+
| object | dict |
+---------------+-------------------+
| array | list |
+---------------+-------------------+
| string | unicode |
+---------------+-------------------+
| number (int) | int, long |
+---------------+-------------------+
| number (real) | float |
+---------------+-------------------+
| true | True |
+---------------+-------------------+
| false | False |
+---------------+-------------------+
| null | None |
+---------------+-------------------+
It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
their corresponding ``float`` values, which is outside the JSON spec.
"""
def __init__(self, encoding=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, strict=True):
"""``encoding`` determines the encoding used to interpret any ``str``
objects decoded by this instance (utf-8 by default). It has no
effect when decoding ``unicode`` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as ``unicode``.
``object_hook``, if specified, will be called with the result
of every JSON object decoded and its return value will be used in
place of the given ``dict``. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN.
This can be used to raise an exception if invalid JSON numbers
are encountered.
"""
self.encoding = encoding
self.object_hook = object_hook
self.parse_float = parse_float or float
self.parse_int = parse_int or int
self.parse_constant = parse_constant or _CONSTANTS.__getitem__
self.strict = strict
self.parse_object = JSONObject
self.parse_array = JSONArray
self.parse_string = scanstring
self.scan_once = make_scanner(self)
def decode(self, s, _w=WHITESPACE.match):
"""Return the Python representation of ``s`` (a ``str`` or ``unicode``
instance containing a JSON document)
"""
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
end = _w(s, end).end()
if end != len(s):
raise ValueError(errmsg("Extra data", s, end, len(s)))
return obj
def raw_decode(self, s, idx=0):
"""Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
This can be used to decode a JSON document from a string that may
have extraneous data at the end.
"""
try:
obj, end = self.scan_once(s, idx)
except StopIteration:
raise ValueError("No JSON object could be decoded")
return obj, end
| Python |
"""JSON token scanner
"""
import re
c_make_scanner = None
__all__ = ['make_scanner']
NUMBER_RE = re.compile(
r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?',
(re.VERBOSE | re.MULTILINE | re.DOTALL))
def py_make_scanner(context):
parse_object = context.parse_object
parse_array = context.parse_array
parse_string = context.parse_string
match_number = NUMBER_RE.match
encoding = context.encoding
strict = context.strict
parse_float = context.parse_float
parse_int = context.parse_int
parse_constant = context.parse_constant
object_hook = context.object_hook
def _scan_once(string, idx):
try:
nextchar = string[idx]
except IndexError:
raise StopIteration
if nextchar == '"':
return parse_string(string, idx + 1, encoding, strict)
elif nextchar == '{':
return parse_object((string, idx + 1), encoding, strict, _scan_once, object_hook)
elif nextchar == '[':
return parse_array((string, idx + 1), _scan_once)
elif nextchar == 'n' and string[idx:idx + 4] == 'null':
return None, idx + 4
elif nextchar == 't' and string[idx:idx + 4] == 'true':
return True, idx + 4
elif nextchar == 'f' and string[idx:idx + 5] == 'false':
return False, idx + 5
m = match_number(string, idx)
if m is not None:
integer, frac, exp = m.groups()
if frac or exp:
res = parse_float(integer + (frac or '') + (exp or ''))
else:
res = parse_int(integer)
return res, m.end()
elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
return parse_constant('NaN'), idx + 3
elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
return parse_constant('Infinity'), idx + 8
elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
return parse_constant('-Infinity'), idx + 9
else:
raise StopIteration
return _scan_once
make_scanner = c_make_scanner or py_make_scanner
| Python |
"""Implementation of JSONEncoder
"""
import re
c_encode_basestring_ascii = None
c_make_encoder = None
ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
HAS_UTF8 = re.compile(r'[\x80-\xff]')
ESCAPE_DCT = {
'\\': '\\\\',
'"': '\\"',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
}
for i in range(0x20):
#ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
# Assume this produces an infinity on all machines (probably not guaranteed)
INFINITY = float('1e66666')
FLOAT_REPR = repr
def encode_basestring(s):
"""Return a JSON representation of a Python string
"""
def replace(match):
return ESCAPE_DCT[match.group(0)]
return '"' + ESCAPE.sub(replace, s) + '"'
def py_encode_basestring_ascii(s):
"""Return an ASCII-only JSON representation of a Python string
"""
if isinstance(s, str) and HAS_UTF8.search(s) is not None:
s = s.decode('utf-8')
def replace(match):
s = match.group(0)
try:
return ESCAPE_DCT[s]
except KeyError:
n = ord(s)
if n < 0x10000:
#return '\\u{0:04x}'.format(n)
return '\\u%04x' % (n,)
else:
# surrogate pair
n -= 0x10000
s1 = 0xd800 | ((n >> 10) & 0x3ff)
s2 = 0xdc00 | (n & 0x3ff)
#return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
return '\\u%04x\\u%04x' % (s1, s2)
return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
encode_basestring_ascii = c_encode_basestring_ascii or py_encode_basestring_ascii
class JSONEncoder(object):
"""Extensible JSON <http://json.org> encoder for Python data structures.
Supports the following objects and types by default:
+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str, unicode | string |
+-------------------+---------------+
| int, long, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+
To extend this to recognize other objects, subclass and implement a
``.default()`` method with another method that returns a serializable
object for ``o`` if possible, otherwise it should call the superclass
implementation (to raise ``TypeError``).
"""
item_separator = ', '
key_separator = ': '
def __init__(self, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=False,
indent=None, separators=None, encoding='utf-8', default=None):
"""Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt
encoding of keys that are not str, int, long, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str
objects with all incoming unicode characters escaped. If
ensure_ascii is false, the output will be unicode object.
If check_circular is true, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an OverflowError).
Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array
elements and object members will be pretty-printed with that
indent level. An indent level of 0 will only insert newlines.
None is the most compact representation.
If specified, separators should be a (item_separator, key_separator)
tuple. The default is (', ', ': '). To get the most compact JSON
representation you should specify (',', ':') to eliminate whitespace.
If specified, default is a function that gets called for objects
that can't otherwise be serialized. It should return a JSON encodable
version of the object or raise a ``TypeError``.
If encoding is not None, then all input strings will be
transformed into unicode using that encoding prior to JSON-encoding.
The default is UTF-8.
"""
self.skipkeys = skipkeys
self.ensure_ascii = ensure_ascii
self.check_circular = check_circular
self.allow_nan = allow_nan
self.sort_keys = sort_keys
self.indent = indent
if separators is not None:
self.item_separator, self.key_separator = separators
if default is not None:
self.default = default
self.encoding = encoding
def default(self, o):
"""Implement this method in a subclass such that it returns
a serializable object for ``o``, or calls the base implementation
(to raise a ``TypeError``).
For example, to support arbitrary iterators, you could
implement default like this::
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)
"""
raise TypeError(repr(o) + " is not JSON serializable")
def encode(self, o):
"""Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
"""
# This is for extremely simple cases and benchmarks.
if isinstance(o, basestring):
if isinstance(o, str):
_encoding = self.encoding
if (_encoding is not None
and not (_encoding == 'utf-8')):
o = o.decode(_encoding)
if self.ensure_ascii:
return encode_basestring_ascii(o)
else:
return encode_basestring(o)
# This doesn't pass the iterator directly to ''.join() because the
# exceptions aren't as detailed. The list call should be roughly
# equivalent to the PySequence_Fast that ''.join() would do.
chunks = self.iterencode(o, _one_shot=True)
if not isinstance(chunks, (list, tuple)):
chunks = list(chunks)
return ''.join(chunks)
def iterencode(self, o, _one_shot=False):
"""Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
"""
if self.check_circular:
markers = {}
else:
markers = None
if self.ensure_ascii:
_encoder = encode_basestring_ascii
else:
_encoder = encode_basestring
if self.encoding != 'utf-8':
def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
if isinstance(o, str):
o = o.decode(_encoding)
return _orig_encoder(o)
def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):
# Check for specials. Note that this type of test is processor- and/or
# platform-specific, so do tests which don't depend on the internals.
if o != o:
text = 'NaN'
elif o == _inf:
text = 'Infinity'
elif o == _neginf:
text = '-Infinity'
else:
return _repr(o)
if not allow_nan:
raise ValueError(
"Out of range float values are not JSON compliant: " +
repr(o))
return text
if _one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys:
_iterencode = c_make_encoder(
markers, self.default, _encoder, self.indent,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, self.allow_nan)
else:
_iterencode = _make_iterencode(
markers, self.default, _encoder, self.indent, floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot)
return _iterencode(o, 0)
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
## HACK: hand-optimized bytecode; turn globals into locals
False=False,
True=True,
ValueError=ValueError,
basestring=basestring,
dict=dict,
float=float,
id=id,
int=int,
isinstance=isinstance,
list=list,
long=long,
str=str,
tuple=tuple,
):
def _iterencode_list(lst, _current_indent_level):
if not lst:
yield '[]'
return
if markers is not None:
markerid = id(lst)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = lst
buf = '['
if _indent is not None:
_current_indent_level += 1
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
separator = _item_separator + newline_indent
buf += newline_indent
else:
newline_indent = None
separator = _item_separator
first = True
for value in lst:
if first:
first = False
else:
buf = separator
if isinstance(value, basestring):
yield buf + _encoder(value)
elif value is None:
yield buf + 'null'
elif value is True:
yield buf + 'true'
elif value is False:
yield buf + 'false'
elif isinstance(value, (int, long)):
yield buf + str(value)
elif isinstance(value, float):
yield buf + _floatstr(value)
else:
yield buf
if isinstance(value, (list, tuple)):
chunks = _iterencode_list(value, _current_indent_level)
elif isinstance(value, dict):
chunks = _iterencode_dict(value, _current_indent_level)
else:
chunks = _iterencode(value, _current_indent_level)
for chunk in chunks:
yield chunk
if newline_indent is not None:
_current_indent_level -= 1
yield '\n' + (' ' * (_indent * _current_indent_level))
yield ']'
if markers is not None:
del markers[markerid]
def _iterencode_dict(dct, _current_indent_level):
if not dct:
yield '{}'
return
if markers is not None:
markerid = id(dct)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = dct
yield '{'
if _indent is not None:
_current_indent_level += 1
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
item_separator = _item_separator + newline_indent
yield newline_indent
else:
newline_indent = None
item_separator = _item_separator
first = True
if _sort_keys:
items = dct.items()
items.sort(key=lambda kv: kv[0])
else:
items = dct.iteritems()
for key, value in items:
if isinstance(key, basestring):
pass
# JavaScript is weakly typed for these, so it makes sense to
# also allow them. Many encoders seem to do something like this.
elif isinstance(key, float):
key = _floatstr(key)
elif key is True:
key = 'true'
elif key is False:
key = 'false'
elif key is None:
key = 'null'
elif isinstance(key, (int, long)):
key = str(key)
elif _skipkeys:
continue
else:
raise TypeError("key " + repr(key) + " is not a string")
if first:
first = False
else:
yield item_separator
yield _encoder(key)
yield _key_separator
if isinstance(value, basestring):
yield _encoder(value)
elif value is None:
yield 'null'
elif value is True:
yield 'true'
elif value is False:
yield 'false'
elif isinstance(value, (int, long)):
yield str(value)
elif isinstance(value, float):
yield _floatstr(value)
else:
if isinstance(value, (list, tuple)):
chunks = _iterencode_list(value, _current_indent_level)
elif isinstance(value, dict):
chunks = _iterencode_dict(value, _current_indent_level)
else:
chunks = _iterencode(value, _current_indent_level)
for chunk in chunks:
yield chunk
if newline_indent is not None:
_current_indent_level -= 1
yield '\n' + (' ' * (_indent * _current_indent_level))
yield '}'
if markers is not None:
del markers[markerid]
def _iterencode(o, _current_indent_level):
if isinstance(o, basestring):
yield _encoder(o)
elif o is None:
yield 'null'
elif o is True:
yield 'true'
elif o is False:
yield 'false'
elif isinstance(o, (int, long)):
yield str(o)
elif isinstance(o, float):
yield _floatstr(o)
elif isinstance(o, (list, tuple)):
for chunk in _iterencode_list(o, _current_indent_level):
yield chunk
elif isinstance(o, dict):
for chunk in _iterencode_dict(o, _current_indent_level):
yield chunk
else:
if markers is not None:
markerid = id(o)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = o
o = _default(o)
for chunk in _iterencode(o, _current_indent_level):
yield chunk
if markers is not None:
del markers[markerid]
return _iterencode
| Python |
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
:mod:`simplejson` exposes an API familiar to users of the standard library
:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
version of the :mod:`json` library contained in Python 2.6, but maintains
compatibility with Python 2.4 and Python 2.5 and (currently) has
significant performance advantages, even without using the optional C
extension for speedups.
Encoding basic Python object hierarchies::
>>> import simplejson as json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print json.dumps("\"foo\bar")
"\"foo\bar"
>>> print json.dumps(u'\u1234')
"\u1234"
>>> print json.dumps('\\')
"\\"
>>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
{"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
Compact encoding::
>>> import simplejson as json
>>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
'[1,2,3,{"4":5,"6":7}]'
Pretty printing::
>>> import simplejson as json
>>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
>>> print '\n'.join([l.rstrip() for l in s.splitlines()])
{
"4": 5,
"6": 7
}
Decoding JSON::
>>> import simplejson as json
>>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
True
>>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
True
>>> from StringIO import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)[0] == 'streaming API'
True
Specializing JSON object decoding::
>>> import simplejson as json
>>> def as_complex(dct):
... if '__complex__' in dct:
... return complex(dct['real'], dct['imag'])
... return dct
...
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
... object_hook=as_complex)
(1+2j)
>>> import decimal
>>> json.loads('1.1', parse_float=decimal.Decimal) == decimal.Decimal('1.1')
True
Specializing JSON object encoding::
>>> import simplejson as json
>>> def encode_complex(obj):
... if isinstance(obj, complex):
... return [obj.real, obj.imag]
... raise TypeError(repr(o) + " is not JSON serializable")
...
>>> json.dumps(2 + 1j, default=encode_complex)
'[2.0, 1.0]'
>>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
'[2.0, 1.0]'
>>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
'[2.0, 1.0]'
Using simplejson.tool from the shell to validate and pretty-print::
$ echo '{"json":"obj"}' | python -m simplejson.tool
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -m simplejson.tool
Expecting property name: line 1 column 2 (char 2)
"""
__version__ = '2.0.9'
__all__ = [
'dump', 'dumps', 'load', 'loads',
'JSONDecoder', 'JSONEncoder',
]
__author__ = 'Bob Ippolito <bob@redivi.com>'
from decoder import JSONDecoder
from encoder import JSONEncoder
_default_encoder = JSONEncoder(
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
indent=None,
separators=None,
encoding='utf-8',
default=None,
)
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw):
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, then the some chunks written to ``fp``
may be ``unicode`` instances, subject to normal Python ``str`` to
``unicode`` coercion rules. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
to cause an error.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
in strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and object
members will be pretty-printed with that indent level. An indent level
of 0 will only insert newlines. ``None`` is the most compact representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (not skipkeys and ensure_ascii and
check_circular and allow_nan and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and not kw):
iterable = _default_encoder.iterencode(obj)
else:
if cls is None:
cls = JSONEncoder
iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding,
default=default, **kw).iterencode(obj)
# could accelerate with writelines in some versions of Python, at
# a debuggability cost
for chunk in iterable:
fp.write(chunk)
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw):
"""Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is false then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, then the return value will be a
``unicode`` instance subject to normal Python ``str`` to ``unicode``
coercion rules instead of being escaped to an ASCII ``str``.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (not skipkeys and ensure_ascii and
check_circular and allow_nan and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and not kw):
return _default_encoder.encode(obj)
if cls is None:
cls = JSONEncoder
return cls(
skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding, default=default,
**kw).encode(obj)
_default_decoder = JSONDecoder(encoding=None, object_hook=None)
def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw):
"""Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
If the contents of ``fp`` is encoded with an ASCII based encoding other
than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
be specified. Encodings that are not ASCII based (such as UCS-2) are
not allowed, and should be wrapped with
``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
object and passed to ``loads()``
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
return loads(fp.read(),
encoding=encoding, cls=cls, object_hook=object_hook,
parse_float=parse_float, parse_int=parse_int,
parse_constant=parse_constant, **kw)
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw):
"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
if (cls is None and encoding is None and object_hook is None and
parse_int is None and parse_float is None and
parse_constant is None and not kw):
return _default_decoder.decode(s)
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw['object_hook'] = object_hook
if parse_float is not None:
kw['parse_float'] = parse_float
if parse_int is not None:
kw['parse_int'] = parse_int
if parse_constant is not None:
kw['parse_constant'] = parse_constant
return cls(encoding=encoding, **kw).decode(s)
| Python |
'''post changesets to a reviewboard server'''
import os, errno, re
import cStringIO
from distutils.version import LooseVersion
from mercurial import cmdutil, hg, ui, mdiff, patch, util, node
from mercurial.i18n import _
from reviewboard import make_rbclient, ReviewBoardError
def postreview(ui, repo, rev='.', **opts):
'''post a changeset to a Review Board server
This command creates a new review request on a Review Board server, or updates
an existing review request, based on a changeset in the repository. If no
revision number is specified the parent revision of the working directory is
used.
By default, the diff uploaded to the server is based on the parent of the
revision to be reviewed. A different parent may be specified using the
--parent or --longdiff options. --parent r specifies the revision to use on the
left side while --longdiff looks at the upstream repository specified in .hg/hgrc
to find a common ancestor to use on the left side. --parent may need one of
the options below if the Review Board server can't see the parent.
If the parent revision is not available to the Review Board server (e.g. it
exists in your local repository but not in the one that Review Board has
access to) you must tell postreview how to determine the base revision
to use for a parent diff. The --outgoing, --outgoingrepo or --master options
may be used for this purpose. The --outgoing option is the simplest of these;
it assumes that the upstream repository specified in .hg/hgrc is the same as
the one known to Review Board. The other two options offer more control if
this is not the case. In these cases two diffs are uploaded to Review Board:
the first is the difference between Reviewboard's view of the repo and your
parent revision(left side), the second is the difference between your parent
revision and your review revision(right side). Only the second diff is
under review. If you wish to review all the changes local to your repo use
the --longdiff option above.
The --outgoing option recognizes the path entries 'reviewboard', 'default-push'
and 'default' in this order of precedence. 'reviewboard' may be used if the
repository accessible to Review Board is not the upstream repository.
The --git option causes postreview to generate diffs in Git extended format,
which includes information about file renames and copies. ReviewBoard 1.6 beta
2 or later is required in order to use this feature.
The reviewboard extension may be configured by adding a [reviewboard] section
to your .hgrc or mercurial.ini file, or to the .hg/hgrc file of an individual
repository. The following options are available::
[reviewboard]
# REQUIRED
server = <server_url> # The URL of your ReviewBoard server
# OPTIONAL
http_proxy = <proxy_url> # HTTP proxy to use for the connection
user = <rb_username> # Username to use for ReviewBoard
# connections
password = <rb_password> # Password to use for ReviewBoard
# connections
repoid = <repoid> # ReviewBoard repository ID (normally only
# useful in a repository-specific hgrc)
target_groups = <groups> # Default groups for new review requests
# (comma-separated list)
target_people = <users> # Default users for new review requests
# (comma-separated list)
explicit_publish_update = <bool> # If True, updates posted using the -e
# option will not be published immediately
# unless the -p option is also used
launch_webbrowser = <bool> # If True, new or updated requests will
# always be shown in a web browser after
# posting.
'''
server = opts.get('server')
if not server:
server = ui.config('reviewboard', 'server')
if not server:
raise util.Abort(
_('please specify a reviewboard server in your .hgrc file') )
'''We are going to fetch the setting string from hg prefs, there we can set
our own proxy, or specify 'none' to pass an empty dictionary to urllib2
which overides the default autodetection when we want to force no proxy'''
http_proxy = ui.config('reviewboard', 'http_proxy' )
if http_proxy:
if http_proxy == 'none':
proxy = {}
else:
proxy = { 'http':http_proxy }
else:
proxy=None
def getdiff(ui, repo, r, parent, opts):
'''return diff for the specified revision'''
output = ""
if opts.get('git') or ui.configbool('diff', 'git'):
# Git diffs don't include the revision numbers with each file, so
# we have to put them in the header instead.
output += "# Node ID " + node.hex(r.node()) + "\n"
output += "# Parent " + node.hex(parent.node()) + "\n"
diffopts = patch.diffopts(ui, opts)
for chunk in patch.diff(repo, parent.node(), r.node(), opts=diffopts):
output += chunk
return output
parent = opts.get('parent')
if parent:
parent = repo[parent]
else:
parent = repo[rev].parents()[0]
outgoing = opts.get('outgoing')
outgoingrepo = opts.get('outgoingrepo')
master = opts.get('master')
repo_id_opt = opts.get('repoid')
longdiff = opts.get('longdiff')
if not repo_id_opt:
repo_id_opt = ui.config('reviewboard','repoid')
if master:
rparent = repo[master]
elif outgoingrepo:
rparent = remoteparent(ui, repo, opts, rev, upstream=outgoingrepo)
elif outgoing:
rparent = remoteparent(ui, repo, opts, rev)
elif longdiff:
parent = remoteparent(ui, repo, opts, rev)
rparent = None
else:
rparent = None
ui.debug(_('Parent is %s\n' % parent))
ui.debug(_('Remote parent is %s\n' % rparent))
request_id = None
if opts.get('existing'):
request_id = opts.get('existing')
fields = {}
c = repo.changectx(rev)
changesets_string = get_changesets_string(repo, parent, c)
# Don't clobber the summary and description for an existing request
# unless specifically asked for
if opts.get('update') or not request_id:
fields['summary'] = toascii(c.description().splitlines()[0])
fields['description'] = toascii(changesets_string)
fields['branch'] = toascii(c.branch())
if opts.get('summary'):
fields['summary'] = toascii(opts.get('summary'))
diff = getdiff(ui, repo, c, parent, opts)
ui.debug('\n=== Diff from parent to rev ===\n')
ui.debug(diff + '\n')
if rparent and parent != rparent:
parentdiff = getdiff(ui, repo, parent, rparent, opts)
ui.debug('\n=== Diff from rparent to parent ===\n')
ui.debug(parentdiff + '\n')
else:
parentdiff = ''
for field in ('target_groups', 'target_people'):
if opts.get(field):
value = ','.join(opts.get(field))
else:
value = ui.config('reviewboard', field)
if value:
fields[field] = toascii(value)
ui.status('\n%s\n' % changesets_string)
ui.status('reviewboard:\t%s\n' % server)
ui.status('\n')
username = opts.get('username') or ui.config('reviewboard', 'user')
if username:
ui.status('username: %s\n' % username)
password = opts.get('password') or ui.config('reviewboard', 'password')
if password:
ui.status('password: %s\n' % '**********')
try:
reviewboard = make_rbclient(server, username, password, proxy=proxy,
apiver=opts.get('apiver'))
except Exception, e:
raise util.Abort(_(str(e)))
if request_id:
try:
reviewboard.update_request(request_id, fields=fields, diff=diff,
parentdiff=parentdiff, publish=opts.get('publish') or
not ui.configbool('reviewboard', 'explicit_publish_update'))
except ReviewBoardError, msg:
raise util.Abort(_(str(msg)))
else:
if repo_id_opt:
repo_id = str(int(repo_id_opt))
else:
try:
repositories = reviewboard.repositories()
except ReviewBoardError, msg:
raise util.Abort(_(str(msg)))
if not repositories:
raise util.Abort(_('no repositories configured at %s' % server))
ui.status('Repositories:\n')
repo_ids = set()
for r in repositories:
ui.status('[%s] %s\n' % (r.id, r.name) )
repo_ids.add(str(r.id))
if len(repositories) > 1:
repo_id = ui.prompt('repository id:', 0)
if not repo_id in repo_ids:
raise util.Abort(_('invalid repository ID: %s') % repo_id)
else:
repo_id = str(repositories[0].id)
ui.status('repository id: %s\n' % repo_id)
try:
request_id = reviewboard.new_request(repo_id, fields, diff, parentdiff)
if opts.get('publish'):
reviewboard.publish(request_id)
except ReviewBoardError, msg:
raise util.Abort(_(str(msg)))
request_url = '%s/%s/%s/' % (server, "r", request_id)
if not request_url.startswith('http'):
request_url = 'http://%s' % request_url
msg = 'review request draft saved: %s\n'
if opts.get('publish'):
msg = 'review request published: %s\n'
ui.status(msg % request_url)
if opts.get('webbrowser') or \
ui.configbool('reviewboard', 'launch_webbrowser'):
launch_browser(ui, request_url)
def remoteparent(ui, repo, opts, rev, upstream=None):
if upstream:
remotepath = ui.expandpath(upstream)
else:
remotepath = ui.expandpath(ui.expandpath('reviewboard', 'default-push'),
'default')
remoterepo = hg.peer(repo, opts, remotepath)
out = findoutgoing(repo, remoterepo)
ancestors = repo.changelog.ancestors([repo.lookup(rev)])
for o in out:
orev = repo[o]
a, b, c = repo.changelog.nodesbetween([orev.node()], [repo[rev].node()])
if a:
return orev.parents()[0]
def findoutgoing(repo, remoterepo):
# The method for doing this has changed a few times...
try:
from mercurial import discovery
except ImportError:
# Must be earlier than 1.6
return repo.findoutgoing(remoterepo)
try:
if LooseVersion(util.version()) >= LooseVersion('2.1'):
outgoing = discovery.findcommonoutgoing(repo, remoterepo)
return outgoing.missing
common, outheads = discovery.findcommonoutgoing(repo, remoterepo)
return repo.changelog.findmissing(common=common, heads=outheads)
except AttributeError:
# Must be earlier than 1.9
return discovery.findoutgoing(repo, remoterepo)
def launch_browser(ui, request_url):
# not all python installations have the webbrowser module
from mercurial import demandimport
demandimport.disable()
try:
import webbrowser
webbrowser.open(request_url)
except:
ui.status('unable to launch browser - webbrowser module not available.')
demandimport.enable()
def toascii(s):
for i in xrange(len(s)):
if ord(s[i]) >= 128:
s = s[:i] + '?' + s[i+1:]
return s
def get_changesets_string(repo, parentctx, ctx):
"""Build a summary from all changesets included in this review."""
contexts = []
for node in repo.changelog.nodesbetween([parentctx.node()],[ctx.node()])[0]:
currctx = repo[node]
if node == parentctx.node():
continue
contexts.append(currctx)
if len(contexts) == 0:
contexts.append(ctx)
contexts.reverse()
changesets_string = '* * *\n\n'.join(
['Changeset %s:%s\n---------------------------\n%s\n' %
(ctx.rev(), ctx, ctx.description())
for ctx in contexts])
return changesets_string
cmdtable = {
"postreview":
(postreview,
[
('o', 'outgoing', False,
_('use upstream repository to determine the parent diff base')),
('O', 'outgoingrepo', '',
_('use specified repository to determine the parent diff base')),
('i', 'repoid', '',
_('specify repository id on reviewboard server')),
('m', 'master', '',
_('use specified revision as the parent diff base')),
('', 'server', '', _('ReviewBoard server URL')),
('g', 'git', False,
_('use git extended diff format (enables rename/copy support)')),
('e', 'existing', '', _('existing request ID to update')),
('u', 'update', False, _('update the fields of an existing request')),
('p', 'publish', None, _('publish request immediately')),
('', 'parent', '', _('parent revision for the uploaded diff')),
('l','longdiff', False,
_('review all changes since last upstream sync')),
('s', 'summary', '', _('summary for the review request')),
('U', 'target_people', [], _('comma separated list of people needed to review the code')),
('G', 'target_groups', [], _('comma separated list of groups needed to review the code')),
('w', 'webbrowser', False, _('launch browser to show review')),
('', 'username', '', _('username for the ReviewBoard site')),
('', 'password', '', _('password for the ReviewBoard site')),
('', 'apiver', '', _('ReviewBoard API version (e.g. 1.0, 2.0)')),
],
_('hg postreview [OPTION]... [REVISION]')),
}
| Python |
from flask import Flask, session, request, render_template, views, flash, redirect, url_for
# import flask
app = Flask(__name__)
# генерация ключа для работы с сессией
app.secret_key = "b8l\x0b~\xe3<y\xc5D\xb6v9\'D\xd0y\xeap\x80e\xcb&_\xc27"
@app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
else:
if 'logout' in request.form.values():
session.pop('username', None)
return redirect(url_for('login'))
username = request.form['username']
username = username.strip() # убираем пробелы
if username: # не пустая строка
session['username'] = username
return redirect('/welcome/')
else:
flash("Некорректно введено имя")
return redirect(url_for('login'))
@app.route('/welcome/', methods=['GET', 'POST'])
def welcome():
if request.method == 'GET':
if session:
return render_template('welcome.html')
else:
flash("Для доступа к запрашиваемой странице необходимо ввести логин")
return redirect(url_for('login'))
else:
pass
if __name__ == '__main__':
app.debug = True # режим отладки
app.run()
| Python |
import logging, os
# Google App Engine imports.
from google.appengine.ext.webapp import util
# Force Django to reload its settings.
from django.conf import settings
settings._target = None
# Must set this env var before importing any part of Django
# 'project' is the name of the project created with django-admin.py
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher
logging.getLogger().setLevel(logging.DEBUG)
def log_exception(*args, **kwds):
logging.exception('Exception in request:')
# Log errors.
django.dispatch.dispatcher.connect(
log_exception, django.core.signals.got_request_exception)
# Unregister the rollback event handler.
django.dispatch.dispatcher.disconnect(
django.db._rollback_on_exception,
django.core.signals.got_request_exception)
def main():
# Create a Django application for WSGI.
application = django.core.handlers.wsgi.WSGIHandler()
# Run the WSGI CGI handler with that application.
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| Python |
from google.appengine.api import users
from google.appengine.ext import db
from django.http import HttpResponse
from project.experts.models import User
def create(request):
experts = '''
Kundan Singh
kundan10@gmail.com
+1-917-621-6392
http://www.google.com
San Francisco, CA, USA
An independent consultant in VoIP/SIP, Python, programming.
sip, voip, python, programming
Available on weekdays during work hours.
Bill Gates
bill@microsoft.com
+1-111-111-1111
http://microsoft.com
Redmond, WA, USA
Founder of Microsoft Inc.
Windows, software, programming
Not available.
'''
response = []
for para in experts.strip().split('\n\n'):
if not para: continue
name, email, phone, website, address, description, tags, availability = map(str.strip, para.strip().split('\n'))
account = users.User(email=email)
user = db.GqlQuery('SELECT * FROM User WHERE account = :1', account).get()
if user:
response.append('User ' + email + ' exists')
else:
user = User(name=name, account=account, phone=phone, website=website, address=address, description=description,
tags=[x.strip() for x in tags.split(',') if x.strip()], availability=availability)
user.put()
response.append('Created User ' + email)
return HttpResponse('<br/>'.join(response))
| Python |
import random
from google.appengine.ext import db
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from project.experts.views.common import get_login_user, get_url
def _get_popular_topics(max_count=10):
tags = db.GqlQuery('SELECT * FROM Tag ORDER BY count DESC').fetch(max_count)
return [x.name for x in tags]
def _get_featured_experts(max_count=4, tags_count=2):
experts = db.GqlQuery('SELECT * FROM User ORDER BY rating DESC').fetch(max_count * 4)
experts = random.sample(experts, min(max_count, len(experts)))
return [{'email': u.email(),
'name': u.name,
'tags': ', '.join(random.sample(u.tags, min(tags_count, len(u.tags))))} for u in experts]
def index(request):
user = get_login_user(request)
if not user.is_active or user.name:
popular_topics = _get_popular_topics()
featured_experts = _get_featured_experts()
return render_to_response('experts/index.html',
{'user': user, 'popular_topics': popular_topics, 'featured_experts': featured_experts})
else:
return HttpResponseRedirect('/experts/%s/profile?continue=%s'%(user.email(), get_url(request)))
| Python |
import datetime, time, random, logging, sys, traceback
from google.appengine.api import users, channel, xmpp
from google.appengine.ext import db
from django.http import HttpResponse, HttpResponseServerError, HttpResponseForbidden
from django.shortcuts import render_to_response
from django.utils import simplejson as json
from project.experts.models import ClientStream, OfflineMessage
from project.experts.views.common import get_login_user
def index(request, account):
user = get_login_user(request)
stream = str(random.randint(100000000, 999999999))
token = channel.create_channel(stream)
is_my_office = bool(user.email() == account)
if is_my_office:
profile = user
else:
target = users.User(email=account)
profile = db.GqlQuery('SELECT * FROM User WHERE account = :1', target).get()
return render_to_response('experts/talk.html',
{'user': user, 'profile': profile, 'account': account,
'stream': stream, 'token': token, 'is_my_office': is_my_office})
# All GQL queries are done in separate methods.
def get_stream(clientId):
return db.GqlQuery('SELECT * FROM ClientStream WHERE clientId = :1', clientId).get()
def get_stream_by_publish(url):
return db.GqlQuery('SELECT * FROM ClientStream WHERE publish = :1', url).get()
def get_streams_of_owner(owner):
return db.GqlQuery('SELECT * FROM ClientStream WHERE owner = :1 AND is_owner = :2', owner, True)
def get_streams_of_visitors(owner):
return db.GqlQuery('SELECT * FROM ClientStream WHERE owner = :1 AND is_owner = :2', owner, False)
def get_streams_of_owner_by_visitor(owner, visitor):
return db.GqlQuery('SELECT * FROM ClientStream WHERE owner = :1 AND visitor = :2 AND is_owner = :3', owner, visitor, False)
def get_streams_expired():
return db.GqlQuery('SELECT * FROM ClientStream WHERE modified_on < :1', datetime.datetime.fromtimestamp(time.time()-90))
def get_messages_of_owner(owner):
return db.GqlQuery('SELECT * FROM OfflineMessage WHERE receiver = :1 ORDER BY created_on', owner)
# All channel messages are created in separate methods.
def get_disconnect_message():
return json.dumps({'method': 'connect', 'clientId': None, 'url': None})
def get_connect_message(stream):
return json.dumps({'method': 'connect', 'clientId': stream.clientId, 'name': stream.name, 'url': stream.publish})
def get_userlist_message(added=None, removed=None):
added, removed = added or [], removed or []
return json.dumps({'method': 'userlist', 'added': [x.get_object() for x in added], 'removed': [x.get_object(full=False) for x in removed]})
def get_send_message(senderId, senderName, text):
return json.dumps({'method':'send', 'senderId': senderId, 'senderName': senderName, 'text': text })
def get_send_error_message(error):
return json.dumps({'method':'send', 'senderId': None, 'senderName': 'System', 'text': error})
def send_message(stream, data):
try:
# logging.info('send_message %r %r'%(stream.clientId, data))
channel.send_message(stream.clientId, data)
except channel.InvalidChannelClientIdError:
pass
# Send a message using xmpp to the google chat user.
def send_message_to_google_chat(email, msg):
if email.endswith('@gmail.com'):
target = users.User(email=email)
target = db.GqlQuery('SELECT * FROM User WHERE account = :1', target).get()
if target and target.has_chat:
xmpp.send_message(email, msg)
def xmpp_handler(sender, receiver, body):
data = get_send_message('0', sender + ' (via Google chat)', body)
count = 0
if receiver[0] == '@':
stream = get_stream(receiver[1:])
if stream:
send_message(stream, data)
count = 1
elif '@' in receiver:
for stream in get_streams_of_owner_by_visitor(sender, receiver):
send_message(stream, data)
count += 1
return count
# Clean up the given stream by disconnecting it's other participant,
# and if delete is set, also delete this stream.
def cleanup_stream(stream, delete=True):
if stream.play:
other = get_stream_by_publish(stream.play)
if other:
if other.play:
send_message(other, get_disconnect_message())
other.play = None
other.put()
if delete:
# logging.info('cleanup_stream deleting %r'%(stream.clientId,))
stream.delete()
else:
stream.play = None
stream.put()
send_message(stream, get_disconnect_message())
# update the visitors list by sending userlist message to the owner
def update_visitors(owner, added=None, removed=None):
data = get_userlist_message(added, removed)
for stream in get_streams_of_owner(owner):
send_message(stream, data)
def command(request, account, command):
try:
return command_safe(request, account, command)
except:
type, value, tb = sys.exc_info()
printable = '\n'.join(traceback.format_exception(type, value, tb))
logging.info('exception in %s: %s'%(command, printable))
return HttpResponseServerError('Exception: ' + printable)
def command_safe(request, account, command):
user = get_login_user(request)
is_my_office = bool(user.email() == account)
if request.method == 'POST':
# for stream in db.GqlQuery('SELECT * FROM ClientStream'):
# logging.info(' stream: ' + str(stream))
input = json.loads(request.raw_post_data)
if command == 'end':
stream = get_stream(input['clientId'])
if stream:
if stream.visitor and stream.visitor != user.email():
return HttpResponseForbidden() # do not allow removal by others
cleanup_stream(stream)
if not is_my_office:
update_visitors(account, removed=[stream])
elif command == 'accept' or command == 'reject':
if not is_my_office:
# logging.info('found accept/reject without is_my_office')
return HttpResponseForbidden()
mine = get_stream(input['clientId'])
yours = get_stream(input['targetId'])
# logging.info('command=%r\n mine=%r\n yours=%r\n input=%r'%(command, mine, yours, input))
# disconnect previous participant when accepting a new one
if mine and command == 'accept' and mine.play and (not yours or mine.play != yours.publish):
# logging.info('deleting previous partner %r'%(mine.play,))
previous = get_stream_by_publish(mine.play)
if previous:
previous.play = None
previous.put()
send_message(previous, get_disconnect_message())
mine.play = None
# now connect mine and yours streams
if mine and yours:
if command == 'accept' and not mine.play and not yours.play:
# logging.info('connecting %r and %r'%(mine.clientId, yours.clientId))
mine.play, yours.play = yours.publish, mine.publish
elif command == 'reject' and (mine.play == yours.publish or yours.play == mine.publish):
# logging.info('disconnecting %r and %r'%(mine.clientId, yours.clientId))
mine.play = yours.play = None
mine.put()
yours.put()
if command == 'accept':
send_message(mine, get_connect_message(yours))
send_message(yours, get_connect_message(mine))
elif command == 'reject':
send_message(mine, get_disconnect_message())
send_message(yours, get_disconnect_message())
else:
return HttpResponseServerError('Some data on the server is not valid')
elif command == 'send':
# logging.info(' send input = %r'%(input,))
sender, senderName, text = get_stream(input['senderId']), input['senderName'], input['text']
if sender and sender.visitor and sender.visitor != user.email():
# logging.info('sender is invalid %r, user=%r'%(sender, user.email()))
return HttpResponseForbidden() # do not allow by others
if 'receiver' in input:
# send an inline message to the stream, and on error send back error message
receiver = get_stream_by_publish(input['receiver'])
if receiver:
# logging.info(' sending message to receiver %r'%(receiver,))
send_message(receiver, get_send_message(sender.clientId, senderName, text))
else:
# logging.info(' did not find receiver')
send_message(sender, get_send_error_message('Did not send message because you are not connected'))
if 'owner' in input and input['owner'] == account:
# put a message to all streams of this user
receivers = get_streams_of_owner(input['owner'])
sent_count = 0
for receiver in receivers:
input['senderName'] += ' (not connected)'
send_message(receiver, get_send_message(sender.clientId, senderName + ' (not connected)', text))
sent_count += 1
# put offline message if it could not be sent to existing streams
if sent_count == 0:
msg = OfflineMessage(sender=user.email(), senderName=senderName + ' (offline message)', receiver=input['owner'], text=text)
msg.put()
# also send message to google chat if possible
if not is_my_office:
send_message_to_google_chat(account, senderName + ' says ' + text)
elif command == 'publish':
# first delete any expired stream
for stream in get_streams_expired():
cleanup_stream(stream)
if not stream.is_owner:
data = get_userlist_message(removed=[stream])
for owner in get_streams_of_owner(stream.owner):
send_message(owner, data)
stream = get_stream(input['clientId'])
if not stream:
# create new Stream object
stream = ClientStream(clientId=input['clientId'], visitor=user.email(), name=input['name'], publish=input['url'], owner=account, is_owner=is_my_office)
stream.put()
# first update user list of owner
if not is_my_office:
data = get_userlist_message(added=[stream])
found = False
for owner in get_streams_of_owner(account):
send_message(owner, data)
found = True
# then send to google chat if account user is not online here
if not found:
contact = user.email() if user.email() else '@' + stream.clientId
msg = '%s visited your video office on %s GMT. Send your reply starting with %s to this person.'%(user.name, datetime.datetime.now(), contact)
send_message_to_google_chat(account, msg)
else:
stream.publish, stream.name = input['url'], input['name']
stream.modified_on = datetime.datetime.now()
stream.put() # so that last modified is updated
# logging.info('sending userlist and chathistory in response %r %r %r'%(is_my_office, user.email(), account))
if is_my_office: # return user list also
visitors = get_streams_of_visitors(account)
messages = get_messages_of_owner(account)
response = {'userlist': [x.get_object() for x in visitors], 'chathistory': [x.get_object() for x in messages]}
if response['chathistory']:
db.delete([x for x in messages])
return HttpResponse(json.dumps(response))
return HttpResponse('')
| Python |
from google.appengine.api import users
from google.appengine.ext import db
from django.shortcuts import render_to_response
from project.experts.views.common import get_login_user, clean_html
def search_result(user): # what to display in search result
return u'''
<li>
<a href="/experts/%s/calendar" title="View calendar"><img src="/static/media/img/admin/icon_calendar.gif"></img></a>
<b><a href="/experts/%s/profile" title="View profile">%s</a></b>: %s
<div class="rating_bar" style="float: right;" title="%.1f stars of %d reviews">
<div style="width:%d%%"></div>
</div>
<blockquote>%s%s</blockquote>
</li>
'''%(user.email(), user.email(), user.name, (', '.join(user.tags))[:100],
user.rating or 0.0, user.rating_count, int((user.rating or 0.0) * 20),
('%s %s %s<br/>'%(clean_html(user.phone_number) or '',
user.website and '<a href="' + clean_html(user.website) + '">' + clean_html(user.website) + '</a>' or '',
clean_html(user.address) or '')) if user.phone_number or user.address or user.website else '',
clean_html(user.description) or 'No description')
def index(request):
user = get_login_user(request)
error_message = status = ''
q = request.GET.get('q', '')
limit = int(request.GET.get('limit', '10'))
offset = int(request.GET.get('offset', '0'))
if ':' not in q:
tags = [x for x in q.split(' ') if x]
if tags:
query = 'SELECT * FROM User WHERE ' + ' AND '.join(['tags = :%d'%(i+1,) for i, x in enumerate(tags)]) + ' ORDER BY rating DESC'
result = db.GqlQuery(query, *tags).fetch(limit, offset)
result = [search_result(u) for u in result]
else:
result = []
else:
attr, value = [x.strip() for x in q.split(':', 1)]
if attr not in ('name', 'email', 'phone'):
error_message = 'Invalid attribute "%s", must be one of name, email or phone.'%(attr,)
else:
if attr == 'name':
query, arg = 'SELECT * FROM User WHERE name = :1', value
elif attr == 'email':
query, arg = 'SELECT * FROM User WHERE account = :1', users.User(email=value)
elif attr == 'phone':
query, arg = 'SELECT * FROM User WHERE phone_number = :1', value
result = db.GqlQuery(query, arg).fetch(limit, offset)
result = [search_result(u) for u in result]
if not result:
error_message = 'No match found. Please enter case sensitive exact value instead of "%s"'%(value,)
return render_to_response('experts/search.html',
{'user': user, 'status': status, 'error_message': error_message,
'query': q, 'result': result})
| Python |
from google.appengine.api import users
from project.experts.models import get_current_user
def get_url(request):
return 'http://' + request.META['HTTP_HOST'] + request.META['PATH_INFO'] + request.META['SCRIPT_NAME'] + ('?' + request.META['QUERY_STRING'] if request.META['QUERY_STRING'] else '')
def get_login_user(request):
user = get_current_user()
user.login_url = users.create_login_url(get_url(request))
user.logout_url = users.create_logout_url(get_url(request))
return user
def clean_html(string):
return string and string.replace('&', '&').replace('<', '<').replace('>', '>') or string
| Python |
from google.appengine.api import users, xmpp
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from project import xmpp
from project.experts.models import User, Tag, Review
from project.experts.views.common import get_login_user
class ProfileForm(djangoforms.ModelForm):
class Meta:
model = User
exclude = ('account', 'rating', 'rating_count')
def _update_tags_counts(old_tags, new_tags):
old_tags = set(old_tags)
new_tags = set(new_tags)
for word in old_tags:
if word not in new_tags:
tag = db.GqlQuery('SELECT * FROM Tag WHERE name = :1', word).get()
if tag:
tag.count -= 1
if tag.count > 0:
tag.put()
else:
tag.delete()
for word in new_tags:
if word not in old_tags:
tag = db.GqlQuery('SELECT * FROM Tag WHERE name = :1', word).get()
if tag:
tag.count += 1
else:
tag = Tag(name=word, count=1)
tag.put()
def index(request, account):
user = get_login_user(request)
if user.email() == account:
status = ''
if request.method == 'POST':
old_tags = user.tags if user and user.tags else []
form = ProfileForm(request.POST, instance=user)
if form.is_valid():
old_has_chat = user.has_chat
user = form.save(commit=False)
if user.tags:
user.tags = [x.lower() for x in user.tags if x]
user.put()
_update_tags_counts(old_tags, user.tags)
status = 'Successfully saved the user profile'
if not old_has_chat and user.has_chat:
if account.endswith('@gmail.com'):
xmpp.send_invite(account)
status = 'Successfully saved the user profile. Please accept chat invitation from flash-videoio@appspot.com'
if 'continue' in request.GET:
return HttpResponseRedirect(request.GET.get('continue'))
else:
if not user.name and user.account:
user.name = user.account.nickname()
form = ProfileForm(instance=user)
return render_to_response('experts/myprofile.html', {'user': user, 'account': account,
'status': status, 'form': form, 'website': user.website})
else:
status = error_message = ''
target = users.User(email=account)
profile = db.GqlQuery('SELECT * FROM User WHERE account = :1', target).get()
if profile and user.account and request.method == 'POST' and 'rating' in request.POST:
rating, description = int(request.POST.get('rating')), request.POST.get('review')
if description == 'Write review here!':
description = ''
review = db.GqlQuery('SELECT * FROM Review WHERE for_user = :1 AND by_user = :2', profile, user).get()
if review:
old_rating = review.rating
review.rating = rating
review.description = description
if old_rating != rating:
if profile.rating_count == 0:
profile.rating_count = 1
profile.rating = (profile.rating*profile.rating_count - old_rating + rating)/profile.rating_count
else:
review = Review(for_user=profile, by_user=user, rating=rating, description=description)
profile.rating = (profile.rating*profile.rating_count + rating)/(profile.rating_count + 1)
profile.rating_count += 1
review.put()
profile.put()
if profile:
rating, rating_percent = '%.1f'%(profile.rating or 0.0,), int((profile.rating or 0.0)*20)
reviews = db.GqlQuery('SELECT * FROM Review WHERE for_user = :1', profile).fetch(100)
for review in reviews:
review.rating_percent = int(review.rating * 20)
allow_review = bool(user.account)
else:
rating, rating_percent, reviews, allow_review = 0, 0, [], False
return render_to_response('experts/profile.html', {'user': user, 'account': account, 'profile': profile, 'status': status, 'error_message': error_message,
'reviews': reviews, 'rating': rating, 'rating_percent': rating_percent, 'allow_review': allow_review})
| Python |
import datetime, calendar
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
from django.shortcuts import render_to_response
from project.experts.models import Event
from project.experts.views.common import get_login_user
from django.http import HttpResponse, HttpResponseRedirect
def index(request, account):
user = get_login_user(request)
now = datetime.datetime.now()
return render_to_response('experts/calendar.html',
{'user': user, 'account': account, 'today': now.strftime('%Y-%m-%d')})
def get_frame_url(account, tzoffset, dt):
return '/experts/%s/calendar/%s/%s'%(account, tzoffset, dt.strftime('%Y-%m-%d') if isinstance(dt, datetime.datetime) else dt)
class MyCalendar(calendar.HTMLCalendar):
def __init__(self, now, firstdayweek=6):
calendar.HTMLCalendar.__init__(self, firstdayweek)
self.now = now
def formatday(self, day, weekday):
if day == 0:
return '<td class="noday"> </td>' # day outside month
else:
body = '<div style="width: 100%%; height: 100%%;" onclick="window.location=\'../%d-%d-%d\'">%d</div>'%(self.now.year, self.now.month, day, day)
return '<td class="%s">%s</td>' % (self.cssclasses[weekday] if day != self.now.day else 'today', body)
def formatweek(self, theweek):
s = ''.join(self.formatday(d, wd) for (d, wd) in theweek)
return '<tr>%s</tr>' % s
def formatweekday(self, day):
return '<th class="%s">%s</th>' % (self.cssclasses[day], calendar.day_abbr[day])
def formatweekheader(self):
s = ''.join(self.formatweekday(i) for i in self.iterweekdays())
return '<tr>%s</tr>' % s
def formatmonthname(self, theyear, themonth, withyear=True):
s = str(calendar.month_name[themonth])
if withyear:
prev = '../%d-%d-1'%(theyear if themonth > 1 else theyear - 1, themonth - 1 if themonth > 1 else 12)
next = '../%d-%d-1'%(theyear if themonth < 12 else theyear + 1, themonth + 1 if themonth < 12 else 1)
s = '%s %s<div style="float:left;"><a href="%s"><<prev</a></div><div style="float:right;"><a href="%s">next>></a></div>'%(s, theyear, prev, next)
return '<tr><th colspan="7" class="month">%s</th></tr>' % s
class EventForm(djangoforms.ModelForm):
class Meta:
model = Event
exclude = ('owner', 'visitor', 'created_on')
def edit(request, account, tzoffset, date, key):
user = get_login_user(request)
tzdelta = datetime.timedelta(minutes=int(tzoffset))
if account == user.email():
target = user
else:
target = users.User(email=account)
target = db.GqlQuery('SELECT * FROM User WHERE account = :1', target).get()
event = db.get(key)
if not event:
return HttpResponse('Calendar event does not exist for key "%s"'%(key,))
start_time, end_time = event.start_time - tzdelta, event.end_time - tzdelta
event.start_time, event.end_time = start_time, end_time
if request.method == 'POST':
form = EventForm(request.POST, instance=event)
if form.is_valid():
event1 = form.save(commit=False)
if user.email() == account:
event.start_time = event1.start_time + tzdelta
event.end_time = event1.end_time + tzdelta
event.subject, event.description = event1.subject, event1.description
event.put()
return HttpResponseRedirect(get_frame_url(account, tzoffset, date))
else:
form = EventForm(instance=event)
return render_to_response('experts/calendaredit.html',
{'user': user, 'account': account, 'date': event.start_time.strftime('%A, %d %b'),
'form': form, 'is_my_calendar': bool(user.email() == account),
'person': target.name if user.email() == account else user.name,
'start_time': start_time.strftime('%A, %d %b %I:%M %p '),
'end_time': end_time.strftime('%A, %d %b %I:%M %p ') })
def frame(request, account, tzoffset, date):
user = get_login_user(request)
error_message = status = ''
tzdelta = datetime.timedelta(minutes=int(tzoffset))
now = datetime.datetime.now() - tzdelta
if date != 'now':
yy, mm, dd = map(int, date.split('-', 2))
now = datetime.datetime(year=yy, month=mm, day=dd, hour=now.hour, minute=now.minute, second=now.second)
c = MyCalendar(now)
text = c.formatmonth(now.year, now.month)
if account:
if account == user.email():
target = user
else:
target = users.User(email=account)
target = db.GqlQuery('SELECT * FROM User WHERE account = :1', target).get()
if request.method == 'POST' and 'add_event' in request.POST:
subject0, time0, duration0, desc0 = [request.POST.get(x) for x in ('subject', 'time', 'duration', 'description')]
start_time = now.replace(hour=int(time0.split(':')[0])+(12 if time0.endswith('pm') else 0),
minute=int(time0.split(' ')[0].split(':')[1]),
second=0, microsecond=0) + tzdelta
end_time = start_time + datetime.timedelta(hours=1)
# return HttpResponse('start_time=' + str(start_time) + ' end_time=' + str(end_time)
# + ' provider=' + account.email() + ' user=' + user.email() + " subject=" + subject0)
event = Event(subject=subject0, owner=account, visitor=user.email(), start_time=start_time, end_time=end_time, description=desc0)
event.put()
status = 'Added "%s" at %s'%(event.subject, event.start_time.strftime('%I:%M %p'))
if request.method == 'GET' and 'delete' in request.GET:
key = request.GET.get('delete')
event = db.get(key)
if event and (event.owner == user.email() or event.visitor == user.email()):
status = 'Deleted "%s" at %s'%(event.subject, (event.start_time - tzdelta).strftime('%I:%M %p'))
event.delete()
else:
error_message = 'Cannot delete event with key "%s"'%(key,)
start_time = now.replace(hour=0, minute=0, second=1, microsecond=0) + tzdelta
end_time = now.replace(hour=23, minute=59, second=59, microsecond=0) + tzdelta
events = db.GqlQuery('SELECT * FROM Event WHERE owner = :1 AND start_time >= :2 AND start_time < :3 ORDER BY start_time', account, start_time, end_time).fetch(100)
appointments = []
for event in events:
is_my_event = bool(event.owner == user.email() or event.visitor == user.email())
description = '%s<br/>%s'%(event.subject or '', event.description or '') if is_my_event else 'Busy'
start_time, end_time = (event.start_time - tzdelta).strftime('%I:%M %p'), (event.end_time - tzdelta).strftime('%I:%M %p')
appointments.append({'key': event.key(),
'time': '%s-%s'%(start_time[:-3] if start_time[-3:] == end_time[-3:] else start_time, end_time),
'description': description, 'is_my_event': is_my_event,
'person': event.visitor if event.owner == user.email() else event.owner
})
prev = now.replace(day=1, month=now.month-1 if now.month > 1 else 12, year=now.year if now.month > 1 else now.year - 1)
next = now.replace(day=1, month=now.month+1 if now.month < 12 else 1, year=now.year if now.month < 12 else now.year + 1)
start_time = now.replace(day=1, hour=0, minute=0, second=1, microsecond=0) + tzdelta
end_time = start_time.replace(day=1, month=now.month+1 if now.month < 12 else 1, year=now.year if now.month < 12 else now.year + 1) + tzdelta
events = db.GqlQuery('SELECT * FROM Event WHERE owner = :1 AND start_time >= :2 AND start_time < :3 ORDER BY start_time', account, start_time, end_time).fetch(1000)
by_day = {}
for event in events:
start_time = event.start_time - tzdelta
if start_time.day not in by_day:
by_day[start_time.day] = []
by_day[start_time.day].append(event)
for day, event_list in by_day.iteritems():
pattern = '>%d</div>'%(day,)
text = text.replace(pattern, '>%d<br/>%s</div>'%(day, ', '.join([(event.start_time - tzdelta).strftime('%H:%M') for event in event_list])))
return render_to_response('experts/calendarframe.html',
{'user': user, 'account': account, 'status': status, 'error_message': error_message,
'calendar': text, 'appointments': appointments, 'date': now.strftime('%A, %d %b, %I:%M %p'),
'availability': target.availability, 'is_my_calendar': bool(user.email() == account),
'prev': get_frame_url(account, tzoffset, prev),
'next': get_frame_url(account, tzoffset, next)
})
| Python |
import datetime
from google.appengine.api import users
from google.appengine.ext import db
class User(db.Model):
name = db.StringProperty('Full Name')
account = db.UserProperty()
phone_number = db.PhoneNumberProperty('Phone Number')
address = db.PostalAddressProperty('Postal Address')
website = db.StringProperty('Homepage URL')
description = db.TextProperty('Brief Biography')
rating = db.FloatProperty(default=0.0)
rating_count = db.IntegerProperty(default=0)
tags = db.StringListProperty('Expertise, one per line', default=None)
availability = db.TextProperty('Availability', default='Available by appointment on weekdays in PST timezone')
has_chat = db.BooleanProperty('Use Google Chat', default=False)
def email(self):
result = self.account.nickname() if self.account else ''
return (result + '@gmail.com') if result and '@' not in result else result
def get_current_user():
account = users.get_current_user()
if account:
user = db.GqlQuery('SELECT * FROM User WHERE account = :1', account).get()
if not user:
user = User(name='', account=account)
user.put()
user.is_active = True
user.is_staff = users.is_current_user_admin()
else:
user = User()
user.is_active = False
return user
class Tag(db.Model):
name = db.StringProperty(required=True)
count = db.IntegerProperty(default=1)
class Event(db.Model):
subject = db.StringProperty()
description = db.TextProperty()
owner = db.StringProperty()
visitor = db.StringProperty()
start_time = db.DateTimeProperty()
end_time = db.DateTimeProperty()
created_on = db.DateTimeProperty(auto_now_add=True)
class Review(db.Model):
event = db.ReferenceProperty(Event, collection_name='event_set') # TODO make required=True
for_user = db.ReferenceProperty(User, required=True, collection_name='for_user_set')
by_user = db.ReferenceProperty(User, required=True, collection_name='by_user_set')
rating = db.IntegerProperty(default=3)
description = db.TextProperty()
modified_on = db.DateTimeProperty(auto_now=True)
class ClientStream(db.Model):
clientId = db.StringProperty(required=True)
visitor = db.StringProperty()
name = db.StringProperty(default='Anonymous')
publish = db.StringProperty(required=True)
play = db.StringProperty()
is_owner = db.BooleanProperty(default=False)
owner = db.StringProperty(required=True)
modified_on = db.DateTimeProperty(auto_now=True)
created_on = db.DateTimeProperty(auto_now_add=True)
def __repr__(self):
return '<ClientStream clientId=%r visitor=%r name=%r is_owner=%r owner=%r />'%(self.clientId, self.visitor, self.name, self.is_owner, self.owner)
def get_object(self, full=True):
if full:
return {'clientId': self.clientId, 'name': self.name, 'url': self.publish}
else:
return {'clientId': self.clientId}
class OfflineMessage(db.Model):
sender = db.StringProperty()
senderName = db.StringProperty()
receiver = db.StringProperty()
text = db.StringProperty(multiline=True)
created_on = db.DateTimeProperty(auto_now_add=True)
def __repr__(self):
return '<OfflineMessage sender=%r senderName=%r receiver=%r text=%r />'%(self.sender, self.senderName, self.receiver, self.text)
def get_object(self):
return {'senderName': self.senderName, 'text': self.text}
| Python |
"""
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".
Replace these with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.failUnlessEqual(1 + 1, 2)
__test__ = {"doctest": """
Another way to test that 1 + 1 is equal to 2.
>>> 1 + 1 == 2
True
"""}
| Python |
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
#from django.contrib import admin
#admin.autodiscover()
urlpatterns = patterns('project.experts.views',
(r'^$', 'main.index'),
(r'^search/', 'search.index'),
(r'^(?P<account>[^\/]+)/profile/', 'profile.index'),
(r'^(?P<account>[^\/]+)/calendar/(?P<tzoffset>[^\/]+)/(?P<date>[^\/]+)/edit/(?P<key>[^\/]+)/', 'cal.edit'),
(r'^(?P<account>[^\/]+)/calendar/(?P<tzoffset>[^\/]+)/(?P<date>[^\/]+)/', 'cal.frame'),
(r'^(?P<account>[^\/]+)/calendar/', 'cal.index'),
(r'^(?P<account>[^\/]+)/talk/(?P<command>[^\/]+)/', 'talk.command'),
(r'^(?P<account>[^\/]+)/talk/', 'talk.index'),
(r'^initialize/', 'tests.create'),
)
| Python |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Python |
from google.appengine.ext import db
class Owner(db.Model):
email = db.StringProperty(required=True)
gtalk = db.BooleanProperty(default=True)
def __repr__(self):
return '<Owner email=%r gtalk=%r />'%(self.email, self.gtalk)
class Visitor(db.Model):
clientId = db.StringProperty(required=True)
email = db.StringProperty()
name = db.StringProperty(default='Anonymous')
purpose = db.StringProperty()
publish = db.StringProperty()
play = db.StringProperty()
is_owner = db.BooleanProperty(default=False)
owner = db.StringProperty(required=True)
modified_on = db.DateTimeProperty(auto_now=True)
def __repr__(self):
return '<Visitor clientId=%r email=%r name=%r is_owner=%r owner=%r />'%(self.clientId, self.email, self.name, self.is_owner, self.owner)
def get_object(self, full=True):
if full:
return {'clientId': self.clientId, 'name': self.name, 'url': self.publish, 'purpose': self.purpose}
else:
return {'clientId': self.clientId}
class Message(db.Model):
sender = db.StringProperty()
senderName = db.StringProperty()
receiver = db.StringProperty()
text = db.StringProperty(multiline=True)
created_on = db.DateTimeProperty(auto_now_add=True)
def __repr__(self):
return '<Message sender=%r senderName=%r receiver=%r text=%r />'%(self.sender, self.senderName, self.receiver, self.text)
def get_object(self):
return {'senderName': self.senderName, 'text': self.text}
| Python |
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
#from django.contrib import admin
#admin.autodiscover()
urlpatterns = patterns('project.office.views',
(r'^(?P<owner>[^\/]+)/(?P<command>[^\/]+)/', 'command'),
(r'^(?P<owner>[^\/]+)/$', 'index'),
(r'^', 'redirect'),
)
| Python |
import datetime, time, random, logging, sys, traceback, cgi
from google.appengine.api import users, channel, xmpp
from google.appengine.ext import db
from django.http import HttpResponse, HttpResponseServerError, HttpResponseForbidden, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.utils import simplejson as json
from project.office.models import Visitor, Owner, Message
def index(request, owner=None):
owner = cgi.escape(owner)
user_email = get_current_user_email()
login_url = users.create_login_url(get_url(request))
logout_url = users.create_logout_url(get_url(request))
if user_email and owner == user_email:
account = db.GqlQuery('SELECT * FROM Owner WHERE email = :1', user_email).get()
if not account:
account = Owner(email=user_email)
account.put()
if account.gtalk and user_email.endswith('@gmail.com'):
xmpp.send_invite(user_email)
stream = 'o' + str(random.randint(100000000, 999999999))
token = channel.create_channel(stream)
is_my_office = bool(user_email == owner)
return render_to_response('office/index.html', {'user_email': user_email, 'owner': owner,
'is_my_office': is_my_office, 'stream': stream, 'token': token,
'login_url': login_url, 'logout_url': logout_url})
def redirect(request):
return HttpResponseRedirect('/office/kundan10@gmail.com/')
# Authentication related methods
def escapeHTML(value):
return value.replace('<', '')
def get_url(request):
return 'http://' + request.META['HTTP_HOST'] + request.META['PATH_INFO'] + request.META['SCRIPT_NAME'] + ('?' + request.META['QUERY_STRING'] if request.META['QUERY_STRING'] else '')
def get_current_user_email():
user = users.get_current_user()
user_email = user.nickname() if user else ''
return user_email if not user_email or '@' in user_email else (user_email + '@gmail.com')
# All GQL queries are done in separate methods.
def get_stream(clientId):
return db.GqlQuery('SELECT * FROM Visitor WHERE clientId = :1', clientId).get()
def get_stream_by_publish(url):
return db.GqlQuery('SELECT * FROM Visitor WHERE publish = :1', url).get()
def get_streams_of_owner(owner):
return db.GqlQuery('SELECT * FROM Visitor WHERE owner = :1 AND is_owner = :2', owner, True)
def get_streams_of_visitors(owner):
return db.GqlQuery('SELECT * FROM Visitor WHERE owner = :1 AND is_owner = :2', owner, False)
def get_streams_of_owner_by_visitor(owner, visitor):
return db.GqlQuery('SELECT * FROM Visitor WHERE owner = :1 AND email = :2 AND is_owner = :3', owner, visitor, False)
def get_streams_expired():
return db.GqlQuery('SELECT * FROM Visitor WHERE modified_on < :1', datetime.datetime.fromtimestamp(time.time()-90))
def get_messages_of_owner(owner):
return db.GqlQuery('SELECT * FROM Message WHERE receiver = :1 ORDER BY created_on', owner)
# All channel messages are created in separate methods.
def get_disconnect_message():
return json.dumps({'method': 'connect', 'clientId': None, 'url': None})
def get_connect_message(stream):
return json.dumps({'method': 'connect', 'clientId': stream.clientId, 'name': stream.name, 'url': stream.publish})
def get_userlist_message(added=None, removed=None):
added, removed = added or [], removed or []
return json.dumps({'method': 'userlist', 'added': [x.get_object() for x in added], 'removed': [x.get_object(full=False) for x in removed]})
def get_send_message(senderId, senderName, text):
return json.dumps({'method':'send', 'senderId': senderId, 'senderName': senderName, 'text': text })
def get_send_error_message(error):
return json.dumps({'method':'send', 'senderId': None, 'senderName': 'System', 'text': error})
def send_message(stream, data):
try:
# logging.info('send_message %r %r'%(stream.clientId, data))
channel.send_message(stream.clientId, data)
except channel.InvalidChannelClientIdError:
pass
# Send a message using xmpp to the google chat user.
def send_message_to_google_chat(email, msg):
if email.endswith('@gmail.com'):
account = db.GqlQuery('SELECT * FROM Owner WHERE email = :1', email).get()
if account and account.gtalk:
xmpp.send_message(email, msg)
def xmpp_handler(sender, receiver, body):
data = get_send_message('0', sender + ' (via Google chat)', body)
count = 0
if receiver[0] == '@':
stream = get_stream(receiver[1:])
if stream:
send_message(stream, data)
count = 1
elif '@' in receiver:
for stream in get_streams_of_owner_by_visitor(sender, receiver):
send_message(stream, data)
count += 1
return count
# Clean up the given stream by disconnecting it's other participant,
# and if delete is set, also delete this stream.
def cleanup_stream(stream, delete=True):
if stream.play:
other = get_stream_by_publish(stream.play)
if other:
if other.play:
send_message(other, get_disconnect_message())
other.play = None
other.put()
if delete:
# logging.info('cleanup_stream deleting %r'%(stream.clientId,))
stream.delete()
else:
stream.play = None
stream.put()
send_message(stream, get_disconnect_message())
# update the visitors list by sending userlist message to the owner
def update_visitors(owner, added=None, removed=None):
data = get_userlist_message(added, removed)
for stream in get_streams_of_owner(owner):
send_message(stream, data)
def command(request, owner, command):
try:
return command_safe(request, owner, command)
except:
type, value, tb = sys.exc_info()
printable = '\n'.join(traceback.format_exception(type, value, tb))
logging.info('exception in %s: %s'%(command, printable))
return HttpResponseServerError('Exception: ' + printable)
def command_safe(request, account, command):
account = cgi.escape(account)
user_email = get_current_user_email()
is_my_office = bool(user_email == account)
if request.method == 'POST':
# for stream in db.GqlQuery('SELECT * FROM Visitor'):
# logging.info(' stream: ' + str(stream))
input = json.loads(request.raw_post_data)
if command == 'end':
stream = get_stream(input['clientId'])
if stream:
if stream.email and stream.email != user_email:
return HttpResponseForbidden() # do not allow removal by others
cleanup_stream(stream)
if not is_my_office:
update_visitors(account, removed=[stream])
elif command == 'accept' or command == 'reject':
if not is_my_office:
# logging.info('found accept/reject without is_my_office')
return HttpResponseForbidden()
mine = get_stream(input['clientId'])
yours = get_stream(input['targetId'])
# logging.info('command=%r\n mine=%r\n yours=%r\n input=%r'%(command, mine, yours, input))
# disconnect previous participant when accepting a new one
if mine and command == 'accept' and mine.play and (not yours or mine.play != yours.publish):
# logging.info('deleting previous partner %r'%(mine.play,))
previous = get_stream_by_publish(mine.play)
if previous:
previous.play = None
previous.put()
send_message(previous, get_disconnect_message())
mine.play = None
# now connect mine and yours streams
if mine and yours:
if command == 'accept' and not mine.play and not yours.play:
# logging.info('connecting %r and %r'%(mine.clientId, yours.clientId))
mine.play, yours.play = yours.publish, mine.publish
elif command == 'reject' and (mine.play == yours.publish or yours.play == mine.publish):
# logging.info('disconnecting %r and %r'%(mine.clientId, yours.clientId))
mine.play = yours.play = None
mine.put()
yours.put()
if command == 'accept':
send_message(mine, get_connect_message(yours))
send_message(yours, get_connect_message(mine))
elif command == 'reject':
send_message(mine, get_disconnect_message())
send_message(yours, get_disconnect_message())
else:
return HttpResponseServerError('Some data on the server is not valid')
elif command == 'send':
# logging.info(' send input = %r'%(input,))
senderId, senderName, text = input['senderId'], input['senderName'], input['text']
sender = get_stream(senderId)
if sender and sender.email and sender.email != user_email:
# logging.info('sender is invalid %r, user=%r'%(sender, user.email()))
return HttpResponseForbidden() # do not allow by others
if 'receiver' in input:
# send an inline message to the stream, and on error send back error message
receiver = get_stream_by_publish(input['receiver'])
if receiver:
# logging.info(' sending message to receiver %r'%(receiver,))
send_message(receiver, get_send_message(senderId, senderName, text))
else:
# logging.info(' did not find receiver')
send_message(sender, get_send_error_message('Did not send message because you are not connected'))
if 'owner' in input and input['owner'] == account:
# put a message to all streams of this user
receivers = get_streams_of_owner(input['owner'])
sent_count = 0
for receiver in receivers:
# logging.info('sending to stream: ' + receiver.clientId)
send_message(receiver, get_send_message(senderId, senderName + ' (not connected)', text))
sent_count += 1
# put offline message if it could not be sent to existing streams
if sent_count == 0:
# logging.info('created offline message')
msg = Message(sender=user_email, senderName=senderName + ' (offline message)', receiver=input['owner'], text=text)
msg.put()
# also send message to google chat if possible
if not is_my_office:
send_message_to_google_chat(account, senderName + ' says ' + text)
#else:
# logging.info('sent to ' + sent_count)
elif command == 'publish':
# first delete any expired stream
for stream in get_streams_expired():
cleanup_stream(stream)
if not stream.is_owner:
data = get_userlist_message(removed=[stream])
for owner in get_streams_of_owner(stream.owner):
send_message(owner, data)
stream = get_stream(input['clientId'])
if not stream:
# create new Stream object
stream = Visitor(clientId=input['clientId'], email=user_email, name=input['name'], publish=input['url'], owner=account, is_owner=is_my_office)
stream.purpose = input.get('purpose', None)
stream.put()
# first update user list of owner
if not is_my_office:
data = get_userlist_message(added=[stream])
found = False
for owner in get_streams_of_owner(account):
send_message(owner, data)
found = True
# then send to google chat if account user is not online here
if not found:
contact = user_email if user_email else '@' + stream.clientId
msg = '%s (%s) visited your video office on %s GMT. Send your reply starting with %s to this person.'%(stream.name, stream.purpose, datetime.datetime.now(), contact)
send_message_to_google_chat(account, msg)
else:
stream.publish, stream.name = input['url'], input['name']
stream.modified_on = datetime.datetime.now()
stream.put() # so that last modified is updated
# logging.info('sending userlist and chathistory in response %r %r %r'%(is_my_office, user.email(), account))
if is_my_office: # return user list also
visitors = get_streams_of_visitors(account)
messages = get_messages_of_owner(account)
response = {'userlist': [x.get_object() for x in visitors], 'chathistory': [x.get_object() for x in messages]}
if response['chathistory']:
db.delete([x for x in messages])
return HttpResponse(json.dumps(response))
return HttpResponse('')
| Python |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Python |
from django.conf.urls.defaults import *
from project.xmpp import xmpp_handler
# Uncomment the next two lines to enable the admin:
#from django.contrib import admin
#admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^chat/', include('project.chat.urls')),
# (r'^random/', include('project.random.urls')),
(r'^office/', include('project.office.urls')),
(r'^experts/', include('project.experts.urls')),
# (r'^talk2me/', include('project.talk2me.urls')),
('^_ah/xmpp/message/chat/', 'project.xmpp.xmpp_handler'),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
#(r'^admin/', include(admin.site.urls)),
)
| 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.