code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
import os
from Tkinter import *
from Tkconstants import W, E
import Tkinter as tk
from tkMessageBox import askyesnocancel
from multiprocessing import freeze_support
from globalconst import *
from aboutbox import AboutBox
from setupboard import SetupBoard
from gamemanager import GameManager
from centeredwindow import CenteredWindow
from prefdlg import PreferencesDialog
class MainFrame(object, CenteredWindow):
def __init__(self, master):
self.root = master
self.root.withdraw()
self.root.iconbitmap(RAVEN_ICON)
self.root.title('Raven ' + VERSION)
self.root.protocol('WM_DELETE_WINDOW', self._on_close)
self.thinkTime = IntVar(value=5)
self.manager = GameManager(root=self.root, parent=self)
self.menubar = tk.Menu(self.root)
self.create_game_menu()
self.create_options_menu()
self.create_help_menu()
self.root.config(menu=self.menubar)
CenteredWindow.__init__(self, self.root)
self.root.deiconify()
def _on_close(self):
if self.manager.view.is_dirty():
msg = 'Do you want to save your changes before exiting?'
result = askyesnocancel(TITLE, msg)
if result == True:
self.manager.save_game()
elif result == None:
return
self.root.destroy()
def set_title_bar_filename(self, filename=None):
if not filename:
self.root.title(TITLE)
else:
self.root.title(TITLE + ' - ' + os.path.basename(filename))
def undo_all_moves(self, *args):
self.stop_processes()
self.manager.model.undo_all_moves(None,
self.manager.view.get_annotation())
self.manager._controller1.remove_highlights()
self.manager._controller2.remove_highlights()
self.manager.view.update_statusbar()
def redo_all_moves(self, *args):
self.stop_processes()
self.manager.model.redo_all_moves(None,
self.manager.view.get_annotation())
self.manager._controller1.remove_highlights()
self.manager._controller2.remove_highlights()
self.manager.view.update_statusbar()
def undo_single_move(self, *args):
self.stop_processes()
self.manager.model.undo_move(None, None, True, True,
self.manager.view.get_annotation())
self.manager._controller1.remove_highlights()
self.manager._controller2.remove_highlights()
self.manager.view.update_statusbar()
def redo_single_move(self, *args):
self.stop_processes()
annotation = self.manager.view.get_annotation()
self.manager.model.redo_move(None, None, annotation)
self.manager._controller1.remove_highlights()
self.manager._controller2.remove_highlights()
self.manager.view.update_statusbar()
def create_game_menu(self):
game = Menu(self.menubar, tearoff=0)
game.add_command(label='New game', underline=0,
command=self.manager.new_game)
game.add_command(label='Open game ...', underline=0,
command=self.manager.open_game)
game.add_separator()
game.add_command(label='Save game', underline=0,
command=self.manager.save_game)
game.add_command(label='Save game As ...', underline=10,
command=self.manager.save_game_as)
game.add_separator()
game.add_command(label='Set up Board ...', underline=7,
command=self.show_setup_board_dialog)
game.add_command(label='Flip board', underline=0,
command=self.flip_board)
game.add_separator()
game.add_command(label='Exit', underline=0,
command=self._on_close)
self.menubar.add_cascade(label='Game', menu=game)
def create_options_menu(self):
options = Menu(self.menubar, tearoff=0)
think = Menu(options, tearoff=0)
think.add_radiobutton(label="1 second", underline=None,
command=self.set_think_time,
variable=self.thinkTime,
value=1)
think.add_radiobutton(label="2 seconds", underline=None,
command=self.set_think_time,
variable=self.thinkTime,
value=2)
think.add_radiobutton(label="5 seconds", underline=None,
command=self.set_think_time,
variable=self.thinkTime,
value=5)
think.add_radiobutton(label="10 seconds", underline=None,
command=self.set_think_time,
variable=self.thinkTime,
value=10)
think.add_radiobutton(label="30 seconds", underline=None,
command=self.set_think_time,
variable=self.thinkTime,
value=30)
think.add_radiobutton(label="1 minute", underline=None,
command=self.set_think_time,
variable=self.thinkTime,
value=60)
options.add_cascade(label='CPU think time', underline=0,
menu=think)
options.add_separator()
options.add_command(label='Preferences ...', underline=0,
command=self.show_preferences_dialog)
self.menubar.add_cascade(label='Options', menu=options)
def create_help_menu(self):
helpmenu = Menu(self.menubar, tearoff=0)
helpmenu.add_command(label='About Raven ...', underline=0,
command=self.show_about_box)
self.menubar.add_cascade(label='Help', menu=helpmenu)
def stop_processes(self):
# stop any controller processes from making moves
self.manager.model.curr_state.ok_to_move = False
self.manager._controller1.stop_process()
self.manager._controller2.stop_process()
def show_about_box(self):
AboutBox(self.root, 'About Raven')
def show_setup_board_dialog(self):
self.stop_processes()
dlg = SetupBoard(self.root, 'Set up board', self.manager)
self.manager.set_controllers()
self.root.focus_set()
self.manager.turn_finished()
def show_preferences_dialog(self):
font, size = get_preferences_from_file()
dlg = PreferencesDialog(self.root, 'Preferences', font, size)
if dlg.result:
self.manager.view.init_font_sizes(dlg.font, dlg.size)
self.manager.view.init_tags()
write_preferences_to_file(dlg.font, dlg.size)
def set_think_time(self):
self.manager._controller1.set_search_time(self.thinkTime.get())
self.manager._controller2.set_search_time(self.thinkTime.get())
def flip_board(self):
if self.manager.model.to_move == BLACK:
self.manager._controller1.remove_highlights()
else:
self.manager._controller2.remove_highlights()
self.manager.view.flip_board(not self.manager.view.flip_view)
if self.manager.model.to_move == BLACK:
self.manager._controller1.add_highlights()
else:
self.manager._controller2.add_highlights()
def start():
root = Tk()
mainframe = MainFrame(root)
mainframe.root.update()
mainframe.root.mainloop()
if __name__=='__main__':
freeze_support()
start()
| [
[
1,
0,
0.0053,
0.0053,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0107,
0.0053,
0,
0.66,
0.0714,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.016,
0.0053,
0,
0... | [
"import os",
"from Tkinter import *",
"from Tkconstants import W, E",
"import Tkinter as tk",
"from tkMessageBox import askyesnocancel",
"from multiprocessing import freeze_support",
"from globalconst import *",
"from aboutbox import AboutBox",
"from setupboard import SetupBoard",
"from gamemanage... |
from globalconst import BLACK, WHITE, MAN, KING
from goalevaluator import GoalEvaluator
from onekingattack import Goal_OneKingAttack
class OneKingAttackOneKingEvaluator(GoalEvaluator):
def __init__(self, bias):
GoalEvaluator.__init__(self, bias)
def calculateDesirability(self, board):
plr_color = board.to_move
enemy_color = board.enemy
# if we don't have one man on each side or the player
# doesn't have the opposition, then goal is undesirable.
if (board.count(BLACK) != 1 or board.count(WHITE) != 1 or
not board.has_opposition(plr_color)):
return 0.0
player = board.get_pieces(plr_color)[0]
p_idx, p_val = player
p_row, p_col = board.row_col_for_index(p_idx)
enemy = board.get_pieces(enemy_color)[0]
e_idx, e_val = enemy
e_row, e_col = board.row_col_for_index(e_idx)
# must be two kings against each other and the distance
# between them at least three rows away
if ((p_val & KING) and (e_val & KING) and
(abs(p_row - e_row) > 2 or abs(p_col - e_col) > 2)):
return 1.0
return 0.0
def setGoal(self, board):
player = board.to_move
board.removeAllSubgoals()
if player == WHITE:
goalset = board.addWhiteSubgoal
else:
goalset = board.addBlackSubgoal
goalset(Goal_OneKingAttack(board))
class OneKingFleeOneKingEvaluator(GoalEvaluator):
def __init__(self, bias):
GoalEvaluator.__init__(self, bias)
def calculateDesirability(self, board):
plr_color = board.to_move
enemy_color = board.enemy
# if we don't have one man on each side or the player
# has the opposition (meaning we should attack instead),
# then goal is not applicable.
if (board.count(BLACK) != 1 or board.count(WHITE) != 1 or
board.has_opposition(plr_color)):
return 0.0
player = board.get_pieces(plr_color)[0]
p_idx, p_val = player
enemy = board.get_pieces(enemy_color)[0]
e_idx, e_val = enemy
# must be two kings against each other; otherwise it's
# not applicable.
if not ((p_val & KING) and (e_val & KING)):
return 0.0
return 1.0
def setGoal(self, board):
player = board.to_move
board.removeAllSubgoals()
if player == WHITE:
goalset = board.addWhiteSubgoal
else:
goalset = board.addBlackSubgoal
goalset(Goal_OneKingFlee(board))
| [
[
1,
0,
0.0145,
0.0145,
0,
0.66,
0,
871,
0,
4,
0,
0,
871,
0,
0
],
[
1,
0,
0.029,
0.0145,
0,
0.66,
0.25,
37,
0,
1,
0,
0,
37,
0,
0
],
[
1,
0,
0.0435,
0.0145,
0,
0.66,... | [
"from globalconst import BLACK, WHITE, MAN, KING",
"from goalevaluator import GoalEvaluator",
"from onekingattack import Goal_OneKingAttack",
"class OneKingAttackOneKingEvaluator(GoalEvaluator):\n def __init__(self, bias):\n GoalEvaluator.__init__(self, bias)\n\n def calculateDesirability(self, b... |
from Tkinter import *
class CenteredWindow:
def __init__(self, root):
self.root = root
self.root.after_idle(self.center_on_screen)
self.root.update()
def center_on_screen(self):
self.root.update_idletasks()
sw = self.root.winfo_screenwidth()
sh = self.root.winfo_screenheight()
w = self.root.winfo_reqwidth()
h = self.root.winfo_reqheight()
new_geometry = "+%d+%d" % ((sw-w)/2, (sh-h)/2)
self.root.geometry(newGeometry=new_geometry) | [
[
1,
0,
0.0625,
0.0625,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
3,
0,
0.5938,
0.875,
0,
0.66,
1,
592,
0,
2,
0,
0,
0,
0,
8
],
[
2,
1,
0.3438,
0.25,
1,
0.19,
... | [
"from Tkinter import *",
"class CenteredWindow:\n def __init__(self, root):\n self.root = root\n self.root.after_idle(self.center_on_screen)\n self.root.update()\n\n def center_on_screen(self):\n self.root.update_idletasks()",
" def __init__(self, root):\n self.root =... |
import sys
from goal import Goal
from composite import CompositeGoal
class Goal_OneKingFlee(CompositeGoal):
def __init__(self, owner):
CompositeGoal.__init__(self, owner)
def activate(self):
self.status = self.ACTIVE
self.removeAllSubgoals()
# because goals are *pushed* onto the front of the subgoal list they must
# be added in reverse order.
self.addSubgoal(Goal_MoveTowardNearestDoubleCorner(self.owner))
self.addSubgoal(Goal_SeeSaw(self.owner))
def process(self):
self.activateIfInactive()
return self.processSubgoals()
def terminate(self):
self.status = self.INACTIVE
class Goal_MoveTowardBestDoubleCorner(Goal):
def __init__(self, owner):
Goal.__init__(self, owner)
self.dc = [8, 13, 27, 32]
def activate(self):
self.status = self.ACTIVE
def process(self):
# if status is inactive, activate
self.activateIfInactive()
# only moves (not captures) are a valid goal
if self.owner.captures:
self.status = self.FAILED
return
# identify player king and enemy king
plr_color = self.owner.to_move
enemy_color = self.owner.enemy
player = self.owner.get_pieces(plr_color)[0]
p_idx, _ = player
p_row, p_col = self.owner.row_col_for_index(p_idx)
enemy = self.owner.get_pieces(enemy_color)[0]
e_idx, _ = enemy
e_row, e_col = self.owner.row_col_for_index(e_idx)
# pick DC that isn't blocked by enemy
lowest_dist = sys.maxint
dc = 0
for i in self.dc:
dc_row, dc_col = self.owner.row_col_for_index(i)
pdist = abs(dc_row - p_row) + abs(dc_col - p_col)
edist = abs(dc_row - e_row) + abs(dc_col - e_col)
if pdist < lowest_dist and edist > pdist:
lowest_dist = pdist
dc = i
# if lowest distance is 0, then goal is complete.
if lowest_dist == 0:
self.status = self.COMPLETED
return
# select the available move that decreases the distance
# between the original player position and the chosen double corner.
# If no such move exists, the goal has failed.
dc_row, dc_col = self.owner.row_col_for_index(dc)
good_move = None
for m in self.owner.moves:
# try a move and gather the new row & col for the player
self.owner.make_move(m, False, False)
plr_update = self.owner.get_pieces(plr_color)[0]
pu_idx, _ = plr_update
pu_row, pu_col = self.owner.row_col_for_index(pu_idx)
self.owner.undo_move(m, False, False)
new_diff = abs(pu_row - dc_row) + abs(pu_col - dc_col)
if new_diff < lowest_dist:
good_move = m
break
if good_move:
self.owner.make_move(good_move, True, True)
else:
self.status = self.FAILED
def terminate(self):
self.status = self.INACTIVE
class Goal_SeeSaw(Goal):
def __init__(self, owner):
Goal.__init__(self, owner)
def activate(self):
self.status = self.ACTIVE
def process(self):
# for now, I'm not even sure I need this goal, but I'm saving it
# as a placeholder.
self.status = self.COMPLETED
def terminate(self):
self.status = self.INACTIVE
| [
[
1,
0,
0.0095,
0.0095,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.019,
0.0095,
0,
0.66,
0.2,
914,
0,
1,
0,
0,
914,
0,
0
],
[
1,
0,
0.0286,
0.0095,
0,
0.66... | [
"import sys",
"from goal import Goal",
"from composite import CompositeGoal",
"class Goal_OneKingFlee(CompositeGoal):\n def __init__(self, owner):\n CompositeGoal.__init__(self, owner)\n\n def activate(self):\n self.status = self.ACTIVE\n self.removeAllSubgoals()\n # because ... |
class Move(object):
def __init__(self, squares, annotation=''):
self.affected_squares = squares
self.annotation = annotation
def __repr__(self):
return str(self.affected_squares)
| [
[
3,
0,
0.5714,
1,
0,
0.66,
0,
512,
0,
2,
0,
0,
186,
0,
1
],
[
2,
1,
0.4286,
0.4286,
1,
0.24,
0,
555,
0,
3,
0,
0,
0,
0,
0
],
[
14,
2,
0.4286,
0.1429,
2,
0.14,
0... | [
"class Move(object):\n def __init__(self, squares, annotation=''):\n self.affected_squares = squares\n self.annotation = annotation\n\n def __repr__(self):\n return str(self.affected_squares)",
" def __init__(self, squares, annotation=''):\n self.affected_squares = squares\n ... |
from Tkinter import *
from tkSimpleDialog import Dialog
from globalconst import *
class AboutBox(Dialog):
def body(self, master):
self.canvas = Canvas(self, width=300, height=275)
self.canvas.pack(side=TOP, fill=BOTH, expand=0)
self.canvas.create_text(152,47,text='Raven', fill='black',
font=('Helvetica', 36))
self.canvas.create_text(150,45,text='Raven', fill='white',
font=('Helvetica', 36))
self.canvas.create_text(150,85,text='Version '+ VERSION,
fill='black',
font=('Helvetica', 12))
self.canvas.create_text(150,115,text='An open source checkers program',
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,130,text='by Brandon Corfman',
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,160,text='Evaluation function translated from',
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,175,text="Martin Fierz's Simple Checkers",
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,205,text="Alpha-beta search code written by",
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,220,text="Peter Norvig for the AIMA project;",
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,235,text="adopted for checkers usage",
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,250,text="by Brandon Corfman",
fill='black',
font=('Helvetica', 10))
return self.canvas
def cancel(self, event=None):
self.destroy()
def buttonbox(self):
self.button = Button(self, text='OK', padx='5m', command=self.cancel)
self.blank = Canvas(self, width=10, height=20)
self.blank.pack(side=BOTTOM, fill=BOTH, expand=0)
self.button.pack(side=BOTTOM)
self.button.focus_set()
self.bind("<Escape>", self.cancel)
| [
[
1,
0,
0.0196,
0.0196,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.0392,
0.0196,
0,
0.66,
0.3333,
774,
0,
1,
0,
0,
774,
0,
0
],
[
1,
0,
0.0588,
0.0196,
0,
... | [
"from Tkinter import *",
"from tkSimpleDialog import Dialog",
"from globalconst import *",
"class AboutBox(Dialog):\n def body(self, master):\n self.canvas = Canvas(self, width=300, height=275)\n self.canvas.pack(side=TOP, fill=BOTH, expand=0)\n self.canvas.create_text(152,47,text='Rav... |
from Tkinter import Widget
from controller import Controller
from globalconst import *
class PlayerController(Controller):
def __init__(self, **props):
self._model = props['model']
self._view = props['view']
self._before_turn_event = None
self._end_turn_event = props['end_turn_event']
self._highlights = []
self._move_in_progress = False
def _register_event_handlers(self):
Widget.bind(self._view.canvas, '<Button-1>', self.mouse_click)
def _unregister_event_handlers(self):
Widget.unbind(self._view.canvas, '<Button-1>')
def stop_process(self):
pass
def set_search_time(self, time):
pass
def get_player_type(self):
return HUMAN
def set_before_turn_event(self, evt):
self._before_turn_event = evt
def add_highlights(self):
for h in self._highlights:
self._view.highlight_square(h, OUTLINE_COLOR)
def remove_highlights(self):
for h in self._highlights:
self._view.highlight_square(h, DARK_SQUARES)
def start_turn(self):
self._register_event_handlers()
self._model.curr_state.attach(self._view)
def end_turn(self):
self._unregister_event_handlers()
self._model.curr_state.detach(self._view)
def mouse_click(self, event):
xi, yi = self._view.calc_board_loc(event.x, event.y)
pos = self._view.calc_board_pos(xi, yi)
sq = self._model.curr_state.squares[pos]
if not self._move_in_progress:
player = self._model.curr_state.to_move
self.moves = self._model.legal_moves()
if (sq & player) and self.moves:
self._before_turn_event()
# highlight the start square the user clicked on
self._view.highlight_square(pos, OUTLINE_COLOR)
self._highlights = [pos]
# reduce moves to number matching the positions entered
self.moves = self._filter_moves(pos, self.moves, 0)
self.idx = 2 if self._model.captures_available() else 1
# if only one move available, take it.
if len(self.moves) == 1:
self._make_move()
self._view.canvas.after(100, self._end_turn_event)
return
self._move_in_progress = True
else:
if sq & FREE:
self.moves = self._filter_moves(pos, self.moves, self.idx)
if len(self.moves) == 0: # illegal move
# remove previous square highlights
for h in self._highlights:
self._view.highlight_square(h, DARK_SQUARES)
self._move_in_progress = False
return
else:
self._view.highlight_square(pos, OUTLINE_COLOR)
self._highlights.append(pos)
if len(self.moves) == 1:
self._make_move()
self._view.canvas.after(100, self._end_turn_event)
return
self.idx += 2 if self._model.captures_available() else 1
def _filter_moves(self, pos, moves, idx):
del_list = []
for i, m in enumerate(moves):
if pos != m.affected_squares[idx][0]:
del_list.append(i)
for i in reversed(del_list):
del moves[i]
return moves
def _make_move(self):
move = self.moves[0].affected_squares
step = 2 if len(move) > 2 else 1
# highlight remaining board squares used in move
for m in move[step::step]:
idx = m[0]
self._view.highlight_square(idx, OUTLINE_COLOR)
self._highlights.append(idx)
self._model.make_move(self.moves[0], None, True, True,
self._view.get_annotation())
# a new move obliterates any more redo's along a branch of the game tree
self._model.curr_state.delete_redo_list()
self._move_in_progress = False
| [
[
1,
0,
0.0092,
0.0092,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.0183,
0.0092,
0,
0.66,
0.3333,
360,
0,
1,
0,
0,
360,
0,
0
],
[
1,
0,
0.0275,
0.0092,
0,
... | [
"from Tkinter import Widget",
"from controller import Controller",
"from globalconst import *",
"class PlayerController(Controller):\n def __init__(self, **props):\n self._model = props['model']\n self._view = props['view']\n self._before_turn_event = None\n self._end_turn_event... |
from abc import ABCMeta, abstractmethod
class GoalEvaluator(object):
__metaclass__ = ABCMeta
def __init__(self, bias):
self.bias = bias
@abstractmethod
def calculateDesirability(self, board):
pass
@abstractmethod
def setGoal(self, board):
pass
| [
[
1,
0,
0.0556,
0.0556,
0,
0.66,
0,
38,
0,
2,
0,
0,
38,
0,
0
],
[
3,
0,
0.5556,
0.7222,
0,
0.66,
1,
985,
0,
3,
0,
0,
186,
0,
0
],
[
14,
1,
0.2778,
0.0556,
1,
0.17,
... | [
"from abc import ABCMeta, abstractmethod",
"class GoalEvaluator(object):\n __metaclass__ = ABCMeta\n\n def __init__(self, bias):\n self.bias = bias\n\n @abstractmethod\n def calculateDesirability(self, board):",
" __metaclass__ = ABCMeta",
" def __init__(self, bias):\n self.bia... |
from Tkinter import *
from time import time, localtime, strftime
class ToolTip( Toplevel ):
"""
Provides a ToolTip widget for Tkinter.
To apply a ToolTip to any Tkinter widget, simply pass the widget to the
ToolTip constructor
"""
def __init__( self, wdgt, msg=None, msgFunc=None, delay=1, follow=True ):
"""
Initialize the ToolTip
Arguments:
wdgt: The widget this ToolTip is assigned to
msg: A static string message assigned to the ToolTip
msgFunc: A function that retrieves a string to use as the ToolTip text
delay: The delay in seconds before the ToolTip appears(may be float)
follow: If True, the ToolTip follows motion, otherwise hides
"""
self.wdgt = wdgt
self.parent = self.wdgt.master # The parent of the ToolTip is the parent of the ToolTips widget
Toplevel.__init__( self, self.parent, bg='black', padx=1, pady=1 ) # Initalise the Toplevel
self.withdraw() # Hide initially
self.overrideredirect( True ) # The ToolTip Toplevel should have no frame or title bar
self.msgVar = StringVar() # The msgVar will contain the text displayed by the ToolTip
if msg == None:
self.msgVar.set( 'No message provided' )
else:
self.msgVar.set( msg )
self.msgFunc = msgFunc
self.delay = delay
self.follow = follow
self.visible = 0
self.lastMotion = 0
Message( self, textvariable=self.msgVar, bg='#FFFFDD',
aspect=1000 ).grid() # The test of the ToolTip is displayed in a Message widget
self.wdgt.bind( '<Enter>', self.spawn, '+' ) # Add bindings to the widget. This will NOT override bindings that the widget already has
self.wdgt.bind( '<Leave>', self.hide, '+' )
self.wdgt.bind( '<Motion>', self.move, '+' )
def spawn( self, event=None ):
"""
Spawn the ToolTip. This simply makes the ToolTip eligible for display.
Usually this is caused by entering the widget
Arguments:
event: The event that called this funciton
"""
self.visible = 1
self.after( int( self.delay * 1000 ), self.show ) # The after function takes a time argument in miliseconds
def show( self ):
"""
Displays the ToolTip if the time delay has been long enough
"""
if self.visible == 1 and time() - self.lastMotion > self.delay:
self.visible = 2
if self.visible == 2:
self.deiconify()
def move( self, event ):
"""
Processes motion within the widget.
Arguments:
event: The event that called this function
"""
self.lastMotion = time()
if self.follow == False: # If the follow flag is not set, motion within the widget will make the ToolTip dissapear
self.withdraw()
self.visible = 1
self.geometry( '+%i+%i' % ( event.x_root+10, event.y_root+10 ) ) # Offset the ToolTip 10x10 pixes southwest of the pointer
try:
self.msgVar.set( self.msgFunc() ) # Try to call the message function. Will not change the message if the message function is None or the message function fails
except:
pass
self.after( int( self.delay * 1000 ), self.show )
def hide( self, event=None ):
"""
Hides the ToolTip. Usually this is caused by leaving the widget
Arguments:
event: The event that called this function
"""
self.visible = 0
self.withdraw()
def xrange2d( n,m ):
"""
Returns a generator of values in a 2d range
Arguments:
n: The number of rows in the 2d range
m: The number of columns in the 2d range
Returns:
A generator of values in a 2d range
"""
return ( (i,j) for i in xrange(n) for j in xrange(m) )
def range2d( n,m ):
"""
Returns a list of values in a 2d range
Arguments:
n: The number of rows in the 2d range
m: The number of columns in the 2d range
Returns:
A list of values in a 2d range
"""
return [(i,j) for i in range(n) for j in range(m) ]
def print_time():
"""
Prints the current time in the following format:
HH:MM:SS.00
"""
t = time()
timeString = 'time='
timeString += strftime( '%H:%M:', localtime(t) )
timeString += '%.2f' % ( t%60, )
return timeString
def main():
root = Tk()
btnList = []
for (i,j) in range2d( 6, 4 ):
text = 'delay=%i\n' % i
delay = i
if j >= 2:
follow=True
text += '+follow\n'
else:
follow = False
text += '-follow\n'
if j % 2 == 0:
msg = None
msgFunc = print_time
text += 'Message Function'
else:
msg = 'Button at %s' % str( (i,j) )
msgFunc = None
text += 'Static Message'
btnList.append( Button( root, text=text ) )
ToolTip( btnList[-1], msg=msg, msgFunc=msgFunc, follow=follow, delay=delay)
btnList[-1].grid( row=i, column=j, sticky=N+S+E+W )
root.mainloop()
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0066,
0.0066,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.0132,
0.0066,
0,
0.66,
0.1429,
654,
0,
3,
0,
0,
654,
0,
0
],
[
3,
0,
0.3059,
0.5658,
0,
... | [
"from Tkinter import *",
"from time import time, localtime, strftime",
"class ToolTip( Toplevel ):\n \"\"\"\n Provides a ToolTip widget for Tkinter.\n To apply a ToolTip to any Tkinter widget, simply pass the widget to the\n ToolTip constructor\n \"\"\" \n def __init__( self, wdgt, msg=None, m... |
class Command(object):
def __init__(self, **props):
self.add = props.get('add') or []
self.remove = props.get('remove') or []
| [
[
3,
0,
0.625,
1,
0,
0.66,
0,
73,
0,
1,
0,
0,
186,
0,
2
],
[
2,
1,
0.75,
0.75,
1,
0.87,
0,
555,
0,
2,
0,
0,
0,
0,
2
],
[
14,
2,
0.75,
0.25,
2,
0.53,
0,
231,... | [
"class Command(object):\n def __init__(self, **props):\n self.add = props.get('add') or []\n self.remove = props.get('remove') or []",
" def __init__(self, **props):\n self.add = props.get('add') or []\n self.remove = props.get('remove') or []",
" self.add = props.get('a... |
from globalconst import BLACK, WHITE, KING
import checkers
class Operator(object):
pass
class OneKingAttackOneKing(Operator):
def precondition(self, board):
plr_color = board.to_move
opp_color = board.enemy
return (board.count(plr_color) == 1 and board.count(opp_color) == 1 and
any((x & KING for x in board.get_pieces(opp_color))) and
any((x & KING for x in board.get_pieces(plr_color))) and
board.has_opposition(plr_color))
def postcondition(self, board):
board.make_move()
class PinEnemyKingInCornerWithPlayerKing(Operator):
def __init__(self):
self.pidx = 0
self.eidx = 0
self.goal = 8
def precondition(self, state):
self.pidx, plr = self.plr_lst[0] # only 1 piece per side
self.eidx, enemy = self.enemy_lst[0]
delta = abs(self.pidx - self.eidx)
return ((self.player_total == 1) and (self.enemy_total == 1) and
(plr & KING > 0) and (enemy & KING > 0) and
not (8 <= delta <= 10) and state.have_opposition(plr))
def postcondition(self, state):
new_state = None
old_delta = abs(self.eidx - self.pidx)
goal_delta = abs(self.goal - old_delta)
for move in state.moves:
for m in move:
newidx, _, _ = m[1]
new_delta = abs(self.eidx - newidx)
if abs(goal - new_delta) < goal_delta:
new_state = state.make_move(move)
break
return new_state
# (white)
# 37 38 39 40
# 32 33 34 35
# 28 29 30 31
# 23 24 25 26
# 19 20 21 22
# 14 15 16 17
# 10 11 12 13
# 5 6 7 8
# (black)
class SingleKingFleeToDoubleCorner(Operator):
def __init__(self):
self.pidx = 0
self.eidx = 0
self.dest = [8, 13, 27, 32]
self.goal_delta = 0
def precondition(self, state):
# fail fast
if self.player_total == 1 and self.enemy_total == 1:
return False
self.pidx, _ = self.plr_lst[0]
self.eidx, _ = self.enemy_lst[0]
for sq in self.dest:
if abs(self.pidx - sq) < abs(self.eidx - sq):
self.goal = sq
return True
return False
def postcondition(self, state):
self.goal_delta = abs(self.goal - self.pidx)
for move in state.moves:
for m in move:
newidx, _, _ = m[1]
new_delta = abs(self.goal - newidx)
if new_delta < self.goal_delta:
new_state = state.make_move(move)
break
return new_state
class FormShortDyke(Operator):
def precondition(self):
pass
| [
[
1,
0,
0.0111,
0.0111,
0,
0.66,
0,
871,
0,
3,
0,
0,
871,
0,
0
],
[
1,
0,
0.0222,
0.0111,
0,
0.66,
0.1667,
901,
0,
1,
0,
0,
901,
0,
0
],
[
3,
0,
0.05,
0.0222,
0,
0.... | [
"from globalconst import BLACK, WHITE, KING",
"import checkers",
"class Operator(object):\n pass",
"class OneKingAttackOneKing(Operator):\n def precondition(self, board):\n plr_color = board.to_move\n opp_color = board.enemy\n return (board.count(plr_color) == 1 and board.count(opp_... |
class Controller(object):
def stop_process(self):
pass
| [
[
3,
0,
0.6,
0.6,
0,
0.66,
0,
93,
0,
1,
0,
0,
186,
0,
0
],
[
2,
1,
0.7,
0.4,
1,
0.88,
0,
116,
0,
1,
0,
0,
0,
0,
0
]
] | [
"class Controller(object):\n def stop_process(self):\n pass",
" def stop_process(self):\n pass"
] |
from abc import ABCMeta, abstractmethod
class Goal:
__metaclass__ = ABCMeta
INACTIVE = 0
ACTIVE = 1
COMPLETED = 2
FAILED = 3
def __init__(self, owner):
self.owner = owner
self.status = self.INACTIVE
@abstractmethod
def activate(self):
pass
@abstractmethod
def process(self):
pass
@abstractmethod
def terminate(self):
pass
def handleMessage(self, msg):
return False
def addSubgoal(self, goal):
raise NotImplementedError('Cannot add goals to atomic goals')
def reactivateIfFailed(self):
if self.status == self.FAILED:
self.status = self.INACTIVE
def activateIfInactive(self):
if self.status == self.INACTIVE:
self.status = self.ACTIVE
| [
[
1,
0,
0.0256,
0.0256,
0,
0.66,
0,
38,
0,
2,
0,
0,
38,
0,
0
],
[
3,
0,
0.5385,
0.9487,
0,
0.66,
1,
302,
0,
8,
0,
0,
0,
0,
1
],
[
14,
1,
0.1026,
0.0256,
1,
0.55,
... | [
"from abc import ABCMeta, abstractmethod",
"class Goal:\n __metaclass__ = ABCMeta\n\n INACTIVE = 0\n ACTIVE = 1\n COMPLETED = 2\n FAILED = 3",
" __metaclass__ = ABCMeta",
" INACTIVE = 0",
" ACTIVE = 1",
" COMPLETED = 2",
" FAILED = 3",
" def __init__(self, owner):\n ... |
from Tkinter import *
from ttk import Checkbutton
from tkSimpleDialog import Dialog
from globalconst import *
class SetupBoard(Dialog):
def __init__(self, parent, title, gameManager):
self._master = parent
self._manager = gameManager
self._load_entry_box_vars()
self.result = False
Dialog.__init__(self, parent, title)
def body(self, master):
self._npLFrame = LabelFrame(master, text='No. of players:')
self._npFrameEx1 = Frame(self._npLFrame, width=30)
self._npFrameEx1.pack(side=LEFT, pady=5, expand=1)
self._npButton1 = Radiobutton(self._npLFrame, text='Zero (autoplay)',
value=0, variable=self._num_players,
command=self._disable_player_color)
self._npButton1.pack(side=LEFT, pady=5, expand=1)
self._npButton2 = Radiobutton(self._npLFrame, text='One',
value=1, variable=self._num_players,
command=self._enable_player_color)
self._npButton2.pack(side=LEFT, pady=5, expand=1)
self._npButton3 = Radiobutton(self._npLFrame, text='Two',
value=2, variable=self._num_players,
command=self._disable_player_color)
self._npButton3.pack(side=LEFT, pady=5, expand=1)
self._npFrameEx2 = Frame(self._npLFrame, width=30)
self._npFrameEx2.pack(side=LEFT, pady=5, expand=1)
self._npLFrame.pack(fill=X)
self._playerFrame = LabelFrame(master, text='Player color:')
self._playerFrameEx1 = Frame(self._playerFrame, width=50)
self._playerFrameEx1.pack(side=LEFT, pady=5, expand=1)
self._rbColor1 = Radiobutton(self._playerFrame, text='Black',
value=BLACK, variable=self._player_color)
self._rbColor1.pack(side=LEFT, padx=0, pady=5, expand=1)
self._rbColor2 = Radiobutton(self._playerFrame, text='White',
value=WHITE, variable=self._player_color)
self._rbColor2.pack(side=LEFT, padx=0, pady=5, expand=1)
self._playerFrameEx2 = Frame(self._playerFrame, width=50)
self._playerFrameEx2.pack(side=LEFT, pady=5, expand=1)
self._playerFrame.pack(fill=X)
self._rbFrame = LabelFrame(master, text='Next to move:')
self._rbFrameEx1 = Frame(self._rbFrame, width=50)
self._rbFrameEx1.pack(side=LEFT, pady=5, expand=1)
self._rbTurn1 = Radiobutton(self._rbFrame, text='Black',
value=BLACK, variable=self._player_turn)
self._rbTurn1.pack(side=LEFT, padx=0, pady=5, expand=1)
self._rbTurn2 = Radiobutton(self._rbFrame, text='White',
value=WHITE, variable=self._player_turn)
self._rbTurn2.pack(side=LEFT, padx=0, pady=5, expand=1)
self._rbFrameEx2 = Frame(self._rbFrame, width=50)
self._rbFrameEx2.pack(side=LEFT, pady=5, expand=1)
self._rbFrame.pack(fill=X)
self._bcFrame = LabelFrame(master, text='Board configuration')
self._wmFrame = Frame(self._bcFrame, borderwidth=0)
self._wmLabel = Label(self._wmFrame, text='White men:')
self._wmLabel.pack(side=LEFT, padx=7, pady=10)
self._wmEntry = Entry(self._wmFrame, width=40,
textvariable=self._white_men)
self._wmEntry.pack(side=LEFT, padx=10)
self._wmFrame.pack()
self._wkFrame = Frame(self._bcFrame, borderwidth=0)
self._wkLabel = Label(self._wkFrame, text='White kings:')
self._wkLabel.pack(side=LEFT, padx=5, pady=10)
self._wkEntry = Entry(self._wkFrame, width=40,
textvariable=self._white_kings)
self._wkEntry.pack(side=LEFT, padx=10)
self._wkFrame.pack()
self._bmFrame = Frame(self._bcFrame, borderwidth=0)
self._bmLabel = Label(self._bmFrame, text='Black men:')
self._bmLabel.pack(side=LEFT, padx=7, pady=10)
self._bmEntry = Entry(self._bmFrame, width=40,
textvariable=self._black_men)
self._bmEntry.pack(side=LEFT, padx=10)
self._bmFrame.pack()
self._bkFrame = Frame(self._bcFrame, borderwidth=0)
self._bkLabel = Label(self._bkFrame, text='Black kings:')
self._bkLabel.pack(side=LEFT, padx=5, pady=10)
self._bkEntry = Entry(self._bkFrame, width=40,
textvariable=self._black_kings)
self._bkEntry.pack(side=LEFT, padx=10)
self._bkFrame.pack()
self._bcFrame.pack(fill=X)
self._bsState = IntVar()
self._bsFrame = Frame(master, borderwidth=0)
self._bsCheck = Checkbutton(self._bsFrame, variable=self._bsState,
text='Start new game with the current setup?')
self._bsCheck.pack()
self._bsFrame.pack(fill=X)
if self._num_players.get() == 1:
self._enable_player_color()
else:
self._disable_player_color()
def validate(self):
self.wm_list = self._parse_int_list(self._white_men.get())
self.wk_list = self._parse_int_list(self._white_kings.get())
self.bm_list = self._parse_int_list(self._black_men.get())
self.bk_list = self._parse_int_list(self._black_kings.get())
if (self.wm_list == None or self.wk_list == None
or self.bm_list == None or self.bk_list == None):
return 0 # Error occurred during parsing
if not self._all_unique(self.wm_list, self.wk_list,
self.bm_list, self.bk_list):
return 0 # A repeated index occurred
return 1
def apply(self):
mgr = self._manager
model = mgr.model
view = mgr.view
state = model.curr_state
mgr.player_color = self._player_color.get()
mgr.num_players = self._num_players.get()
mgr.model.curr_state.to_move = self._player_turn.get()
# only reset the BoardView if men or kings have new positions
if (sorted(self.wm_list) != sorted(self._orig_white_men) or
sorted(self.wk_list) != sorted(self._orig_white_kings) or
sorted(self.bm_list) != sorted(self._orig_black_men) or
sorted(self.bk_list) != sorted(self._orig_black_kings) or
self._bsState.get() == 1):
state.clear()
sq = state.squares
for item in self.wm_list:
idx = squaremap[item]
sq[idx] = WHITE | MAN
for item in self.wk_list:
idx = squaremap[item]
sq[idx] = WHITE | KING
for item in self.bm_list:
idx = squaremap[item]
sq[idx] = BLACK | MAN
for item in self.bk_list:
idx = squaremap[item]
sq[idx] = BLACK | KING
state.to_move = self._player_turn.get()
state.reset_undo()
view.reset_view(mgr.model)
if self._bsState.get() == 1:
mgr.filename = None
mgr.parent.set_title_bar_filename()
state.ok_to_move = True
self.result = True
self.destroy()
def cancel(self, event=None):
self.destroy()
def _load_entry_box_vars(self):
self._white_men = StringVar()
self._white_kings = StringVar()
self._black_men = StringVar()
self._black_kings = StringVar()
self._player_color = IntVar()
self._player_turn = IntVar()
self._num_players = IntVar()
self._player_color.set(self._manager.player_color)
self._num_players.set(self._manager.num_players)
model = self._manager.model
self._player_turn.set(model.curr_state.to_move)
view = self._manager.view
self._white_men.set(', '.join(view.get_positions(WHITE | MAN)))
self._white_kings.set(', '.join(view.get_positions(WHITE | KING)))
self._black_men.set(', '.join(view.get_positions(BLACK | MAN)))
self._black_kings.set(', '.join(view.get_positions(BLACK | KING)))
self._orig_white_men = map(int, view.get_positions(WHITE | MAN))
self._orig_white_kings = map(int, view.get_positions(WHITE | KING))
self._orig_black_men = map(int, view.get_positions(BLACK | MAN))
self._orig_black_kings = map(int, view.get_positions(BLACK | KING))
def _disable_player_color(self):
self._rbColor1.configure(state=DISABLED)
self._rbColor2.configure(state=DISABLED)
def _enable_player_color(self):
self._rbColor1.configure(state=NORMAL)
self._rbColor2.configure(state=NORMAL)
def _all_unique(self, *lists):
s = set()
total_list = []
for i in lists:
total_list.extend(i)
s = s.union(i)
return sorted(total_list) == sorted(s)
def _parse_int_list(self, parsestr):
try:
lst = parsestr.split(',')
except AttributeError:
return None
if lst == ['']:
return []
try:
lst = [int(i) for i in lst]
except ValueError:
return None
if not all(((x>=1 and x<=MAX_VALID_SQ) for x in lst)):
return None
return lst
| [
[
1,
0,
0.0046,
0.0046,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.0093,
0.0046,
0,
0.66,
0.25,
718,
0,
1,
0,
0,
718,
0,
0
],
[
1,
0,
0.0139,
0.0046,
0,
0.... | [
"from Tkinter import *",
"from ttk import Checkbutton",
"from tkSimpleDialog import Dialog",
"from globalconst import *",
"class SetupBoard(Dialog):\n def __init__(self, parent, title, gameManager):\n self._master = parent\n self._manager = gameManager\n self._load_entry_box_vars()\n... |
from Tkinter import *
class HyperlinkManager(object):
def __init__(self, textWidget, linkFunc):
self.txt = textWidget
self.linkfunc = linkFunc
self.txt.tag_config('hyper', foreground='blue', underline=1)
self.txt.tag_bind('hyper', '<Enter>', self._enter)
self.txt.tag_bind('hyper', '<Leave>', self._leave)
self.txt.tag_bind('hyper', '<Button-1>', self._click)
self.reset()
def reset(self):
self.filenames = {}
def add(self, filename):
# Add a link with associated filename. The link function returns tags
# to use in the associated text widget.
tag = 'hyper-%d' % len(self.filenames)
self.filenames[tag] = filename
return 'hyper', tag
def _enter(self, event):
self.txt.config(cursor='hand2')
def _leave(self, event):
self.txt.config(cursor='')
def _click(self, event):
for tag in self.txt.tag_names(CURRENT):
if tag.startswith('hyper-'):
self.linkfunc(self.filenames[tag])
return
| [
[
1,
0,
0.0303,
0.0303,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
3,
0,
0.5455,
0.9394,
0,
0.66,
1,
220,
0,
6,
0,
0,
186,
0,
11
],
[
2,
1,
0.2273,
0.2424,
1,
0.7,... | [
"from Tkinter import *",
"class HyperlinkManager(object):\n def __init__(self, textWidget, linkFunc):\n self.txt = textWidget\n self.linkfunc = linkFunc\n self.txt.tag_config('hyper', foreground='blue', underline=1)\n self.txt.tag_bind('hyper', '<Enter>', self._enter)\n self.... |
class DocNode(object):
"""
A node in the document.
"""
def __init__(self, kind='', parent=None, content=None):
self.children = []
self.parent = parent
self.kind = kind
self.content = content
if self.parent is not None:
self.parent.children.append(self)
| [
[
3,
0,
0.5417,
1,
0,
0.66,
0,
61,
0,
1,
0,
0,
186,
0,
1
],
[
8,
1,
0.25,
0.25,
1,
0.45,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
2,
1,
0.75,
0.5833,
1,
0.45,
1,
555,... | [
"class DocNode(object):\n \"\"\"\n A node in the document.\n \"\"\"\n\n def __init__(self, kind='', parent=None, content=None):\n self.children = []\n self.parent = parent",
" \"\"\"\n A node in the document.\n \"\"\"",
" def __init__(self, kind='', parent=None, content=Non... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the "File Uploader" for Python
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorQuickUpload( FCKeditorConnectorBase,
UploadFileCommandMixin,
BaseHttpMixin, BaseHtmlMixin):
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"")
command = 'QuickUpload'
# The file type (from the QueryString, by default 'File').
resourceType = self.request.get('Type','File')
currentFolder = "/"
# Check for invalid paths
if currentFolder is None:
return self.sendUploadResults(102, '', '', "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendUploadResults( 1, '', '', 'Invalid type specified' )
# Setup paths
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFile(resourceType, currentFolder)
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorQuickUpload()
data = conn.doResponse()
for header in conn.headers:
if not header is None:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| [
[
1,
0,
0.0213,
0.0213,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0638,
0.0213,
0,
0.66,
0.2,
630,
0,
1,
0,
0,
630,
0,
0
],
[
1,
0,
0.0851,
0.0213,
0,
0.6... | [
"import os",
"from fckutil import *",
"from fckcommands import * \t# default command's implementation",
"from fckconnector import FCKeditorConnectorBase # import base connector",
"import config as Config",
"class FCKeditorQuickUpload(\tFCKeditorConnectorBase,\n\t\t\t\t\t\t\tUploadFileCommandMixin,\n\t\t\t... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
from time import gmtime, strftime
import string
def escape(text, replace=string.replace):
"""
Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
return text
def convertToXmlAttribute(value):
if (value is None):
value = ""
return escape(value)
class BaseHttpMixin(object):
def setHttpHeaders(self, content_type='text/xml'):
"Purpose: to prepare the headers for the xml to return"
# Prevent the browser from caching the result.
# Date in the past
self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT')
# always modified
self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()))
# HTTP/1.1
self.setHeader('Cache-Control','no-store, no-cache, must-revalidate')
self.setHeader('Cache-Control','post-check=0, pre-check=0')
# HTTP/1.0
self.setHeader('Pragma','no-cache')
# Set the response format.
self.setHeader( 'Content-Type', content_type + '; charset=utf-8' )
return
class BaseXmlMixin(object):
def createXmlHeader(self, command, resourceType, currentFolder, url):
"Purpose: returns the xml header"
self.setHttpHeaders()
# Create the XML document header
s = """<?xml version="1.0" encoding="utf-8" ?>"""
# Create the main connector node
s += """<Connector command="%s" resourceType="%s">""" % (
command,
resourceType
)
# Add the current folder node
s += """<CurrentFolder path="%s" url="%s" />""" % (
convertToXmlAttribute(currentFolder),
convertToXmlAttribute(url),
)
return s
def createXmlFooter(self):
"Purpose: returns the xml footer"
return """</Connector>"""
def sendError(self, number, text):
"Purpose: in the event of an error, return an xml based error"
self.setHttpHeaders()
return ("""<?xml version="1.0" encoding="utf-8" ?>""" +
"""<Connector>""" +
self.sendErrorNode (number, text) +
"""</Connector>""" )
def sendErrorNode(self, number, text):
if number != 1:
return """<Error number="%s" />""" % (number)
else:
return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text))
class BaseHtmlMixin(object):
def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ):
self.setHttpHeaders("text/html")
"This is the function that sends the results of the uploading process"
"Minified version of the document.domain automatic fix script (#1919)."
"The original script can be found at _dev/domain_fix_template.js"
return """<script type="text/javascript">
(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();
window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s");
</script>""" % {
'errorNumber': errorNo,
'fileUrl': fileUrl.replace ('"', '\\"'),
'fileName': fileName.replace ( '"', '\\"' ) ,
'customMsg': customMsg.replace ( '"', '\\"' ),
}
| [
[
8,
0,
0.1176,
0.1933,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2269,
0.0084,
0,
0.66,
0.1429,
654,
0,
2,
0,
0,
654,
0,
0
],
[
1,
0,
0.2353,
0.0084,
0,
0.66... | [
"\"\"\"\nFCKeditor - The text editor for Internet - http://www.fckeditor.net\nCopyright (C) 2003-2010 Frederico Caldeira Knabben\n\n== BEGIN LICENSE ==\n\nLicensed under the terms of any of the following licenses at your\nchoice:",
"from time import gmtime, strftime",
"import string",
"def escape(text, replac... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the "File Uploader" for Python
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorQuickUpload( FCKeditorConnectorBase,
UploadFileCommandMixin,
BaseHttpMixin, BaseHtmlMixin):
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"")
command = 'QuickUpload'
# The file type (from the QueryString, by default 'File').
resourceType = self.request.get('Type','File')
currentFolder = "/"
# Check for invalid paths
if currentFolder is None:
return self.sendUploadResults(102, '', '', "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendUploadResults( 1, '', '', 'Invalid type specified' )
# Setup paths
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFile(resourceType, currentFolder)
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorQuickUpload()
data = conn.doResponse()
for header in conn.headers:
if not header is None:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| [
[
1,
0,
0.0213,
0.0213,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0638,
0.0213,
0,
0.66,
0.2,
630,
0,
1,
0,
0,
630,
0,
0
],
[
1,
0,
0.0851,
0.0213,
0,
0.6... | [
"import os",
"from fckutil import *",
"from fckcommands import * \t# default command's implementation",
"from fckconnector import FCKeditorConnectorBase # import base connector",
"import config as Config",
"class FCKeditorQuickUpload(\tFCKeditorConnectorBase,\n\t\t\t\t\t\t\tUploadFileCommandMixin,\n\t\t\t... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Base Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import cgi, os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
import config as Config
class FCKeditorConnectorBase( object ):
"The base connector class. Subclass it to extend functionality (see Zope example)"
def __init__(self, environ=None):
"Constructor: Here you should parse request fields, initialize variables, etc."
self.request = FCKeditorRequest(environ) # Parse request
self.headers = [] # Clean Headers
if environ:
self.environ = environ
else:
self.environ = os.environ
# local functions
def setHeader(self, key, value):
self.headers.append ((key, value))
return
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, environ):
if environ: # WSGI
self.request = cgi.FieldStorage(fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=1)
self.environ = environ
else: # plain old cgi
self.environ = os.environ
self.request = cgi.FieldStorage()
if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ:
if self.environ['REQUEST_METHOD'].upper()=='POST':
# we are in a POST, but GET query_string exists
# cgi parses by default POST data, so parse GET QUERY_STRING too
self.get_request = cgi.FieldStorage(fp=None,
environ={
'REQUEST_METHOD':'GET',
'QUERY_STRING':self.environ['QUERY_STRING'],
},
)
else:
self.get_request={}
def has_key(self, key):
return self.request.has_key(key) or self.get_request.has_key(key)
def get(self, key, default=None):
if key in self.request.keys():
field = self.request[key]
elif key in self.get_request.keys():
field = self.get_request[key]
else:
return default
if hasattr(field,"filename") and field.filename: #file upload, do not convert return value
return field
else:
return field.value
| [
[
8,
0,
0.1667,
0.2778,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3111,
0.0111,
0,
0.66,
0.1429,
934,
0,
2,
0,
0,
934,
0,
0
],
[
1,
0,
0.3333,
0.0111,
0,
0.66... | [
"\"\"\"\nFCKeditor - The text editor for Internet - http://www.fckeditor.net\nCopyright (C) 2003-2010 Frederico Caldeira Knabben\n\n== BEGIN LICENSE ==\n\nLicensed under the terms of any of the following licenses at your\nchoice:",
"import cgi, os",
"from fckutil import *",
"from fckcommands import * \t# defa... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector/QuickUpload for Python (WSGI wrapper).
See config.py for configuration settings
"""
from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload
import cgitb
from cStringIO import StringIO
# Running from WSGI capable server (recomended)
def App(environ, start_response):
"WSGI entry point. Run the connector"
if environ['SCRIPT_NAME'].endswith("connector.py"):
conn = FCKeditorConnector(environ)
elif environ['SCRIPT_NAME'].endswith("upload.py"):
conn = FCKeditorQuickUpload(environ)
else:
start_response ("200 Ok", [('Content-Type','text/html')])
yield "Unknown page requested: "
yield environ['SCRIPT_NAME']
return
try:
# run the connector
data = conn.doResponse()
# Start WSGI response:
start_response ("200 Ok", conn.headers)
# Send response text
yield data
except:
start_response("500 Internal Server Error",[("Content-type","text/html")])
file = StringIO()
cgitb.Hook(file = file).handle()
yield file.getvalue()
| [
[
8,
0,
0.2586,
0.431,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5,
0.0172,
0,
0.66,
0.2,
385,
0,
1,
0,
0,
385,
0,
0
],
[
1,
0,
0.5172,
0.0172,
0,
0.66,
0... | [
"\"\"\"\nFCKeditor - The text editor for Internet - http://www.fckeditor.net\nCopyright (C) 2003-2010 Frederico Caldeira Knabben\n\n== BEGIN LICENSE ==\n\nLicensed under the terms of any of the following licenses at your\nchoice:",
"from connector import FCKeditorConnector",
"from upload import FCKeditorQuickUp... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
if (command == "FileUpload"):
return self.sendUploadResults( errorNo = 102, customMsg = "" )
else:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| [
[
1,
0,
0.0127,
0.0127,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.038,
0.0127,
0,
0.66,
0.1667,
630,
0,
1,
0,
0,
630,
0,
0
],
[
1,
0,
0.0506,
0.0127,
0,
0... | [
"import os",
"from fckutil import *",
"from fckcommands import * \t# default command's implementation",
"from fckoutput import * \t# base http, xml and html output mixins",
"from fckconnector import FCKeditorConnectorBase # import base connector",
"import config as Config",
"class FCKeditorConnector(\tF... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
from time import gmtime, strftime
import string
def escape(text, replace=string.replace):
"""
Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
return text
def convertToXmlAttribute(value):
if (value is None):
value = ""
return escape(value)
class BaseHttpMixin(object):
def setHttpHeaders(self, content_type='text/xml'):
"Purpose: to prepare the headers for the xml to return"
# Prevent the browser from caching the result.
# Date in the past
self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT')
# always modified
self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()))
# HTTP/1.1
self.setHeader('Cache-Control','no-store, no-cache, must-revalidate')
self.setHeader('Cache-Control','post-check=0, pre-check=0')
# HTTP/1.0
self.setHeader('Pragma','no-cache')
# Set the response format.
self.setHeader( 'Content-Type', content_type + '; charset=utf-8' )
return
class BaseXmlMixin(object):
def createXmlHeader(self, command, resourceType, currentFolder, url):
"Purpose: returns the xml header"
self.setHttpHeaders()
# Create the XML document header
s = """<?xml version="1.0" encoding="utf-8" ?>"""
# Create the main connector node
s += """<Connector command="%s" resourceType="%s">""" % (
command,
resourceType
)
# Add the current folder node
s += """<CurrentFolder path="%s" url="%s" />""" % (
convertToXmlAttribute(currentFolder),
convertToXmlAttribute(url),
)
return s
def createXmlFooter(self):
"Purpose: returns the xml footer"
return """</Connector>"""
def sendError(self, number, text):
"Purpose: in the event of an error, return an xml based error"
self.setHttpHeaders()
return ("""<?xml version="1.0" encoding="utf-8" ?>""" +
"""<Connector>""" +
self.sendErrorNode (number, text) +
"""</Connector>""" )
def sendErrorNode(self, number, text):
if number != 1:
return """<Error number="%s" />""" % (number)
else:
return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text))
class BaseHtmlMixin(object):
def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ):
self.setHttpHeaders("text/html")
"This is the function that sends the results of the uploading process"
"Minified version of the document.domain automatic fix script (#1919)."
"The original script can be found at _dev/domain_fix_template.js"
return """<script type="text/javascript">
(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();
window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s");
</script>""" % {
'errorNumber': errorNo,
'fileUrl': fileUrl.replace ('"', '\\"'),
'fileName': fileName.replace ( '"', '\\"' ) ,
'customMsg': customMsg.replace ( '"', '\\"' ),
}
| [
[
8,
0,
0.1176,
0.1933,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2269,
0.0084,
0,
0.66,
0.1429,
654,
0,
2,
0,
0,
654,
0,
0
],
[
1,
0,
0.2353,
0.0084,
0,
0.66... | [
"\"\"\"\nFCKeditor - The text editor for Internet - http://www.fckeditor.net\nCopyright (C) 2003-2010 Frederico Caldeira Knabben\n\n== BEGIN LICENSE ==\n\nLicensed under the terms of any of the following licenses at your\nchoice:",
"from time import gmtime, strftime",
"import string",
"def escape(text, replac... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Base Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import cgi, os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
import config as Config
class FCKeditorConnectorBase( object ):
"The base connector class. Subclass it to extend functionality (see Zope example)"
def __init__(self, environ=None):
"Constructor: Here you should parse request fields, initialize variables, etc."
self.request = FCKeditorRequest(environ) # Parse request
self.headers = [] # Clean Headers
if environ:
self.environ = environ
else:
self.environ = os.environ
# local functions
def setHeader(self, key, value):
self.headers.append ((key, value))
return
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, environ):
if environ: # WSGI
self.request = cgi.FieldStorage(fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=1)
self.environ = environ
else: # plain old cgi
self.environ = os.environ
self.request = cgi.FieldStorage()
if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ:
if self.environ['REQUEST_METHOD'].upper()=='POST':
# we are in a POST, but GET query_string exists
# cgi parses by default POST data, so parse GET QUERY_STRING too
self.get_request = cgi.FieldStorage(fp=None,
environ={
'REQUEST_METHOD':'GET',
'QUERY_STRING':self.environ['QUERY_STRING'],
},
)
else:
self.get_request={}
def has_key(self, key):
return self.request.has_key(key) or self.get_request.has_key(key)
def get(self, key, default=None):
if key in self.request.keys():
field = self.request[key]
elif key in self.get_request.keys():
field = self.get_request[key]
else:
return default
if hasattr(field,"filename") and field.filename: #file upload, do not convert return value
return field
else:
return field.value
| [
[
8,
0,
0.1667,
0.2778,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3111,
0.0111,
0,
0.66,
0.1429,
934,
0,
2,
0,
0,
934,
0,
0
],
[
1,
0,
0.3333,
0.0111,
0,
0.66... | [
"\"\"\"\nFCKeditor - The text editor for Internet - http://www.fckeditor.net\nCopyright (C) 2003-2010 Frederico Caldeira Knabben\n\n== BEGIN LICENSE ==\n\nLicensed under the terms of any of the following licenses at your\nchoice:",
"import cgi, os",
"from fckutil import *",
"from fckcommands import * \t# defa... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector/QuickUpload for Python (WSGI wrapper).
See config.py for configuration settings
"""
from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload
import cgitb
from cStringIO import StringIO
# Running from WSGI capable server (recomended)
def App(environ, start_response):
"WSGI entry point. Run the connector"
if environ['SCRIPT_NAME'].endswith("connector.py"):
conn = FCKeditorConnector(environ)
elif environ['SCRIPT_NAME'].endswith("upload.py"):
conn = FCKeditorQuickUpload(environ)
else:
start_response ("200 Ok", [('Content-Type','text/html')])
yield "Unknown page requested: "
yield environ['SCRIPT_NAME']
return
try:
# run the connector
data = conn.doResponse()
# Start WSGI response:
start_response ("200 Ok", conn.headers)
# Send response text
yield data
except:
start_response("500 Internal Server Error",[("Content-type","text/html")])
file = StringIO()
cgitb.Hook(file = file).handle()
yield file.getvalue()
| [
[
8,
0,
0.2586,
0.431,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5,
0.0172,
0,
0.66,
0.2,
385,
0,
1,
0,
0,
385,
0,
0
],
[
1,
0,
0.5172,
0.0172,
0,
0.66,
0... | [
"\"\"\"\nFCKeditor - The text editor for Internet - http://www.fckeditor.net\nCopyright (C) 2003-2010 Frederico Caldeira Knabben\n\n== BEGIN LICENSE ==\n\nLicensed under the terms of any of the following licenses at your\nchoice:",
"from connector import FCKeditorConnector",
"from upload import FCKeditorQuickUp... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
if (command == "FileUpload"):
return self.sendUploadResults( errorNo = 102, customMsg = "" )
else:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| [
[
1,
0,
0.0127,
0.0127,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.038,
0.0127,
0,
0.66,
0.1667,
630,
0,
1,
0,
0,
630,
0,
0
],
[
1,
0,
0.0506,
0.0127,
0,
0... | [
"import os",
"from fckutil import *",
"from fckcommands import * \t# default command's implementation",
"from fckoutput import * \t# base http, xml and html output mixins",
"from fckconnector import FCKeditorConnectorBase # import base connector",
"import config as Config",
"class FCKeditorConnector(\tF... |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This page lists the data posted by a form.
"""
import cgi
import os
# Tell the browser to render html
print "Content-Type: text/html"
print ""
try:
# Create a cgi object
form = cgi.FieldStorage()
except Exception, e:
print e
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Samples - Posted Data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
"""
# This is the real work
print """
<h1>FCKeditor - Samples - Posted Data</h1>
This page lists all data posted by the form.
<hr>
<table border="1" cellspacing="0" id="outputSample">
<colgroup><col width="80"><col></colgroup>
<thead>
<tr>
<th>Field Name</th>
<th>Value</th>
</tr>
</thead>
"""
for key in form.keys():
try:
value = form[key].value
print """
<tr>
<th>%s</th>
<td><pre>%s</pre></td>
</tr>
""" % (cgi.escape(key), cgi.escape(value))
except Exception, e:
print e
print "</table>"
# For testing your environments
#print "<hr>"
#for key in os.environ.keys():
# print "%s: %s<br>" % (key, os.environ.get(key, ""))
#print "<hr>"
# Document footer
print """
</body>
</html>
"""
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.6667,
0.3333,
0,
0.66,
1,
688,
0,
1,
0,
0,
688,
0,
0
]
] | [
"import cgi",
"import os"
] |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Sample page.
"""
import cgi
import os
# Ensure that the fckeditor.py is included in your classpath
import fckeditor
# Tell the browser to render html
print "Content-Type: text/html"
print ""
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>FCKeditor - Python - Sample 1</h1>
This sample displays a normal HTML form with an FCKeditor with full features
enabled.
<hr>
<form action="sampleposteddata.py" method="post" target="_blank">
"""
# This is the real work
try:
sBasePath = os.environ.get("SCRIPT_NAME")
sBasePath = sBasePath[0:sBasePath.find("_samples")]
oFCKeditor = fckeditor.FCKeditor('FCKeditor1')
oFCKeditor.BasePath = sBasePath
oFCKeditor.Value = """<p>This is some <strong>sample text</strong>. You are using <a href="http://www.fckeditor.net/">FCKeditor</a>.</p>"""
print oFCKeditor.Create()
except Exception, e:
print e
print """
<br>
<input type="submit" value="Submit">
</form>
"""
# For testing your environments
#print "<hr>"
#for key in os.environ.keys():
# print "%s: %s<br>" % (key, os.environ.get(key, ""))
#print "<hr>"
# Document footer
print """
</body>
</html>
"""
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.5,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.8,
0.2,
0,
0.66,
1,
669,... | [
"import cgi",
"import os",
"import fckeditor"
] |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This page lists the data posted by a form.
"""
import cgi
import os
# Tell the browser to render html
print "Content-Type: text/html"
print ""
try:
# Create a cgi object
form = cgi.FieldStorage()
except Exception, e:
print e
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Samples - Posted Data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
"""
# This is the real work
print """
<h1>FCKeditor - Samples - Posted Data</h1>
This page lists all data posted by the form.
<hr>
<table border="1" cellspacing="0" id="outputSample">
<colgroup><col width="80"><col></colgroup>
<thead>
<tr>
<th>Field Name</th>
<th>Value</th>
</tr>
</thead>
"""
for key in form.keys():
try:
value = form[key].value
print """
<tr>
<th>%s</th>
<td><pre>%s</pre></td>
</tr>
""" % (cgi.escape(key), cgi.escape(value))
except Exception, e:
print e
print "</table>"
# For testing your environments
#print "<hr>"
#for key in os.environ.keys():
# print "%s: %s<br>" % (key, os.environ.get(key, ""))
#print "<hr>"
# Document footer
print """
</body>
</html>
"""
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.6667,
0.3333,
0,
0.66,
1,
688,
0,
1,
0,
0,
688,
0,
0
]
] | [
"import cgi",
"import os"
] |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Sample page.
"""
import cgi
import os
# Ensure that the fckeditor.py is included in your classpath
import fckeditor
# Tell the browser to render html
print "Content-Type: text/html"
print ""
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>FCKeditor - Python - Sample 1</h1>
This sample displays a normal HTML form with an FCKeditor with full features
enabled.
<hr>
<form action="sampleposteddata.py" method="post" target="_blank">
"""
# This is the real work
try:
sBasePath = os.environ.get("SCRIPT_NAME")
sBasePath = sBasePath[0:sBasePath.find("_samples")]
oFCKeditor = fckeditor.FCKeditor('FCKeditor1')
oFCKeditor.BasePath = sBasePath
oFCKeditor.Value = """<p>This is some <strong>sample text</strong>. You are using <a href="http://www.fckeditor.net/">FCKeditor</a>.</p>"""
print oFCKeditor.Create()
except Exception, e:
print e
print """
<br>
<input type="submit" value="Submit">
</form>
"""
# For testing your environments
#print "<hr>"
#for key in os.environ.keys():
# print "%s: %s<br>" % (key, os.environ.get(key, ""))
#print "<hr>"
# Document footer
print """
</body>
</html>
"""
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.5,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.8,
0.2,
0,
0.66,
1,
669,... | [
"import cgi",
"import os",
"import fckeditor"
] |
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2010 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the integration file for Python.
"""
import cgi
import os
import re
import string
def escape(text, replace=string.replace):
"""Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
text = replace(text, "'", ''')
return text
# The FCKeditor class
class FCKeditor(object):
def __init__(self, instanceName):
self.InstanceName = instanceName
self.BasePath = '/fckeditor/'
self.Width = '100%'
self.Height = '200'
self.ToolbarSet = 'Default'
self.Value = '';
self.Config = {}
def Create(self):
return self.CreateHtml()
def CreateHtml(self):
HtmlValue = escape(self.Value)
Html = ""
if (self.IsCompatible()):
File = "fckeditor.html"
Link = "%seditor/%s?InstanceName=%s" % (
self.BasePath,
File,
self.InstanceName
)
if (self.ToolbarSet is not None):
Link += "&Toolbar=%s" % self.ToolbarSet
# Render the linked hidden field
Html += "<input type=\"hidden\" id=\"%s\" name=\"%s\" value=\"%s\" style=\"display:none\" />" % (
self.InstanceName,
self.InstanceName,
HtmlValue
)
# Render the configurations hidden field
Html += "<input type=\"hidden\" id=\"%s___Config\" value=\"%s\" style=\"display:none\" />" % (
self.InstanceName,
self.GetConfigFieldString()
)
# Render the editor iframe
Html += "<iframe id=\"%s\__Frame\" src=\"%s\" width=\"%s\" height=\"%s\" frameborder=\"0\" scrolling=\"no\"></iframe>" % (
self.InstanceName,
Link,
self.Width,
self.Height
)
else:
if (self.Width.find("%%") < 0):
WidthCSS = "%spx" % self.Width
else:
WidthCSS = self.Width
if (self.Height.find("%%") < 0):
HeightCSS = "%spx" % self.Height
else:
HeightCSS = self.Height
Html += "<textarea name=\"%s\" rows=\"4\" cols=\"40\" style=\"width: %s; height: %s;\" wrap=\"virtual\">%s</textarea>" % (
self.InstanceName,
WidthCSS,
HeightCSS,
HtmlValue
)
return Html
def IsCompatible(self):
if (os.environ.has_key("HTTP_USER_AGENT")):
sAgent = os.environ.get("HTTP_USER_AGENT", "")
else:
sAgent = ""
if (sAgent.find("MSIE") >= 0) and (sAgent.find("mac") < 0) and (sAgent.find("Opera") < 0):
i = sAgent.find("MSIE")
iVersion = float(sAgent[i+5:i+5+3])
if (iVersion >= 5.5):
return True
return False
elif (sAgent.find("Gecko/") >= 0):
i = sAgent.find("Gecko/")
iVersion = int(sAgent[i+6:i+6+8])
if (iVersion >= 20030210):
return True
return False
elif (sAgent.find("Opera/") >= 0):
i = sAgent.find("Opera/")
iVersion = float(sAgent[i+6:i+6+4])
if (iVersion >= 9.5):
return True
return False
elif (sAgent.find("AppleWebKit/") >= 0):
p = re.compile('AppleWebKit\/(\d+)', re.IGNORECASE)
m = p.search(sAgent)
if (m.group(1) >= 522):
return True
return False
else:
return False
def GetConfigFieldString(self):
sParams = ""
bFirst = True
for sKey in self.Config.keys():
sValue = self.Config[sKey]
if (not bFirst):
sParams += "&"
else:
bFirst = False
if (sValue):
k = escape(sKey)
v = escape(sValue)
if (sValue == "true"):
sParams += "%s=true" % k
elif (sValue == "false"):
sParams += "%s=false" % k
else:
sParams += "%s=%s" % (k, v)
return sParams
| [
[
8,
0,
0.0719,
0.1375,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.15,
0.0063,
0,
0.66,
0.1667,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.1562,
0.0063,
0,
0.66,
... | [
"\"\"\"\nFCKeditor - The text editor for Internet - http://www.fckeditor.net\nCopyright (C) 2003-2010 Frederico Caldeira Knabben\n\n== BEGIN LICENSE ==\n\nLicensed under the terms of any of the following licenses at your\nchoice:",
"import cgi",
"import os",
"import re",
"import string",
"def escape(text,... |
#!/usr/bin/python
# Copyright 2011 Google, Inc. All Rights Reserved.
# simple script to walk source tree looking for third-party licenses
# dumps resulting html page to stdout
import os, re, mimetypes, sys
# read source directories to scan from command line
SOURCE = sys.argv[1:]
# regex to find /* */ style comment blocks
COMMENT_BLOCK = re.compile(r"(/\*.+?\*/)", re.MULTILINE | re.DOTALL)
# regex used to detect if comment block is a license
COMMENT_LICENSE = re.compile(r"(license)", re.IGNORECASE)
COMMENT_COPYRIGHT = re.compile(r"(copyright)", re.IGNORECASE)
EXCLUDE_TYPES = [
"application/xml",
"image/png",
]
# list of known licenses; keys are derived by stripping all whitespace and
# forcing to lowercase to help combine multiple files that have same license.
KNOWN_LICENSES = {}
class License:
def __init__(self, license_text):
self.license_text = license_text
self.filenames = []
# add filename to the list of files that have the same license text
def add_file(self, filename):
if filename not in self.filenames:
self.filenames.append(filename)
LICENSE_KEY = re.compile(r"[^\w]")
def find_license(license_text):
# TODO(alice): a lot these licenses are almost identical Apache licenses.
# Most of them differ in origin/modifications. Consider combining similar
# licenses.
license_key = LICENSE_KEY.sub("", license_text).lower()
if license_key not in KNOWN_LICENSES:
KNOWN_LICENSES[license_key] = License(license_text)
return KNOWN_LICENSES[license_key]
def discover_license(exact_path, filename):
# when filename ends with LICENSE, assume applies to filename prefixed
if filename.endswith("LICENSE"):
with open(exact_path) as file:
license_text = file.read()
target_filename = filename[:-len("LICENSE")]
if target_filename.endswith("."): target_filename = target_filename[:-1]
find_license(license_text).add_file(target_filename)
return None
# try searching for license blocks in raw file
mimetype = mimetypes.guess_type(filename)
if mimetype in EXCLUDE_TYPES: return None
with open(exact_path) as file:
raw_file = file.read()
# include comments that have both "license" and "copyright" in the text
for comment in COMMENT_BLOCK.finditer(raw_file):
comment = comment.group(1)
if COMMENT_LICENSE.search(comment) is None: continue
if COMMENT_COPYRIGHT.search(comment) is None: continue
find_license(comment).add_file(filename)
for source in SOURCE:
for root, dirs, files in os.walk(source):
for name in files:
discover_license(os.path.join(root, name), name)
print "<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body>"
for license in KNOWN_LICENSES.values():
print "<h3>Notices for files:</h3><ul>"
filenames = license.filenames
filenames.sort()
for filename in filenames:
print "<li>%s</li>" % (filename)
print "</ul>"
print "<pre>%s</pre>" % license.license_text
print "</body></html>"
| [
[
1,
0,
0.0816,
0.0102,
0,
0.66,
0,
688,
0,
4,
0,
0,
688,
0,
0
],
[
14,
0,
0.1224,
0.0102,
0,
0.66,
0.0714,
792,
6,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1531,
0.0102,
0,
... | [
"import os, re, mimetypes, sys",
"SOURCE = sys.argv[1:]",
"COMMENT_BLOCK = re.compile(r\"(/\\*.+?\\*/)\", re.MULTILINE | re.DOTALL)",
"COMMENT_LICENSE = re.compile(r\"(license)\", re.IGNORECASE)",
"COMMENT_COPYRIGHT = re.compile(r\"(copyright)\", re.IGNORECASE)",
"EXCLUDE_TYPES = [\n \"application/xml\... |
# Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'includes': [
'build_angle.gypi',
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
| [
[
8,
0,
0.4667,
0.3333,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
] | [
"{\n 'includes': [\n 'build_angle.gypi',\n ],\n}"
] |
# Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'angle_code': 1,
},
'target_defaults': {
'defines': [
'ANGLE_DISABLE_TRACE',
'ANGLE_COMPILE_OPTIMIZATION_LEVEL=D3DCOMPILE_OPTIMIZATION_LEVEL1',
'ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES={ TEXT("d3dcompiler_46.dll"), TEXT("d3dcompiler_43.dll") }',
],
},
'targets': [
{
'target_name': 'preprocessor',
'type': 'static_library',
'include_dirs': [
],
'sources': [
'compiler/preprocessor/DiagnosticsBase.cpp',
'compiler/preprocessor/DiagnosticsBase.h',
'compiler/preprocessor/DirectiveHandlerBase.cpp',
'compiler/preprocessor/DirectiveHandlerBase.h',
'compiler/preprocessor/DirectiveParser.cpp',
'compiler/preprocessor/DirectiveParser.h',
'compiler/preprocessor/ExpressionParser.cpp',
'compiler/preprocessor/ExpressionParser.h',
'compiler/preprocessor/Input.cpp',
'compiler/preprocessor/Input.h',
'compiler/preprocessor/length_limits.h',
'compiler/preprocessor/Lexer.cpp',
'compiler/preprocessor/Lexer.h',
'compiler/preprocessor/Macro.cpp',
'compiler/preprocessor/Macro.h',
'compiler/preprocessor/MacroExpander.cpp',
'compiler/preprocessor/MacroExpander.h',
'compiler/preprocessor/numeric_lex.h',
'compiler/preprocessor/pp_utils.h',
'compiler/preprocessor/Preprocessor.cpp',
'compiler/preprocessor/Preprocessor.h',
'compiler/preprocessor/SourceLocation.h',
'compiler/preprocessor/Token.cpp',
'compiler/preprocessor/Token.h',
'compiler/preprocessor/Tokenizer.cpp',
'compiler/preprocessor/Tokenizer.h',
],
# TODO(jschuh): http://crbug.com/167187
'msvs_disabled_warnings': [
4267,
],
},
{
'target_name': 'translator_common',
'type': 'static_library',
'dependencies': ['preprocessor'],
'include_dirs': [
'.',
'../include',
],
'defines': [
'COMPILER_IMPLEMENTATION',
],
'sources': [
'compiler/BaseTypes.h',
'compiler/BuiltInFunctionEmulator.cpp',
'compiler/BuiltInFunctionEmulator.h',
'compiler/Common.h',
'compiler/Compiler.cpp',
'compiler/ConstantUnion.h',
'compiler/debug.cpp',
'compiler/debug.h',
'compiler/DetectCallDepth.cpp',
'compiler/DetectCallDepth.h',
'compiler/Diagnostics.h',
'compiler/Diagnostics.cpp',
'compiler/DirectiveHandler.h',
'compiler/DirectiveHandler.cpp',
'compiler/ExtensionBehavior.h',
'compiler/ForLoopUnroll.cpp',
'compiler/ForLoopUnroll.h',
'compiler/glslang.h',
'compiler/glslang_lex.cpp',
'compiler/glslang_tab.cpp',
'compiler/glslang_tab.h',
'compiler/HashNames.h',
'compiler/InfoSink.cpp',
'compiler/InfoSink.h',
'compiler/Initialize.cpp',
'compiler/Initialize.h',
'compiler/InitializeDll.cpp',
'compiler/InitializeDll.h',
'compiler/InitializeGlobals.h',
'compiler/InitializeParseContext.cpp',
'compiler/InitializeParseContext.h',
'compiler/Intermediate.cpp',
'compiler/intermediate.h',
'compiler/intermOut.cpp',
'compiler/IntermTraverse.cpp',
'compiler/localintermediate.h',
'compiler/MapLongVariableNames.cpp',
'compiler/MapLongVariableNames.h',
'compiler/MMap.h',
'compiler/osinclude.h',
'compiler/parseConst.cpp',
'compiler/ParseHelper.cpp',
'compiler/ParseHelper.h',
'compiler/PoolAlloc.cpp',
'compiler/PoolAlloc.h',
'compiler/QualifierAlive.cpp',
'compiler/QualifierAlive.h',
'compiler/RemoveTree.cpp',
'compiler/RemoveTree.h',
'compiler/RenameFunction.h',
'compiler/ShHandle.h',
'compiler/SymbolTable.cpp',
'compiler/SymbolTable.h',
'compiler/Types.h',
'compiler/Uniform.cpp',
'compiler/Uniform.h',
'compiler/util.cpp',
'compiler/util.h',
'compiler/ValidateLimitations.cpp',
'compiler/ValidateLimitations.h',
'compiler/VariableInfo.cpp',
'compiler/VariableInfo.h',
'compiler/VariablePacker.cpp',
'compiler/VariablePacker.h',
# Dependency graph
'compiler/depgraph/DependencyGraph.cpp',
'compiler/depgraph/DependencyGraph.h',
'compiler/depgraph/DependencyGraphBuilder.cpp',
'compiler/depgraph/DependencyGraphBuilder.h',
'compiler/depgraph/DependencyGraphOutput.cpp',
'compiler/depgraph/DependencyGraphOutput.h',
'compiler/depgraph/DependencyGraphTraverse.cpp',
# Timing restrictions
'compiler/timing/RestrictFragmentShaderTiming.cpp',
'compiler/timing/RestrictFragmentShaderTiming.h',
'compiler/timing/RestrictVertexShaderTiming.cpp',
'compiler/timing/RestrictVertexShaderTiming.h',
'third_party/compiler/ArrayBoundsClamper.cpp',
'third_party/compiler/ArrayBoundsClamper.h',
],
'conditions': [
['OS=="win"', {
# TODO(jschuh): http://crbug.com/167187 size_t -> int
'msvs_disabled_warnings': [ 4267 ],
'sources': ['compiler/ossource_win.cpp'],
}, { # else: posix
'sources': ['compiler/ossource_posix.cpp'],
}],
],
},
{
'target_name': 'translator_glsl',
'type': '<(component)',
'dependencies': ['translator_common'],
'include_dirs': [
'.',
'../include',
],
'defines': [
'COMPILER_IMPLEMENTATION',
],
'sources': [
'compiler/CodeGenGLSL.cpp',
'compiler/OutputESSL.cpp',
'compiler/OutputESSL.h',
'compiler/OutputGLSLBase.cpp',
'compiler/OutputGLSLBase.h',
'compiler/OutputGLSL.cpp',
'compiler/OutputGLSL.h',
'compiler/ShaderLang.cpp',
'compiler/TranslatorESSL.cpp',
'compiler/TranslatorESSL.h',
'compiler/TranslatorGLSL.cpp',
'compiler/TranslatorGLSL.h',
'compiler/VersionGLSL.cpp',
'compiler/VersionGLSL.h',
],
# TODO(jschuh): http://crbug.com/167187 size_t -> int
'msvs_disabled_warnings': [ 4267 ],
},
],
'conditions': [
['OS=="win"', {
'targets': [
{
'target_name': 'translator_hlsl',
'type': '<(component)',
'dependencies': ['translator_common'],
'include_dirs': [
'.',
'../include',
],
'defines': [
'COMPILER_IMPLEMENTATION',
],
'sources': [
'compiler/ShaderLang.cpp',
'compiler/DetectDiscontinuity.cpp',
'compiler/DetectDiscontinuity.h',
'compiler/CodeGenHLSL.cpp',
'compiler/OutputHLSL.cpp',
'compiler/OutputHLSL.h',
'compiler/TranslatorHLSL.cpp',
'compiler/TranslatorHLSL.h',
'compiler/UnfoldShortCircuit.cpp',
'compiler/UnfoldShortCircuit.h',
'compiler/SearchSymbol.cpp',
'compiler/SearchSymbol.h',
],
# TODO(jschuh): http://crbug.com/167187 size_t -> int
'msvs_disabled_warnings': [ 4267 ],
},
{
'target_name': 'libGLESv2',
'type': 'shared_library',
'dependencies': ['translator_hlsl'],
'include_dirs': [
'.',
'../include',
'libGLESv2',
],
'sources': [
'third_party/murmurhash/MurmurHash3.h',
'third_party/murmurhash/MurmurHash3.cpp',
'common/angleutils.h',
'common/debug.cpp',
'common/debug.h',
'common/RefCountObject.cpp',
'common/RefCountObject.h',
'common/version.h',
'libGLESv2/precompiled.h',
'libGLESv2/precompiled.cpp',
'libGLESv2/BinaryStream.h',
'libGLESv2/Buffer.cpp',
'libGLESv2/Buffer.h',
'libGLESv2/constants.h',
'libGLESv2/Context.cpp',
'libGLESv2/Context.h',
'libGLESv2/angletypes.h',
'libGLESv2/Fence.cpp',
'libGLESv2/Fence.h',
'libGLESv2/Float16ToFloat32.cpp',
'libGLESv2/Framebuffer.cpp',
'libGLESv2/Framebuffer.h',
'libGLESv2/HandleAllocator.cpp',
'libGLESv2/HandleAllocator.h',
'libGLESv2/libGLESv2.cpp',
'libGLESv2/libGLESv2.def',
'libGLESv2/libGLESv2.rc',
'libGLESv2/main.cpp',
'libGLESv2/main.h',
'libGLESv2/mathutil.h',
'libGLESv2/Program.cpp',
'libGLESv2/Program.h',
'libGLESv2/ProgramBinary.cpp',
'libGLESv2/ProgramBinary.h',
'libGLESv2/Query.h',
'libGLESv2/Query.cpp',
'libGLESv2/Renderbuffer.cpp',
'libGLESv2/Renderbuffer.h',
'libGLESv2/renderer/Blit.cpp',
'libGLESv2/renderer/Blit.h',
'libGLESv2/renderer/BufferStorage.h',
'libGLESv2/renderer/BufferStorage.cpp',
'libGLESv2/renderer/BufferStorage9.cpp',
'libGLESv2/renderer/BufferStorage9.h',
'libGLESv2/renderer/BufferStorage11.cpp',
'libGLESv2/renderer/BufferStorage11.h',
'libGLESv2/renderer/FenceImpl.h',
'libGLESv2/renderer/Fence9.cpp',
'libGLESv2/renderer/Fence9.h',
'libGLESv2/renderer/Fence11.cpp',
'libGLESv2/renderer/Fence11.h',
'libGLESv2/renderer/generatemip.h',
'libGLESv2/renderer/Image.cpp',
'libGLESv2/renderer/Image.h',
'libGLESv2/renderer/Image11.cpp',
'libGLESv2/renderer/Image11.h',
'libGLESv2/renderer/Image9.cpp',
'libGLESv2/renderer/Image9.h',
'libGLESv2/renderer/ImageSSE2.cpp',
'libGLESv2/renderer/IndexBuffer.cpp',
'libGLESv2/renderer/IndexBuffer.h',
'libGLESv2/renderer/IndexBuffer9.cpp',
'libGLESv2/renderer/IndexBuffer9.h',
'libGLESv2/renderer/IndexBuffer11.cpp',
'libGLESv2/renderer/IndexBuffer11.h',
'libGLESv2/renderer/IndexDataManager.cpp',
'libGLESv2/renderer/IndexDataManager.h',
'libGLESv2/renderer/InputLayoutCache.cpp',
'libGLESv2/renderer/InputLayoutCache.h',
'libGLESv2/renderer/QueryImpl.h',
'libGLESv2/renderer/Query9.cpp',
'libGLESv2/renderer/Query9.h',
'libGLESv2/renderer/Query11.cpp',
'libGLESv2/renderer/Query11.h',
'libGLESv2/renderer/Renderer.cpp',
'libGLESv2/renderer/Renderer.h',
'libGLESv2/renderer/Renderer11.cpp',
'libGLESv2/renderer/Renderer11.h',
'libGLESv2/renderer/renderer11_utils.cpp',
'libGLESv2/renderer/renderer11_utils.h',
'libGLESv2/renderer/Renderer9.cpp',
'libGLESv2/renderer/Renderer9.h',
'libGLESv2/renderer/renderer9_utils.cpp',
'libGLESv2/renderer/renderer9_utils.h',
'libGLESv2/renderer/RenderStateCache.cpp',
'libGLESv2/renderer/RenderStateCache.h',
'libGLESv2/renderer/RenderTarget.h',
'libGLESv2/renderer/RenderTarget11.h',
'libGLESv2/renderer/RenderTarget11.cpp',
'libGLESv2/renderer/RenderTarget9.h',
'libGLESv2/renderer/RenderTarget9.cpp',
'libGLESv2/renderer/ShaderCache.h',
'libGLESv2/renderer/ShaderExecutable.h',
'libGLESv2/renderer/ShaderExecutable9.cpp',
'libGLESv2/renderer/ShaderExecutable9.h',
'libGLESv2/renderer/ShaderExecutable11.cpp',
'libGLESv2/renderer/ShaderExecutable11.h',
'libGLESv2/renderer/SwapChain.h',
'libGLESv2/renderer/SwapChain9.cpp',
'libGLESv2/renderer/SwapChain9.h',
'libGLESv2/renderer/SwapChain11.cpp',
'libGLESv2/renderer/SwapChain11.h',
'libGLESv2/renderer/TextureStorage.cpp',
'libGLESv2/renderer/TextureStorage.h',
'libGLESv2/renderer/TextureStorage11.cpp',
'libGLESv2/renderer/TextureStorage11.h',
'libGLESv2/renderer/TextureStorage9.cpp',
'libGLESv2/renderer/TextureStorage9.h',
'libGLESv2/renderer/VertexBuffer.cpp',
'libGLESv2/renderer/VertexBuffer.h',
'libGLESv2/renderer/VertexBuffer9.cpp',
'libGLESv2/renderer/VertexBuffer9.h',
'libGLESv2/renderer/VertexBuffer11.cpp',
'libGLESv2/renderer/VertexBuffer11.h',
'libGLESv2/renderer/vertexconversion.h',
'libGLESv2/renderer/VertexDataManager.cpp',
'libGLESv2/renderer/VertexDataManager.h',
'libGLESv2/renderer/VertexDeclarationCache.cpp',
'libGLESv2/renderer/VertexDeclarationCache.h',
'libGLESv2/ResourceManager.cpp',
'libGLESv2/ResourceManager.h',
'libGLESv2/Shader.cpp',
'libGLESv2/Shader.h',
'libGLESv2/Texture.cpp',
'libGLESv2/Texture.h',
'libGLESv2/Uniform.cpp',
'libGLESv2/Uniform.h',
'libGLESv2/utilities.cpp',
'libGLESv2/utilities.h',
],
# TODO(jschuh): http://crbug.com/167187 size_t -> int
'msvs_disabled_warnings': [ 4267 ],
'msvs_settings': {
'VCLinkerTool': {
'AdditionalDependencies': [
'd3d9.lib',
'dxguid.lib',
],
}
},
},
{
'target_name': 'libEGL',
'type': 'shared_library',
'dependencies': ['libGLESv2'],
'include_dirs': [
'.',
'../include',
'libGLESv2',
],
'sources': [
'common/angleutils.h',
'common/debug.cpp',
'common/debug.h',
'common/RefCountObject.cpp',
'common/RefCountObject.h',
'common/version.h',
'libEGL/Config.cpp',
'libEGL/Config.h',
'libEGL/Display.cpp',
'libEGL/Display.h',
'libEGL/libEGL.cpp',
'libEGL/libEGL.def',
'libEGL/libEGL.rc',
'libEGL/main.cpp',
'libEGL/main.h',
'libEGL/Surface.cpp',
'libEGL/Surface.h',
],
# TODO(jschuh): http://crbug.com/167187 size_t -> int
'msvs_disabled_warnings': [ 4267 ],
'msvs_settings': {
'VCLinkerTool': {
'AdditionalDependencies': [
'd3d9.lib',
],
}
},
},
],
}],
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
# Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
| [
[
8,
0,
0.4952,
0.969,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
] | [
"{\n 'variables': {\n 'angle_code': 1,\n },\n 'target_defaults': {\n 'defines': [\n 'ANGLE_DISABLE_TRACE',\n 'ANGLE_COMPILE_OPTIMIZATION_LEVEL=D3DCOMPILE_OPTIMIZATION_LEVEL1',"
] |
# Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# This script generates a function that converts 16-bit precision floating
# point numbers to 32-bit.
# It is based on ftp://ftp.fox-toolkit.org/pub/fasthalffloatconversion.pdf.
def convertMantissa(i):
if i == 0:
return 0
elif i < 1024:
m = i << 13
e = 0
while not (m & 0x00800000):
e -= 0x00800000
m = m << 1
m &= ~0x00800000
e += 0x38800000
return m | e
else:
return 0x38000000 + ((i - 1024) << 13)
def convertExponent(i):
if i == 0:
return 0
elif i in range(1, 31):
return i << 23
elif i == 31:
return 0x47800000
elif i == 32:
return 0x80000000
elif i in range(33, 63):
return 0x80000000 + ((i - 32) << 23)
else:
return 0xC7800000
def convertOffset(i):
if i == 0 or i == 32:
return 0
else:
return 1024
print """//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file is automatically generated.
namespace gl
{
"""
print "const static unsigned g_mantissa[2048] = {"
for i in range(0, 2048):
print " %#010x," % convertMantissa(i)
print "};\n"
print "const static unsigned g_exponent[64] = {"
for i in range(0, 64):
print " %#010x," % convertExponent(i)
print "};\n"
print "const static unsigned g_offset[64] = {"
for i in range(0, 64):
print " %#010x," % convertOffset(i)
print "};\n"
print """float float16ToFloat32(unsigned short h)
{
unsigned i32 = g_mantissa[g_offset[h >> 10] + (h & 0x3ff)] + g_exponent[h >> 10];
return *(float*) &i32;
}
}
"""
| [
[
2,
0,
0.2143,
0.4,
0,
0.66,
0,
107,
0,
1,
1,
0,
0,
0,
0
],
[
4,
1,
0.2286,
0.3714,
1,
0.68,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[
13,
2,
0.0857,
0.0286,
2,
0.69,
0,
... | [
"def convertMantissa(i):\n if i == 0:\n return 0\n elif i < 1024:\n m = i << 13\n e = 0\n while not (m & 0x00800000):\n e -= 0x00800000",
" if i == 0:\n return 0\n elif i < 1024:\n m = i << 13\n e = 0\n while not (m & 0x00800000):\n ... |
deps = {
"trunk/third_party/gyp":
"http://gyp.googlecode.com/svn/trunk@1564",
"trunk/third_party/googletest":
"http://googletest.googlecode.com/svn/trunk@573", #release 1.6.0
"trunk/third_party/googlemock":
"http://googlemock.googlecode.com/svn/trunk@387", #release 1.6.0
}
hooks = [
{
# A change to a .gyp, .gypi, or to GYP itself should run the generator.
"pattern": ".",
"action": ["python", "trunk/build/gyp_angle"],
},
]
| [
[
14,
0,
0.3056,
0.5556,
0,
0.66,
0,
565,
0,
0,
0,
0,
0,
6,
0
],
[
14,
0,
0.8333,
0.3889,
0,
0.66,
1,
91,
0,
0,
0,
0,
0,
5,
0
]
] | [
"deps = {\n \"trunk/third_party/gyp\":\n \"http://gyp.googlecode.com/svn/trunk@1564\",\n\n \"trunk/third_party/googletest\":\n \"http://googletest.googlecode.com/svn/trunk@573\", #release 1.6.0\n\n \"trunk/third_party/googlemock\":",
"hooks = [\n {\n # A change to a .gyp, .gypi, or to GYP itself ... |
# Copyright (c) 2010 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'essl_to_glsl',
'type': 'executable',
'dependencies': [
'../src/build_angle.gyp:translator_glsl',
],
'include_dirs': [
'../include',
],
'sources': [
'translator/translator.cpp',
],
},
],
'conditions': [
['OS=="win"', {
'targets': [
{
'target_name': 'essl_to_hlsl',
'type': 'executable',
'dependencies': [
'../src/build_angle.gyp:translator_hlsl',
],
'include_dirs': [
'../include',
'../src',
],
'sources': [
'translator/translator.cpp',
'../src/common/debug.cpp',
],
'msvs_settings': {
'VCLinkerTool': {
'AdditionalDependencies': ['d3d9.lib'],
}
}
},
{
'target_name': 'es_util',
'type': 'static_library',
'dependencies': [
'../src/build_angle.gyp:libEGL',
'../src/build_angle.gyp:libGLESv2',
],
'include_dirs': [
'gles2_book/Common',
'../include',
],
'sources': [
'gles2_book/Common/esShader.c',
'gles2_book/Common/esShapes.c',
'gles2_book/Common/esTransform.c',
'gles2_book/Common/esUtil.c',
'gles2_book/Common/esUtil.h',
'gles2_book/Common/esUtil_win.h',
'gles2_book/Common/Win32/esUtil_TGA.c',
'gles2_book/Common/Win32/esUtil_win32.c',
],
'direct_dependent_settings': {
'include_dirs': [
'gles2_book/Common',
'../include',
],
},
},
{
'target_name': 'hello_triangle',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/Hello_Triangle/Hello_Triangle.c',
],
},
{
'target_name': 'mip_map_2d',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/MipMap2D/MipMap2D.c',
],
},
{
'target_name': 'multi_texture',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/MultiTexture/MultiTexture.c',
],
'copies': [
{
'destination': '<(PRODUCT_DIR)',
'files': [
'gles2_book/MultiTexture/basemap.tga',
'gles2_book/MultiTexture/lightmap.tga',
],
},
],
},
{
'target_name': 'particle_system',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/ParticleSystem/ParticleSystem.c',
],
'copies': [
{
'destination': '<(PRODUCT_DIR)',
'files': [
'gles2_book/ParticleSystem/smoke.tga',
],
},
],
},
{
'target_name': 'simple_texture_2d',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/Simple_Texture2D/Simple_Texture2D.c',
],
},
{
'target_name': 'simple_texture_cubemap',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/Simple_TextureCubemap/Simple_TextureCubemap.c',
],
},
{
'target_name': 'simple_vertex_shader',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/Simple_VertexShader/Simple_VertexShader.c',
],
},
{
'target_name': 'stencil_test',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/Stencil_Test/Stencil_Test.c',
],
},
{
'target_name': 'texture_wrap',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/TextureWrap/TextureWrap.c',
],
},
{
'target_name': 'post_sub_buffer',
'type': 'executable',
'dependencies': ['es_util'],
'sources': [
'gles2_book/PostSubBuffer/PostSubBuffer.c',
],
},
],
}],
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
| [
[
8,
0,
0.4972,
0.9438,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
] | [
"{\n 'targets': [\n {\n 'target_name': 'essl_to_glsl',\n 'type': 'executable',\n 'dependencies': [\n '../src/build_angle.gyp:translator_glsl',\n ],"
] |
# Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'gtest',
'type': 'static_library',
'include_dirs': [
'../third_party/googletest',
'../third_party/googletest/include',
],
'sources': [
'../third_party/googletest/src/gtest-all.cc',
],
},
{
'target_name': 'gmock',
'type': 'static_library',
'include_dirs': [
'../third_party/googlemock',
'../third_party/googlemock/include',
'../third_party/googletest/include',
],
'sources': [
'../third_party/googlemock/src/gmock-all.cc',
],
},
{
'target_name': 'preprocessor_tests',
'type': 'executable',
'dependencies': [
'../src/build_angle.gyp:preprocessor',
'gtest',
'gmock',
],
'include_dirs': [
'../src/compiler/preprocessor',
'../third_party/googletest/include',
'../third_party/googlemock/include',
],
'sources': [
'../third_party/googlemock/src/gmock_main.cc',
'preprocessor_tests/char_test.cpp',
'preprocessor_tests/comment_test.cpp',
'preprocessor_tests/define_test.cpp',
'preprocessor_tests/error_test.cpp',
'preprocessor_tests/extension_test.cpp',
'preprocessor_tests/identifier_test.cpp',
'preprocessor_tests/if_test.cpp',
'preprocessor_tests/input_test.cpp',
'preprocessor_tests/location_test.cpp',
'preprocessor_tests/MockDiagnostics.h',
'preprocessor_tests/MockDirectiveHandler.h',
'preprocessor_tests/number_test.cpp',
'preprocessor_tests/operator_test.cpp',
'preprocessor_tests/pragma_test.cpp',
'preprocessor_tests/PreprocessorTest.cpp',
'preprocessor_tests/PreprocessorTest.h',
'preprocessor_tests/space_test.cpp',
'preprocessor_tests/token_test.cpp',
'preprocessor_tests/version_test.cpp',
],
},
{
'target_name': 'compiler_tests',
'type': 'executable',
'dependencies': [
'../src/build_angle.gyp:translator_glsl',
'gtest',
'gmock',
],
'include_dirs': [
'../include',
'../src',
'../third_party/googletest/include',
'../third_party/googlemock/include',
],
'sources': [
'../third_party/googlemock/src/gmock_main.cc',
'compiler_tests/ExpressionLimit_test.cpp',
'compiler_tests/VariablePacker_test.cpp',
],
},
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
| [
[
8,
0,
0.4946,
0.8925,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
] | [
"{\n 'targets': [\n {\n 'target_name': 'gtest',\n 'type': 'static_library',\n 'include_dirs': [\n '../third_party/googletest',\n '../third_party/googletest/include',"
] |
#====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ====================================================================
#
# This software consists of voluntary contributions made by many
# individuals on behalf of the Apache Software Foundation. For more
# information on the Apache Software Foundation, please see
# <http://www.apache.org/>.
#
import os
import re
import tempfile
import shutil
ignore_pattern = re.compile('^(.svn|target|bin|classes)')
java_pattern = re.compile('^.*\.java')
annot_pattern = re.compile('import org\.apache\.http\.annotation\.')
def process_dir(dir):
files = os.listdir(dir)
for file in files:
f = os.path.join(dir, file)
if os.path.isdir(f):
if not ignore_pattern.match(file):
process_dir(f)
else:
if java_pattern.match(file):
process_source(f)
def process_source(filename):
tmp = tempfile.mkstemp()
tmpfd = tmp[0]
tmpfile = tmp[1]
try:
changed = False
dst = os.fdopen(tmpfd, 'w')
try:
src = open(filename)
try:
for line in src:
if annot_pattern.match(line):
changed = True
line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.')
dst.write(line)
finally:
src.close()
finally:
dst.close();
if changed:
shutil.move(tmpfile, filename)
else:
os.remove(tmpfile)
except:
os.remove(tmpfile)
process_dir('.')
| [
[
1,
0,
0.3514,
0.0135,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3649,
0.0135,
0,
0.66,
0.1111,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.3784,
0.0135,
0,
... | [
"import os",
"import re",
"import tempfile",
"import shutil",
"ignore_pattern = re.compile('^(.svn|target|bin|classes)')",
"java_pattern = re.compile('^.*\\.java')",
"annot_pattern = re.compile('import org\\.apache\\.http\\.annotation\\.')",
"def process_dir(dir):\n files = os.listdir(dir)\n for... |
#!/usr/bin/env python
from os import mkdir, makedirs, environ, chdir, getcwd, system, listdir
from os.path import join
from shutil import copy, copytree, move, rmtree
# Usage
def Usage():
return 'Usage: createversion.py <version>'
# Run Xcode
def RunXcode(project, target):
system('/usr/bin/xcodebuild -project "%s" -target "%s" -configuration Release clean build' % (project, target))
# Get version from args
import sys
if len(sys.argv) <= 1:
print Usage()
exit(1)
version = sys.argv[1]
# Change to root dir of Core Plot
chdir('..')
projectRoot = getcwd()
# Remove old docset files
frameworkDir = join(projectRoot, 'framework')
rmtree(join(frameworkDir, 'CorePlotDocs.docset'), True)
rmtree(join(frameworkDir, 'CorePlotTouchDocs.docset'), True)
# Remove old build directories
rmtree(join(frameworkDir, 'build'), True)
examples = listdir('examples')
for ex in examples:
exampleDir = join('examples', ex)
rmtree(join(exampleDir, 'build'), True)
# Make directory bundle
desktopDir = join(environ['HOME'], 'Desktop')
releaseRootDir = join(desktopDir, 'CorePlot_' + version)
mkdir(releaseRootDir)
# Copy license and READMEs
copy('License.txt', releaseRootDir)
copytree('READMEs', join(releaseRootDir, 'READMEs'))
# Add source code
sourceDir = join(releaseRootDir, 'Source')
copytree('framework', join(sourceDir, 'framework'))
copytree('examples', join(sourceDir, 'examples'))
copy('License.txt', sourceDir)
# Binaries
binariesDir = join(releaseRootDir, 'Binaries')
macosDir = join(binariesDir, 'MacOS')
iosDir = join(binariesDir, 'iOS')
makedirs(macosDir)
mkdir(iosDir)
# Build Mac Framework
chdir('framework')
RunXcode('CorePlot.xcodeproj', 'CorePlot')
macProductsDir = join(projectRoot, 'build/Release')
macFramework = join(macProductsDir, 'CorePlot.framework')
copytree(macFramework, join(macosDir, 'CorePlot.framework'))
# Build iOS SDK
RunXcode('CorePlot-CocoaTouch.xcodeproj', 'Build SDK')
sdkZipFile = join(desktopDir, 'CorePlot.zip')
move(sdkZipFile, iosDir)
# Build Docs
RunXcode('CorePlot.xcodeproj', 'Documentation')
RunXcode('CorePlot-CocoaTouch.xcodeproj', 'Documentation')
# Copy Docs
docDir = join(releaseRootDir, 'Documentation')
copytree(join(projectRoot, 'documentation'), docDir)
homeDir = environ['HOME']
docsetsDir = join(homeDir, 'Library/Developer/Shared/Documentation/DocSets')
copytree(join(docsetsDir, 'com.CorePlot.Framework.docset'), join(docDir, 'com.CorePlot.Framework.docset'))
copytree(join(docsetsDir, 'com.CorePlotTouch.Framework.docset'), join(docDir, 'com.CorePlotTouch.Framework.docset'))
| [
[
1,
0,
0.0357,
0.0119,
0,
0.66,
0,
688,
0,
7,
0,
0,
688,
0,
0
],
[
1,
0,
0.0476,
0.0119,
0,
0.66,
0.0222,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.0595,
0.0119,
0,
0.... | [
"from os import mkdir, makedirs, environ, chdir, getcwd, system, listdir",
"from os.path import join",
"from shutil import copy, copytree, move, rmtree",
"def Usage():\n return 'Usage: createversion.py <version>'",
" return 'Usage: createversion.py <version>'",
"def RunXcode(project, target):\n s... |
dataTypes = ["CPUndefinedDataType", "CPIntegerDataType", "CPUnsignedIntegerDataType", "CPFloatingPointDataType", "CPComplexFloatingPointDataType", "CPDecimalDataType"]
types = { "CPUndefinedDataType" : [],
"CPIntegerDataType" : ["int8_t", "int16_t", "int32_t", "int64_t"],
"CPUnsignedIntegerDataType" : ["uint8_t", "uint16_t", "uint32_t", "uint64_t"],
"CPFloatingPointDataType" : ["float", "double"],
"CPComplexFloatingPointDataType" : ["float complex", "double complex"],
"CPDecimalDataType" : ["NSDecimal"] }
nsnumber_factory = { "int8_t" : "Char",
"int16_t" : "Short",
"int32_t" : "Long",
"int64_t" : "LongLong",
"uint8_t" : "UnsignedChar",
"uint16_t" : "UnsignedShort",
"uint32_t" : "UnsignedLong",
"uint64_t" : "UnsignedLongLong",
"float" : "Float",
"double" : "Double",
"float complex" : "Float",
"double complex" : "Double",
"NSDecimal" : "Decimal"
}
nsnumber_methods = { "int8_t" : "char",
"int16_t" : "short",
"int32_t" : "long",
"int64_t" : "longLong",
"uint8_t" : "unsignedChar",
"uint16_t" : "unsignedShort",
"uint32_t" : "unsignedLong",
"uint64_t" : "unsignedLongLong",
"float" : "float",
"double" : "double",
"float complex" : "float",
"double complex" : "double",
"NSDecimal" : "decimal"
}
null_values = { "int8_t" : "0",
"int16_t" : "0",
"int32_t" : "0",
"int64_t" : "0",
"uint8_t" : "0",
"uint16_t" : "0",
"uint32_t" : "0",
"uint64_t" : "0",
"float" : "NAN",
"double" : "NAN",
"float complex" : "NAN",
"double complex" : "NAN",
"NSDecimal" : "CPDecimalNaN()"
}
print "[CPNumericData sampleValue:]"
print ""
print "switch ( self.dataTypeFormat ) {"
for dt in dataTypes:
print "\tcase %s:" % dt
if ( len(types[dt]) == 0 ):
print '\t\t[NSException raise:NSInvalidArgumentException format:@"Unsupported data type (%s)"];' % (dt)
else:
print "\t\tswitch ( self.sampleBytes ) {"
for t in types[dt]:
print "\t\t\tcase sizeof(%s):" % t
if ( t == "NSDecimal" ):
number_class = "NSDecimalNumber"
number_method = "decimalNumber"
else:
number_class = "NSNumber"
number_method = "number"
print "\t\t\t\tresult = [%s %sWith%s:*(%s *)[self samplePointer:sample]];" % (number_class, number_method, nsnumber_factory[t], t)
print "\t\t\t\tbreak;"
print "\t\t}"
print "\t\tbreak;"
print "}"
print "\n\n"
print "---------------"
print "\n\n"
print "[CPNumericData dataFromArray:dataType:]"
print ""
print "switch ( newDataType.dataTypeFormat ) {"
for dt in dataTypes:
print "\tcase %s:" % dt
if ( len(types[dt]) == 0 ):
print "\t\t// Unsupported"
else:
print "\t\tswitch ( newDataType.sampleBytes ) {"
for t in types[dt]:
print "\t\t\tcase sizeof(%s): {" % t
print "\t\t\t\t%s *toBytes = (%s *)sampleData.mutableBytes;" % (t, t)
print "\t\t\t\tfor ( id sample in newData ) {"
print "\t\t\t\t\tif ( [sample respondsToSelector:@selector(%sValue)] ) {" % nsnumber_methods[t]
print "\t\t\t\t\t\t*toBytes++ = (%s)[(NSNumber *)sample %sValue];" % (t, nsnumber_methods[t])
print "\t\t\t\t\t}"
print "\t\t\t\t\telse {"
print "\t\t\t\t\t\t*toBytes++ = %s;" % null_values[t]
print "\t\t\t\t\t}"
print "\t\t\t\t}"
print "\t\t\t}"
print "\t\t\t\tbreak;"
print "\t\t}"
print "\t\tbreak;"
print "}"
print "\n\n"
print "---------------"
print "\n\n"
print "[CPNumericData convertData:dataType:toData:dataType:]"
print ""
print "switch ( sourceDataType->dataTypeFormat ) {"
for dt in dataTypes:
print "\tcase %s:" % dt
if ( len(types[dt]) > 0 ):
print "\t\tswitch ( sourceDataType->sampleBytes ) {"
for t in types[dt]:
print "\t\t\tcase sizeof(%s):" % t
print "\t\t\t\tswitch ( destDataType->dataTypeFormat ) {"
for ndt in dataTypes:
print "\t\t\t\t\tcase %s:" % ndt
if ( len(types[ndt]) > 0 ):
print "\t\t\t\t\t\tswitch ( destDataType->sampleBytes ) {"
for nt in types[ndt]:
print "\t\t\t\t\t\t\tcase sizeof(%s): { // %s -> %s" % (nt, t, nt)
if ( t == nt ):
print "\t\t\t\t\t\t\t\t\tmemcpy(destData.mutableBytes, sourceData.bytes, sampleCount * sizeof(%s));" % t
else:
print "\t\t\t\t\t\t\t\t\tconst %s *fromBytes = (%s *)sourceData.bytes;" % (t, t)
print "\t\t\t\t\t\t\t\t\tconst %s *lastSample = fromBytes + sampleCount;" % t
print "\t\t\t\t\t\t\t\t\t%s *toBytes = (%s *)destData.mutableBytes;" % (nt, nt)
if ( t == "NSDecimal" ):
print "\t\t\t\t\t\t\t\t\twhile ( fromBytes < lastSample ) *toBytes++ = CPDecimal%sValue(*fromBytes++);" % nsnumber_factory[nt]
elif ( nt == "NSDecimal" ):
print "\t\t\t\t\t\t\t\t\twhile ( fromBytes < lastSample ) *toBytes++ = CPDecimalFrom%s(*fromBytes++);" % nsnumber_factory[t]
else:
print "\t\t\t\t\t\t\t\t\twhile ( fromBytes < lastSample ) *toBytes++ = (%s)*fromBytes++;" % nt
print "\t\t\t\t\t\t\t\t}"
print "\t\t\t\t\t\t\t\tbreak;"
print "\t\t\t\t\t\t}"
print "\t\t\t\t\t\tbreak;"
print "\t\t\t\t}"
print "\t\t\t\tbreak;"
print "\t\t}"
print "\t\tbreak;"
print "}"
| [
[
14,
0,
0.0068,
0.0068,
0,
0.66,
0,
302,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
0.0372,
0.0405,
0,
0.66,
0.04,
209,
0,
0,
0,
0,
0,
6,
0
],
[
14,
0,
0.1115,
0.0946,
0,
0.6... | [
"dataTypes = [\"CPUndefinedDataType\", \"CPIntegerDataType\", \"CPUnsignedIntegerDataType\", \"CPFloatingPointDataType\", \"CPComplexFloatingPointDataType\", \"CPDecimalDataType\"]",
"types = { \"CPUndefinedDataType\" : [],\n \"CPIntegerDataType\" : [\"int8_t\", \"int16_t\", \"int32_t\", \"int64_t\"],\n ... |
#!/usr/bin/env python
"create rootfs"
import sys
import os
import getopt
support_fs_tbl = ["yaffs", "cramfs", "ramfs"]
#line swith char
linesep = os.linesep
#option table
#if option has param,must follow char':' or '=' when long opt
opt_short_tbl = 'hf:v'
opt_long_tbl = ["help", "fstype="]
#usage string for tips
usage_str = '[options] -f fsname' + linesep +\
'\t-f, --fstype=name\tfilesystem types name' + linesep +\
'\t support list:' + str(support_fs_tbl) +linesep +\
'\t-v\t\t\tverbose mode' + linesep +\
'\t-h, --help\t\tprint this message'
#is verbose mode
debug = False
#parse type
fstype = "unsupport"
#my debug fucntion
def mydebug(*arglist, **argdict):
global debug
if not debug:
return 0
for i in arglist:
print i,
print
for i in argdict:
print i, argdict[i],
def yaffs_fs_create():
mydebug('create yaffs')
def ramfs_fs_create():
mydebug('create ramfs')
def cramfs_fs_create():
mydebug('create cramfs')
def usage():
global usage_str
print 'usage:%s %s' % (sys.argv[0], usage_str)
def main():
"main function for rootfs create dispatch"
#print sys.argv
#get argv count
if len(sys.argv) < 2:
print 'no options input.'
usage()
return 2
try:
#parse command line options
opts, args = getopt.getopt(sys.argv[1:],
opt_short_tbl,
opt_long_tbl)
except getopt.GetoptError:
print 'get options error.'
usage()
return 2
else:
global fstype, debug
for o, a in opts:
if o == "-v":
debug = True
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-f", "--fstype"):
fstype = a
mydebug('input fstype=', a)
break
if fstype == support_fs_tbl[0]:
yaffs_fs_create()
elif fstype == support_fs_tbl[1]:
cramfs_fs_create()
elif fstype == support_fs_tbl[2]:
ramfs_fs_create()
else:
print 'unsupport fs type:%s.' % (fstype)
usage()
return 0
if __name__ == '__main__':
main()
| [
[
8,
0,
0.0286,
0.0095,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0476,
0.0095,
0,
0.66,
0.0588,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0571,
0.0095,
0,
0.66... | [
"\"create rootfs\"",
"import sys",
"import os",
"import getopt",
"support_fs_tbl = [\"yaffs\", \"cramfs\", \"ramfs\"]",
"linesep = os.linesep",
"opt_short_tbl = 'hf:v'",
"opt_long_tbl = [\"help\", \"fstype=\"]",
"usage_str = '[options] -f fsname' + linesep +\\\n '\\t-f, --fstype=name\\tfi... |
#!/usr/bin/env python
"create rootfs"
import sys
import os
import getopt
import time
#line swith char
linesep = os.linesep
#rootfs class, base is object
class CRootFs(object):
"""
rootfs base class
"""
def __init__(self, name, fstype):
global linesep
#time stamp
self.stamp = time.strftime("%Y%m%d%H%M%S")
self.name = fstype
self.path = name + self.stamp + '.' + self.name
mydebug('Init rootfs')
def info(self):
print 'path is: %s%s' % (self.path, linesep)
#yaffs class
class CYaffsFs(CRootFs):
"""
yaffs
"""
def __init__(self, name):
super(CYaffsFs, self).__init__(name, 'yaffs')
mydebug('Init yaffs')
#ramfs class
class CRamFs(CRootFs):
"""
ramfs
"""
def __init__(self, name):
super(CRamFs, self).__init__(name, 'ramfs')
mydebug('Init ramfs')
#cramfs class
class CCramFs(CRootFs):
"""
cramfs
"""
def __init__(self, name):
super(CCramFs, self).__init__(name, 'cramfs')
mydebug('Init cramfs')
#global variables define
support_fs_tbl = {
"yaffs":CYaffsFs,
"ramfs":CRamFs,
"cramfs":CCramFs,
}
#option table
#if option has param,must follow char':' or '=' when long opt
opt_short_tbl = 'hf:v'
opt_long_tbl = ["help", "fstype="]
#usage string for tips
usage_str = '[options] -f fsname' + linesep +\
'\t-f, --fstype=name\tfilesystem types name' + linesep +\
'\t support list:' + str(support_fs_tbl.keys()) +linesep +\
'\t-v\t\t\tverbose mode' + linesep +\
'\t-h, --help\t\tprint this message'
#is verbose mode
debug = False
#my debug fucntion
def mydebug(*arglist, **argdict):
global debug
if not debug:
return 0
for i in arglist:
print i,
print
for i in argdict:
print i, argdict[i],
#virtual rootfs class
class RootFs(object):
"""
rootfs
"""
def __init__(self, key, name):
global support_fs_tbl
self.key = key
self.cls_tab = support_fs_tbl
self.cls_name = self.cls_tab[key];
self.instance = self.cls_name(name)
def dump(self, dump_name):
print dump_name
super(self.cls_name, self.instance).info()
def usage():
global usage_str
print 'usage:%s %s' % (sys.argv[0], usage_str)
def main():
"main function for rootfs create dispatch"
#print sys.argv
#get argv count
if len(sys.argv) < 2:
print 'no options input.'
usage()
return 2
try:
#parse command line options
opts, args = getopt.getopt(sys.argv[1:],
opt_short_tbl,
opt_long_tbl)
except getopt.GetoptError:
print 'get options error.'
usage()
return 2
else:
global debug
fstype = "unsupport"
for o, a in opts:
if o == "-v":
debug = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-f", "--fstype"):
fstype = a
mydebug('input fstype=', a)
else:
pass
if fstype not in support_fs_tbl.keys():
print 'unsupport fs type:%s.' % (fstype)
usage()
return 0
else:
myrootfs = RootFs(fstype, "img")
myrootfs.dump("elvon dump:")
if __name__ == '__main__':
main()
| [
[
8,
0,
0.0184,
0.0061,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0307,
0.0061,
0,
0.66,
0.0526,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0368,
0.0061,
0,
0.66... | [
"\"create rootfs\"",
"import sys",
"import os",
"import getopt",
"import time",
"linesep = os.linesep",
"class CRootFs(object):\n \"\"\"\n rootfs base class\n \"\"\"\n def __init__(self, name, fstype):\n global linesep\n #time stamp\n self.stamp = time.strftime(\"%Y%m%d%... |
#!/usr/bin/env python
i = 1 + 2 * 4
print i,
print 'test raw input'
i = raw_input('pls input:\n')
print int(i)
print 'test while'
count = 0
while count <= 10:
print count
count += 1
print 'test for'
for i in range(11):
print i
print 'test if elif else'
i = int(raw_input('input num\n'))
if i > 0:
print 'sign is +'
elif i < 0:
print 'sign is -'
else:
print 'num is 0'
print 'test list OR array'
numset = [1,2,3,4,5]
total = 0
for i in range(5):
total += numset[i]
print 'total is', total
for i in range(5):
numset[i] = int(raw_input('pls input ' + str(i+1) + ' number\n'))
print 'sum is', sum(numset)
print 'average is', float(sum(numset))/5
print 'test x < y < x'
while 1:
if 1 <= int(raw_input('input a num between 1 - 100\n')) <= 100:
break
else:
print 'error'
print 'test sort'
i = int(raw_input('input num 1\n'))
j = int(raw_input('input num 2\n'))
k = int(raw_input('input num 3\n'))
count = 0
for count in range(2):
if i > j:
tmp = i
i = j
j = tmp
if j > k:
tmp = j
j = k
k = tmp
print i, j, k
print 'test Tkinter'
import Tkinter
top = Tkinter.Tk()
hello = Tkinter.Label(top, text='hello world')
hello.pack()
quit = Tkinter.Button(top, text='Quit',
command=top.quit, bg='red', fg='white')
quit.pack(fill=Tkinter.X, expand=1)
Tkinter.mainloop()
| [
[
14,
0,
0.027,
0.0135,
0,
0.66,
0,
826,
4,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.0405,
0.0135,
0,
0.66,
0.027,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.0676,
0.0135,
0,
0.66,... | [
"i = 1 + 2 * 4",
"print(i,)",
"print('test raw input')",
"i = raw_input('pls input:\\n')",
"print(int(i))",
"print('test while')",
"count = 0",
"while count <= 10:\n print(count)\n count += 1",
" print(count)",
"print('test for')",
"for i in range(11):\n print(i)",
" print(i)",
... |
#!/usr/bin/env python
"""
Network Monitoring System Server Mock
"""
import json, socket
hash_number = 1;
def register(params):
answer = { 'command':'register' }
global hash_number
services=''
client_hash = params['hash']
client_port = params['port']
client_service_list = params['service_list']
if client_hash == '':
answer['status'] = 1 # 1 - means ok
answer['hash'] = hash_number
hash_number += 1
elif client_hash == -1:
answer['status'] = 2 # 2 - force new hash
answer['hash'] = ''
else:
answer['status'] = 0 # 0 - means hash reuse
answer['hash'] = client_hash
for i in client_service_list:
services = services + i
print (str(client_hash) + ';' + str(client_port) + ';' + services)
return answer;
# End of function
def unsupported():
return { 'command' : 'unknown', 'status' : -1 }
# End of funciton
options = {}
options['host'] = ''
options['port'] = 5000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((options['host'],options['port']))
server.listen(5)
print 'Network Monitoring Simple Server started'
while 1:
client, address = server.accept()
clientData = client.recv(1024)
question = json.loads(clientData)
if question['command'] == 'register':
response = register(question['params'])
else:
print "Unsupported command"
response = unsupported()
response = json.dumps(response)
client.send(response)
exit(0)
| [
[
8,
0,
0.0692,
0.0615,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1231,
0.0154,
0,
0.66,
0.0833,
463,
0,
2,
0,
0,
463,
0,
0
],
[
14,
0,
0.1538,
0.0154,
0,
0.6... | [
"\"\"\"\nNetwork Monitoring System Server Mock\n\n\"\"\"",
"import json, socket",
"hash_number = 1;",
"def register(params):\n\tanswer = { 'command':'register' }\n\tglobal hash_number\n\tservices=''\n\tclient_hash = params['hash']\n\tclient_port = params['port']\n\tclient_service_list = params['service_list']... |
#!/usr/bin/env python
"""
Network Monitoring System Server Mock
"""
import json, socket
hash_number = 1;
def register(params):
answer = { 'command':'register' }
global hash_number
services=''
client_hash = params['hash']
client_port = params['port']
client_service_list = params['service_list']
if client_hash == '':
answer['status'] = 1 # 1 - means ok
answer['hash'] = hash_number
hash_number += 1
elif client_hash == -1:
answer['status'] = 2 # 2 - force new hash
answer['hash'] = ''
else:
answer['status'] = 0 # 0 - means hash reuse
answer['hash'] = client_hash
for i in client_service_list:
services = services + i
print (str(client_hash) + ';' + str(client_port) + ';' + services)
return answer;
# End of function
def unsupported():
return { 'command' : 'unknown', 'status' : -1 }
# End of funciton
options = {}
options['host'] = ''
options['port'] = 5000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((options['host'],options['port']))
server.listen(5)
print 'Network Monitoring Simple Server started'
while 1:
client, address = server.accept()
clientData = client.recv(1024)
question = json.loads(clientData)
if question['command'] == 'register':
response = register(question['params'])
else:
print "Unsupported command"
response = unsupported()
response = json.dumps(response)
client.send(response)
exit(0)
| [
[
8,
0,
0.0692,
0.0615,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1231,
0.0154,
0,
0.66,
0.0833,
463,
0,
2,
0,
0,
463,
0,
0
],
[
14,
0,
0.1538,
0.0154,
0,
0.6... | [
"\"\"\"\nNetwork Monitoring System Server Mock\n\n\"\"\"",
"import json, socket",
"hash_number = 1;",
"def register(params):\n\tanswer = { 'command':'register' }\n\tglobal hash_number\n\tservices=''\n\tclient_hash = params['hash']\n\tclient_port = params['port']\n\tclient_service_list = params['service_list']... |
#!/usr/bin/env python
"""
NetSpy Client
by Marcin Ciechowicz for ZPR
v0.01
"""
import socket
import json
from subprocess import call
import logging
import argparse
import os.path
appName = 'NetSpyClient'
scriptDir = 'scripts'
logger = logging.getLogger(appName)
def initLogger():
formatter = logging.Formatter('%(asctime)s %(levelname)s::%(message)s')
hdlrFile = logging.FileHandler(appName + '.log')
hdlrFile.setFormatter(formatter)
hdlrStd = logging.StreamHandler()
hdlrStd.setFormatter(formatter)
logger.addHandler(hdlrFile)
logger.addHandler(hdlrStd)
logger.setLevel(logging.DEBUG)
class Service:
name = ''
testerPath = ''
def __init__(self, name, testerPath):
"""Creates service"""
self.name = name
self.testerPath = testerPath
def getName(self):
return self.name
def getCheckerPath(self):
return self.checkerPath
def executeCheck(self):
return call(testerPath,'1')
class Config:
options = {}
def __init__(self, fileName = "netspy.conf"):
"""Initialize config from file """
self.options = {'port' : '', 'server_port' : '', 'server_ip': '', 'service_list': [] }
self.fileName = fileName
self.loadFromFile(self.fileName)
def loadFromFile(self,fileName):
try:
logger.info("Reading config file: " + fileName)
configFile = file(fileName,'r')
line = configFile.readline()
active_options = ('port','server_port','server_ip')
while line != '' :
tokens = line.strip().split(' ')
if tokens[0] == 'service':
if (tokens[1] == 'alive'):
logger.warning("Service " + tokens[1] + " is already definied, please use different name")
elif (os.path.isfile(scriptDir+'/'+tokens[2])):
self.options['service_list'].append(Service(tokens[1],tokens[2]))
logger.debug("New service added: " + tokens[1])
else:
logger.warning("Service " + tokens[1] +" error: Can't find script : " + scriptDir + '/' + tokens[2])
logger.warning("Service " + tokens[1] +" creation failed")
elif tokens[0] in active_options:
self.options[tokens[0]]=tokens[1]
logger.debug(tokens[0] + " set to " + tokens[1])
else:
logger.warning("Unkown option " + tokens[0])
line = configFile.readline()
configFile.close()
except IOError:
logger.error( "Can't read " + fileName)
exit()
def getPort(self):
return self.options['port']
def getServerPort(self):
return self.options['server_port']
def getServerIp(self):
return self.options['server_ip']
def getServiceList(self):
return self.options['service_list']
class ClientApp:
config = ''
def getHash(self):
hashValue=''
try:
hashFile=file(".netspy.hash","r")
hashValue = hashFile.readline()
except IOError:
logger.warining( "No hash found")
finally:
return hashValue
def setHash(self,hashValue):
""" Function doc """
if (hashValue!=''):
try:
hashFile=file(".netspy.hash","w")
hashFile.write(hashValue)
except IOError:
logger.error( "Can't store hash value")
exit(0)
def setConfig(self, config):
self.config = config
def __init__(self,config=None):
if config!=None:
self.setConfig(config)
def hashCheck(self,hashValue):
return True
def init(self):
logger.info('Client - running ')
def registerAtServer(self):
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect((self.config.getServerIp(), int(self.config.getServerPort()) ))
except IOError:
logger.error("Can't register at monitoring server - connection problem")
return False
service_list = [];
for i in self.config.getServiceList():
service_list.append(i.getName())
service_list.append('alive')
message = { 'command' : 'register', 'payload': {'hash' : self.getHash(), 'port' : self.config.getPort(), 'service_list' : service_list }}
messageToSend = json.dumps(message)
server.send(messageToSend)
data = server.recv(1024)
server.close()
answer = json.loads(data)
if (answer['command'] != 'register'):
logger.error("Bad command type - expected 'register'")
return False
if (answer['payload']['status'] == 0):
logger.info("Reusing old hash")
return True
elif (answer['payload']['status'] == 1):
logger.info("Saving new hash: " + str(answer['payload']['hash']))
hashValue = answer['payload']['hash']
self.setHash(str(hashValue))
return True
elif (answer['payload']['status'] == 2):
clear = file('.netspy.hash','w')
clear.write('')
return False
else:
return False
def performServiceCheck(self,message):
try:
question = json.loads(message)
if question['command'] != 'check_status':
logger.error("Unknown command '" + question['command'] + "'received from server")
logger.error("No check performed")
return
else:
logger.info("Performing check")
resultList = []
alive = { 'alive' : 0 }
resultList.append(alive)
for service in self.config.getServiceList():
tmp = service.executeCheck()
result = {service.getName() : tmp }
resultList.append(result)
answer = {'command' : 'check_status', 'payload' : {'check_result' : resultList }}
return json.dumps(answer);
except ValueError:
logger.error("Unsupported command format")
logger.error("No check performed")
def run(self):
logger.info("Client - registering at monitoring server")
i=0
while (i<3 and not self.registerAtServer()):
i=i+1
if (i==3):
logger.error("Connect to monitoring server failed - can't connect to specified host")
logger.error("Please check your config file")
return
logger.info("Client - register succesful")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.bind(('',int(self.config.getPort())))
client.listen(5)
logger.info('Client - waiting for commands from server')
while 1:
request, address = client.accept()
message = request.recv(1024)
answer = self.performServiceCheck(message)
request.send(answer)
request.close()
def parseArgs():
parser = argparse.ArgumentParser(prog=appName, usage='%(prog)s [options]')
parser.add_argument('--verbose','-v', action='store_false', help='verbose mode')
parser.add_argument('--config','-c', action='store', help='config filename')
args = parser.parse_args()
if args.verbose == True:
logger.setLevel(logging.ERROR)
if args.config != None:
return Config(args.config)
else:
return Config()
#---------- main --------------------------#
initLogger()
client = ClientApp(parseArgs())
client.init()
client.run()
#-----------------------------------------#
| [
[
8,
0,
0.0205,
0.0205,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0369,
0.0041,
0,
0.66,
0.0556,
687,
0,
1,
0,
0,
687,
0,
0
],
[
1,
0,
0.041,
0.0041,
0,
0.66,... | [
"\"\"\"\nNetSpy Client\t\t\nby Marcin Ciechowicz for ZPR\nv0.01\n\"\"\"",
"import socket",
"import json",
"from subprocess import call",
"import logging",
"import argparse",
"import os.path",
"appName = 'NetSpyClient'",
"scriptDir = 'scripts'",
"logger = logging.getLogger(appName)",
"def initLog... |
#!/usr/bin/env python
"""
NetSpy Client
by Marcin Ciechowicz for ZPR
v0.01
"""
import socket
import json
from subprocess import call
import logging
import argparse
import os.path
appName = 'NetSpyClient'
scriptDir = 'scripts'
logger = logging.getLogger(appName)
def initLogger():
formatter = logging.Formatter('%(asctime)s %(levelname)s::%(message)s')
hdlrFile = logging.FileHandler(appName + '.log')
hdlrFile.setFormatter(formatter)
hdlrStd = logging.StreamHandler()
hdlrStd.setFormatter(formatter)
logger.addHandler(hdlrFile)
logger.addHandler(hdlrStd)
logger.setLevel(logging.DEBUG)
class Service:
name = ''
testerPath = ''
def __init__(self, name, testerPath):
"""Creates service"""
self.name = name
self.testerPath = testerPath
def getName(self):
return self.name
def getCheckerPath(self):
return self.checkerPath
def executeCheck(self):
return call(testerPath,'1')
class Config:
options = {}
def __init__(self, fileName = "netspy.conf"):
"""Initialize config from file """
self.options = {'port' : '', 'server_port' : '', 'server_ip': '', 'service_list': [] }
self.fileName = fileName
self.loadFromFile(self.fileName)
def loadFromFile(self,fileName):
try:
logger.info("Reading config file: " + fileName)
configFile = file(fileName,'r')
line = configFile.readline()
active_options = ('port','server_port','server_ip')
while line != '' :
tokens = line.strip().split(' ')
if tokens[0] == 'service':
if (tokens[1] == 'alive'):
logger.warning("Service " + tokens[1] + " is already definied, please use different name")
elif (os.path.isfile(scriptDir+'/'+tokens[2])):
self.options['service_list'].append(Service(tokens[1],tokens[2]))
logger.debug("New service added: " + tokens[1])
else:
logger.warning("Service " + tokens[1] +" error: Can't find script : " + scriptDir + '/' + tokens[2])
logger.warning("Service " + tokens[1] +" creation failed")
elif tokens[0] in active_options:
self.options[tokens[0]]=tokens[1]
logger.debug(tokens[0] + " set to " + tokens[1])
else:
logger.warning("Unkown option " + tokens[0])
line = configFile.readline()
configFile.close()
except IOError:
logger.error( "Can't read " + fileName)
exit()
def getPort(self):
return self.options['port']
def getServerPort(self):
return self.options['server_port']
def getServerIp(self):
return self.options['server_ip']
def getServiceList(self):
return self.options['service_list']
class ClientApp:
config = ''
def getHash(self):
hashValue=''
try:
hashFile=file(".netspy.hash","r")
hashValue = hashFile.readline()
except IOError:
logger.warining( "No hash found")
finally:
return hashValue
def setHash(self,hashValue):
""" Function doc """
if (hashValue!=''):
try:
hashFile=file(".netspy.hash","w")
hashFile.write(hashValue)
except IOError:
logger.error( "Can't store hash value")
exit(0)
def setConfig(self, config):
self.config = config
def __init__(self,config=None):
if config!=None:
self.setConfig(config)
def hashCheck(self,hashValue):
return True
def init(self):
logger.info('Client - running ')
def registerAtServer(self):
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect((self.config.getServerIp(), int(self.config.getServerPort()) ))
except IOError:
logger.error("Can't register at monitoring server - connection problem")
return False
service_list = [];
for i in self.config.getServiceList():
service_list.append(i.getName())
service_list.append('alive')
message = { 'command' : 'register', 'payload': {'hash' : self.getHash(), 'port' : self.config.getPort(), 'service_list' : service_list }}
messageToSend = json.dumps(message)
server.send(messageToSend)
data = server.recv(1024)
server.close()
answer = json.loads(data)
if (answer['command'] != 'register'):
logger.error("Bad command type - expected 'register'")
return False
if (answer['payload']['status'] == 0):
logger.info("Reusing old hash")
return True
elif (answer['payload']['status'] == 1):
logger.info("Saving new hash: " + str(answer['payload']['hash']))
hashValue = answer['payload']['hash']
self.setHash(str(hashValue))
return True
elif (answer['payload']['status'] == 2):
clear = file('.netspy.hash','w')
clear.write('')
return False
else:
return False
def performServiceCheck(self,message):
try:
question = json.loads(message)
if question['command'] != 'check_status':
logger.error("Unknown command '" + question['command'] + "'received from server")
logger.error("No check performed")
return
else:
logger.info("Performing check")
resultList = []
alive = { 'alive' : 0 }
resultList.append(alive)
for service in self.config.getServiceList():
tmp = service.executeCheck()
result = {service.getName() : tmp }
resultList.append(result)
answer = {'command' : 'check_status', 'payload' : {'check_result' : resultList }}
return json.dumps(answer);
except ValueError:
logger.error("Unsupported command format")
logger.error("No check performed")
def run(self):
logger.info("Client - registering at monitoring server")
i=0
while (i<3 and not self.registerAtServer()):
i=i+1
if (i==3):
logger.error("Connect to monitoring server failed - can't connect to specified host")
logger.error("Please check your config file")
return
logger.info("Client - register succesful")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.bind(('',int(self.config.getPort())))
client.listen(5)
logger.info('Client - waiting for commands from server')
while 1:
request, address = client.accept()
message = request.recv(1024)
answer = self.performServiceCheck(message)
request.send(answer)
request.close()
def parseArgs():
parser = argparse.ArgumentParser(prog=appName, usage='%(prog)s [options]')
parser.add_argument('--verbose','-v', action='store_false', help='verbose mode')
parser.add_argument('--config','-c', action='store', help='config filename')
args = parser.parse_args()
if args.verbose == True:
logger.setLevel(logging.ERROR)
if args.config != None:
return Config(args.config)
else:
return Config()
#---------- main --------------------------#
initLogger()
client = ClientApp(parseArgs())
client.init()
client.run()
#-----------------------------------------#
| [
[
8,
0,
0.0205,
0.0205,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0369,
0.0041,
0,
0.66,
0.0556,
687,
0,
1,
0,
0,
687,
0,
0
],
[
1,
0,
0.041,
0.0041,
0,
0.66,... | [
"\"\"\"\nNetSpy Client\t\t\nby Marcin Ciechowicz for ZPR\nv0.01\n\"\"\"",
"import socket",
"import json",
"from subprocess import call",
"import logging",
"import argparse",
"import os.path",
"appName = 'NetSpyClient'",
"scriptDir = 'scripts'",
"logger = logging.getLogger(appName)",
"def initLog... |
#-------- DEFAULT ---------------------------
flags = ['-O2','-Wall','-pedantic']
lib_boost = ['boost_system', 'boost_thread','boost_random','boost_program_options']
lib_cppcms = ['cppcms','cppdb']
libs = lib_boost + lib_cppcms
env = Environment(CPPFLAGS=flags, LIBS=libs)
netspy = 'netspy-server'
dbtest = 'dbtest'
sources = Split("""
main.cpp
Message.cpp
JSONParser.cpp
ClientRegistrar.cpp
RequestManager.cpp
Config.cpp
ClientChecker.cpp
ClientManager.cpp
DataProxy.cpp
""")
dbtestSources = Split("""
DataProxy.cpp
Config.cpp
DataTest.cpp
""")
targets = {
netspy : sources,
dbtest : dbtestSources
}
default = env.Program( target=netspy, source = env.Object(targets[netspy]) )
Default(default)
env.Program(target=dbtest, source = env.Object(targets[dbtest]))
| [
[
14,
0,
0.06,
0.02,
0,
0.66,
0,
375,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
0.1,
0.02,
0,
0.66,
0.0833,
384,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
0.12,
0.02,
0,
0.66,
0.16... | [
"flags = ['-O2','-Wall','-pedantic']",
"lib_boost = ['boost_system', 'boost_thread','boost_random','boost_program_options']",
"lib_cppcms = ['cppcms','cppdb']",
"libs = lib_boost + lib_cppcms",
"env = Environment(CPPFLAGS=flags, LIBS=libs)",
"netspy = 'netspy-server'",
"dbtest = 'dbtest'",
"sources = ... |
#!/usr/bin/env python
import gluon
from gluon.fileutils import untar
import os
import sys
def main():
path = gluon.__path__
out_path = os.getcwd()
try:
if sys.argv[1] and os.path.exists(sys.argv[1]):# To untar the web2py env to the selected path
out_path = sys.argv[1]
else:
os.mkdir(sys.argv[1])
out_path = sys.argv[1]
except:
pass
try:
print "Creating a web2py env in: " + out_path
untar(os.path.join(path[0],'env.tar'),out_path)
except:
print "Failed to create the web2py env"
print "Please reinstall web2py from pip"
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0741,
0.037,
0,
0.66,
0,
826,
0,
1,
0,
0,
826,
0,
0
],
[
1,
0,
0.1111,
0.037,
0,
0.66,
0.2,
948,
0,
1,
0,
0,
948,
0,
0
],
[
1,
0,
0.1481,
0.037,
0,
0.66,
... | [
"import gluon",
"from gluon.fileutils import untar",
"import os",
"import sys",
"def main():\n path = gluon.__path__\n out_path = os.getcwd()\n try:\n if sys.argv[1] and os.path.exists(sys.argv[1]):# To untar the web2py env to the selected path\n out_path = sys.argv[1]\n el... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
This is a WSGI handler for Apache
Requires apache+mod_wsgi.
In httpd.conf put something like:
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias / /path/to/wsgihandler.py
"""
# change these parameters as required
LOGGING = False
SOFTCRON = False
import sys
import os
path = os.path.dirname(os.path.abspath(__file__))
os.chdir(path)
sys.path = [path] + [p for p in sys.path if not p == path]
sys.stdout = sys.stderr
import gluon.main
if LOGGING:
application = gluon.main.appfactory(wsgiapp=gluon.main.wsgibase,
logfilename='httpserver.log',
profilerfilename=None)
else:
application = gluon.main.wsgibase
if SOFTCRON:
from gluon.settings import global_settings
global_settings.web2py_crontype = 'soft'
| [
[
8,
0,
0.25,
0.3409,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.4773,
0.0227,
0,
0.66,
0.0909,
136,
1,
0,
0,
0,
0,
4,
0
],
[
14,
0,
0.5,
0.0227,
0,
0.66,
... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\n\nThis is a WSGI handler for Apache\nRequires apache+mod_wsgi.",
"LOGGING = False",
"SOFTCRON = False",
"import sys",
"import os",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
This is a handler for lighttpd+fastcgi
This file has to be in the PYTHONPATH
Put something like this in the lighttpd.conf file:
server.port = 8000
server.bind = '127.0.0.1'
server.event-handler = 'freebsd-kqueue'
server.modules = ('mod_rewrite', 'mod_fastcgi')
server.error-handler-404 = '/test.fcgi'
server.document-root = '/somewhere/web2py'
server.errorlog = '/tmp/error.log'
fastcgi.server = ('.fcgi' =>
('localhost' =>
('min-procs' => 1,
'socket' => '/tmp/fcgi.sock'
)
)
)
"""
LOGGING = False
SOFTCRON = False
import sys
import os
path = os.path.dirname(os.path.abspath(__file__))
os.chdir(path)
sys.path = [path] + [p for p in sys.path if not p == path]
import gluon.main
import gluon.contrib.gateways.fcgi as fcgi
if LOGGING:
application = gluon.main.appfactory(wsgiapp=gluon.main.wsgibase,
logfilename='httpserver.log',
profilerfilename=None)
else:
application = gluon.main.wsgibase
if SOFTCRON:
from gluon.settings import global_settings
global_settings.web2py_crontype = 'soft'
fcgi.WSGIServer(application, bindAddress='/tmp/fcgi.sock').run()
| [
[
8,
0,
0.2925,
0.4528,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.5472,
0.0189,
0,
0.66,
0.0833,
136,
1,
0,
0,
0,
0,
4,
0
],
[
14,
0,
0.566,
0.0189,
0,
0.66,... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\nThis is a handler for lighttpd+fastcgi\nThis file has to be in the PYTHONPATH\nPut something like this in the lighttpd.conf file:",
"LOGGIN... |
def webapp_add_wsgi_middleware(app):
from google.appengine.ext.appstats import recording
app = recording.appstats_wsgi_middleware(app)
return app
| [
[
2,
0,
0.625,
1,
0,
0.66,
0,
156,
0,
1,
1,
0,
0,
0,
1
],
[
1,
1,
0.5,
0.25,
1,
0.03,
0,
215,
0,
1,
0,
0,
215,
0,
0
],
[
14,
1,
0.75,
0.25,
1,
0.03,
0.5,
49... | [
"def webapp_add_wsgi_middleware(app):\n from google.appengine.ext.appstats import recording\n app = recording.appstats_wsgi_middleware(app)\n return app",
" from google.appengine.ext.appstats import recording",
" app = recording.appstats_wsgi_middleware(app)",
" return app"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
scgihandler.py - handler for SCGI protocol
Modified by Michele Comitini <michele.comitini@glisco.it>
from fcgihandler.py to support SCGI
fcgihandler has the following copyright:
" This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"
This is a handler for lighttpd+scgi
This file has to be in the PYTHONPATH
Put something like this in the lighttpd.conf file:
server.document-root="/var/www/web2py/"
# for >= linux-2.6
server.event-handler = "linux-sysepoll"
url.rewrite-once = (
"^(/.+?/static/.+)$" => "/applications$1",
"(^|/.*)$" => "/handler_web2py.scgi$1",
)
scgi.server = ( "/handler_web2py.scgi" =>
("handler_web2py" =>
( "host" => "127.0.0.1",
"port" => "4000",
"check-local" => "disable", # don't forget to set "disable"!
)
)
)
"""
LOGGING = False
SOFTCRON = False
import sys
import os
path = os.path.dirname(os.path.abspath(__file__))
os.chdir(path)
sys.path = [path] + [p for p in sys.path if not p == path]
import gluon.main
# uncomment one of the two imports below depending on the SCGIWSGI server installed
#import paste.util.scgiserver as scgi
from wsgitools.scgi.forkpool import SCGIServer
from wsgitools.filters import WSGIFilterMiddleware, GzipWSGIFilter
wsgiapp = WSGIFilterMiddleware(gluon.main.wsgibase, GzipWSGIFilter)
if LOGGING:
application = gluon.main.appfactory(wsgiapp=wsgiapp,
logfilename='httpserver.log',
profilerfilename=None)
else:
application = wsgiapp
if SOFTCRON:
from gluon.settings import global_settings
global_settings.web2py_crontype = 'soft'
# uncomment one of the two rows below depending on the SCGIWSGI server installed
#scgi.serve_application(application, '', 4000).run()
SCGIServer(application, port=4000).enable_sighandler().run()
| [
[
8,
0,
0.2973,
0.5,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.5676,
0.0135,
0,
0.66,
0.0714,
136,
1,
0,
0,
0,
0,
4,
0
],
[
14,
0,
0.5811,
0.0135,
0,
0.66,
... | [
"\"\"\"\nscgihandler.py - handler for SCGI protocol\n\nModified by Michele Comitini <michele.comitini@glisco.it>\nfrom fcgihandler.py to support SCGI\n\nfcgihandler has the following copyright:\n\" This file is part of the web2py Web Framework",
"LOGGING = False",
"SOFTCRON = False",
"import sys",
"import o... |
# -*- coding: utf-8 -*-
# when web2py is run as a windows service (web2py.py -W)
# it does not load the command line options but it
# expects to find configuration settings in a file called
#
# web2py/options.py
#
# this file is an example for options.py
import socket
import os
ip = '0.0.0.0'
port = 80
interfaces = [('0.0.0.0', 80)]
#,('0.0.0.0',443,'ssl_private_key.pem','ssl_certificate.pem')]
password = '<recycle>' # ## <recycle> means use the previous password
pid_filename = 'httpserver.pid'
log_filename = 'httpserver.log'
profiler_filename = None
ssl_certificate = '' # 'ssl_certificate.pem' # ## path to certificate file
ssl_private_key = '' # 'ssl_private_key.pem' # ## path to private key file
#numthreads = 50 # ## deprecated; remove
minthreads = None
maxthreads = None
server_name = socket.gethostname()
request_queue_size = 5
timeout = 30
shutdown_timeout = 5
folder = os.getcwd()
extcron = None
nocron = None
| [
[
1,
0,
0.3333,
0.0303,
0,
0.66,
0,
687,
0,
1,
0,
0,
687,
0,
0
],
[
1,
0,
0.3636,
0.0303,
0,
0.66,
0.0526,
688,
0,
1,
0,
0,
688,
0,
0
],
[
14,
0,
0.4242,
0.0303,
0,
... | [
"import socket",
"import os",
"ip = '0.0.0.0'",
"port = 80",
"interfaces = [('0.0.0.0', 80)]",
"password = '<recycle>' # ## <recycle> means use the previous password",
"pid_filename = 'httpserver.pid'",
"log_filename = 'httpserver.log'",
"profiler_filename = None",
"ssl_certificate = '' # 'ssl_c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
This file is based, although a rewrite, on MIT-licensed code from the Bottle web framework.
"""
import os
import sys
import optparse
import urllib
path = os.path.dirname(os.path.abspath(__file__))
os.chdir(path)
sys.path = [path] + [p for p in sys.path if not p == path]
class Servers:
@staticmethod
def cgi(app, address=None, **options):
from wsgiref.handlers import CGIHandler
CGIHandler().run(app) # Just ignore host and port here
@staticmethod
def flup(app, address, **options):
import flup.server.fcgi
flup.server.fcgi.WSGIServer(app, bindAddress=address).run()
@staticmethod
def wsgiref(app, address, **options): # pragma: no cover
from wsgiref.simple_server import make_server, WSGIRequestHandler
class QuietHandler(WSGIRequestHandler):
def log_request(*args, **kw):
pass
options['handler_class'] = QuietHandler
srv = make_server(address[0], address[1], app, **options)
srv.serve_forever()
@staticmethod
def cherrypy(app, address, **options):
from cherrypy import wsgiserver
server = wsgiserver.CherryPyWSGIServer(address, app)
server.start()
@staticmethod
def rocket(app, address, **options):
from gluon.rocket import CherryPyWSGIServer
server = CherryPyWSGIServer(address, app)
server.start()
@staticmethod
def rocket_with_repoze_profiler(app, address, **options):
from gluon.rocket import CherryPyWSGIServer
from repoze.profile.profiler import AccumulatingProfileMiddleware
from gluon.settings import global_settings
global_settings.web2py_crontype = 'none'
wrapped = AccumulatingProfileMiddleware(
app,
log_filename='wsgi.prof',
discard_first_request=True,
flush_at_shutdown=True,
path='/__profile__'
)
server = CherryPyWSGIServer(address, wrapped)
server.start()
@staticmethod
def paste(app, address, **options):
from paste import httpserver
from paste.translogger import TransLogger
httpserver.serve(app, host=address[0], port=address[1], **options)
@staticmethod
def fapws(app, address, **options):
import fapws._evwsgi as evwsgi
from fapws import base
evwsgi.start(address[0], str(address[1]))
evwsgi.set_base_module(base)
def app(environ, start_response):
environ['wsgi.multiprocess'] = False
return app(environ, start_response)
evwsgi.wsgi_cb(('', app))
evwsgi.run()
@staticmethod
def gevent(app, address, **options):
from gevent import pywsgi
from gevent.pool import Pool
pywsgi.WSGIServer(address, app, spawn='workers' in options and Pool(
int(options.workers)) or 'default').serve_forever()
@staticmethod
def bjoern(app, address, **options):
import bjoern
bjoern.run(app, *address)
@staticmethod
def tornado(app, address, **options):
import tornado.wsgi
import tornado.httpserver
import tornado.ioloop
container = tornado.wsgi.WSGIContainer(app)
server = tornado.httpserver.HTTPServer(container)
server.listen(address=address[0], port=address[1])
tornado.ioloop.IOLoop.instance().start()
@staticmethod
def twisted(app, address, **options):
from twisted.web import server, wsgi
from twisted.python.threadpool import ThreadPool
from twisted.internet import reactor
thread_pool = ThreadPool()
thread_pool.start()
reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop)
factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, app))
reactor.listenTCP(address[1], factory, interface=address[0])
reactor.run()
@staticmethod
def diesel(app, address, **options):
from diesel.protocols.wsgi import WSGIApplication
app = WSGIApplication(app, port=address[1])
app.run()
@staticmethod
def gunicorn(app, address, **options):
from gunicorn.app.base import Application
config = {'bind': "%s:%d" % address}
config.update(options)
sys.argv = ['anyserver.py']
class GunicornApplication(Application):
def init(self, parser, opts, args):
return config
def load(self):
return app
g = GunicornApplication()
g.run()
@staticmethod
def eventlet(app, address, **options):
from eventlet import wsgi, listen
wsgi.server(listen(address), app)
@staticmethod
def mongrel2(app, address, **options):
import uuid
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
from mongrel2 import handler
conn = handler.Connection(str(uuid.uuid4()),
"tcp://127.0.0.1:9997",
"tcp://127.0.0.1:9996")
mongrel2_handler(app, conn, debug=False)
@staticmethod
def motor(app, address, **options):
#https://github.com/rpedroso/motor
import motor
app = motor.WSGIContainer(app)
http_server = motor.HTTPServer(app)
http_server.listen(address=address[0], port=address[1])
#http_server.start(2)
motor.IOLoop.instance().start()
@staticmethod
def pulsar(app, address, **options):
from pulsar.apps import wsgi
sys.argv = ['anyserver.py']
s = wsgi.WSGIServer(callable=app, bind="%s:%d" % address)
s.start()
def run(servername, ip, port, softcron=True, logging=False, profiler=None):
if servername == 'gevent':
from gevent import monkey
monkey.patch_all()
import gluon.main
if logging:
application = gluon.main.appfactory(wsgiapp=gluon.main.wsgibase,
logfilename='httpserver.log',
profilerfilename=profiler)
else:
application = gluon.main.wsgibase
if softcron:
from gluon.settings import global_settings
global_settings.web2py_crontype = 'soft'
getattr(Servers, servername)(application, (ip, int(port)))
def mongrel2_handler(application, conn, debug=False):
"""
Based on :
https://github.com/berry/Mongrel2-WSGI-Handler/blob/master/wsgi-handler.py
WSGI handler based on the Python wsgiref SimpleHandler.
A WSGI application should return a iterable op StringTypes.
Any encoding must be handled by the WSGI application itself.
"""
from wsgiref.handlers import SimpleHandler
try:
import cStringIO as StringIO
except:
import StringIO
# TODO - this wsgi handler executes the application and renders a page
# in memory completely before returning it as a response to the client.
# Thus, it does not "stream" the result back to the client. It should be
# possible though. The SimpleHandler accepts file-like stream objects. So,
# it should be just a matter of connecting 0MQ requests/response streams to
# the SimpleHandler requests and response streams. However, the Python API
# for Mongrel2 doesn't seem to support file-like stream objects for requests
# and responses. Unless I have missed something.
while True:
if debug:
print "WAITING FOR REQUEST"
# receive a request
req = conn.recv()
if debug:
print "REQUEST BODY: %r\n" % req.body
if req.is_disconnect():
if debug:
print "DISCONNECT"
continue # effectively ignore the disconnect from the client
# Set a couple of environment attributes a.k.a. header attributes
# that are a must according to PEP 333
environ = req.headers
environ['SERVER_PROTOCOL'] = 'HTTP/1.1' # SimpleHandler expects a server_protocol, lets assume it is HTTP 1.1
environ['REQUEST_METHOD'] = environ['METHOD']
if ':' in environ['Host']:
environ['SERVER_NAME'] = environ['Host'].split(':')[0]
environ['SERVER_PORT'] = environ['Host'].split(':')[1]
else:
environ['SERVER_NAME'] = environ['Host']
environ['SERVER_PORT'] = ''
environ['SCRIPT_NAME'] = '' # empty for now
environ['PATH_INFO'] = urllib.unquote(environ['PATH'])
if '?' in environ['URI']:
environ['QUERY_STRING'] = environ['URI'].split('?')[1]
else:
environ['QUERY_STRING'] = ''
if 'Content-Length' in environ:
environ['CONTENT_LENGTH'] = environ[
'Content-Length'] # necessary for POST to work with Django
environ['wsgi.input'] = req.body
if debug:
print "ENVIRON: %r\n" % environ
# SimpleHandler needs file-like stream objects for
# requests, errors and responses
reqIO = StringIO.StringIO(req.body)
errIO = StringIO.StringIO()
respIO = StringIO.StringIO()
# execute the application
handler = SimpleHandler(reqIO, respIO, errIO, environ,
multithread=False, multiprocess=False)
handler.run(application)
# Get the response and filter out the response (=data) itself,
# the response headers,
# the response status code and the response status description
response = respIO.getvalue()
response = response.split("\r\n")
data = response[-1]
headers = dict([r.split(": ") for r in response[1:-2]])
code = response[0][9:12]
status = response[0][13:]
# strip BOM's from response data
# Especially the WSGI handler from Django seems to generate them (2 actually, huh?)
# a BOM isn't really necessary and cause HTML parsing errors in Chrome and Safari
# See also: http://www.xs4all.nl/~mechiel/projects/bomstrip/
# Although I still find this a ugly hack, it does work.
data = data.replace('\xef\xbb\xbf', '')
# Get the generated errors
errors = errIO.getvalue()
# return the response
if debug:
print "RESPONSE: %r\n" % response
if errors:
if debug:
print "ERRORS: %r" % errors
data = "%s\r\n\r\n%s" % (data, errors)
conn.reply_http(
req, data, code=code, status=status, headers=headers)
def main():
usage = "python anyserver.py -s tornado -i 127.0.0.1 -p 8000 -l -P"
try:
version = open('VERSION','r')
except IOError:
version = ''
parser = optparse.OptionParser(usage, None, optparse.Option, version)
parser.add_option('-l',
'--logging',
action='store_true',
default=False,
dest='logging',
help='log into httpserver.log')
parser.add_option('-P',
'--profiler',
default=False,
dest='profiler',
help='profiler filename')
servers = ', '.join(x for x in dir(Servers) if not x[0] == '_')
parser.add_option('-s',
'--server',
default='rocket',
dest='server',
help='server name (%s)' % servers)
parser.add_option('-i',
'--ip',
default='127.0.0.1',
dest='ip',
help='ip address')
parser.add_option('-p',
'--port',
default='8000',
dest='port',
help='port number')
parser.add_option('-w',
'--workers',
default='',
dest='workers',
help='number of workers number')
(options, args) = parser.parse_args()
print 'starting %s on %s:%s...' % (
options.server, options.ip, options.port)
run(options.server, options.ip, options.port,
logging=options.logging, profiler=options.profiler)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.0202,
0.0202,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0346,
0.0029,
0,
0.66,
0.0833,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0375,
0.0029,
0,
0.66... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\nThis file is based, although a rewrite, on MIT-licensed code from the Bottle web framework.\n\"\"\"",
"import os",
"import sys",
"impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Usage:
Install py2exe: http://sourceforge.net/projects/py2exe/files/
Copy script to the web2py directory
c:\bin\python26\python build_windows_exe.py py2exe
Adapted from http://bazaar.launchpad.net/~flavour/sahana-eden/trunk/view/head:/static/scripts/tools/standalone_exe.py
"""
from distutils.core import setup
import py2exe
from gluon.import_all import base_modules, contributed_modules
from gluon.fileutils import readlines_file
from glob import glob
import fnmatch
import os
import shutil
import sys
import re
import zipfile
#read web2py version from VERSION file
web2py_version_line = readlines_file('VERSION')[0]
#use regular expression to get just the version number
v_re = re.compile('[0-9]+\.[0-9]+\.[0-9]+')
web2py_version = v_re.search(web2py_version_line).group(0)
#pull in preferences from config file
import ConfigParser
Config = ConfigParser.ConfigParser()
Config.read('setup_exe.conf')
remove_msft_dlls = Config.getboolean("Setup", "remove_microsoft_dlls")
copy_apps = Config.getboolean("Setup", "copy_apps")
copy_site_packages = Config.getboolean("Setup", "copy_site_packages")
copy_scripts = Config.getboolean("Setup", "copy_scripts")
make_zip = Config.getboolean("Setup", "make_zip")
zip_filename = Config.get("Setup", "zip_filename")
remove_build_files = Config.getboolean("Setup", "remove_build_files")
# Python base version
python_version = sys.version[:3]
# List of modules deprecated in python2.6 that are in the above set
py26_deprecated = ['mhlib', 'multifile', 'mimify', 'sets', 'MimeWriter']
if python_version == '2.6':
base_modules += ['json', 'multiprocessing']
base_modules = list(set(base_modules).difference(set(py26_deprecated)))
#I don't know if this is even necessary
if python_version == '2.6':
# Python26 compatibility: http://www.py2exe.org/index.cgi/Tutorial#Step52
try:
shutil.copytree('C:\Bin\Microsoft.VC90.CRT', 'dist/')
except:
print "You MUST copy Microsoft.VC90.CRT folder into the dist directory"
setup(
console=['web2py.py'],
windows=[{'script':'web2py.py',
'dest_base':'web2py_no_console' # MUST NOT be just 'web2py' otherwise it overrides the standard web2py.exe
}],
name="web2py",
version=web2py_version,
description="web2py web framework",
author="Massimo DiPierro",
license="LGPL v3",
data_files=[
'ABOUT',
'LICENSE',
'VERSION',
'splashlogo.gif',
'logging.example.conf',
'options_std.py',
'app.example.yaml',
'queue.example.yaml'
],
options={'py2exe': {
'packages': contributed_modules,
'includes': base_modules,
}},
)
print "web2py binary successfully built"
def copy_folders(source, destination):
"""Copy files & folders from source to destination (within dist/)"""
if os.path.exists(os.path.join('dist', destination)):
shutil.rmtree(os.path.join('dist', destination))
shutil.copytree(os.path.join(source), os.path.join('dist', destination))
#should we remove Windows OS dlls user is unlikely to be able to distribute
if remove_msft_dlls:
print "Deleted Microsoft files not licensed for open source distribution"
print "You are still responsible for making sure you have the rights to distribute any other included files!"
#delete the API-MS-Win-Core DLLs
for f in glob('dist/API-MS-Win-*.dll'):
os.unlink(f)
#then delete some other files belonging to Microsoft
other_ms_files = ['KERNELBASE.dll', 'MPR.dll', 'MSWSOCK.dll',
'POWRPROF.dll']
for f in other_ms_files:
try:
os.unlink(os.path.join('dist', f))
except:
print "unable to delete dist/" + f
#sys.exit(1)
#Should we include applications?
if copy_apps:
copy_folders('applications', 'applications')
print "Your application(s) have been added"
else:
#only copy web2py's default applications
copy_folders('applications/admin', 'applications/admin')
copy_folders('applications/welcome', 'applications/welcome')
copy_folders('applications/examples', 'applications/examples')
print "Only web2py's admin, examples & welcome applications have been added"
#should we copy project's site-packages into dist/site-packages
if copy_site_packages:
#copy site-packages
copy_folders('site-packages', 'site-packages')
else:
#no worries, web2py will create the (empty) folder first run
print "Skipping site-packages"
pass
#should we copy project's scripts into dist/scripts
if copy_scripts:
#copy scripts
copy_folders('scripts', 'scripts')
else:
#no worries, web2py will create the (empty) folder first run
print "Skipping scripts"
pass
#borrowed from http://bytes.com/topic/python/answers/851018-how-zip-directory-python-using-zipfile
def recursive_zip(zipf, directory, folder=""):
for item in os.listdir(directory):
if os.path.isfile(os.path.join(directory, item)):
zipf.write(os.path.join(directory, item), folder + os.sep + item)
elif os.path.isdir(os.path.join(directory, item)):
recursive_zip(
zipf, os.path.join(directory, item), folder + os.sep + item)
#should we create a zip file of the build?
if make_zip:
#to keep consistent with how official web2py windows zip file is setup,
#create a web2py folder & copy dist's files into it
shutil.copytree('dist', 'zip_temp/web2py')
#create zip file
#use filename specified via command line
zipf = zipfile.ZipFile(
zip_filename + ".zip", "w", compression=zipfile.ZIP_DEFLATED)
path = 'zip_temp' # just temp so the web2py directory is included in our zip file
recursive_zip(
zipf, path) # leave the first folder as None, as path is root.
zipf.close()
shutil.rmtree('zip_temp')
print "Your Windows binary version of web2py can be found in " + \
zip_filename + ".zip"
print "You may extract the archive anywhere and then run web2py/web2py.exe"
#should py2exe build files be removed?
if remove_build_files:
shutil.rmtree('build')
shutil.rmtree('deposit')
shutil.rmtree('dist')
print "py2exe build files removed"
#final info
if not make_zip and not remove_build_files:
print "Your Windows binary & associated files can also be found in /dist"
print "Finished!"
print "Enjoy web2py " + web2py_version_line
| [
[
8,
0,
0.0401,
0.0428,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0695,
0.0053,
0,
0.66,
0.0244,
152,
0,
1,
0,
0,
152,
0,
0
],
[
1,
0,
0.0749,
0.0053,
0,
0.66... | [
"\"\"\"\nUsage:\n Install py2exe: http://sourceforge.net/projects/py2exe/files/\n Copy script to the web2py directory\n c:\\bin\\python26\\python build_windows_exe.py py2exe\n\nAdapted from http://bazaar.launchpad.net/~flavour/sahana-eden/trunk/view/head:/static/scripts/tools/standalone_exe.py\n\"\"\"",
... |
#!/usr/bin/env python
import os
import sys
"""
Author: Christopher Steel on behalf of Voice of Access
Copyright: Copyrighted (c) by Massimo Di Pierro (2007-2013)
web2py_clone becomes part of the web2py distribution available
on Pypi via 'pip install web2py'
web2py_clone is one of multiple commands that become available after running
'pip install web2py' in a virtual environment. It requires
mercurial to be installed in the virtual environment.
web2py_clone creates a local clone from the Web2py google code
project in the directory "./web2py," a directory called web2py
one directory up from the location of this script.
./bin/web2py_clone
./web2py
"""
def main():
iwd = cwd = os.getcwd() # set initial and current working directories
script_filename = os.path.realpath(__file__)
script_dirname = os.path.dirname(script_filename)
try:
print ("cwd now: %s" % cwd)
except:
print ("command failed %s" % cwd)
try:
os.chdir(script_dirname)
cwd = os.getcwd()
print ("cwd now: %s" % cwd)
source = "https://code.google.com/p/web2py/"
target = os.path.join('..','web2py')
print ("attempting to clone %s" % source)
print ("to %s" % target)
if os.path.isdir(target):
print ("found directory called web2py at %s" % target)
print ("is web2py already installed?")
print ("aborting clone attempt")
else:
os.system("hg clone %s %s" % (source,target))
os.chdir(iwd) # return to our initial working directory
cwd = iwd # set current working directory
except:
print ("web2py-clone failed in second try statement %s" % cwd)
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0364,
0.0182,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0545,
0.0182,
0,
0.66,
0.25,
509,
0,
1,
0,
0,
509,
0,
0
],
[
8,
0,
0.2455,
0.3273,
0,
0.... | [
"import os",
"import sys",
"\"\"\"\nAuthor: Christopher Steel on behalf of Voice of Access\nCopyright: Copyrighted (c) by Massimo Di Pierro (2007-2013)\n\nweb2py_clone becomes part of the web2py distribution available\non Pypi via 'pip install web2py'\n\nweb2py_clone is one of multiple commands that become avai... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
path = os.getcwd()
try:
if sys.argv[1] and os.path.exists(sys.argv[1]):
path = sys.argv[1]
except:
pass
os.chdir(path)
sys.path = [path]+[p for p in sys.path if not p==path]
# import gluon.import_all ##### This should be uncommented for py2exe.py
import gluon.widget
def main():
# Start Web2py and Web2py cron service!
gluon.widget.start(cron=True)
if __name__ == '__main__':
main()
| [
[
1,
0,
0.1667,
0.0417,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.2083,
0.0417,
0,
0.66,
0.125,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.2917,
0.0417,
0,
... | [
"import os",
"import sys",
"path = os.getcwd()",
"try:\n if sys.argv[1] and os.path.exists(sys.argv[1]):\n path = sys.argv[1]\nexcept:\n pass",
" if sys.argv[1] and os.path.exists(sys.argv[1]):\n path = sys.argv[1]",
" path = sys.argv[1]",
"os.chdir(path)",
"sys.path = [p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# portalocker.py
# Cross-platform (posix/nt) API for flock-style file locking.
# Requires python 1.5.2 or better.
"""
Cross-platform (posix/nt) API for flock-style file locking.
Synopsis:
import portalocker
file = open(\"somefile\", \"r+\")
portalocker.lock(file, portalocker.LOCK_EX)
file.seek(12)
file.write(\"foo\")
file.close()
If you know what you're doing, you may choose to
portalocker.unlock(file)
before closing the file, but why?
Methods:
lock( file, flags )
unlock( file )
Constants:
LOCK_EX
LOCK_SH
LOCK_NB
I learned the win32 technique for locking files from sample code
provided by John Nielsen <nielsenjf@my-deja.com> in the documentation
that accompanies the win32 modules.
Author: Jonathan Feinberg <jdf@pobox.com>
Version: $Id: portalocker.py,v 1.3 2001/05/29 18:47:55 Administrator Exp $
"""
import logging
import platform
logger = logging.getLogger("web2py")
os_locking = None
try:
import google.appengine
os_locking = 'gae'
except:
try:
import fcntl
os_locking = 'posix'
except:
try:
import win32con
import win32file
import pywintypes
os_locking = 'windows'
except:
pass
if os_locking == 'windows':
LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
LOCK_SH = 0 # the default
LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
# is there any reason not to reuse the following structure?
__overlapped = pywintypes.OVERLAPPED()
def lock(file, flags):
hfile = win32file._get_osfhandle(file.fileno())
win32file.LockFileEx(hfile, flags, 0, 0x7fff0000, __overlapped)
def unlock(file):
hfile = win32file._get_osfhandle(file.fileno())
win32file.UnlockFileEx(hfile, 0, 0x7fff0000, __overlapped)
elif os_locking == 'posix':
LOCK_EX = fcntl.LOCK_EX
LOCK_SH = fcntl.LOCK_SH
LOCK_NB = fcntl.LOCK_NB
def lock(file, flags):
fcntl.flock(file.fileno(), flags)
def unlock(file):
fcntl.flock(file.fileno(), fcntl.LOCK_UN)
else:
if platform.system() == 'Windows':
logger.error('no file locking, you must install the win32 extensions from: http://sourceforge.net/projects/pywin32/files/')
elif os_locking != 'gae':
logger.debug('no file locking, this will cause problems')
LOCK_EX = None
LOCK_SH = None
LOCK_NB = None
def lock(file, flags):
pass
def unlock(file):
pass
class LockedFile(object):
def __init__(self, filename, mode='rb'):
self.filename = filename
self.mode = mode
self.file = None
if 'r' in mode:
self.file = open(filename, mode)
lock(self.file, LOCK_SH)
elif 'w' in mode or 'a' in mode:
self.file = open(filename, mode.replace('w', 'a'))
lock(self.file, LOCK_EX)
if not 'a' in mode:
self.file.seek(0)
self.file.truncate()
else:
raise RuntimeError("invalid LockedFile(...,mode)")
def read(self, size=None):
return self.file.read() if size is None else self.file.read(size)
def readline(self):
return self.file.readline()
def readlines(self):
return self.file.readlines()
def write(self, data):
self.file.write(data)
self.file.flush()
def close(self):
if not self.file is None:
unlock(self.file)
self.file.close()
self.file = None
def __del__(self):
if not self.file is None:
self.close()
def read_locked(filename):
fp = LockedFile(filename, 'r')
data = fp.read()
fp.close()
return data
def write_locked(filename, data):
fp = LockedFile(filename, 'w')
data = fp.write(data)
fp.close()
if __name__ == '__main__':
f = LockedFile('test.txt', mode='wb')
f.write('test ok')
f.close()
f = LockedFile('test.txt', mode='rb')
sys.stdout.write(f.read()+'\n')
f.close()
| [
[
8,
0,
0.1433,
0.2105,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2573,
0.0058,
0,
0.66,
0.1,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.2632,
0.0058,
0,
0.66,
... | [
"\"\"\"\nCross-platform (posix/nt) API for flock-style file locking.\n\nSynopsis:\n\n import portalocker\n file = open(\\\"somefile\\\", \\\"r+\\\")\n portalocker.lock(file, portalocker.LOCK_EX)",
"import logging",
"import platform",
"logger = logging.getLogger(\"web2py\")",
"os_locking = None",
"tr... |
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
import os
import sys
import socket
import platform
from storage import Storage
global_settings = Storage()
settings = global_settings # legacy compatibility
if not hasattr(os, 'mkdir'):
global_settings.db_sessions = True
if global_settings.db_sessions is not True:
global_settings.db_sessions = set()
global_settings.gluon_parent = \
os.environ.get('web2py_path', os.getcwd())
global_settings.applications_parent = global_settings.gluon_parent
global_settings.app_folders = set()
global_settings.debugging = False
global_settings.is_pypy = \
hasattr(platform, 'python_implementation') and \
platform.python_implementation() == 'PyPy'
global_settings.is_jython = \
'java' in sys.platform.lower() or \
hasattr(sys, 'JYTHON_JAR') or \
str(sys.copyright).find('Jython') > 0
| [
[
8,
0,
0.0789,
0.1316,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1842,
0.0263,
0,
0.66,
0.0667,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.2105,
0.0263,
0,
0.66... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\"\"\"",
"import os",
"import sys",
"import socket",
"import platform",
"from storage import Storage",
"global_settings = Storage()... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
import re
__all__ = ['HTTP', 'redirect']
defined_status = {
200: 'OK',
201: 'CREATED',
202: 'ACCEPTED',
203: 'NON-AUTHORITATIVE INFORMATION',
204: 'NO CONTENT',
205: 'RESET CONTENT',
206: 'PARTIAL CONTENT',
301: 'MOVED PERMANENTLY',
302: 'FOUND',
303: 'SEE OTHER',
304: 'NOT MODIFIED',
305: 'USE PROXY',
307: 'TEMPORARY REDIRECT',
400: 'BAD REQUEST',
401: 'UNAUTHORIZED',
403: 'FORBIDDEN',
404: 'NOT FOUND',
405: 'METHOD NOT ALLOWED',
406: 'NOT ACCEPTABLE',
407: 'PROXY AUTHENTICATION REQUIRED',
408: 'REQUEST TIMEOUT',
409: 'CONFLICT',
410: 'GONE',
411: 'LENGTH REQUIRED',
412: 'PRECONDITION FAILED',
413: 'REQUEST ENTITY TOO LARGE',
414: 'REQUEST-URI TOO LONG',
415: 'UNSUPPORTED MEDIA TYPE',
416: 'REQUESTED RANGE NOT SATISFIABLE',
417: 'EXPECTATION FAILED',
422: 'UNPROCESSABLE ENTITY',
500: 'INTERNAL SERVER ERROR',
501: 'NOT IMPLEMENTED',
502: 'BAD GATEWAY',
503: 'SERVICE UNAVAILABLE',
504: 'GATEWAY TIMEOUT',
505: 'HTTP VERSION NOT SUPPORTED',
}
# If web2py is executed with python2.4 we need
# to use Exception instead of BaseException
try:
BaseException
except NameError:
BaseException = Exception
regex_status = re.compile('^\d{3} \w+$')
class HTTP(BaseException):
def __init__(
self,
status,
body='',
cookies=None,
status_message='',
**headers
):
self.status = status
self.body = body
self.headers = headers
self.cookies2headers(cookies)
self.status_message = status_message
def cookies2headers(self, cookies):
if cookies and len(cookies) > 0:
self.headers['Set-Cookie'] = [
str(cookie)[11:] for cookie in cookies.values()]
def to(self, responder, env=None):
env = env or {}
status = self.status
headers = self.headers
status_message = status
if status in defined_status:
if status_message:
status = str(status) + ' ' + str(status_message)
else:
status = '%d %s' % (status, defined_status[status])
else:
status = str(status) + ' ' + status_message
if not regex_status.match(status):
status = '500 %s' % (defined_status[500])
headers.setdefault('Content-Type', 'text/html; charset=UTF-8')
body = self.body
if status[:1] == '4':
if not body:
body = status
if isinstance(body, str):
headers['Content-Length'] = len(body)
rheaders = []
for k, v in headers.iteritems():
if isinstance(v, list):
rheaders += [(k, str(item)) for item in v]
elif not v is None:
rheaders.append((k, str(v)))
responder(status, rheaders)
if env.get('request_method', '') == 'HEAD':
return ['']
elif isinstance(body, str):
return [body]
elif hasattr(body, '__iter__'):
return body
else:
return [str(body)]
@property
def message(self):
"""
compose a message describing this exception
"status defined_status [web2py_error]"
message elements that are not defined are omitted
"""
msg = '%(status)d'
status_message = ''
if self.status_message:
status_message = self.status_message
elif self.status in defined_status:
status_message = defined_status.get(self.status)
if status_message:
msg = '%(status)d %(defined_status)s'
if 'web2py_error' in self.headers:
msg += ' [%(web2py_error)s]'
return msg % dict(status=self.status,
defined_status=status_message,
web2py_error=self.headers.get('web2py_error'))
def __str__(self):
"stringify me"
return self.message
def redirect(location='', how=303, client_side=False):
if location:
from gluon import current
loc = location.replace('\r', '%0D').replace('\n', '%0A')
if client_side and current.request.ajax:
raise HTTP(200, **{'web2py-redirect-location': loc})
else:
raise HTTP(how,
'You are being redirected <a href="%s">here</a>' % loc,
Location=loc)
else:
from gluon import current
if client_side and current.request.ajax:
raise HTTP(200, **{'web2py-component-command': 'window.location.reload(true)'})
| [
[
8,
0,
0.0366,
0.0305,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.061,
0.0061,
0,
0.66,
0.1429,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0732,
0.0061,
0,
0.66... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\"\"\"",
"import re",
"__all__ = ['HTTP', 'redirect']",
"defined_status = {\n 200: 'OK',\n 201: 'CREATED',\n 202: 'ACCEPTED',\n ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>,
limodou <limodou@gmail.com> and srackham <srackham@gmail.com>.
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
import logging
import os
import pdb
import Queue
import sys
logger = logging.getLogger("web2py")
class Pipe(Queue.Queue):
def __init__(self, name, mode='r', *args, **kwargs):
self.__name = name
Queue.Queue.__init__(self, *args, **kwargs)
def write(self, data):
logger.debug("debug %s writting %s" % (self.__name, data))
self.put(data)
def flush(self):
# mark checkpoint (complete message)
logger.debug("debug %s flushing..." % self.__name)
self.put(None)
# wait until it is processed
self.join()
logger.debug("debug %s flush done" % self.__name)
def read(self, count=None, timeout=None):
logger.debug("debug %s reading..." % (self.__name, ))
data = self.get(block=True, timeout=timeout)
# signal that we are ready
self.task_done()
logger.debug("debug %s read %s" % (self.__name, data))
return data
def readline(self):
logger.debug("debug %s readline..." % (self.__name, ))
return self.read()
pipe_in = Pipe('in')
pipe_out = Pipe('out')
debugger = pdb.Pdb(completekey=None, stdin=pipe_in, stdout=pipe_out,)
def set_trace():
"breakpoint shortcut (like pdb)"
logger.info("DEBUG: set_trace!")
debugger.set_trace(sys._getframe().f_back)
def stop_trace():
"stop waiting for the debugger (called atexit)"
# this should prevent communicate is wait forever a command result
# and the main thread has finished
logger.info("DEBUG: stop_trace!")
pipe_out.write("debug finished!")
pipe_out.write(None)
#pipe_out.flush()
def communicate(command=None):
"send command to debbuger, wait result"
if command is not None:
logger.info("DEBUG: sending command %s" % command)
pipe_in.write(command)
#pipe_in.flush()
result = []
while True:
data = pipe_out.read()
if data is None:
break
result.append(data)
logger.info("DEBUG: result %s" % repr(result))
return ''.join(result)
# New debugger implementation using qdb and a web UI
import gluon.contrib.qdb as qdb
from threading import RLock
interact_lock = RLock()
run_lock = RLock()
def check_interaction(fn):
"Decorator to clean and prevent interaction when not available"
def check_fn(self, *args, **kwargs):
interact_lock.acquire()
try:
if self.filename:
self.clear_interaction()
return fn(self, *args, **kwargs)
finally:
interact_lock.release()
return check_fn
class WebDebugger(qdb.Frontend):
"Qdb web2py interface"
def __init__(self, pipe, completekey='tab', stdin=None, stdout=None):
qdb.Frontend.__init__(self, pipe)
self.clear_interaction()
def clear_interaction(self):
self.filename = None
self.lineno = None
self.exception_info = None
self.context = None
# redefine Frontend methods:
def run(self):
run_lock.acquire()
try:
while self.pipe.poll():
qdb.Frontend.run(self)
finally:
run_lock.release()
def interaction(self, filename, lineno, line, **context):
# store current status
interact_lock.acquire()
try:
self.filename = filename
self.lineno = lineno
self.context = context
finally:
interact_lock.release()
def exception(self, title, extype, exvalue, trace, request):
self.exception_info = {'title': title,
'extype': extype, 'exvalue': exvalue,
'trace': trace, 'request': request}
@check_interaction
def do_continue(self):
qdb.Frontend.do_continue(self)
@check_interaction
def do_step(self):
qdb.Frontend.do_step(self)
@check_interaction
def do_return(self):
qdb.Frontend.do_return(self)
@check_interaction
def do_next(self):
qdb.Frontend.do_next(self)
@check_interaction
def do_quit(self):
qdb.Frontend.do_quit(self)
def do_exec(self, statement):
interact_lock.acquire()
try:
# check to see if we're inside interaction
if self.filename:
# avoid spurious interaction notifications:
self.set_burst(2)
# execute the statement in the remote debugger:
return qdb.Frontend.do_exec(self, statement)
finally:
interact_lock.release()
# create the connection between threads:
parent_queue, child_queue = Queue.Queue(), Queue.Queue()
front_conn = qdb.QueuePipe("parent", parent_queue, child_queue)
child_conn = qdb.QueuePipe("child", child_queue, parent_queue)
web_debugger = WebDebugger(front_conn) # frontend
qdb_debugger = qdb.Qdb(
pipe=child_conn, redirect_stdio=False, skip=None) # backend
dbg = qdb_debugger
# enable getting context (stack, globals/locals) at interaction
qdb_debugger.set_params(dict(call_stack=True, environment=True))
import gluon.main
gluon.main.global_settings.debugging = True
| [
[
8,
0,
0.0357,
0.0357,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0612,
0.0051,
0,
0.66,
0.0357,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0663,
0.0051,
0,
0.66... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nDeveloped by Massimo Di Pierro <mdipierro@cs.depaul.edu>,\nlimodou <limodou@gmail.com> and srackham <srackham@gmail.com>.\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\n\"\"\"",
"import logging",
"import os",
"import pdb",
"import Queue",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
This file specifically includes utilities for security.
"""
import threading
import struct
import hashlib
import hmac
import uuid
import random
import time
import os
import re
import sys
import logging
import socket
import base64
import zlib
python_version = sys.version_info[0]
if python_version == 2:
import cPickle as pickle
else:
import pickle
try:
from Crypto.Cipher import AES
except ImportError:
import contrib.aes as AES
try:
from contrib.pbkdf2 import pbkdf2_hex
HAVE_PBKDF2 = True
except ImportError:
try:
from .pbkdf2 import pbkdf2_hex
HAVE_PBKDF2 = True
except (ImportError, ValueError):
HAVE_PBKDF2 = False
logger = logging.getLogger("web2py")
def AES_new(key, IV=None):
""" Returns an AES cipher object and random IV if None specified """
if IV is None:
IV = fast_urandom16()
return AES.new(key, AES.MODE_CBC, IV), IV
def compare(a, b):
""" compares two strings and not vulnerable to timing attacks """
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
def md5_hash(text):
""" Generate a md5 hash with the given text """
return hashlib.md5(text).hexdigest()
def simple_hash(text, key='', salt='', digest_alg='md5'):
"""
Generates hash with the given text using the specified
digest hashing algorithm
"""
if not digest_alg:
raise RuntimeError("simple_hash with digest_alg=None")
elif not isinstance(digest_alg, str): # manual approach
h = digest_alg(text + key + salt)
elif digest_alg.startswith('pbkdf2'): # latest and coolest!
iterations, keylen, alg = digest_alg[7:-1].split(',')
return pbkdf2_hex(text, salt, int(iterations),
int(keylen), get_digest(alg))
elif key: # use hmac
digest_alg = get_digest(digest_alg)
h = hmac.new(key + salt, text, digest_alg)
else: # compatible with third party systems
h = hashlib.new(digest_alg)
h.update(text + salt)
return h.hexdigest()
def get_digest(value):
"""
Returns a hashlib digest algorithm from a string
"""
if not isinstance(value, str):
return value
value = value.lower()
if value == "md5":
return hashlib.md5
elif value == "sha1":
return hashlib.sha1
elif value == "sha224":
return hashlib.sha224
elif value == "sha256":
return hashlib.sha256
elif value == "sha384":
return hashlib.sha384
elif value == "sha512":
return hashlib.sha512
else:
raise ValueError("Invalid digest algorithm: %s" % value)
DIGEST_ALG_BY_SIZE = {
128 / 4: 'md5',
160 / 4: 'sha1',
224 / 4: 'sha224',
256 / 4: 'sha256',
384 / 4: 'sha384',
512 / 4: 'sha512',
}
def pad(s, n=32, padchar=' '):
return s + (32 - len(s) % 32) * padchar
def secure_dumps(data, encryption_key, hash_key=None, compression_level=None):
if not hash_key:
hash_key = hashlib.sha1(encryption_key).hexdigest()
dump = pickle.dumps(data)
if compression_level:
dump = zlib.compress(dump, compression_level)
key = pad(encryption_key[:32])
cipher, IV = AES_new(key)
encrypted_data = base64.urlsafe_b64encode(IV + cipher.encrypt(pad(dump)))
signature = hmac.new(hash_key, encrypted_data).hexdigest()
return signature + ':' + encrypted_data
def secure_loads(data, encryption_key, hash_key=None, compression_level=None):
if not ':' in data:
return None
if not hash_key:
hash_key = hashlib.sha1(encryption_key).hexdigest()
signature, encrypted_data = data.split(':', 1)
actual_signature = hmac.new(hash_key, encrypted_data).hexdigest()
if not compare(signature, actual_signature):
return None
key = pad(encryption_key[:32])
encrypted_data = base64.urlsafe_b64decode(encrypted_data)
IV, encrypted_data = encrypted_data[:16], encrypted_data[16:]
cipher, _ = AES_new(key, IV=IV)
try:
data = cipher.decrypt(encrypted_data)
data = data.rstrip(' ')
if compression_level:
data = zlib.decompress(data)
return pickle.loads(data)
except (TypeError, pickle.UnpicklingError):
return None
### compute constant CTOKENS
def initialize_urandom():
"""
This function and the web2py_uuid follow from the following discussion:
http://groups.google.com/group/web2py-developers/browse_thread/thread/7fd5789a7da3f09
At startup web2py compute a unique ID that identifies the machine by adding
uuid.getnode() + int(time.time() * 1e3)
This is a 48-bit number. It converts the number into 16 8-bit tokens.
It uses this value to initialize the entropy source ('/dev/urandom') and to seed random.
If os.random() is not supported, it falls back to using random and issues a warning.
"""
node_id = uuid.getnode()
microseconds = int(time.time() * 1e6)
ctokens = [((node_id + microseconds) >> ((i % 6) * 8)) %
256 for i in range(16)]
random.seed(node_id + microseconds)
try:
os.urandom(1)
have_urandom = True
try:
# try to add process-specific entropy
frandom = open('/dev/urandom', 'wb')
try:
if python_version == 2:
frandom.write(''.join(chr(t) for t in ctokens)) # python 2
else:
frandom.write(bytes([]).join(bytes([t]) for t in ctokens)) # python 3
finally:
frandom.close()
except IOError:
# works anyway
pass
except NotImplementedError:
have_urandom = False
logger.warning(
"""Cryptographically secure session management is not possible on your system because
your system does not provide a cryptographically secure entropy source.
This is not specific to web2py; consider deploying on a different operating system.""")
if python_version == 2:
packed = ''.join(chr(x) for x in ctokens) # python 2
else:
packed = bytes([]).join(bytes([x]) for x in ctokens) # python 3
unpacked_ctokens = struct.unpack('=QQ', packed)
return unpacked_ctokens, have_urandom
UNPACKED_CTOKENS, HAVE_URANDOM = initialize_urandom()
def fast_urandom16(urandom=[], locker=threading.RLock()):
"""
this is 4x faster than calling os.urandom(16) and prevents
the "too many files open" issue with concurrent access to os.urandom()
"""
try:
return urandom.pop()
except IndexError:
try:
locker.acquire()
ur = os.urandom(16 * 1024)
urandom += [ur[i:i + 16] for i in xrange(16, 1024 * 16, 16)]
return ur[0:16]
finally:
locker.release()
def web2py_uuid(ctokens=UNPACKED_CTOKENS):
"""
This function follows from the following discussion:
http://groups.google.com/group/web2py-developers/browse_thread/thread/7fd5789a7da3f09
It works like uuid.uuid4 except that tries to use os.urandom() if possible
and it XORs the output with the tokens uniquely associated with this machine.
"""
rand_longs = (random.getrandbits(64), random.getrandbits(64))
if HAVE_URANDOM:
urand_longs = struct.unpack('=QQ', fast_urandom16())
byte_s = struct.pack('=QQ',
rand_longs[0] ^ urand_longs[0] ^ ctokens[0],
rand_longs[1] ^ urand_longs[1] ^ ctokens[1])
else:
byte_s = struct.pack('=QQ',
rand_longs[0] ^ ctokens[0],
rand_longs[1] ^ ctokens[1])
return str(uuid.UUID(bytes=byte_s, version=4))
REGEX_IPv4 = re.compile('(\d+)\.(\d+)\.(\d+)\.(\d+)')
def is_valid_ip_address(address):
"""
>>> is_valid_ip_address('127.0')
False
>>> is_valid_ip_address('127.0.0.1')
True
>>> is_valid_ip_address('2001:660::1')
True
"""
# deal with special cases
if address.lower() in ('127.0.0.1', 'localhost', '::1', '::ffff:127.0.0.1'):
return True
elif address.lower() in ('unknown', ''):
return False
elif address.count('.') == 3: # assume IPv4
if address.startswith('::ffff:'):
address = address[7:]
if hasattr(socket, 'inet_aton'): # try validate using the OS
try:
socket.inet_aton(address)
return True
except socket.error: # invalid address
return False
else: # try validate using Regex
match = REGEX_IPv4.match(address)
if match and all(0 <= int(match.group(i)) < 256 for i in (1, 2, 3, 4)):
return True
return False
elif hasattr(socket, 'inet_pton'): # assume IPv6, try using the OS
try:
socket.inet_pton(socket.AF_INET6, address)
return True
except socket.error: # invalid address
return False
else: # do not know what to do? assume it is a valid address
return True
def is_loopback_ip_address(ip=None, addrinfo=None):
"""
Determines whether the address appears to be a loopback address.
This assumes that the IP is valid.
"""
if addrinfo: # see socket.getaddrinfo() for layout of addrinfo tuple
if addrinfo[0] == socket.AF_INET or addrinfo[0] == socket.AF_INET6:
ip = addrinfo[4]
if not isinstance(ip, basestring):
return False
# IPv4 or IPv6-embedded IPv4 or IPv4-compatible IPv6
if ip.count('.') == 3:
return ip.lower().startswith(('127', '::127', '0:0:0:0:0:0:127',
'::ffff:127', '0:0:0:0:0:ffff:127'))
return ip == '::1' or ip == '0:0:0:0:0:0:0:1' # IPv6 loopback
def getipaddrinfo(host):
"""
Filter out non-IP and bad IP addresses from getaddrinfo
"""
try:
return [addrinfo for addrinfo in socket.getaddrinfo(host, None)
if (addrinfo[0] == socket.AF_INET or
addrinfo[0] == socket.AF_INET6)
and isinstance(addrinfo[4][0], basestring)]
except socket.error:
return []
| [
[
8,
0,
0.0215,
0.0215,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0369,
0.0031,
0,
0.66,
0.0278,
83,
0,
1,
0,
0,
83,
0,
0
],
[
1,
0,
0.04,
0.0031,
0,
0.66,
... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\nThis file specifically includes utilities for security.\n\"\"\"",
"import threading",
"import struct",
"import hashlib",
"import hmac... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Provides:
- List; like list but returns None instead of IndexOutOfBounds
- Storage; like dictionary allowing also for `obj.foo` for `obj['foo']`
"""
import cPickle
import portalocker
__all__ = ['List', 'Storage', 'Settings', 'Messages',
'StorageList', 'load_storage', 'save_storage']
DEFAULT = lambda:0
class Storage(dict):
"""
A Storage object is like a dictionary except `obj.foo` can be used
in addition to `obj['foo']`, and setting obj.foo = None deletes item foo.
>>> o = Storage(a=1)
>>> print o.a
1
>>> o['a']
1
>>> o.a = 2
>>> print o['a']
2
>>> del o.a
>>> print o.a
None
"""
__slots__ = ()
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
__getitem__ = dict.get
__getattr__ = dict.get
__repr__ = lambda self: '<Storage %s>' % dict.__repr__(self)
# http://stackoverflow.com/questions/5247250/why-does-pickle-getstate-accept-as-a-return-value-the-very-instance-it-requi
__getstate__ = lambda self: None
__copy__ = lambda self: Storage(self)
def getlist(self, key):
"""
Return a Storage value as a list.
If the value is a list it will be returned as-is.
If object is None, an empty list will be returned.
Otherwise, [value] will be returned.
Example output for a query string of ?x=abc&y=abc&y=def
>>> request = Storage()
>>> request.vars = Storage()
>>> request.vars.x = 'abc'
>>> request.vars.y = ['abc', 'def']
>>> request.vars.getlist('x')
['abc']
>>> request.vars.getlist('y')
['abc', 'def']
>>> request.vars.getlist('z')
[]
"""
value = self.get(key, [])
if value is None or isinstance(value, (list, tuple)):
return value
else:
return [value]
def getfirst(self, key, default=None):
"""
Return the first or only value when given a request.vars-style key.
If the value is a list, its first item will be returned;
otherwise, the value will be returned as-is.
Example output for a query string of ?x=abc&y=abc&y=def
>>> request = Storage()
>>> request.vars = Storage()
>>> request.vars.x = 'abc'
>>> request.vars.y = ['abc', 'def']
>>> request.vars.getfirst('x')
'abc'
>>> request.vars.getfirst('y')
'abc'
>>> request.vars.getfirst('z')
"""
values = self.getlist(key)
return values[0] if values else default
def getlast(self, key, default=None):
"""
Returns the last or only single value when
given a request.vars-style key.
If the value is a list, the last item will be returned;
otherwise, the value will be returned as-is.
Simulated output with a query string of ?x=abc&y=abc&y=def
>>> request = Storage()
>>> request.vars = Storage()
>>> request.vars.x = 'abc'
>>> request.vars.y = ['abc', 'def']
>>> request.vars.getlast('x')
'abc'
>>> request.vars.getlast('y')
'def'
>>> request.vars.getlast('z')
"""
values = self.getlist(key)
return values[-1] if values else default
PICKABLE = (str, int, long, float, bool, list, dict, tuple, set)
class StorageList(Storage):
"""
like Storage but missing elements default to [] instead of None
"""
def __getitem__(self, key):
return self.__getattr__(key)
def __getattr__(self, key):
if key in self:
return getattr(self, key)
else:
r = []
setattr(self, key, r)
return r
def load_storage(filename):
fp = None
try:
fp = portalocker.LockedFile(filename, 'rb')
storage = cPickle.load(fp)
finally:
if fp:
fp.close()
return Storage(storage)
def save_storage(storage, filename):
fp = None
try:
fp = portalocker.LockedFile(filename, 'wb')
cPickle.dump(dict(storage), fp)
finally:
if fp:
fp.close()
class Settings(Storage):
def __setattr__(self, key, value):
if key != 'lock_keys' and self['lock_keys'] and key not in self:
raise SyntaxError('setting key \'%s\' does not exist' % key)
if key != 'lock_values' and self['lock_values']:
raise SyntaxError('setting value cannot be changed: %s' % key)
self[key] = value
class Messages(Settings):
def __init__(self, T):
Storage.__init__(self, T=T)
def __getattr__(self, key):
value = self[key]
if isinstance(value, str):
return str(self.T(value))
return value
class FastStorage(dict):
"""
Eventually this should replace class Storage but causes memory leak
because of http://bugs.python.org/issue1469629
>>> s = FastStorage()
>>> s.a = 1
>>> s.a
1
>>> s['a']
1
>>> s.b
>>> s['b']
>>> s['b']=2
>>> s['b']
2
>>> s.b
2
>>> isinstance(s,dict)
True
>>> dict(s)
{'a': 1, 'b': 2}
>>> dict(FastStorage(s))
{'a': 1, 'b': 2}
>>> import pickle
>>> s = pickle.loads(pickle.dumps(s))
>>> dict(s)
{'a': 1, 'b': 2}
>>> del s.b
>>> del s.a
>>> s.a
>>> s.b
>>> s['a']
>>> s['b']
"""
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
def __getattr__(self, key):
return getattr(self, key) if key in self else None
def __getitem__(self, key):
return dict.get(self, key, None)
def copy(self):
self.__dict__ = {}
s = FastStorage(self)
self.__dict__ = self
return s
def __repr__(self):
return '<Storage %s>' % dict.__repr__(self)
def __getstate__(self):
return dict(self)
def __setstate__(self, sdict):
dict.__init__(self, sdict)
self.__dict__ = self
def update(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
class List(list):
"""
Like a regular python list but a[i] if i is out of bounds return None
instead of IndexOutOfBounds
"""
def __call__(self, i, default=DEFAULT, cast=None, otherwise=None):
"""
request.args(0,default=0,cast=int,otherwise='http://error_url')
request.args(0,default=0,cast=int,otherwise=lambda:...)
"""
n = len(self)
if 0 <= i < n or -n <= i < 0:
value = self[i]
elif default is DEFAULT:
value = None
else:
value, cast = default, False
if cast:
try:
value = cast(value)
except (ValueError, TypeError):
from http import HTTP, redirect
if otherwise is None:
raise HTTP(404)
elif isinstance(otherwise, str):
redirect(otherwise)
elif callable(otherwise):
return otherwise()
else:
raise RuntimeError("invalid otherwise")
return value
if __name__ == '__main__':
import doctest
doctest.testmod()
| [
[
8,
0,
0.0299,
0.0352,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0528,
0.0035,
0,
0.66,
0.0714,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.0563,
0.0035,
0,
0.66... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\nProvides:\n\n- List; like list but returns None instead of IndexOutOfBounds",
"import cPickle",
"import portalocker",
"__all__ = ['List... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
import re
# pattern to find defined tables
regex_tables = re.compile(
"""^[\w]+\.define_table\(\s*[\'\"](?P<name>\w+)[\'\"]""",
flags=re.M)
# pattern to find exposed functions in controller
regex_expose = re.compile(
'^def\s+(?P<name>_?[a-zA-Z0-9]\w*)\( *\)\s*:',
flags=re.M)
regex_include = re.compile(
'(?P<all>\{\{\s*include\s+[\'"](?P<name>[^\'"]*)[\'"]\s*\}\})')
regex_extend = re.compile(
'^\s*(?P<all>\{\{\s*extend\s+[\'"](?P<name>[^\'"]+)[\'"]\s*\}\})', re.MULTILINE)
| [
[
8,
0,
0.2143,
0.1786,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3571,
0.0357,
0,
0.66,
0.2,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.5357,
0.1071,
0,
0.66,
... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\"\"\"",
"import re",
"regex_tables = re.compile(\n \"\"\"^[\\w]+\\.define_table\\(\\s*[\\'\\\"](?P<name>\\w+)[\\'\\\"]\"\"\",\n flag... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Created by Vladyslav Kozlovskyy (Ukraine) <dbdevelop©gmail.com>
for Web2py project
Utilities and class for UTF8 strings managing
===========================================
"""
import __builtin__
__all__ = ['Utf8']
repr_escape_tab = {}
for i in range(1, 32):
repr_escape_tab[i] = ur'\x%02x' % i
repr_escape_tab[7] = u'\\a'
repr_escape_tab[8] = u'\\b'
repr_escape_tab[9] = u'\\t'
repr_escape_tab[10] = u'\\n'
repr_escape_tab[11] = u'\\v'
repr_escape_tab[12] = u'\\f'
repr_escape_tab[13] = u'\\r'
repr_escape_tab[ord('\\')] = u'\\\\'
repr_escape_tab2 = repr_escape_tab.copy()
repr_escape_tab2[ord('\'')] = u"\\'"
def sort_key(s):
""" Unicode Collation Algorithm (UCA) (http://www.unicode.org/reports/tr10/)
is used for utf-8 and unicode strings sorting and for utf-8 strings
comparison
NOTE: pyuca is a very memory cost module! It loads the whole
"allkey.txt" file (~2mb!) into the memory. But this
functionality is needed only when sort_key() is called as a
part of sort() function or when Utf8 strings are compared.
So, it is a lazy "sort_key" function which (ONLY ONCE, ON ITS
FIRST CALL) imports pyuca and replaces itself with a real
sort_key() function
"""
global sort_key
try:
from contrib.pyuca import unicode_collator
unicode_sort_key = unicode_collator.sort_key
sort_key = lambda s: unicode_sort_key(
unicode(s, 'utf-8') if isinstance(s, str) else s)
except:
sort_key = lambda s: (
unicode(s, 'utf-8') if isinstance(s, str) else s).lower()
return sort_key(s)
def ord(char):
""" returns unicode id for utf8 or unicode *char* character
SUPPOSE that *char* is an utf-8 or unicode character only
"""
if isinstance(char, unicode):
return __builtin__.ord(char)
return __builtin__.ord(unicode(char, 'utf-8'))
def chr(code):
""" return utf8-character with *code* unicode id """
return Utf8(unichr(code))
def size(string):
""" return length of utf-8 string in bytes
NOTE! The length of correspondent utf-8
string is returned for unicode string
"""
return Utf8(string).__size__()
def truncate(string, length, dots='...'):
""" returns string of length < *length* or truncate
string with adding *dots* suffix to the string's end
args:
length (int): max length of string
dots (str or unicode): string suffix, when string is cutted
returns:
(utf8-str): original or cutted string
"""
text = unicode(string, 'utf-8')
dots = unicode(dots, 'utf-8') if isinstance(dots, str) else dots
if len(text) > length:
text = text[:length - len(dots)] + dots
return str.__new__(Utf8, text.encode('utf-8'))
class Utf8(str):
"""
Class for utf8 string storing and manipulations
The base presupposition of this class usage is:
"ALL strings in the application are either of
utf-8 or unicode type, even when simple str
type is used. UTF-8 is only a "packed" version
of unicode, so Utf-8 and unicode strings are
interchangeable."
CAUTION! This class is slower than str/unicode!
Do NOT use it inside intensive loops. Simply
decode string(s) to unicode before loop and
encode it back to utf-8 string(s) after
intensive calculation.
You can see the benefit of this class in doctests() below
"""
def __new__(cls, content='', codepage='utf-8'):
if isinstance(content, unicode):
return str.__new__(cls, unicode.encode(content, 'utf-8'))
elif codepage in ('utf-8', 'utf8') or isinstance(content, cls):
return str.__new__(cls, content)
else:
return str.__new__(cls, unicode(content, codepage).encode('utf-8'))
def __repr__(self):
r''' # note that we use raw strings to avoid having to use double back slashes below
NOTE! This function is a clone of web2py:gluon.languages.utf_repl() function
utf8.__repr__() works same as str.repr() when processing ascii string
>>> repr(Utf8('abc')) == repr(Utf8("abc")) == repr('abc') == repr("abc") == "'abc'"
True
>>> repr(Utf8('a"b"c')) == repr('a"b"c') == '\'a"b"c\''
True
>>> repr(Utf8("a'b'c")) == repr("a'b'c") == '"a\'b\'c"'
True
>>> repr(Utf8('a\'b"c')) == repr('a\'b"c') == repr(Utf8("a'b\"c")) == repr("a'b\"c") == '\'a\\\'b"c\''
True
>>> repr(Utf8('a\r\nb')) == repr('a\r\nb') == "'a\\r\\nb'" # Test for \r, \n
True
Unlike str.repr(), Utf8.__repr__() remains utf8 content when processing utf8 string
>>> repr(Utf8('中文字')) == repr(Utf8("中文字")) == "'中文字'" != repr('中文字')
True
>>> repr(Utf8('中"文"字')) == "'中\"文\"字'" != repr('中"文"字')
True
>>> repr(Utf8("中'文'字")) == '"中\'文\'字"' != repr("中'文'字")
True
>>> repr(Utf8('中\'文"字')) == repr(Utf8("中'文\"字")) == '\'中\\\'文"字\'' != repr('中\'文"字') == repr("中'文\"字")
True
>>> repr(Utf8('中\r\n文')) == "'中\\r\\n文'" != repr('中\r\n文') # Test for \r, \n
True
'''
if str.find(self, "'") >= 0 and str.find(self, '"') < 0: # only single quote exists
return '"' + unicode(self, 'utf-8').translate(repr_escape_tab).encode('utf-8') + '"'
else:
return "'" + unicode(self, 'utf-8').translate(repr_escape_tab2).encode('utf-8') + "'"
def __size__(self):
""" length of utf-8 string in bytes """
return str.__len__(self)
def __contains__(self, other):
return str.__contains__(self, Utf8(other))
def __getitem__(self, index):
return str.__new__(Utf8, unicode(self, 'utf-8')[index].encode('utf-8'))
def __getslice__(self, begin, end):
return str.__new__(Utf8, unicode(self, 'utf-8')[begin:end].encode('utf-8'))
def __add__(self, other):
return str.__new__(Utf8, str.__add__(self, unicode.encode(other, 'utf-8')
if isinstance(other, unicode) else other))
def __len__(self):
return len(unicode(self, 'utf-8'))
def __mul__(self, integer):
return str.__new__(Utf8, str.__mul__(self, integer))
def __eq__(self, string):
return str.__eq__(self, Utf8(string))
def __ne__(self, string):
return str.__ne__(self, Utf8(string))
def capitalize(self):
return str.__new__(Utf8, unicode(self, 'utf-8').capitalize().encode('utf-8'))
def center(self, length):
return str.__new__(Utf8, unicode(self, 'utf-8').center(length).encode('utf-8'))
def upper(self):
return str.__new__(Utf8, unicode(self, 'utf-8').upper().encode('utf-8'))
def lower(self):
return str.__new__(Utf8, unicode(self, 'utf-8').lower().encode('utf-8'))
def title(self):
return str.__new__(Utf8, unicode(self, 'utf-8').title().encode('utf-8'))
def index(self, string):
return unicode(self, 'utf-8').index(string if isinstance(string, unicode) else unicode(string, 'utf-8'))
def isalnum(self):
return unicode(self, 'utf-8').isalnum()
def isalpha(self):
return unicode(self, 'utf-8').isalpha()
def isdigit(self):
return unicode(self, 'utf-8').isdigit()
def islower(self):
return unicode(self, 'utf-8').islower()
def isspace(self):
return unicode(self, 'utf-8').isspace()
def istitle(self):
return unicode(self, 'utf-8').istitle()
def isupper(self):
return unicode(self, 'utf-8').isupper()
def zfill(self, length):
return str.__new__(Utf8, unicode(self, 'utf-8').zfill(length).encode('utf-8'))
def join(self, iter):
return str.__new__(Utf8, str.join(self, [Utf8(c) for c in
list(unicode(iter, 'utf-8') if
isinstance(iter, str) else
iter)]))
def lstrip(self, chars=None):
return str.__new__(Utf8, str.lstrip(self, None if chars is None else Utf8(chars)))
def rstrip(self, chars=None):
return str.__new__(Utf8, str.rstrip(self, None if chars is None else Utf8(chars)))
def strip(self, chars=None):
return str.__new__(Utf8, str.strip(self, None if chars is None else Utf8(chars)))
def swapcase(self):
return str.__new__(Utf8, unicode(self, 'utf-8').swapcase().encode('utf-8'))
def count(self, sub, start=0, end=None):
unistr = unicode(self, 'utf-8')
return unistr.count(
unicode(sub, 'utf-8') if isinstance(sub, str) else sub,
start, len(unistr) if end is None else end)
def decode(self, encoding='utf-8', errors='strict'):
return str.decode(self, encoding, errors)
def encode(self, encoding, errors='strict'):
return unicode(self, 'utf-8').encode(encoding, errors)
def expandtabs(self, tabsize=8):
return str.__new__(Utf8, unicode(self, 'utf-8').expandtabs(tabsize).encode('utf-8'))
def find(self, sub, start=None, end=None):
return unicode(self, 'utf-8').find(unicode(sub, 'utf-8')
if isinstance(sub, str) else sub, start, end)
def ljust(self, width, fillchar=' '):
return str.__new__(Utf8, unicode(self, 'utf-8').ljust(width, unicode(fillchar, 'utf-8')
if isinstance(fillchar, str) else fillchar).encode('utf-8'))
def partition(self, sep):
(head, sep, tail) = str.partition(self, Utf8(sep))
return (str.__new__(Utf8, head),
str.__new__(Utf8, sep),
str.__new__(Utf8, tail))
def replace(self, old, new, count=-1):
return str.__new__(Utf8, str.replace(self, Utf8(old), Utf8(new), count))
def rfind(self, sub, start=None, end=None):
return unicode(self, 'utf-8').rfind(unicode(sub, 'utf-8')
if isinstance(sub, str) else sub, start, end)
def rindex(self, string):
return unicode(self, 'utf-8').rindex(string if isinstance(string, unicode)
else unicode(string, 'utf-8'))
def rjust(self, width, fillchar=' '):
return str.__new__(Utf8, unicode(self, 'utf-8').rjust(width, unicode(fillchar, 'utf-8')
if isinstance(fillchar, str) else fillchar).encode('utf-8'))
def rpartition(self, sep):
(head, sep, tail) = str.rpartition(self, Utf8(sep))
return (str.__new__(Utf8, head),
str.__new__(Utf8, sep),
str.__new__(Utf8, tail))
def rsplit(self, sep=None, maxsplit=-1):
return [str.__new__(Utf8, part) for part in str.rsplit(self,
None if sep is None else Utf8(sep), maxsplit)]
def split(self, sep=None, maxsplit=-1):
return [str.__new__(Utf8, part) for part in str.split(self,
None if sep is None else Utf8(sep), maxsplit)]
def splitlines(self, keepends=False):
return [str.__new__(Utf8, part) for part in str.splitlines(self, keepends)]
def startswith(self, prefix, start=0, end=None):
unistr = unicode(self, 'utf-8')
if isinstance(prefix, tuple):
prefix = tuple(unicode(
s, 'utf-8') if isinstance(s, str) else s for s in prefix)
elif isinstance(prefix, str):
prefix = unicode(prefix, 'utf-8')
return unistr.startswith(prefix, start, len(unistr) if end is None else end)
def translate(self, table, deletechars=''):
if isinstance(table, dict):
return str.__new__(Utf8, unicode(self, 'utf-8').translate(table).encode('utf-8'))
else:
return str.__new__(Utf8, str.translate(self, table, deletechars))
def endswith(self, prefix, start=0, end=None):
unistr = unicode(self, 'utf-8')
if isinstance(prefix, tuple):
prefix = tuple(unicode(
s, 'utf-8') if isinstance(s, str) else s for s in prefix)
elif isinstance(prefix, str):
prefix = unicode(prefix, 'utf-8')
return unistr.endswith(prefix, start, len(unistr) if end is None else end)
if hasattr(str, 'format'): # Python 2.5 hasn't got str.format() method
def format(self, *args, **kwargs):
args = [unicode(
s, 'utf-8') if isinstance(s, str) else s for s in args]
kwargs = dict((unicode(k, 'utf-8') if isinstance(k, str) else k,
unicode(v, 'utf-8') if isinstance(v, str) else v)
for k, v in kwargs.iteritems())
return str.__new__(Utf8, unicode(self, 'utf-8').
format(*args, **kwargs).encode('utf-8'))
def __mod__(self, right):
if isinstance(right, tuple):
right = tuple(unicode(v, 'utf-8') if isinstance(v, str) else v
for v in right)
elif isinstance(right, dict):
right = dict((unicode(k, 'utf-8') if isinstance(k, str) else k,
unicode(v, 'utf-8') if isinstance(v, str) else v)
for k, v in right.iteritems())
elif isinstance(right, str):
right = unicode(right, 'utf-8')
return str.__new__(Utf8, unicode(self, 'utf-8').__mod__(right).encode('utf-8'))
def __ge__(self, string):
return sort_key(self) >= sort_key(string)
def __gt__(self, string):
return sort_key(self) > sort_key(string)
def __le__(self, string):
return sort_key(self) <= sort_key(string)
def __lt__(self, string):
return sort_key(self) < sort_key(string)
if __name__ == '__main__':
def doctests():
u"""
doctests:
>>> test_unicode=u'ПРоба Є PRobe'
>>> test_unicode_word=u'ПРоба'
>>> test_number_str='12345'
>>> test_unicode
u'\\u041f\\u0420\\u043e\\u0431\\u0430 \\u0404 PRobe'
>>> print test_unicode
ПРоба Є PRobe
>>> test_word=test_unicode_word.encode('utf-8')
>>> test_str=test_unicode.encode('utf-8')
>>> s=Utf8(test_str)
>>> s
'ПРоба Є PRobe'
>>> type(s)
<class '__main__.Utf8'>
>>> s == test_str
True
>>> len(test_str) # wrong length of utf8-string!
19
>>> len(test_unicode) # RIGHT!
13
>>> len(s) # RIGHT!
13
>>> size(test_str) # size of utf-8 string (in bytes) == len(str)
19
>>> size(test_unicode) # size of unicode string in bytes (packed to utf-8 string)
19
>>> size(s) # size of utf-8 string in bytes
19
>>> try: # utf-8 is a multibyte string. Convert it to unicode for use with builtin ord()
... __builtin__.ord('б') # ascii string
... except Exception, e:
... print 'Exception:', e
Exception: ord() expected a character, but string of length 2 found
>>> ord('б') # utf8.ord() is used(!!!)
1073
>>> ord(u'б') # utf8.ord() is used(!!!)
1073
>>> ord(s[3]) # utf8.ord() is used(!!!)
1073
>>> chr(ord(s[3])) # utf8.chr() and utf8.chr() is used(!!!)
'б'
>>> type(chr(1073)) # utf8.chr() is used(!!!)
<class '__main__.Utf8'>
>>> s=Utf8(test_unicode)
>>> s
'ПРоба Є PRobe'
>>> s == test_str
True
>>> test_str == s
True
>>> s == test_unicode
True
>>> test_unicode == s
True
>>> print test_str.upper() # only ASCII characters uppered
ПРоба Є PROBE
>>> print test_unicode.upper() # unicode gives right result
ПРОБА Є PROBE
>>> s.upper() # utf8 class use unicode.upper()
'ПРОБА Є PROBE'
>>> type(s.upper())
<class '__main__.Utf8'>
>>> s.lower()
'проба є probe'
>>> type(s.lower())
<class '__main__.Utf8'>
>>> s.capitalize()
'Проба є probe'
>>> type(s.capitalize())
<class '__main__.Utf8'>
>>> len(s)
13
>>> len(test_unicode)
13
>>> s+'. Probe is проба'
'ПРоба Є PRobe. Probe is проба'
>>> type(s+'. Probe is проба')
<class '__main__.Utf8'>
>>> s+u'. Probe is проба'
'ПРоба Є PRobe. Probe is проба'
>>> type(s+u'. Probe is проба')
<class '__main__.Utf8'>
>>> s+s
'ПРоба Є PRobeПРоба Є PRobe'
>>> type(s+s)
<class '__main__.Utf8'>
>>> a=s
>>> a+=s
>>> a+=test_unicode
>>> a+=test_str
>>> a
'ПРоба Є PRobeПРоба Є PRobeПРоба Є PRobeПРоба Є PRobe'
>>> type(a)
<class '__main__.Utf8'>
>>> s*3
'ПРоба Є PRobeПРоба Є PRobeПРоба Є PRobe'
>>> type(s*3)
<class '__main__.Utf8'>
>>> a=Utf8("-проба-")
>>> a*=10
>>> a
'-проба--проба--проба--проба--проба--проба--проба--проба--проба--проба-'
>>> type(a)
<class '__main__.Utf8'>
>>> print "'"+test_str.center(17)+"'" # WRONG RESULT!
'ПРоба Є PRobe'
>>> s.center(17) # RIGHT!
' ПРоба Є PRobe '
>>> type(s.center(17))
<class '__main__.Utf8'>
>>> (test_word+test_number_str).isalnum() # WRONG RESULT! non ASCII chars are detected as non alpha
False
>>> Utf8(test_word+test_number_str).isalnum()
True
>>> s.isalnum()
False
>>> test_word.isalpha() # WRONG RESULT! Non ASCII characters are detected as non alpha
False
>>> Utf8(test_word).isalpha() # RIGHT!
True
>>> s.lower().islower()
True
>>> s.upper().isupper()
True
>>> print test_str.zfill(17) # WRONG RESULT!
ПРоба Є PRobe
>>> s.zfill(17) # RIGHT!
'0000ПРоба Є PRobe'
>>> type(s.zfill(17))
<class '__main__.Utf8'>
>>> s.istitle()
False
>>> s.title().istitle()
True
>>> Utf8('1234').isdigit()
True
>>> Utf8(' \t').isspace()
True
>>> s.join('•|•')
'•ПРоба Є PRobe|ПРоба Є PRobe•'
>>> s.join((str('(utf8 тест1)'), unicode('(unicode тест2)','utf-8'), '(ascii test3)'))
'(utf8 тест1)ПРоба Є PRobe(unicode тест2)ПРоба Є PRobe(ascii test3)'
>>> type(s)
<class '__main__.Utf8'>
>>> s==test_str
True
>>> s==test_unicode
True
>>> s.swapcase()
'прОБА є prOBE'
>>> type(s.swapcase())
<class '__main__.Utf8'>
>>> truncate(s, 10)
'ПРоба Є...'
>>> truncate(s, 20)
'ПРоба Є PRobe'
>>> truncate(s, 10, '•••') # utf-8 string as *dots*
'ПРоба Є•••'
>>> truncate(s, 10, u'®') # you can use unicode string as *dots*
'ПРоба Є P®'
>>> type(truncate(s, 10))
<class '__main__.Utf8'>
>>> Utf8(s.encode('koi8-u'), 'koi8-u')
'ПРоба Є PRobe'
>>> s.decode() # convert utf-8 string to unicode
u'\\u041f\\u0420\\u043e\\u0431\\u0430 \\u0404 PRobe'
>>> a='про\\tba'
>>> str_tmp=a.expandtabs()
>>> utf8_tmp=Utf8(a).expandtabs()
>>> utf8_tmp.replace(' ','.') # RIGHT! (default tabsize is 8)
'про.....ba'
>>> utf8_tmp.index('b')
8
>>> print "'"+str_tmp.replace(' ','.')+"'" # WRONG STRING LENGTH!
'про..ba'
>>> str_tmp.index('b') # WRONG index of 'b' character
8
>>> print "'"+a.expandtabs(4).replace(' ','.')+"'" # WRONG RESULT!
'про..ba'
>>> Utf8(a).expandtabs(4).replace(' ','.') # RIGHT!
'про.ba'
>>> s.find('Є')
6
>>> s.find(u'Є')
6
>>> s.find(' ', 6)
7
>>> s.rfind(' ')
7
>>> s.partition('Є')
('ПРоба ', 'Є', ' PRobe')
>>> s.partition(u'Є')
('ПРоба ', 'Є', ' PRobe')
>>> (a,b,c) = s.partition('Є')
>>> type(a), type(b), type(c)
(<class '__main__.Utf8'>, <class '__main__.Utf8'>, <class '__main__.Utf8'>)
>>> s.partition(' ')
('ПРоба', ' ', 'Є PRobe')
>>> s.rpartition(' ')
('ПРоба Є', ' ', 'PRobe')
>>> s.index('Є')
6
>>> s.rindex(u'Є')
6
>>> s.index(' ')
5
>>> s.rindex(' ')
7
>>> a=Utf8('а б ц д е а б ц д е а\\tб ц д е')
>>> a.split()
['а', 'б', 'ц', 'д', 'е', 'а', 'б', 'ц', 'д',
'е', 'а', 'б', 'ц', 'д', 'е']
>>> a.rsplit()
['а', 'б', 'ц', 'д', 'е', 'а', 'б', 'ц', 'д',
'е', 'а', 'б', 'ц', 'д', 'е']
>>> a.expandtabs().split('б')
['а ', ' ц д е а ', ' ц д е а ', ' ц д е']
>>> a.expandtabs().rsplit('б')
['а ', ' ц д е а ', ' ц д е а ', ' ц д е']
>>> a.expandtabs().split(u'б', 1)
['а ', ' ц д е а б ц д е а б ц д е']
>>> a.expandtabs().rsplit(u'б', 1)
['а б ц д е а б ц д е а ', ' ц д е']
>>> a=Utf8("рядок1\\nрядок2\\nрядок3")
>>> a.splitlines()
['рядок1', 'рядок2', 'рядок3']
>>> a.splitlines(True)
['рядок1\\n', 'рядок2\\n', 'рядок3']
>>> s[6]
'Є'
>>> s[0]
'П'
>>> s[-1]
'e'
>>> s[:10]
'ПРоба Є PR'
>>> s[2:-2:2]
'оаЄPo'
>>> s[::-1]
'eboRP Є абоРП'
>>> s.startswith('ПР')
True
>>> s.startswith(('ПР', u'об'),0)
True
>>> s.startswith(u'об', 2, 4)
True
>>> s.endswith('be')
True
>>> s.endswith(('be', 'PR', u'Є'))
True
>>> s.endswith('PR', 8, 10)
True
>>> s.endswith('Є', -7, -6)
True
>>> s.count(' ')
2
>>> s.count(' ',6)
1
>>> s.count(u'Є')
1
>>> s.count('Є', 0, 5)
0
>>> Utf8(
"Parameters: '%(проба)s', %(probe)04d, %(проба2)s") % { u"проба": s,
... "not used": "???", "probe": 2, "проба2": u"ПРоба Probe" }
"Parameters: 'ПРоба Є PRobe', 0002, ПРоба Probe"
>>> a=Utf8(u"Параметр: (%s)-(%s)-[%s]")
>>> a%=(s, s[::-1], 1000)
>>> a
'Параметр: (ПРоба Є PRobe)-(eboRP Є абоРП)-[1000]'
>>> if hasattr(Utf8, 'format'):
... Utf8("Проба <{0}>, {1}, {param1}, {param2}").format(s, u"中文字",
... param1="барабан", param2=1000) == 'Проба <ПРоба Є PRobe>, 中文字, барабан, 1000'
... else: # format() method is not used in python with version <2.6:
... print True
True
>>> u'Б'<u'Ї' # WRONG ORDER!
False
>>> 'Б'<'Ї' # WRONG ORDER!
False
>>> Utf8('Б')<'Ї' # RIGHT!
True
>>> u'д'>u'ґ' # WRONG ORDER!
False
>>> Utf8('д')>Utf8('ґ') # RIGHT!
True
>>> u'є'<=u'ж' # WRONG ORDER!
False
>>> Utf8('є')<=u'ж' # RIGHT!
True
>>> Utf8('є')<=u'є'
True
>>> u'Ї'>=u'И' # WRONG ORDER!
False
>>> Utf8(u'Ї') >= u'И' # RIGHT
True
>>> Utf8('Є') >= 'Є'
True
>>> a="яжертиуіопшщїасдфгґхйклчєзьцвбнмюЯЖЕРТИУІОПШЩЇАСДФГҐХЙКЛЧЗЬЦВБНМЮЄ" # str type
>>> b=u"яжертиуіопшщїасдфгґхйклчєзьцвбнмюЯЖЕРТИУІОПШЩЇАСДФГҐХЙКЛЧЗЬЦВБНМЮЄ" # unicode type
>>> c=Utf8("яжертиуіопшщїасдфгґхйклчєзьцвбнмюЯЖЕРТИУІОПШЩЇАСДФГҐХЙКЛЧЗЬЦВБНМЮЄ") # utf8 class
>>> result = "".join(sorted(a))
>>> result[0:20] # result is not utf8 string, because bytes, not utf8-characters were sorted
'\\x80\\x81\\x82\\x83\\x84\\x84\\x85\\x86\\x86\\x87\\x87\\x88\\x89\\x8c\\x8e\\x8f\\x90\\x90\\x91\\x91'
>>> try:
... unicode(result, 'utf-8') # try to convert result (utf-8?) to unicode
... except Exception, e:
... print 'Exception:', e
Exception: 'utf8' codec can't decode byte 0x80 in position 0: unexpected code byte
>>> try: # FAILED! (working with bytes, not with utf8-charactes)
... "".join( sorted(a, key=sort_key) ) # utf8.sort_key may be used with utf8 or unicode strings only!
... except Exception, e:
... print 'Exception:', e
Exception: 'utf8' codec can't decode byte 0xd1 in position 0: unexpected end of data
>>> print "".join( sorted(Utf8(a))) # converting *a* to unicode or utf8-string gives us correct result
аАбБвВгГґҐдДеЕєЄжЖзЗиИіІїЇйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩьЬюЮяЯ
>>> print u"".join( sorted(b) ) # WRONG ORDER! Default sort key is used
ЄІЇАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЮЯабвгдежзийклмнопрстуфхцчшщьюяєіїҐґ
>>> print u"".join( sorted(b, key=sort_key) ) # RIGHT ORDER! utf8.sort_key is used
аАбБвВгГґҐдДеЕєЄжЖзЗиИіІїЇйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩьЬюЮяЯ
>>> print "".join( sorted(c) ) # RIGHT ORDER! Utf8 "rich comparison" methods are used
аАбБвВгГґҐдДеЕєЄжЖзЗиИіІїЇйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩьЬюЮяЯ
>>> print "".join( sorted(c, key=sort_key) ) # RIGHT ORDER! utf8.sort_key is used
аАбБвВгГґҐдДеЕєЄжЖзЗиИіІїЇйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩьЬюЮяЯ
>>> Utf8().join(sorted(c.decode(), key=sort_key)) # convert to unicode for better performance
'аАбБвВгГґҐдДеЕєЄжЖзЗиИіІїЇйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩьЬюЮяЯ'
>>> for result in sorted(
["Іа", "Астро", u"гала", Utf8("Гоша"), "Єва", "шовк", "аякс", "Їжа",
... "ґанок", Utf8("Дар'я"), "білінг", "веб", u"Жужа", "проба", u"тест",
... "абетка", "яблуко", "Юляся", "Київ", "лимонад", "ложка", "Матриця",
... ], key=sort_key):
... print result.ljust(20), type(result)
абетка <type 'str'>
Астро <type 'str'>
аякс <type 'str'>
білінг <type 'str'>
веб <type 'str'>
гала <type 'unicode'>
ґанок <type 'str'>
Гоша <class '__main__.Utf8'>
Дар'я <class '__main__.Utf8'>
Єва <type 'str'>
Жужа <type 'unicode'>
Іа <type 'str'>
Їжа <type 'str'>
Київ <type 'str'>
лимонад <type 'str'>
ложка <type 'str'>
Матриця <type 'str'>
проба <type 'str'>
тест <type 'unicode'>
шовк <type 'str'>
Юляся <type 'str'>
яблуко <type 'str'>
>>> a=Utf8("中文字")
>>> L=list(a)
>>> L
['中', '文', '字']
>>> a="".join(L)
>>> print a
中文字
>>> type(a)
<type 'str'>
>>> a="中文字" # standard str type
>>> L=list(a)
>>> L
['\\xe4', '\\xb8', '\\xad', '\\xe6', '\\x96', '\\x87',
'\\xe5', '\\xad', '\\x97']
>>> from string import maketrans
>>> str_tab=maketrans('PRobe','12345')
>>> unicode_tab={ord(u'П'):ord(u'Ж'),
... ord(u'Р') : u'Ш',
... ord(Utf8('о')) : None, # utf8.ord() is used
... ord('б') : None, # -//-//-
... ord(u'а') : u"中文字",
... ord(u'Є') : Utf8('•').decode(), # only unicode type is supported
... }
>>> s.translate(unicode_tab).translate(str_tab, deletechars=' ')
'ЖШ中文字•12345'
"""
import sys
reload(sys)
sys.setdefaultencoding("UTF-8")
import doctest
print "DOCTESTS STARTED..."
doctest.testmod()
print "DOCTESTS FINISHED"
doctests()
| [
[
1,
0,
0.0014,
0.0014,
0,
0.66,
0,
364,
0,
1,
0,
0,
364,
0,
0
],
[
2,
0,
0.0185,
0.033,
0,
0.66,
0.1667,
916,
0,
1,
1,
0,
0,
0,
7
],
[
8,
1,
0.0124,
0.0179,
1,
0.7... | [
"import __builtin__",
"def sort_key(s):\n \"\"\" Unicode Collation Algorithm (UCA) (http://www.unicode.org/reports/tr10/)\n is used for utf-8 and unicode strings sorting and for utf-8 strings\n comparison\n\n NOTE: pyuca is a very memory cost module! It loads the whole\n \"all... |
# this file exists for backward compatibility
__all__ = ['DAL', 'Field', 'DRIVERS']
from dal import DAL, Field, Table, Query, Set, Expression, Row, Rows, DRIVERS, BaseAdapter, SQLField, SQLTable, SQLXorable, SQLQuery, SQLSet, SQLRows, SQLStorage, SQLDB, GQLDB, SQLALL, SQLCustomType
| [
[
14,
0,
0.6,
0.2,
0,
0.66,
0,
272,
0,
0,
0,
0,
0,
5,
0
],
[
1,
0,
1,
0.2,
0,
0.66,
1,
4,
0,
21,
0,
0,
4,
0,
0
]
] | [
"__all__ = ['DAL', 'Field', 'DRIVERS']",
"from dal import DAL, Field, Table, Query, Set, Expression, Row, Rows, DRIVERS, BaseAdapter, SQLField, SQLTable, SQLXorable, SQLQuery, SQLSet, SQLRows, SQLStorage, SQLDB, GQLDB, SQLALL, SQLCustomType"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
::
# from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496942
# Title: Cross-site scripting (XSS) defense
# Submitter: Josh Goldfoot (other recipes)
# Last Updated: 2006/08/05
# Version no: 1.0
"""
from htmllib import HTMLParser
from cgi import escape
from urlparse import urlparse
from formatter import AbstractFormatter
from htmlentitydefs import entitydefs
from xml.sax.saxutils import quoteattr
__all__ = ['sanitize']
def xssescape(text):
"""Gets rid of < and > and & and, for good measure, :"""
return escape(text, quote=True).replace(':', ':')
class XssCleaner(HTMLParser):
def __init__(
self,
permitted_tags=[
'a',
'b',
'blockquote',
'br/',
'i',
'li',
'ol',
'ul',
'p',
'cite',
'code',
'pre',
'img/',
],
allowed_attributes={'a': ['href', 'title'], 'img': ['src', 'alt'
], 'blockquote': ['type']},
fmt=AbstractFormatter,
strip_disallowed=False
):
HTMLParser.__init__(self, fmt)
self.result = ''
self.open_tags = []
self.permitted_tags = [i for i in permitted_tags if i[-1] != '/']
self.requires_no_close = [i[:-1] for i in permitted_tags
if i[-1] == '/']
self.permitted_tags += self.requires_no_close
self.allowed_attributes = allowed_attributes
# The only schemes allowed in URLs (for href and src attributes).
# Adding "javascript" or "vbscript" to this list would not be smart.
self.allowed_schemes = ['http', 'https', 'ftp', 'mailto']
#to strip or escape disallowed tags?
self.strip_disallowed = strip_disallowed
self.in_disallowed = False
def handle_data(self, data):
if data and not self.in_disallowed:
self.result += xssescape(data)
def handle_charref(self, ref):
if self.in_disallowed:
return
elif len(ref) < 7 and ref.isdigit():
self.result += '&#%s;' % ref
else:
self.result += xssescape('&#%s' % ref)
def handle_entityref(self, ref):
if self.in_disallowed:
return
elif ref in entitydefs:
self.result += '&%s;' % ref
else:
self.result += xssescape('&%s' % ref)
def handle_comment(self, comment):
if self.in_disallowed:
return
elif comment:
self.result += xssescape('<!--%s-->' % comment)
def handle_starttag(
self,
tag,
method,
attrs,
):
if tag not in self.permitted_tags:
if self.strip_disallowed:
self.in_disallowed = True
else:
self.result += xssescape('<%s>' % tag)
else:
bt = '<' + tag
if tag in self.allowed_attributes:
attrs = dict(attrs)
self.allowed_attributes_here = [x for x in
self.allowed_attributes[tag] if x in attrs
and len(attrs[x]) > 0]
for attribute in self.allowed_attributes_here:
if attribute in ['href', 'src', 'background']:
if self.url_is_acceptable(attrs[attribute]):
bt += ' %s="%s"' % (attribute,
attrs[attribute])
else:
bt += ' %s=%s' % (xssescape(attribute),
quoteattr(attrs[attribute]))
if bt == '<a' or bt == '<img':
return
if tag in self.requires_no_close:
bt += ' /'
bt += '>'
self.result += bt
self.open_tags.insert(0, tag)
def handle_endtag(self, tag, attrs):
bracketed = '</%s>' % tag
if tag not in self.permitted_tags:
if self.strip_disallowed:
self.in_disallowed = False
else:
self.result += xssescape(bracketed)
elif tag in self.open_tags:
self.result += bracketed
self.open_tags.remove(tag)
def unknown_starttag(self, tag, attributes):
self.handle_starttag(tag, None, attributes)
def unknown_endtag(self, tag):
self.handle_endtag(tag, None)
def url_is_acceptable(self, url):
"""
Accepts relative, absolute, and mailto urls
"""
parsed = urlparse(url)
return (parsed[0] in self.allowed_schemes and '.' in parsed[1]) \
or (parsed[0] in self.allowed_schemes and '@' in parsed[2]) \
or (parsed[0] == '' and parsed[2].startswith('/'))
def strip(self, rawstring, escape=True):
"""
Returns the argument stripped of potentially harmful
HTML or Javascript code
@type escape: boolean
@param escape: If True (default) it escapes the potentially harmful
content, otherwise remove it
"""
if not isinstance(rawstring, str):
return str(rawstring)
for tag in self.requires_no_close:
rawstring = rawstring.replace("<%s/>" % tag, "<%s />" % tag)
if not escape:
self.strip_disallowed = True
self.result = ''
self.feed(rawstring)
for endtag in self.open_tags:
if endtag not in self.requires_no_close:
self.result += '</%s>' % endtag
return self.result
def xtags(self):
"""
Returns a printable string informing the user which tags are allowed
"""
tg = ''
for x in sorted(self.permitted_tags):
tg += '<' + x
if x in self.allowed_attributes:
for y in self.allowed_attributes[x]:
tg += ' %s=""' % y
tg += '> '
return xssescape(tg.strip())
def sanitize(text, permitted_tags=[
'a',
'b',
'blockquote',
'br/',
'i',
'li',
'ol',
'ul',
'p',
'cite',
'code',
'pre',
'img/',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'table', 'tbody', 'thead', 'tfoot', 'tr', 'td', 'div',
'strong', 'span',
],
allowed_attributes={
'a': ['href', 'title'],
'img': ['src', 'alt'],
'blockquote': ['type'],
'td': ['colspan'],
},
escape=True):
if not isinstance(text, basestring):
return str(text)
return XssCleaner(permitted_tags=permitted_tags,
allowed_attributes=allowed_attributes).strip(text, escape)
| [
[
8,
0,
0.0373,
0.0439,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0702,
0.0044,
0,
0.66,
0.1,
193,
0,
1,
0,
0,
193,
0,
0
],
[
1,
0,
0.0746,
0.0044,
0,
0.66,
... | [
"\"\"\"\n::\n\n # from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496942\n # Title: Cross-site scripting (XSS) defense\n # Submitter: Josh Goldfoot (other recipes)\n # Last Updated: 2006/08/05\n # Version no: 1.0",
"from htmllib import HTMLParser",
"from cgi import escape",
"from u... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework (Copyrighted, 2007-2011).
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Author: Thadeus Burgess
Contributors:
- Thank you to Massimo Di Pierro for creating the original gluon/template.py
- Thank you to Jonathan Lundell for extensively testing the regex on Jython.
- Thank you to Limodou (creater of uliweb) who inspired the block-element support for web2py.
"""
import os
import cgi
import logging
from re import compile, sub, escape, DOTALL
try:
import cStringIO as StringIO
except:
from io import StringIO
try:
# have web2py
from restricted import RestrictedError
from globals import current
except ImportError:
# do not have web2py
current = None
def RestrictedError(a, b, c):
logging.error(str(a) + ':' + str(b) + ':' + str(c))
return RuntimeError
class Node(object):
"""
Basic Container Object
"""
def __init__(self, value=None, pre_extend=False):
self.value = value
self.pre_extend = pre_extend
def __str__(self):
return str(self.value)
class SuperNode(Node):
def __init__(self, name='', pre_extend=False):
self.name = name
self.value = None
self.pre_extend = pre_extend
def __str__(self):
if self.value:
return str(self.value)
else:
# raise SyntaxError("Undefined parent block ``%s``. \n" % self.name + "You must define a block before referencing it.\nMake sure you have not left out an ``{{end}}`` tag." )
return ''
def __repr__(self):
return "%s->%s" % (self.name, self.value)
def output_aux(node, blocks):
# If we have a block level
# If we can override this block.
# Override block from vars.
# Else we take the default
# Else its just a string
return (blocks[node.name].output(blocks)
if node.name in blocks else
node.output(blocks)) \
if isinstance(node, BlockNode) \
else str(node)
class BlockNode(Node):
"""
Block Container.
This Node can contain other Nodes and will render in a hierarchical order
of when nodes were added.
ie::
{{ block test }}
This is default block test
{{ end }}
"""
def __init__(self, name='', pre_extend=False, delimiters=('{{', '}}')):
"""
name - Name of this Node.
"""
self.nodes = []
self.name = name
self.pre_extend = pre_extend
self.left, self.right = delimiters
def __repr__(self):
lines = ['%sblock %s%s' % (self.left, self.name, self.right)]
lines += [str(node) for node in self.nodes]
lines.append('%send%s' % (self.left, self.right))
return ''.join(lines)
def __str__(self):
"""
Get this BlockNodes content, not including child Nodes
"""
return ''.join(str(node) for node in self.nodes
if not isinstance(node, BlockNode))
def append(self, node):
"""
Add an element to the nodes.
Keyword Arguments
- node -- Node object or string to append.
"""
if isinstance(node, str) or isinstance(node, Node):
self.nodes.append(node)
else:
raise TypeError("Invalid type; must be instance of ``str`` or ``BlockNode``. %s" % node)
def extend(self, other):
"""
Extend the list of nodes with another BlockNode class.
Keyword Arguments
- other -- BlockNode or Content object to extend from.
"""
if isinstance(other, BlockNode):
self.nodes.extend(other.nodes)
else:
raise TypeError(
"Invalid type; must be instance of ``BlockNode``. %s" % other)
def output(self, blocks):
"""
Merges all nodes into a single string.
blocks -- Dictionary of blocks that are extending
from this template.
"""
return ''.join(output_aux(node, blocks) for node in self.nodes)
class Content(BlockNode):
"""
Parent Container -- Used as the root level BlockNode.
Contains functions that operate as such.
"""
def __init__(self, name="ContentBlock", pre_extend=False):
"""
Keyword Arguments
name -- Unique name for this BlockNode
"""
self.name = name
self.nodes = []
self.blocks = {}
self.pre_extend = pre_extend
def __str__(self):
return ''.join(output_aux(node, self.blocks) for node in self.nodes)
def _insert(self, other, index=0):
"""
Inserts object at index.
"""
if isinstance(other, (str, Node)):
self.nodes.insert(index, other)
else:
raise TypeError(
"Invalid type, must be instance of ``str`` or ``Node``.")
def insert(self, other, index=0):
"""
Inserts object at index.
You may pass a list of objects and have them inserted.
"""
if isinstance(other, (list, tuple)):
# Must reverse so the order stays the same.
other.reverse()
for item in other:
self._insert(item, index)
else:
self._insert(other, index)
def append(self, node):
"""
Adds a node to list. If it is a BlockNode then we assign a block for it.
"""
if isinstance(node, (str, Node)):
self.nodes.append(node)
if isinstance(node, BlockNode):
self.blocks[node.name] = node
else:
raise TypeError("Invalid type, must be instance of ``str`` or ``BlockNode``. %s" % node)
def extend(self, other):
"""
Extends the objects list of nodes with another objects nodes
"""
if isinstance(other, BlockNode):
self.nodes.extend(other.nodes)
self.blocks.update(other.blocks)
else:
raise TypeError(
"Invalid type; must be instance of ``BlockNode``. %s" % other)
def clear_content(self):
self.nodes = []
class TemplateParser(object):
default_delimiters = ('{{', '}}')
r_tag = compile(r'(\{\{.*?\}\})', DOTALL)
r_multiline = compile(r'(""".*?""")|(\'\'\'.*?\'\'\')', DOTALL)
# These are used for re-indentation.
# Indent + 1
re_block = compile('^(elif |else:|except:|except |finally:).*$', DOTALL)
# Indent - 1
re_unblock = compile('^(return|continue|break|raise)( .*)?$', DOTALL)
# Indent - 1
re_pass = compile('^pass( .*)?$', DOTALL)
def __init__(self, text,
name="ParserContainer",
context=dict(),
path='views/',
writer='response.write',
lexers={},
delimiters=('{{', '}}'),
_super_nodes = [],
):
"""
text -- text to parse
context -- context to parse in
path -- folder path to templates
writer -- string of writer class to use
lexers -- dict of custom lexers to use.
delimiters -- for example ('{{','}}')
_super_nodes -- a list of nodes to check for inclusion
this should only be set by "self.extend"
It contains a list of SuperNodes from a child
template that need to be handled.
"""
# Keep a root level name.
self.name = name
# Raw text to start parsing.
self.text = text
# Writer to use (refer to the default for an example).
# This will end up as
# "%s(%s, escape=False)" % (self.writer, value)
self.writer = writer
# Dictionary of custom name lexers to use.
if isinstance(lexers, dict):
self.lexers = lexers
else:
self.lexers = {}
# Path of templates
self.path = path
# Context for templates.
self.context = context
# allow optional alternative delimiters
self.delimiters = delimiters
if delimiters != self.default_delimiters:
escaped_delimiters = (escape(delimiters[0]),
escape(delimiters[1]))
self.r_tag = compile(r'(%s.*?%s)' % escaped_delimiters, DOTALL)
elif hasattr(context.get('response', None), 'delimiters'):
if context['response'].delimiters != self.default_delimiters:
escaped_delimiters = (
escape(context['response'].delimiters[0]),
escape(context['response'].delimiters[1]))
self.r_tag = compile(r'(%s.*?%s)' % escaped_delimiters,
DOTALL)
# Create a root level Content that everything will go into.
self.content = Content(name=name)
# Stack will hold our current stack of nodes.
# As we descend into a node, it will be added to the stack
# And when we leave, it will be removed from the stack.
# self.content should stay on the stack at all times.
self.stack = [self.content]
# This variable will hold a reference to every super block
# that we come across in this template.
self.super_nodes = []
# This variable will hold a reference to the child
# super nodes that need handling.
self.child_super_nodes = _super_nodes
# This variable will hold a reference to every block
# that we come across in this template
self.blocks = {}
# Begin parsing.
self.parse(text)
def to_string(self):
"""
Return the parsed template with correct indentation.
Used to make it easier to port to python3.
"""
return self.reindent(str(self.content))
def __str__(self):
"Make sure str works exactly the same as python 3"
return self.to_string()
def __unicode__(self):
"Make sure str works exactly the same as python 3"
return self.to_string()
def reindent(self, text):
"""
Reindents a string of unindented python code.
"""
# Get each of our lines into an array.
lines = text.split('\n')
# Our new lines
new_lines = []
# Keeps track of how many indents we have.
# Used for when we need to drop a level of indentation
# only to reindent on the next line.
credit = 0
# Current indentation
k = 0
#################
# THINGS TO KNOW
#################
# k += 1 means indent
# k -= 1 means unindent
# credit = 1 means unindent on the next line.
for raw_line in lines:
line = raw_line.strip()
# ignore empty lines
if not line:
continue
# If we have a line that contains python code that
# should be unindented for this line of code.
# and then reindented for the next line.
if TemplateParser.re_block.match(line):
k = k + credit - 1
# We obviously can't have a negative indentation
k = max(k, 0)
# Add the indentation!
new_lines.append(' ' * (4 * k) + line)
# Bank account back to 0 again :(
credit = 0
# If we are a pass block, we obviously de-dent.
if TemplateParser.re_pass.match(line):
k -= 1
# If we are any of the following, de-dent.
# However, we should stay on the same level
# But the line right after us will be de-dented.
# So we add one credit to keep us at the level
# while moving back one indentation level.
if TemplateParser.re_unblock.match(line):
credit = 1
k -= 1
# If we are an if statement, a try, or a semi-colon we
# probably need to indent the next line.
if line.endswith(':') and not line.startswith('#'):
k += 1
# This must come before so that we can raise an error with the
# right content.
new_text = '\n'.join(new_lines)
if k > 0:
self._raise_error('missing "pass" in view', new_text)
elif k < 0:
self._raise_error('too many "pass" in view', new_text)
return new_text
def _raise_error(self, message='', text=None):
"""
Raise an error using itself as the filename and textual content.
"""
raise RestrictedError(self.name, text or self.text, message)
def _get_file_text(self, filename):
"""
Attempt to open ``filename`` and retrieve its text.
This will use self.path to search for the file.
"""
# If they didn't specify a filename, how can we find one!
if not filename.strip():
self._raise_error('Invalid template filename')
# Allow Views to include other views dynamically
context = self.context
if current and not "response" in context:
context["response"] = getattr(current, 'response', None)
# Get the filename; filename looks like ``"template.html"``.
# We need to eval to remove the quotes and get the string type.
filename = eval(filename, context)
# Get the path of the file on the system.
filepath = self.path and os.path.join(self.path, filename) or filename
# try to read the text.
try:
fileobj = open(filepath, 'rb')
text = fileobj.read()
fileobj.close()
except IOError:
self._raise_error('Unable to open included view file: ' + filepath)
return text
def include(self, content, filename):
"""
Include ``filename`` here.
"""
text = self._get_file_text(filename)
t = TemplateParser(text,
name=filename,
context=self.context,
path=self.path,
writer=self.writer,
delimiters=self.delimiters)
content.append(t.content)
def extend(self, filename):
"""
Extend ``filename``. Anything not declared in a block defined by the
parent will be placed in the parent templates ``{{include}}`` block.
"""
text = self._get_file_text(filename)
# Create out nodes list to send to the parent
super_nodes = []
# We want to include any non-handled nodes.
super_nodes.extend(self.child_super_nodes)
# And our nodes as well.
super_nodes.extend(self.super_nodes)
t = TemplateParser(text,
name=filename,
context=self.context,
path=self.path,
writer=self.writer,
delimiters=self.delimiters,
_super_nodes=super_nodes)
# Make a temporary buffer that is unique for parent
# template.
buf = BlockNode(
name='__include__' + filename, delimiters=self.delimiters)
pre = []
# Iterate through each of our nodes
for node in self.content.nodes:
# If a node is a block
if isinstance(node, BlockNode):
# That happens to be in the parent template
if node.name in t.content.blocks:
# Do not include it
continue
if isinstance(node, Node):
# Or if the node was before the extension
# we should not include it
if node.pre_extend:
pre.append(node)
continue
# Otherwise, it should go int the
# Parent templates {{include}} section.
buf.append(node)
else:
buf.append(node)
# Clear our current nodes. We will be replacing this with
# the parent nodes.
self.content.nodes = []
t_content = t.content
# Set our include, unique by filename
t_content.blocks['__include__' + filename] = buf
# Make sure our pre_extended nodes go first
t_content.insert(pre)
# Then we extend our blocks
t_content.extend(self.content)
# Work off the parent node.
self.content = t_content
def parse(self, text):
# Basically, r_tag.split will split the text into
# an array containing, 'non-tag', 'tag', 'non-tag', 'tag'
# so if we alternate this variable, we know
# what to look for. This is alternate to
# line.startswith("{{")
in_tag = False
extend = None
pre_extend = True
# Use a list to store everything in
# This is because later the code will "look ahead"
# for missing strings or brackets.
ij = self.r_tag.split(text)
# j = current index
# i = current item
stack = self.stack
for j in range(len(ij)):
i = ij[j]
if i:
if not stack:
self._raise_error('The "end" tag is unmatched, please check if you have a starting "block" tag')
# Our current element in the stack.
top = stack[-1]
if in_tag:
line = i
# Get rid of '{{' and '}}'
line = line[2:-2].strip()
# This is bad juju, but let's do it anyway
if not line:
continue
# We do not want to replace the newlines in code,
# only in block comments.
def remove_newline(re_val):
# Take the entire match and replace newlines with
# escaped newlines.
return re_val.group(0).replace('\n', '\\n')
# Perform block comment escaping.
# This performs escaping ON anything
# in between """ and """
line = sub(TemplateParser.r_multiline,
remove_newline,
line)
if line.startswith('='):
# IE: {{=response.title}}
name, value = '=', line[1:].strip()
else:
v = line.split(' ', 1)
if len(v) == 1:
# Example
# {{ include }}
# {{ end }}
name = v[0]
value = ''
else:
# Example
# {{ block pie }}
# {{ include "layout.html" }}
# {{ for i in range(10): }}
name = v[0]
value = v[1]
# This will replace newlines in block comments
# with the newline character. This is so that they
# retain their formatting, but squish down to one
# line in the rendered template.
# First check if we have any custom lexers
if name in self.lexers:
# Pass the information to the lexer
# and allow it to inject in the environment
# You can define custom names such as
# '{{<<variable}}' which could potentially
# write unescaped version of the variable.
self.lexers[name](parser=self,
value=value,
top=top,
stack=stack)
elif name == '=':
# So we have a variable to insert into
# the template
buf = "\n%s(%s)" % (self.writer, value)
top.append(Node(buf, pre_extend=pre_extend))
elif name == 'block' and not value.startswith('='):
# Make a new node with name.
node = BlockNode(name=value.strip(),
pre_extend=pre_extend,
delimiters=self.delimiters)
# Append this node to our active node
top.append(node)
# Make sure to add the node to the stack.
# so anything after this gets added
# to this node. This allows us to
# "nest" nodes.
stack.append(node)
elif name == 'end' and not value.startswith('='):
# We are done with this node.
# Save an instance of it
self.blocks[top.name] = top
# Pop it.
stack.pop()
elif name == 'super' and not value.startswith('='):
# Get our correct target name
# If they just called {{super}} without a name
# attempt to assume the top blocks name.
if value:
target_node = value
else:
target_node = top.name
# Create a SuperNode instance
node = SuperNode(name=target_node,
pre_extend=pre_extend)
# Add this to our list to be taken care of
self.super_nodes.append(node)
# And put in in the tree
top.append(node)
elif name == 'include' and not value.startswith('='):
# If we know the target file to include
if value:
self.include(top, value)
# Otherwise, make a temporary include node
# That the child node will know to hook into.
else:
include_node = BlockNode(
name='__include__' + self.name,
pre_extend=pre_extend,
delimiters=self.delimiters)
top.append(include_node)
elif name == 'extend' and not value.startswith('='):
# We need to extend the following
# template.
extend = value
pre_extend = False
else:
# If we don't know where it belongs
# we just add it anyways without formatting.
if line and in_tag:
# Split on the newlines >.<
tokens = line.split('\n')
# We need to look for any instances of
# for i in range(10):
# = i
# pass
# So we can properly put a response.write() in place.
continuation = False
len_parsed = 0
for k, token in enumerate(tokens):
token = tokens[k] = token.strip()
len_parsed += len(token)
if token.startswith('='):
if token.endswith('\\'):
continuation = True
tokens[k] = "\n%s(%s" % (
self.writer, token[1:].strip())
else:
tokens[k] = "\n%s(%s)" % (
self.writer, token[1:].strip())
elif continuation:
tokens[k] += ')'
continuation = False
buf = "\n%s" % '\n'.join(tokens)
top.append(Node(buf, pre_extend=pre_extend))
else:
# It is HTML so just include it.
buf = "\n%s(%r, escape=False)" % (self.writer, i)
top.append(Node(buf, pre_extend=pre_extend))
# Remember: tag, not tag, tag, not tag
in_tag = not in_tag
# Make a list of items to remove from child
to_rm = []
# Go through each of the children nodes
for node in self.child_super_nodes:
# If we declared a block that this node wants to include
if node.name in self.blocks:
# Go ahead and include it!
node.value = self.blocks[node.name]
# Since we processed this child, we don't need to
# pass it along to the parent
to_rm.append(node)
# Remove some of the processed nodes
for node in to_rm:
# Since this is a pointer, it works beautifully.
# Sometimes I miss C-Style pointers... I want my asterisk...
self.child_super_nodes.remove(node)
# If we need to extend a template.
if extend:
self.extend(extend)
# We need this for integration with gluon
def parse_template(filename,
path='views/',
context=dict(),
lexers={},
delimiters=('{{', '}}')
):
"""
filename can be a view filename in the views folder or an input stream
path is the path of a views folder
context is a dictionary of symbols used to render the template
"""
# First, if we have a str try to open the file
if isinstance(filename, str):
try:
fp = open(os.path.join(path, filename), 'rb')
text = fp.read()
fp.close()
except IOError:
raise RestrictedError(filename, '', 'Unable to find the file')
else:
text = filename.read()
# Use the file contents to get a parsed template and return it.
return str(TemplateParser(text, context=context, path=path, lexers=lexers, delimiters=delimiters))
def get_parsed(text):
"""
Returns the indented python code of text. Useful for unit testing.
"""
return str(TemplateParser(text))
class DummyResponse():
def __init__(self):
self.body = StringIO.StringIO()
def write(self, data, escape=True):
if not escape:
self.body.write(str(data))
elif hasattr(data, 'as_html') and callable(data.as_html):
self.body.write(data.as_html())
else:
# make it a string
if not isinstance(data, (str, unicode)):
data = str(data)
elif isinstance(data, unicode):
data = data.encode('utf8', 'xmlcharrefreplace')
data = cgi.escape(data, True).replace("'", "'")
self.body.write(data)
class NOESCAPE():
"""
A little helper to avoid escaping.
"""
def __init__(self, text):
self.text = text
def xml(self):
return self.text
# And this is a generic render function.
# Here for integration with gluon.
def render(content="hello world",
stream=None,
filename=None,
path=None,
context={},
lexers={},
delimiters=('{{', '}}')
):
"""
>>> render()
'hello world'
>>> render(content='abc')
'abc'
>>> render(content='abc\\'')
"abc'"
>>> render(content='a"\\'bc')
'a"\\'bc'
>>> render(content='a\\nbc')
'a\\nbc'
>>> render(content='a"bcd"e')
'a"bcd"e'
>>> render(content="'''a\\nc'''")
"'''a\\nc'''"
>>> render(content="'''a\\'c'''")
"'''a\'c'''"
>>> render(content='{{for i in range(a):}}{{=i}}<br />{{pass}}', context=dict(a=5))
'0<br />1<br />2<br />3<br />4<br />'
>>> render(content='{%for i in range(a):%}{%=i%}<br />{%pass%}', context=dict(a=5),delimiters=('{%','%}'))
'0<br />1<br />2<br />3<br />4<br />'
>>> render(content="{{='''hello\\nworld'''}}")
'hello\\nworld'
>>> render(content='{{for i in range(3):\\n=i\\npass}}')
'012'
"""
# here to avoid circular Imports
try:
from globals import Response
except ImportError:
# Working standalone. Build a mock Response object.
Response = DummyResponse
# Add it to the context so we can use it.
if not 'NOESCAPE' in context:
context['NOESCAPE'] = NOESCAPE
# save current response class
if context and 'response' in context:
old_response_body = context['response'].body
context['response'].body = StringIO.StringIO()
else:
old_response_body = None
context['response'] = Response()
# If we don't have anything to render, why bother?
if not content and not stream and not filename:
raise SyntaxError("Must specify a stream or filename or content")
# Here for legacy purposes, probably can be reduced to
# something more simple.
close_stream = False
if not stream:
if filename:
stream = open(filename, 'rb')
close_stream = True
elif content:
stream = StringIO.StringIO(content)
# Execute the template.
code = str(TemplateParser(stream.read(
), context=context, path=path, lexers=lexers, delimiters=delimiters))
try:
exec(code) in context
except Exception:
# for i,line in enumerate(code.split('\n')): print i,line
raise
if close_stream:
stream.close()
# Returned the rendered content.
text = context['response'].body.getvalue()
if old_response_body is not None:
context['response'].body = old_response_body
return text
if __name__ == '__main__':
import doctest
doctest.testmod()
| [
[
8,
0,
0.0104,
0.0131,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0185,
0.0011,
0,
0.66,
0.0556,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0196,
0.0011,
0,
0.66... | [
"\"\"\"\nThis file is part of the web2py Web Framework (Copyrighted, 2007-2011).\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\nAuthor: Thadeus Burgess\n\nContributors:",
"import os",
"import cgi",
"import logging",
"from re import compile, sub, escape, DOTALL",
"try:\n import cStringIO as... |
import codecs
import encodings
"""Caller will hand this library a buffer and ask it to either convert
it or auto-detect the type.
Based on http://code.activestate.com/recipes/52257/
Licensed under the PSF License
"""
# None represents a potentially variable byte. "##" in the XML spec...
autodetect_dict = { # bytepattern : ("name",
(0x00, 0x00, 0xFE, 0xFF): ("ucs4_be"),
(0xFF, 0xFE, 0x00, 0x00): ("ucs4_le"),
(0xFE, 0xFF, None, None): ("utf_16_be"),
(0xFF, 0xFE, None, None): ("utf_16_le"),
(0x00, 0x3C, 0x00, 0x3F): ("utf_16_be"),
(0x3C, 0x00, 0x3F, 0x00): ("utf_16_le"),
(0x3C, 0x3F, 0x78, 0x6D): ("utf_8"),
(0x4C, 0x6F, 0xA7, 0x94): ("EBCDIC")
}
def autoDetectXMLEncoding(buffer):
""" buffer -> encoding_name
The buffer should be at least 4 bytes long.
Returns None if encoding cannot be detected.
Note that encoding_name might not have an installed
decoder (e.g. EBCDIC)
"""
# a more efficient implementation would not decode the whole
# buffer at once but otherwise we'd have to decode a character at
# a time looking for the quote character...that's a pain
encoding = "utf_8" # according to the XML spec, this is the default
# this code successively tries to refine the default
# whenever it fails to refine, it falls back to
# the last place encoding was set.
if len(buffer) >= 4:
bytes = (byte1, byte2, byte3, byte4) = tuple(map(ord, buffer[0:4]))
enc_info = autodetect_dict.get(bytes, None)
if not enc_info: # try autodetection again removing potentially
# variable bytes
bytes = (byte1, byte2, None, None)
enc_info = autodetect_dict.get(bytes)
else:
enc_info = None
if enc_info:
encoding = enc_info # we've got a guess... these are
#the new defaults
# try to find a more precise encoding using xml declaration
secret_decoder_ring = codecs.lookup(encoding)[1]
(decoded, length) = secret_decoder_ring(buffer)
first_line = decoded.split("\n")[0]
if first_line and first_line.startswith(u"<?xml"):
encoding_pos = first_line.find(u"encoding")
if encoding_pos != -1:
# look for double quote
quote_pos = first_line.find('"', encoding_pos)
if quote_pos == -1: # look for single quote
quote_pos = first_line.find("'", encoding_pos)
if quote_pos > -1:
quote_char, rest = (first_line[quote_pos],
first_line[quote_pos + 1:])
encoding = rest[:rest.find(quote_char)]
return encoding
def decoder(buffer):
encoding = autoDetectXMLEncoding(buffer)
return buffer.decode(encoding).encode('utf8')
| [
[
1,
0,
0.013,
0.013,
0,
0.66,
0,
220,
0,
1,
0,
0,
220,
0,
0
],
[
1,
0,
0.026,
0.013,
0,
0.66,
0.2,
786,
0,
1,
0,
0,
786,
0,
0
],
[
8,
0,
0.0909,
0.0909,
0,
0.66,
... | [
"import codecs",
"import encodings",
"\"\"\"Caller will hand this library a buffer and ask it to either convert\nit or auto-detect the type.\n\nBased on http://code.activestate.com/recipes/52257/\n\nLicensed under the PSF License\n\"\"\"",
"autodetect_dict = { # bytepattern : (\"name\",\n ... |
import logging
import os
try:
import Tkinter
except:
Tkinter = None
class MessageBoxHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
def emit(self, record):
if Tkinter:
msg = self.format(record)
root = Tkinter.Tk()
root.wm_title("web2py logger message")
text = Tkinter.Text()
text["height"] = 12
text.insert(0.1, msg)
text.pack()
button = Tkinter.Button(root, text="OK", command=root.destroy)
button.pack()
root.mainloop()
class NotifySendHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
def emit(self, record):
if Tkinter:
msg = self.format(record)
os.system("notify-send '%s'" % msg)
| [
[
1,
0,
0.0286,
0.0286,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0571,
0.0286,
0,
0.66,
0.25,
688,
0,
1,
0,
0,
688,
0,
0
],
[
7,
0,
0.1571,
0.1143,
0,
0.... | [
"import logging",
"import os",
"try:\n import Tkinter\nexcept:\n Tkinter = None",
" import Tkinter",
" Tkinter = None",
"class MessageBoxHandler(logging.Handler):\n def __init__(self):\n logging.Handler.__init__(self)\n\n def emit(self, record):\n if Tkinter:\n m... |
# encoding utf-8
__author__ = "Thadeus Burgess <thadeusb@thadeusb.com>"
# we classify as "non-reserved" those key words that are explicitly known
# to the parser but are allowed as column or table names. Some key words
# that are otherwise non-reserved cannot be used as function or data type n
# ames and are in the nonreserved list. (Most of these words represent
# built-in functions or data types with special syntax. The function
# or type is still available but it cannot be redefined by the user.)
# Labeled "reserved" are those tokens that are not allowed as column or
# table names. Some reserved key words are allowable as names for
# functions or data typesself.
# Note at the bottom of the list is a dict containing references to the
# tuples, and also if you add a list don't forget to remove its default
# set of COMMON.
# Keywords that are adapter specific. Such as a list of "postgresql"
# or "mysql" keywords
# These are keywords that are common to all SQL dialects, and should
# never be used as a table or column. Even if you use one of these
# the cursor will throw an OperationalError for the SQL syntax.
COMMON = set((
'SELECT',
'INSERT',
'DELETE',
'UPDATE',
'DROP',
'CREATE',
'ALTER',
'WHERE',
'FROM',
'INNER',
'JOIN',
'AND',
'OR',
'LIKE',
'ON',
'IN',
'SET',
'BY',
'GROUP',
'ORDER',
'LEFT',
'OUTER',
'IF',
'END',
'THEN',
'LOOP',
'AS',
'ELSE',
'FOR',
'CASE',
'WHEN',
'MIN',
'MAX',
'DISTINCT',
))
POSTGRESQL = set((
'FALSE',
'TRUE',
'ALL',
'ANALYSE',
'ANALYZE',
'AND',
'ANY',
'ARRAY',
'AS',
'ASC',
'ASYMMETRIC',
'AUTHORIZATION',
'BETWEEN',
'BIGINT',
'BINARY',
'BIT',
'BOOLEAN',
'BOTH',
'CASE',
'CAST',
'CHAR',
'CHARACTER',
'CHECK',
'COALESCE',
'COLLATE',
'COLUMN',
'CONSTRAINT',
'CREATE',
'CROSS',
'CURRENT_CATALOG',
'CURRENT_DATE',
'CURRENT_ROLE',
'CURRENT_SCHEMA',
'CURRENT_TIME',
'CURRENT_TIMESTAMP',
'CURRENT_USER',
'DEC',
'DECIMAL',
'DEFAULT',
'DEFERRABLE',
'DESC',
'DISTINCT',
'DO',
'ELSE',
'END',
'EXCEPT',
'EXISTS',
'EXTRACT',
'FETCH',
'FLOAT',
'FOR',
'FOREIGN',
'FREEZE',
'FROM',
'FULL',
'GRANT',
'GREATEST',
'GROUP',
'HAVING',
'ILIKE',
'IN',
'INITIALLY',
'INNER',
'INOUT',
'INT',
'INTEGER',
'INTERSECT',
'INTERVAL',
'INTO',
'IS',
'ISNULL',
'JOIN',
'LEADING',
'LEAST',
'LEFT',
'LIKE',
'LIMIT',
'LOCALTIME',
'LOCALTIMESTAMP',
'NATIONAL',
'NATURAL',
'NCHAR',
'NEW',
'NONE',
'NOT',
'NOTNULL',
'NULL',
'NULLIF',
'NUMERIC',
'OFF',
'OFFSET',
'OLD',
'ON',
'ONLY',
'OR',
'ORDER',
'OUT',
'OUTER',
'OVERLAPS',
'OVERLAY',
'PLACING',
'POSITION',
'PRECISION',
'PRIMARY',
'REAL',
'REFERENCES',
'RETURNING',
'RIGHT',
'ROW',
'SELECT',
'SESSION_USER',
'SETOF',
'SIMILAR',
'SMALLINT',
'SOME',
'SUBSTRING',
'SYMMETRIC',
'TABLE',
'THEN',
'TIME',
'TIMESTAMP',
'TO',
'TRAILING',
'TREAT',
'TRIM',
'UNION',
'UNIQUE',
'USER',
'USING',
'VALUES',
'VARCHAR',
'VARIADIC',
'VERBOSE',
'WHEN',
'WHERE',
'WITH',
'XMLATTRIBUTES',
'XMLCONCAT',
'XMLELEMENT',
'XMLFOREST',
'XMLPARSE',
'XMLPI',
'XMLROOT',
'XMLSERIALIZE',
))
POSTGRESQL_NONRESERVED = set((
'A',
'ABORT',
'ABS',
'ABSENT',
'ABSOLUTE',
'ACCESS',
'ACCORDING',
'ACTION',
'ADA',
'ADD',
'ADMIN',
'AFTER',
'AGGREGATE',
'ALIAS',
'ALLOCATE',
'ALSO',
'ALTER',
'ALWAYS',
'ARE',
'ARRAY_AGG',
'ASENSITIVE',
'ASSERTION',
'ASSIGNMENT',
'AT',
'ATOMIC',
'ATTRIBUTE',
'ATTRIBUTES',
'AVG',
'BACKWARD',
'BASE64',
'BEFORE',
'BEGIN',
'BERNOULLI',
'BIT_LENGTH',
'BITVAR',
'BLOB',
'BOM',
'BREADTH',
'BY',
'C',
'CACHE',
'CALL',
'CALLED',
'CARDINALITY',
'CASCADE',
'CASCADED',
'CATALOG',
'CATALOG_NAME',
'CEIL',
'CEILING',
'CHAIN',
'CHAR_LENGTH',
'CHARACTER_LENGTH',
'CHARACTER_SET_CATALOG',
'CHARACTER_SET_NAME',
'CHARACTER_SET_SCHEMA',
'CHARACTERISTICS',
'CHARACTERS',
'CHECKED',
'CHECKPOINT',
'CLASS',
'CLASS_ORIGIN',
'CLOB',
'CLOSE',
'CLUSTER',
'COBOL',
'COLLATION',
'COLLATION_CATALOG',
'COLLATION_NAME',
'COLLATION_SCHEMA',
'COLLECT',
'COLUMN_NAME',
'COLUMNS',
'COMMAND_FUNCTION',
'COMMAND_FUNCTION_CODE',
'COMMENT',
'COMMIT',
'COMMITTED',
'COMPLETION',
'CONCURRENTLY',
'CONDITION',
'CONDITION_NUMBER',
'CONFIGURATION',
'CONNECT',
'CONNECTION',
'CONNECTION_NAME',
'CONSTRAINT_CATALOG',
'CONSTRAINT_NAME',
'CONSTRAINT_SCHEMA',
'CONSTRAINTS',
'CONSTRUCTOR',
'CONTAINS',
'CONTENT',
'CONTINUE',
'CONVERSION',
'CONVERT',
'COPY',
'CORR',
'CORRESPONDING',
'COST',
'COUNT',
'COVAR_POP',
'COVAR_SAMP',
'CREATEDB',
'CREATEROLE',
'CREATEUSER',
'CSV',
'CUBE',
'CUME_DIST',
'CURRENT',
'CURRENT_DEFAULT_TRANSFORM_GROUP',
'CURRENT_PATH',
'CURRENT_TRANSFORM_GROUP_FOR_TYPE',
'CURSOR',
'CURSOR_NAME',
'CYCLE',
'DATA',
'DATABASE',
'DATE',
'DATETIME_INTERVAL_CODE',
'DATETIME_INTERVAL_PRECISION',
'DAY',
'DEALLOCATE',
'DECLARE',
'DEFAULTS',
'DEFERRED',
'DEFINED',
'DEFINER',
'DEGREE',
'DELETE',
'DELIMITER',
'DELIMITERS',
'DENSE_RANK',
'DEPTH',
'DEREF',
'DERIVED',
'DESCRIBE',
'DESCRIPTOR',
'DESTROY',
'DESTRUCTOR',
'DETERMINISTIC',
'DIAGNOSTICS',
'DICTIONARY',
'DISABLE',
'DISCARD',
'DISCONNECT',
'DISPATCH',
'DOCUMENT',
'DOMAIN',
'DOUBLE',
'DROP',
'DYNAMIC',
'DYNAMIC_FUNCTION',
'DYNAMIC_FUNCTION_CODE',
'EACH',
'ELEMENT',
'EMPTY',
'ENABLE',
'ENCODING',
'ENCRYPTED',
'END-EXEC',
'ENUM',
'EQUALS',
'ESCAPE',
'EVERY',
'EXCEPTION',
'EXCLUDE',
'EXCLUDING',
'EXCLUSIVE',
'EXEC',
'EXECUTE',
'EXISTING',
'EXP',
'EXPLAIN',
'EXTERNAL',
'FAMILY',
'FILTER',
'FINAL',
'FIRST',
'FIRST_VALUE',
'FLAG',
'FLOOR',
'FOLLOWING',
'FORCE',
'FORTRAN',
'FORWARD',
'FOUND',
'FREE',
'FUNCTION',
'FUSION',
'G',
'GENERAL',
'GENERATED',
'GET',
'GLOBAL',
'GO',
'GOTO',
'GRANTED',
'GROUPING',
'HANDLER',
'HEADER',
'HEX',
'HIERARCHY',
'HOLD',
'HOST',
'HOUR',
# 'ID',
'IDENTITY',
'IF',
'IGNORE',
'IMMEDIATE',
'IMMUTABLE',
'IMPLEMENTATION',
'IMPLICIT',
'INCLUDING',
'INCREMENT',
'INDENT',
'INDEX',
'INDEXES',
'INDICATOR',
'INFIX',
'INHERIT',
'INHERITS',
'INITIALIZE',
'INPUT',
'INSENSITIVE',
'INSERT',
'INSTANCE',
'INSTANTIABLE',
'INSTEAD',
'INTERSECTION',
'INVOKER',
'ISOLATION',
'ITERATE',
'K',
'KEY',
'KEY_MEMBER',
'KEY_TYPE',
'LAG',
'LANCOMPILER',
'LANGUAGE',
'LARGE',
'LAST',
'LAST_VALUE',
'LATERAL',
'LC_COLLATE',
'LC_CTYPE',
'LEAD',
'LENGTH',
'LESS',
'LEVEL',
'LIKE_REGEX',
'LISTEN',
'LN',
'LOAD',
'LOCAL',
'LOCATION',
'LOCATOR',
'LOCK',
'LOGIN',
'LOWER',
'M',
'MAP',
'MAPPING',
'MATCH',
'MATCHED',
'MAX',
'MAX_CARDINALITY',
'MAXVALUE',
'MEMBER',
'MERGE',
'MESSAGE_LENGTH',
'MESSAGE_OCTET_LENGTH',
'MESSAGE_TEXT',
'METHOD',
'MIN',
'MINUTE',
'MINVALUE',
'MOD',
'MODE',
'MODIFIES',
'MODIFY',
'MODULE',
'MONTH',
'MORE',
'MOVE',
'MULTISET',
'MUMPS',
# 'NAME',
'NAMES',
'NAMESPACE',
'NCLOB',
'NESTING',
'NEXT',
'NFC',
'NFD',
'NFKC',
'NFKD',
'NIL',
'NO',
'NOCREATEDB',
'NOCREATEROLE',
'NOCREATEUSER',
'NOINHERIT',
'NOLOGIN',
'NORMALIZE',
'NORMALIZED',
'NOSUPERUSER',
'NOTHING',
'NOTIFY',
'NOWAIT',
'NTH_VALUE',
'NTILE',
'NULLABLE',
'NULLS',
'NUMBER',
'OBJECT',
'OCCURRENCES_REGEX',
'OCTET_LENGTH',
'OCTETS',
'OF',
'OIDS',
'OPEN',
'OPERATION',
'OPERATOR',
'OPTION',
'OPTIONS',
'ORDERING',
'ORDINALITY',
'OTHERS',
'OUTPUT',
'OVER',
'OVERRIDING',
'OWNED',
'OWNER',
'P',
'PAD',
'PARAMETER',
'PARAMETER_MODE',
'PARAMETER_NAME',
'PARAMETER_ORDINAL_POSITION',
'PARAMETER_SPECIFIC_CATALOG',
'PARAMETER_SPECIFIC_NAME',
'PARAMETER_SPECIFIC_SCHEMA',
'PARAMETERS',
'PARSER',
'PARTIAL',
'PARTITION',
'PASCAL',
'PASSING',
# 'PASSWORD',
'PATH',
'PERCENT_RANK',
'PERCENTILE_CONT',
'PERCENTILE_DISC',
'PLANS',
'PLI',
'POSITION_REGEX',
'POSTFIX',
'POWER',
'PRECEDING',
'PREFIX',
'PREORDER',
'PREPARE',
'PREPARED',
'PRESERVE',
'PRIOR',
'PRIVILEGES',
'PROCEDURAL',
'PROCEDURE',
'PUBLIC',
'QUOTE',
'RANGE',
'RANK',
'READ',
'READS',
'REASSIGN',
'RECHECK',
'RECURSIVE',
'REF',
'REFERENCING',
'REGR_AVGX',
'REGR_AVGY',
'REGR_COUNT',
'REGR_INTERCEPT',
'REGR_R2',
'REGR_SLOPE',
'REGR_SXX',
'REGR_SXY',
'REGR_SYY',
'REINDEX',
'RELATIVE',
'RELEASE',
'RENAME',
'REPEATABLE',
'REPLACE',
'REPLICA',
'RESET',
'RESPECT',
'RESTART',
'RESTRICT',
'RESULT',
'RETURN',
'RETURNED_CARDINALITY',
'RETURNED_LENGTH',
'RETURNED_OCTET_LENGTH',
'RETURNED_SQLSTATE',
'RETURNS',
'REVOKE',
# 'ROLE',
'ROLLBACK',
'ROLLUP',
'ROUTINE',
'ROUTINE_CATALOG',
'ROUTINE_NAME',
'ROUTINE_SCHEMA',
'ROW_COUNT',
'ROW_NUMBER',
'ROWS',
'RULE',
'SAVEPOINT',
'SCALE',
'SCHEMA',
'SCHEMA_NAME',
'SCOPE',
'SCOPE_CATALOG',
'SCOPE_NAME',
'SCOPE_SCHEMA',
'SCROLL',
'SEARCH',
'SECOND',
'SECTION',
'SECURITY',
'SELF',
'SENSITIVE',
'SEQUENCE',
'SERIALIZABLE',
'SERVER',
'SERVER_NAME',
'SESSION',
'SET',
'SETS',
'SHARE',
'SHOW',
'SIMPLE',
'SIZE',
'SOURCE',
'SPACE',
'SPECIFIC',
'SPECIFIC_NAME',
'SPECIFICTYPE',
'SQL',
'SQLCODE',
'SQLERROR',
'SQLEXCEPTION',
'SQLSTATE',
'SQLWARNING',
'SQRT',
'STABLE',
'STANDALONE',
'START',
'STATE',
'STATEMENT',
'STATIC',
'STATISTICS',
'STDDEV_POP',
'STDDEV_SAMP',
'STDIN',
'STDOUT',
'STORAGE',
'STRICT',
'STRIP',
'STRUCTURE',
'STYLE',
'SUBCLASS_ORIGIN',
'SUBLIST',
'SUBMULTISET',
'SUBSTRING_REGEX',
'SUM',
'SUPERUSER',
'SYSID',
'SYSTEM',
'SYSTEM_USER',
'T',
# 'TABLE_NAME',
'TABLESAMPLE',
'TABLESPACE',
'TEMP',
'TEMPLATE',
'TEMPORARY',
'TERMINATE',
'TEXT',
'THAN',
'TIES',
'TIMEZONE_HOUR',
'TIMEZONE_MINUTE',
'TOP_LEVEL_COUNT',
'TRANSACTION',
'TRANSACTION_ACTIVE',
'TRANSACTIONS_COMMITTED',
'TRANSACTIONS_ROLLED_BACK',
'TRANSFORM',
'TRANSFORMS',
'TRANSLATE',
'TRANSLATE_REGEX',
'TRANSLATION',
'TRIGGER',
'TRIGGER_CATALOG',
'TRIGGER_NAME',
'TRIGGER_SCHEMA',
'TRIM_ARRAY',
'TRUNCATE',
'TRUSTED',
'TYPE',
'UESCAPE',
'UNBOUNDED',
'UNCOMMITTED',
'UNDER',
'UNENCRYPTED',
'UNKNOWN',
'UNLISTEN',
'UNNAMED',
'UNNEST',
'UNTIL',
'UNTYPED',
'UPDATE',
'UPPER',
'URI',
'USAGE',
'USER_DEFINED_TYPE_CATALOG',
'USER_DEFINED_TYPE_CODE',
'USER_DEFINED_TYPE_NAME',
'USER_DEFINED_TYPE_SCHEMA',
'VACUUM',
'VALID',
'VALIDATOR',
'VALUE',
'VAR_POP',
'VAR_SAMP',
'VARBINARY',
'VARIABLE',
'VARYING',
'VERSION',
'VIEW',
'VOLATILE',
'WHENEVER',
'WHITESPACE',
'WIDTH_BUCKET',
'WINDOW',
'WITHIN',
'WITHOUT',
'WORK',
'WRAPPER',
'WRITE',
'XML',
'XMLAGG',
'XMLBINARY',
'XMLCAST',
'XMLCOMMENT',
'XMLDECLARATION',
'XMLDOCUMENT',
'XMLEXISTS',
'XMLITERATE',
'XMLNAMESPACES',
'XMLQUERY',
'XMLSCHEMA',
'XMLTABLE',
'XMLTEXT',
'XMLVALIDATE',
'YEAR',
'YES',
'ZONE',
))
#Thanks villas
FIREBIRD = set((
'ABS',
'ACTIVE',
'ADMIN',
'AFTER',
'ASCENDING',
'AUTO',
'AUTODDL',
'BASED',
'BASENAME',
'BASE_NAME',
'BEFORE',
'BIT_LENGTH',
'BLOB',
'BLOBEDIT',
'BOOLEAN',
'BOTH',
'BUFFER',
'CACHE',
'CHAR_LENGTH',
'CHARACTER_LENGTH',
'CHECK_POINT_LEN',
'CHECK_POINT_LENGTH',
'CLOSE',
'COMMITTED',
'COMPILETIME',
'COMPUTED',
'CONDITIONAL',
'CONNECT',
'CONTAINING',
'CROSS',
'CSTRING',
'CURRENT_CONNECTION',
'CURRENT_ROLE',
'CURRENT_TRANSACTION',
'CURRENT_USER',
'DATABASE',
'DB_KEY',
'DEBUG',
'DESCENDING',
'DISCONNECT',
'DISPLAY',
'DO',
'ECHO',
'EDIT',
'ENTRY_POINT',
'EVENT',
'EXIT',
'EXTERN',
'FALSE',
'FETCH',
'FILE',
'FILTER',
'FREE_IT',
'FUNCTION',
'GDSCODE',
'GENERATOR',
'GEN_ID',
'GLOBAL',
'GROUP_COMMIT_WAIT',
'GROUP_COMMIT_WAIT_TIME',
'HELP',
'IF',
'INACTIVE',
'INDEX',
'INIT',
'INPUT_TYPE',
'INSENSITIVE',
'ISQL',
'LC_MESSAGES',
'LC_TYPE',
'LEADING',
'LENGTH',
'LEV',
'LOGFILE',
'LOG_BUFFER_SIZE',
'LOG_BUF_SIZE',
'LONG',
'LOWER',
'MANUAL',
'MAXIMUM',
'MAXIMUM_SEGMENT',
'MAX_SEGMENT',
'MERGE',
'MESSAGE',
'MINIMUM',
'MODULE_NAME',
'NOAUTO',
'NUM_LOG_BUFS',
'NUM_LOG_BUFFERS',
'OCTET_LENGTH',
'OPEN',
'OUTPUT_TYPE',
'OVERFLOW',
'PAGE',
'PAGELENGTH',
'PAGES',
'PAGE_SIZE',
'PARAMETER',
# 'PASSWORD',
'PLAN',
'POST_EVENT',
'QUIT',
'RAW_PARTITIONS',
'RDB$DB_KEY',
'RECORD_VERSION',
'RECREATE',
'RECURSIVE',
'RELEASE',
'RESERV',
'RESERVING',
'RETAIN',
'RETURN',
'RETURNING_VALUES',
'RETURNS',
# 'ROLE',
'ROW_COUNT',
'ROWS',
'RUNTIME',
'SAVEPOINT',
'SECOND',
'SENSITIVE',
'SHADOW',
'SHARED',
'SHELL',
'SHOW',
'SINGULAR',
'SNAPSHOT',
'SORT',
'STABILITY',
'START',
'STARTING',
'STARTS',
'STATEMENT',
'STATIC',
'STATISTICS',
'SUB_TYPE',
'SUSPEND',
'TERMINATOR',
'TRAILING',
'TRIGGER',
'TRIM',
'TRUE',
'TYPE',
'UNCOMMITTED',
'UNKNOWN',
'USING',
'VARIABLE',
'VERSION',
'WAIT',
'WEEKDAY',
'WHILE',
'YEARDAY',
))
FIREBIRD_NONRESERVED = set((
'BACKUP',
'BLOCK',
'COALESCE',
'COLLATION',
'COMMENT',
'DELETING',
'DIFFERENCE',
'IIF',
'INSERTING',
'LAST',
'LEAVE',
'LOCK',
'NEXT',
'NULLIF',
'NULLS',
'RESTART',
'RETURNING',
'SCALAR_ARRAY',
'SEQUENCE',
'STATEMENT',
'UPDATING',
'ABS',
'ACCENT',
'ACOS',
'ALWAYS',
'ASCII_CHAR',
'ASCII_VAL',
'ASIN',
'ATAN',
'ATAN2',
'BACKUP',
'BIN_AND',
'BIN_OR',
'BIN_SHL',
'BIN_SHR',
'BIN_XOR',
'BLOCK',
'CEIL',
'CEILING',
'COLLATION',
'COMMENT',
'COS',
'COSH',
'COT',
'DATEADD',
'DATEDIFF',
'DECODE',
'DIFFERENCE',
'EXP',
'FLOOR',
'GEN_UUID',
'GENERATED',
'HASH',
'IIF',
'LIST',
'LN',
'LOG',
'LOG10',
'LPAD',
'MATCHED',
'MATCHING',
'MAXVALUE',
'MILLISECOND',
'MINVALUE',
'MOD',
'NEXT',
'OVERLAY',
'PAD',
'PI',
'PLACING',
'POWER',
'PRESERVE',
'RAND',
'REPLACE',
'RESTART',
'RETURNING',
'REVERSE',
'ROUND',
'RPAD',
'SCALAR_ARRAY',
'SEQUENCE',
'SIGN',
'SIN',
'SINH',
'SPACE',
'SQRT',
'TAN',
'TANH',
'TEMPORARY',
'TRUNC',
'WEEK',
))
# Thanks Jonathan Lundell
MYSQL = set((
'ACCESSIBLE',
'ADD',
'ALL',
'ALTER',
'ANALYZE',
'AND',
'AS',
'ASC',
'ASENSITIVE',
'BEFORE',
'BETWEEN',
'BIGINT',
'BINARY',
'BLOB',
'BOTH',
'BY',
'CALL',
'CASCADE',
'CASE',
'CHANGE',
'CHAR',
'CHARACTER',
'CHECK',
'COLLATE',
'COLUMN',
'CONDITION',
'CONSTRAINT',
'CONTINUE',
'CONVERT',
'CREATE',
'CROSS',
'CURRENT_DATE',
'CURRENT_TIME',
'CURRENT_TIMESTAMP',
'CURRENT_USER',
'CURSOR',
'DATABASE',
'DATABASES',
'DAY_HOUR',
'DAY_MICROSECOND',
'DAY_MINUTE',
'DAY_SECOND',
'DEC',
'DECIMAL',
'DECLARE',
'DEFAULT',
'DELAYED',
'DELETE',
'DESC',
'DESCRIBE',
'DETERMINISTIC',
'DISTINCT',
'DISTINCTROW',
'DIV',
'DOUBLE',
'DROP',
'DUAL',
'EACH',
'ELSE',
'ELSEIF',
'ENCLOSED',
'ESCAPED',
'EXISTS',
'EXIT',
'EXPLAIN',
'FALSE',
'FETCH',
'FLOAT',
'FLOAT4',
'FLOAT8',
'FOR',
'FORCE',
'FOREIGN',
'FROM',
'FULLTEXT',
'GRANT',
'GROUP',
'HAVING',
'HIGH_PRIORITY',
'HOUR_MICROSECOND',
'HOUR_MINUTE',
'HOUR_SECOND',
'IF',
'IGNORE',
'IGNORE_SERVER_IDS',
'IGNORE_SERVER_IDS',
'IN',
'INDEX',
'INFILE',
'INNER',
'INOUT',
'INSENSITIVE',
'INSERT',
'INT',
'INT1',
'INT2',
'INT3',
'INT4',
'INT8',
'INTEGER',
'INTERVAL',
'INTO',
'IS',
'ITERATE',
'JOIN',
'KEY',
'KEYS',
'KILL',
'LEADING',
'LEAVE',
'LEFT',
'LIKE',
'LIMIT',
'LINEAR',
'LINES',
'LOAD',
'LOCALTIME',
'LOCALTIMESTAMP',
'LOCK',
'LONG',
'LONGBLOB',
'LONGTEXT',
'LOOP',
'LOW_PRIORITY',
'MASTER_HEARTBEAT_PERIOD',
'MASTER_HEARTBEAT_PERIOD',
'MASTER_SSL_VERIFY_SERVER_CERT',
'MATCH',
'MAXVALUE',
'MAXVALUE',
'MEDIUMBLOB',
'MEDIUMINT',
'MEDIUMTEXT',
'MIDDLEINT',
'MINUTE_MICROSECOND',
'MINUTE_SECOND',
'MOD',
'MODIFIES',
'NATURAL',
'NO_WRITE_TO_BINLOG',
'NOT',
'NULL',
'NUMERIC',
'ON',
'OPTIMIZE',
'OPTION',
'OPTIONALLY',
'OR',
'ORDER',
'OUT',
'OUTER',
'OUTFILE',
'PRECISION',
'PRIMARY',
'PROCEDURE',
'PURGE',
'RANGE',
'READ',
'READ_WRITE',
'READS',
'REAL',
'REFERENCES',
'REGEXP',
'RELEASE',
'RENAME',
'REPEAT',
'REPLACE',
'REQUIRE',
'RESIGNAL',
'RESIGNAL',
'RESTRICT',
'RETURN',
'REVOKE',
'RIGHT',
'RLIKE',
'SCHEMA',
'SCHEMAS',
'SECOND_MICROSECOND',
'SELECT',
'SENSITIVE',
'SEPARATOR',
'SET',
'SHOW',
'SIGNAL',
'SIGNAL',
'SMALLINT',
'SPATIAL',
'SPECIFIC',
'SQL',
'SQL_BIG_RESULT',
'SQL_CALC_FOUND_ROWS',
'SQL_SMALL_RESULT',
'SQLEXCEPTION',
'SQLSTATE',
'SQLWARNING',
'SSL',
'STARTING',
'STRAIGHT_JOIN',
'TABLE',
'TERMINATED',
'THEN',
'TINYBLOB',
'TINYINT',
'TINYTEXT',
'TO',
'TRAILING',
'TRIGGER',
'TRUE',
'UNDO',
'UNION',
'UNIQUE',
'UNLOCK',
'UNSIGNED',
'UPDATE',
'USAGE',
'USE',
'USING',
'UTC_DATE',
'UTC_TIME',
'UTC_TIMESTAMP',
'VALUES',
'VARBINARY',
'VARCHAR',
'VARCHARACTER',
'VARYING',
'WHEN',
'WHERE',
'WHILE',
'WITH',
'WRITE',
'XOR',
'YEAR_MONTH',
'ZEROFILL',
))
MSSQL = set((
'ADD',
'ALL',
'ALTER',
'AND',
'ANY',
'AS',
'ASC',
'AUTHORIZATION',
'BACKUP',
'BEGIN',
'BETWEEN',
'BREAK',
'BROWSE',
'BULK',
'BY',
'CASCADE',
'CASE',
'CHECK',
'CHECKPOINT',
'CLOSE',
'CLUSTERED',
'COALESCE',
'COLLATE',
'COLUMN',
'COMMIT',
'COMPUTE',
'CONSTRAINT',
'CONTAINS',
'CONTAINSTABLE',
'CONTINUE',
'CONVERT',
'CREATE',
'CROSS',
'CURRENT',
'CURRENT_DATE',
'CURRENT_TIME',
'CURRENT_TIMESTAMP',
'CURRENT_USER',
'CURSOR',
'DATABASE',
'DBCC',
'DEALLOCATE',
'DECLARE',
'DEFAULT',
'DELETE',
'DENY',
'DESC',
'DISK',
'DISTINCT',
'DISTRIBUTED',
'DOUBLE',
'DROP',
'DUMMY',
'DUMP',
'ELSE',
'END',
'ERRLVL',
'ESCAPE',
'EXCEPT',
'EXEC',
'EXECUTE',
'EXISTS',
'EXIT',
'FETCH',
'FILE',
'FILLFACTOR',
'FOR',
'FOREIGN',
'FREETEXT',
'FREETEXTTABLE',
'FROM',
'FULL',
'FUNCTION',
'GOTO',
'GRANT',
'GROUP',
'HAVING',
'HOLDLOCK',
'IDENTITY',
'IDENTITY_INSERT',
'IDENTITYCOL',
'IF',
'IN',
'INDEX',
'INNER',
'INSERT',
'INTERSECT',
'INTO',
'IS',
'JOIN',
'KEY',
'KILL',
'LEFT',
'LIKE',
'LINENO',
'LOAD',
'NATIONAL ',
'NOCHECK',
'NONCLUSTERED',
'NOT',
'NULL',
'NULLIF',
'OF',
'OFF',
'OFFSETS',
'ON',
'OPEN',
'OPENDATASOURCE',
'OPENQUERY',
'OPENROWSET',
'OPENXML',
'OPTION',
'OR',
'ORDER',
'OUTER',
'OVER',
'PERCENT',
'PLAN',
'PRECISION',
'PRIMARY',
'PRINT',
'PROC',
'PROCEDURE',
'PUBLIC',
'RAISERROR',
'READ',
'READTEXT',
'RECONFIGURE',
'REFERENCES',
'REPLICATION',
'RESTORE',
'RESTRICT',
'RETURN',
'REVOKE',
'RIGHT',
'ROLLBACK',
'ROWCOUNT',
'ROWGUIDCOL',
'RULE',
'SAVE',
'SCHEMA',
'SELECT',
'SESSION_USER',
'SET',
'SETUSER',
'SHUTDOWN',
'SOME',
'STATISTICS',
'SYSTEM_USER',
'TABLE',
'TEXTSIZE',
'THEN',
'TO',
'TOP',
'TRAN',
'TRANSACTION',
'TRIGGER',
'TRUNCATE',
'TSEQUAL',
'UNION',
'UNIQUE',
'UPDATE',
'UPDATETEXT',
'USE',
'USER',
'VALUES',
'VARYING',
'VIEW',
'WAITFOR',
'WHEN',
'WHERE',
'WHILE',
'WITH',
'WRITETEXT',
))
ORACLE = set((
'ACCESS',
'ADD',
'ALL',
'ALTER',
'AND',
'ANY',
'AS',
'ASC',
'AUDIT',
'BETWEEN',
'BY',
'CHAR',
'CHECK',
'CLUSTER',
'COLUMN',
'COMMENT',
'COMPRESS',
'CONNECT',
'CREATE',
'CURRENT',
'DATE',
'DECIMAL',
'DEFAULT',
'DELETE',
'DESC',
'DISTINCT',
'DROP',
'ELSE',
'EXCLUSIVE',
'EXISTS',
'FILE',
'FLOAT',
'FOR',
'FROM',
'GRANT',
'GROUP',
'HAVING',
'IDENTIFIED',
'IMMEDIATE',
'IN',
'INCREMENT',
'INDEX',
'INITIAL',
'INSERT',
'INTEGER',
'INTERSECT',
'INTO',
'IS',
'LEVEL',
'LIKE',
'LOCK',
'LONG',
'MAXEXTENTS',
'MINUS',
'MLSLABEL',
'MODE',
'MODIFY',
'NOAUDIT',
'NOCOMPRESS',
'NOT',
'NOWAIT',
'NULL',
'NUMBER',
'OF',
'OFFLINE',
'ON',
'ONLINE',
'OPTION',
'OR',
'ORDER',
'PCTFREE',
'PRIOR',
'PRIVILEGES',
'PUBLIC',
'RAW',
'RENAME',
'RESOURCE',
'REVOKE',
'ROW',
'ROWID',
'ROWNUM',
'ROWS',
'SELECT',
'SESSION',
'SET',
'SHARE',
'SIZE',
'SMALLINT',
'START',
'SUCCESSFUL',
'SYNONYM',
'SYSDATE',
'TABLE',
'THEN',
'TO',
'TRIGGER',
'UID',
'UNION',
'UNIQUE',
'UPDATE',
'USER',
'VALIDATE',
'VALUES',
'VARCHAR',
'VARCHAR2',
'VIEW',
'WHENEVER',
'WHERE',
'WITH',
))
SQLITE = set((
'ABORT',
'ACTION',
'ADD',
'AFTER',
'ALL',
'ALTER',
'ANALYZE',
'AND',
'AS',
'ASC',
'ATTACH',
'AUTOINCREMENT',
'BEFORE',
'BEGIN',
'BETWEEN',
'BY',
'CASCADE',
'CASE',
'CAST',
'CHECK',
'COLLATE',
'COLUMN',
'COMMIT',
'CONFLICT',
'CONSTRAINT',
'CREATE',
'CROSS',
'CURRENT_DATE',
'CURRENT_TIME',
'CURRENT_TIMESTAMP',
'DATABASE',
'DEFAULT',
'DEFERRABLE',
'DEFERRED',
'DELETE',
'DESC',
'DETACH',
'DISTINCT',
'DROP',
'EACH',
'ELSE',
'END',
'ESCAPE',
'EXCEPT',
'EXCLUSIVE',
'EXISTS',
'EXPLAIN',
'FAIL',
'FOR',
'FOREIGN',
'FROM',
'FULL',
'GLOB',
'GROUP',
'HAVING',
'IF',
'IGNORE',
'IMMEDIATE',
'IN',
'INDEX',
'INDEXED',
'INITIALLY',
'INNER',
'INSERT',
'INSTEAD',
'INTERSECT',
'INTO',
'IS',
'ISNULL',
'JOIN',
'KEY',
'LEFT',
'LIKE',
'LIMIT',
'MATCH',
'NATURAL',
'NO',
'NOT',
'NOTNULL',
'NULL',
'OF',
'OFFSET',
'ON',
'OR',
'ORDER',
'OUTER',
'PLAN',
'PRAGMA',
'PRIMARY',
'QUERY',
'RAISE',
'REFERENCES',
'REGEXP',
'REINDEX',
'RELEASE',
'RENAME',
'REPLACE',
'RESTRICT',
'RIGHT',
'ROLLBACK',
'ROW',
'SAVEPOINT',
'SELECT',
'SET',
'TABLE',
'TEMP',
'TEMPORARY',
'THEN',
'TO',
'TRANSACTION',
'TRIGGER',
'UNION',
'UNIQUE',
'UPDATE',
'USING',
'VACUUM',
'VALUES',
'VIEW',
'VIRTUAL',
'WHEN',
'WHERE',
))
MONGODB_NONRESERVED = set(('SAFE',))
# remove from here when you add a list.
JDBCSQLITE = SQLITE
DB2 = INFORMIX = INGRES = JDBCPOSTGRESQL = COMMON
ADAPTERS = {
'sqlite': SQLITE,
'mysql': MYSQL,
'postgres': POSTGRESQL,
'postgres_nonreserved': POSTGRESQL_NONRESERVED,
'oracle': ORACLE,
'mssql': MSSQL,
'mssql2': MSSQL,
'db2': DB2,
'informix': INFORMIX,
'firebird': FIREBIRD,
'firebird_embedded': FIREBIRD,
'firebird_nonreserved': FIREBIRD_NONRESERVED,
'ingres': INGRES,
'ingresu': INGRES,
'jdbc:sqlite': JDBCSQLITE,
'jdbc:postgres': JDBCPOSTGRESQL,
'common': COMMON,
'mongodb_nonreserved': MONGODB_NONRESERVED
}
ADAPTERS['all'] = reduce(lambda a, b: a.union(b), (
x for x in ADAPTERS.values()))
| [
[
14,
0,
0.0017,
0.0006,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0259,
0.0233,
0,
0.66,
0.0714,
63,
3,
1,
0,
0,
21,
10,
1
],
[
14,
0,
0.0812,
0.085,
0,
0... | [
"__author__ = \"Thadeus Burgess <thadeusb@thadeusb.com>\"",
"COMMON = set((\n 'SELECT',\n 'INSERT',\n 'DELETE',\n 'UPDATE',\n 'DROP',\n 'CREATE',\n 'ALTER',",
"POSTGRESQL = set((\n 'FALSE',\n 'TRUE',\n 'ALL',\n 'ANALYSE',\n 'ANALYZE',\n 'AND',\n 'ANY',",
"POSTGRESQL_N... |
# -*- coding: utf-8 -*-
# This file is part of the Rocket Web Server
# Copyright (c) 2011 Timothy Farrell
# Modified by Massimo Di Pierro
# Import System Modules
import sys
import errno
import socket
import logging
import platform
# Define Constants
VERSION = '1.2.6'
SERVER_NAME = socket.gethostname()
SERVER_SOFTWARE = 'Rocket %s' % VERSION
HTTP_SERVER_SOFTWARE = '%s Python/%s' % (
SERVER_SOFTWARE, sys.version.split(' ')[0])
BUF_SIZE = 16384
SOCKET_TIMEOUT = 10 # in secs
THREAD_STOP_CHECK_INTERVAL = 1 # in secs, How often should threads check for a server stop message?
IS_JYTHON = platform.system() == 'Java' # Handle special cases for Jython
IGNORE_ERRORS_ON_CLOSE = set([errno.ECONNABORTED, errno.ECONNRESET])
DEFAULT_LISTEN_QUEUE_SIZE = 5
DEFAULT_MIN_THREADS = 10
DEFAULT_MAX_THREADS = 0
DEFAULTS = dict(LISTEN_QUEUE_SIZE=DEFAULT_LISTEN_QUEUE_SIZE,
MIN_THREADS=DEFAULT_MIN_THREADS,
MAX_THREADS=DEFAULT_MAX_THREADS)
PY3K = sys.version_info[0] > 2
class NullHandler(logging.Handler):
"A Logging handler to prevent library errors."
def emit(self, record):
pass
if PY3K:
def b(val):
""" Convert string/unicode/bytes literals into bytes. This allows for
the same code to run on Python 2.x and 3.x. """
if isinstance(val, str):
return val.encode()
else:
return val
def u(val, encoding="us-ascii"):
""" Convert bytes into string/unicode. This allows for the
same code to run on Python 2.x and 3.x. """
if isinstance(val, bytes):
return val.decode(encoding)
else:
return val
else:
def b(val):
""" Convert string/unicode/bytes literals into bytes. This allows for
the same code to run on Python 2.x and 3.x. """
if isinstance(val, unicode):
return val.encode()
else:
return val
def u(val, encoding="us-ascii"):
""" Convert bytes into string/unicode. This allows for the
same code to run on Python 2.x and 3.x. """
if isinstance(val, str):
return val.decode(encoding)
else:
return val
# Import Package Modules
# package imports removed in monolithic build
__all__ = ['VERSION', 'SERVER_SOFTWARE', 'HTTP_SERVER_SOFTWARE', 'BUF_SIZE',
'IS_JYTHON', 'IGNORE_ERRORS_ON_CLOSE', 'DEFAULTS', 'PY3K', 'b', 'u',
'Rocket', 'CherryPyWSGIServer', 'SERVER_NAME', 'NullHandler']
# Monolithic build...end of module: rocket/__init__.py
# Monolithic build...start of module: rocket/connection.py
# Import System Modules
import sys
import time
import socket
try:
import ssl
has_ssl = True
except ImportError:
has_ssl = False
# Import Package Modules
# package imports removed in monolithic build
# TODO - This part is still very experimental.
#from .filelike import FileLikeSocket
class Connection(object):
__slots__ = [
'setblocking',
'sendall',
'shutdown',
'makefile',
'fileno',
'client_addr',
'client_port',
'server_port',
'socket',
'start_time',
'ssl',
'secure',
'recv',
'send',
'read',
'write'
]
def __init__(self, sock_tuple, port, secure=False):
self.client_addr, self.client_port = sock_tuple[1][:2]
self.server_port = port
self.socket = sock_tuple[0]
self.start_time = time.time()
self.ssl = has_ssl and isinstance(self.socket, ssl.SSLSocket)
self.secure = secure
if IS_JYTHON:
# In Jython we must set TCP_NODELAY here since it does not
# inherit from the listening socket.
# See: http://bugs.jython.org/issue1309
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.socket.settimeout(SOCKET_TIMEOUT)
self.shutdown = self.socket.shutdown
self.fileno = self.socket.fileno
self.setblocking = self.socket.setblocking
self.recv = self.socket.recv
self.send = self.socket.send
self.makefile = self.socket.makefile
if sys.platform == 'darwin':
self.sendall = self._sendall_darwin
else:
self.sendall = self.socket.sendall
def _sendall_darwin(self, buf):
pending = len(buf)
offset = 0
while pending:
try:
sent = self.socket.send(buf[offset:])
pending -= sent
offset += sent
except socket.error:
import errno
info = sys.exc_info()
if info[1].args[0] != errno.EAGAIN:
raise
return offset
# FIXME - this is not ready for prime-time yet.
# def makefile(self, buf_size=BUF_SIZE):
# return FileLikeSocket(self, buf_size)
def close(self):
if hasattr(self.socket, '_sock'):
try:
self.socket._sock.close()
except socket.error:
info = sys.exc_info()
if info[1].args[0] != socket.EBADF:
raise info[1]
else:
pass
self.socket.close()
# Monolithic build...end of module: rocket/connection.py
# Monolithic build...start of module: rocket/filelike.py
# Import System Modules
import socket
try:
from io import StringIO
except ImportError:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
# Import Package Modules
# package imports removed in monolithic build
class FileLikeSocket(object):
def __init__(self, conn, buf_size=BUF_SIZE):
self.conn = conn
self.buf_size = buf_size
self.buffer = StringIO()
self.content_length = None
if self.conn.socket.gettimeout() == 0.0:
self.read = self.non_blocking_read
else:
self.read = self.blocking_read
def __iter__(self):
return self
def recv(self, size):
while True:
try:
return self.conn.recv(size)
except socket.error:
exc = sys.exc_info()
e = exc[1]
# FIXME - Don't raise socket_errors_nonblocking or socket_error_eintr
if (e.args[0] not in set()):
raise
def next(self):
data = self.readline()
if data == '':
raise StopIteration
return data
def non_blocking_read(self, size=None):
# Shamelessly adapted from Cherrypy!
bufr = self.buffer
bufr.seek(0, 2)
if size is None:
while True:
data = self.recv(self.buf_size)
if not data:
break
bufr.write(data)
self.buffer = StringIO()
return bufr.getvalue()
else:
buf_len = self.buffer.tell()
if buf_len >= size:
bufr.seek(0)
data = bufr.read(size)
self.buffer = StringIO(bufr.read())
return data
self.buffer = StringIO()
while True:
remaining = size - buf_len
data = self.recv(remaining)
if not data:
break
n = len(data)
if n == size and not buf_len:
return data
if n == remaining:
bufr.write(data)
del data
break
bufr.write(data)
buf_len += n
del data
return bufr.getvalue()
def blocking_read(self, length=None):
if length is None:
if self.content_length is not None:
length = self.content_length
else:
length = 1
try:
data = self.conn.recv(length)
except:
data = b('')
return data
def readline(self):
data = b("")
char = self.read(1)
while char != b('\n') and char is not b(''):
line = repr(char)
data += char
char = self.read(1)
data += char
return data
def readlines(self, hint="ignored"):
return list(self)
def close(self):
self.conn = None
self.content_length = None
# Monolithic build...end of module: rocket/filelike.py
# Monolithic build...start of module: rocket/futures.py
# Import System Modules
import time
try:
from concurrent.futures import Future, ThreadPoolExecutor
from concurrent.futures.thread import _WorkItem
has_futures = True
except ImportError:
has_futures = False
class Future:
pass
class ThreadPoolExecutor:
pass
class _WorkItem:
pass
class WSGIFuture(Future):
def __init__(self, f_dict, *args, **kwargs):
Future.__init__(self, *args, **kwargs)
self.timeout = None
self._mem_dict = f_dict
self._lifespan = 30
self._name = None
self._start_time = time.time()
def set_running_or_notify_cancel(self):
if time.time() - self._start_time >= self._lifespan:
self.cancel()
else:
return super(WSGIFuture, self).set_running_or_notify_cancel()
def remember(self, name, lifespan=None):
self._lifespan = lifespan or self._lifespan
if name in self._mem_dict:
raise NameError('Cannot remember future by name "%s". ' % name +
'A future already exists with that name.')
self._name = name
self._mem_dict[name] = self
return self
def forget(self):
if self._name in self._mem_dict and self._mem_dict[self._name] is self:
del self._mem_dict[self._name]
self._name = None
class _WorkItem(object):
def __init__(self, future, fn, args, kwargs):
self.future = future
self.fn = fn
self.args = args
self.kwargs = kwargs
def run(self):
if not self.future.set_running_or_notify_cancel():
return
try:
result = self.fn(*self.args, **self.kwargs)
except BaseException:
e = sys.exc_info()[1]
self.future.set_exception(e)
else:
self.future.set_result(result)
class WSGIExecutor(ThreadPoolExecutor):
multithread = True
multiprocess = False
def __init__(self, *args, **kwargs):
ThreadPoolExecutor.__init__(self, *args, **kwargs)
self.futures = dict()
def submit(self, fn, *args, **kwargs):
if self._shutdown_lock.acquire():
if self._shutdown:
self._shutdown_lock.release()
raise RuntimeError(
'Cannot schedule new futures after shutdown')
f = WSGIFuture(self.futures)
w = _WorkItem(f, fn, args, kwargs)
self._work_queue.put(w)
self._adjust_thread_count()
self._shutdown_lock.release()
return f
else:
return False
class FuturesMiddleware(object):
"Futures middleware that adds a Futures Executor to the environment"
def __init__(self, app, threads=5):
self.app = app
self.executor = WSGIExecutor(threads)
def __call__(self, environ, start_response):
environ["wsgiorg.executor"] = self.executor
environ["wsgiorg.futures"] = self.executor.futures
return self.app(environ, start_response)
# Monolithic build...end of module: rocket/futures.py
# Monolithic build...start of module: rocket/listener.py
# Import System Modules
import os
import socket
import logging
import traceback
from threading import Thread
try:
import ssl
from ssl import SSLError
has_ssl = True
except ImportError:
has_ssl = False
class SSLError(socket.error):
pass
# Import Package Modules
# package imports removed in monolithic build
class Listener(Thread):
"""The Listener class is a class responsible for accepting connections
and queuing them to be processed by a worker thread."""
def __init__(self, interface, queue_size, active_queue, *args, **kwargs):
Thread.__init__(self, *args, **kwargs)
# Instance variables
self.active_queue = active_queue
self.interface = interface
self.addr = interface[0]
self.port = interface[1]
self.secure = len(interface) >= 4
self.clientcert_req = (len(interface) == 5 and interface[4])
self.thread = None
self.ready = False
# Error Log
self.err_log = logging.getLogger('Rocket.Errors.Port%i' % self.port)
self.err_log.addHandler(NullHandler())
# Build the socket
if ':' in self.addr:
listener = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if not listener:
self.err_log.error("Failed to get socket.")
return
if self.secure:
if not has_ssl:
self.err_log.error("ssl module required to serve HTTPS.")
return
elif not os.path.exists(interface[2]):
data = (interface[2], interface[0], interface[1])
self.err_log.error("Cannot find key file "
"'%s'. Cannot bind to %s:%s" % data)
return
elif not os.path.exists(interface[3]):
data = (interface[3], interface[0], interface[1])
self.err_log.error("Cannot find certificate file "
"'%s'. Cannot bind to %s:%s" % data)
return
if self.clientcert_req and not os.path.exists(interface[4]):
data = (interface[4], interface[0], interface[1])
self.err_log.error("Cannot find root ca certificate file "
"'%s'. Cannot bind to %s:%s" % data)
return
# Set socket options
try:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except:
msg = "Cannot share socket. Using %s:%i exclusively."
self.err_log.warning(msg % (self.addr, self.port))
try:
if not IS_JYTHON:
listener.setsockopt(socket.IPPROTO_TCP,
socket.TCP_NODELAY,
1)
except:
msg = "Cannot set TCP_NODELAY, things might run a little slower"
self.err_log.warning(msg)
try:
listener.bind((self.addr, self.port))
except:
msg = "Socket %s:%i in use by other process and it won't share."
self.err_log.error(msg % (self.addr, self.port))
else:
# We want socket operations to timeout periodically so we can
# check if the server is shutting down
listener.settimeout(THREAD_STOP_CHECK_INTERVAL)
# Listen for new connections allowing queue_size number of
# connections to wait before rejecting a connection.
listener.listen(queue_size)
self.listener = listener
self.ready = True
def wrap_socket(self, sock):
try:
if self.clientcert_req:
ca_certs = self.interface[4]
cert_reqs = ssl.CERT_OPTIONAL
sock = ssl.wrap_socket(sock,
keyfile=self.interface[2],
certfile=self.interface[3],
server_side=True,
cert_reqs=cert_reqs,
ca_certs=ca_certs,
ssl_version=ssl.PROTOCOL_SSLv23)
else:
sock = ssl.wrap_socket(sock,
keyfile=self.interface[2],
certfile=self.interface[3],
server_side=True,
ssl_version=ssl.PROTOCOL_SSLv23)
except SSLError:
# Generally this happens when an HTTP request is received on a
# secure socket. We don't do anything because it will be detected
# by Worker and dealt with appropriately.
pass
return sock
def start(self):
if not self.ready:
self.err_log.warning('Listener started when not ready.')
return
if self.thread is not None and self.thread.isAlive():
self.err_log.warning('Listener already running.')
return
self.thread = Thread(target=self.listen, name="Port" + str(self.port))
self.thread.start()
def isAlive(self):
if self.thread is None:
return False
return self.thread.isAlive()
def join(self):
if self.thread is None:
return
self.ready = False
self.thread.join()
del self.thread
self.thread = None
self.ready = True
def listen(self):
if __debug__:
self.err_log.debug('Entering main loop.')
while True:
try:
sock, addr = self.listener.accept()
if self.secure:
sock = self.wrap_socket(sock)
self.active_queue.put(((sock, addr),
self.interface[1],
self.secure))
except socket.timeout:
# socket.timeout will be raised every
# THREAD_STOP_CHECK_INTERVAL seconds. When that happens,
# we check if it's time to die.
if not self.ready:
if __debug__:
self.err_log.debug('Listener exiting.')
return
else:
continue
except:
self.err_log.error(traceback.format_exc())
# Monolithic build...end of module: rocket/listener.py
# Monolithic build...start of module: rocket/main.py
# Import System Modules
import sys
import time
import socket
import logging
import traceback
from threading import Lock
try:
from queue import Queue
except ImportError:
from Queue import Queue
# Import Package Modules
# package imports removed in monolithic build
# Setup Logging
log = logging.getLogger('Rocket')
log.addHandler(NullHandler())
class Rocket(object):
"""The Rocket class is responsible for handling threads and accepting and
dispatching connections."""
def __init__(self,
interfaces=('127.0.0.1', 8000),
method='wsgi',
app_info=None,
min_threads=None,
max_threads=None,
queue_size=None,
timeout=600,
handle_signals=True):
self.handle_signals = handle_signals
self.startstop_lock = Lock()
self.timeout = timeout
if not isinstance(interfaces, list):
self.interfaces = [interfaces]
else:
self.interfaces = interfaces
if min_threads is None:
min_threads = DEFAULTS['MIN_THREADS']
if max_threads is None:
max_threads = DEFAULTS['MAX_THREADS']
if not queue_size:
if hasattr(socket, 'SOMAXCONN'):
queue_size = socket.SOMAXCONN
else:
queue_size = DEFAULTS['LISTEN_QUEUE_SIZE']
if max_threads and queue_size > max_threads:
queue_size = max_threads
if isinstance(app_info, dict):
app_info['server_software'] = SERVER_SOFTWARE
self.monitor_queue = Queue()
self.active_queue = Queue()
self._threadpool = ThreadPool(get_method(method),
app_info=app_info,
active_queue=self.active_queue,
monitor_queue=self.monitor_queue,
min_threads=min_threads,
max_threads=max_threads)
# Build our socket listeners
self.listeners = [Listener(
i, queue_size, self.active_queue) for i in self.interfaces]
for ndx in range(len(self.listeners) - 1, 0, -1):
if not self.listeners[ndx].ready:
del self.listeners[ndx]
if not self.listeners:
log.critical("No interfaces to listen on...closing.")
sys.exit(1)
def _sigterm(self, signum, frame):
log.info('Received SIGTERM')
self.stop()
def _sighup(self, signum, frame):
log.info('Received SIGHUP')
self.restart()
def start(self, background=False):
log.info('Starting %s' % SERVER_SOFTWARE)
self.startstop_lock.acquire()
try:
# Set up our shutdown signals
if self.handle_signals:
try:
import signal
signal.signal(signal.SIGTERM, self._sigterm)
signal.signal(signal.SIGUSR1, self._sighup)
except:
log.debug('This platform does not support signals.')
# Start our worker threads
self._threadpool.start()
# Start our monitor thread
self._monitor = Monitor(self.monitor_queue,
self.active_queue,
self.timeout,
self._threadpool)
self._monitor.setDaemon(True)
self._monitor.start()
# I know that EXPR and A or B is bad but I'm keeping it for Py2.4
# compatibility.
str_extract = lambda l: (l.addr, l.port, l.secure and '*' or '')
msg = 'Listening on sockets: '
msg += ', '.join(
['%s:%i%s' % str_extract(l) for l in self.listeners])
log.info(msg)
for l in self.listeners:
l.start()
finally:
self.startstop_lock.release()
if background:
return
while self._monitor.isAlive():
try:
time.sleep(THREAD_STOP_CHECK_INTERVAL)
except KeyboardInterrupt:
# Capture a keyboard interrupt when running from a console
break
except:
if self._monitor.isAlive():
log.error(traceback.format_exc())
continue
return self.stop()
def stop(self, stoplogging=False):
log.info('Stopping %s' % SERVER_SOFTWARE)
self.startstop_lock.acquire()
try:
# Stop listeners
for l in self.listeners:
l.ready = False
# Encourage a context switch
time.sleep(0.01)
for l in self.listeners:
if l.isAlive():
l.join()
# Stop Monitor
self._monitor.stop()
if self._monitor.isAlive():
self._monitor.join()
# Stop Worker threads
self._threadpool.stop()
if stoplogging:
logging.shutdown()
msg = "Calling logging.shutdown() is now the responsibility of \
the application developer. Please update your \
applications to no longer call rocket.stop(True)"
try:
import warnings
raise warnings.DeprecationWarning(msg)
except ImportError:
raise RuntimeError(msg)
finally:
self.startstop_lock.release()
def restart(self):
self.stop()
self.start()
def CherryPyWSGIServer(bind_addr,
wsgi_app,
numthreads=10,
server_name=None,
max=-1,
request_queue_size=5,
timeout=10,
shutdown_timeout=5):
""" A Cherrypy wsgiserver-compatible wrapper. """
max_threads = max
if max_threads < 0:
max_threads = 0
return Rocket(bind_addr, 'wsgi', {'wsgi_app': wsgi_app},
min_threads=numthreads,
max_threads=max_threads,
queue_size=request_queue_size,
timeout=timeout)
# Monolithic build...end of module: rocket/main.py
# Monolithic build...start of module: rocket/monitor.py
# Import System Modules
import time
import logging
import select
from threading import Thread
# Import Package Modules
# package imports removed in monolithic build
class Monitor(Thread):
# Monitor worker class.
def __init__(self,
monitor_queue,
active_queue,
timeout,
threadpool,
*args,
**kwargs):
Thread.__init__(self, *args, **kwargs)
self._threadpool = threadpool
# Instance Variables
self.monitor_queue = monitor_queue
self.active_queue = active_queue
self.timeout = timeout
self.log = logging.getLogger('Rocket.Monitor')
self.log.addHandler(NullHandler())
self.connections = set()
self.active = False
def run(self):
self.active = True
conn_list = list()
list_changed = False
# We need to make sure the queue is empty before we start
while not self.monitor_queue.empty():
self.monitor_queue.get()
if __debug__:
self.log.debug('Entering monitor loop.')
# Enter thread main loop
while self.active:
# Move the queued connections to the selection pool
while not self.monitor_queue.empty():
if __debug__:
self.log.debug('In "receive timed-out connections" loop.')
c = self.monitor_queue.get()
if c is None:
# A non-client is a signal to die
if __debug__:
self.log.debug('Received a death threat.')
self.stop()
break
self.log.debug('Received a timed out connection.')
if __debug__:
assert(c not in self.connections)
if IS_JYTHON:
# Jython requires a socket to be in Non-blocking mode in
# order to select on it.
c.setblocking(False)
if __debug__:
self.log.debug('Adding connection to monitor list.')
self.connections.add(c)
list_changed = True
# Wait on those connections
if list_changed:
conn_list = list(self.connections)
list_changed = False
try:
if len(conn_list):
readable = select.select(conn_list,
[],
[],
THREAD_STOP_CHECK_INTERVAL)[0]
else:
time.sleep(THREAD_STOP_CHECK_INTERVAL)
readable = []
if not self.active:
break
# If we have any readable connections, put them back
for r in readable:
if __debug__:
self.log.debug('Restoring readable connection')
if IS_JYTHON:
# Jython requires a socket to be in Non-blocking mode in
# order to select on it, but the rest of the code requires
# that it be in blocking mode.
r.setblocking(True)
r.start_time = time.time()
self.active_queue.put(r)
self.connections.remove(r)
list_changed = True
except:
if self.active:
raise
else:
break
# If we have any stale connections, kill them off.
if self.timeout:
now = time.time()
stale = set()
for c in self.connections:
if (now - c.start_time) >= self.timeout:
stale.add(c)
for c in stale:
if __debug__:
# "EXPR and A or B" kept for Py2.4 compatibility
data = (
c.client_addr, c.server_port, c.ssl and '*' or '')
self.log.debug(
'Flushing stale connection: %s:%i%s' % data)
self.connections.remove(c)
list_changed = True
try:
c.close()
finally:
del c
# Dynamically resize the threadpool to adapt to our changing needs.
self._threadpool.dynamic_resize()
def stop(self):
self.active = False
if __debug__:
self.log.debug('Flushing waiting connections')
while self.connections:
c = self.connections.pop()
try:
c.close()
finally:
del c
if __debug__:
self.log.debug('Flushing queued connections')
while not self.monitor_queue.empty():
c = self.monitor_queue.get()
if c is None:
continue
try:
c.close()
finally:
del c
# Place a None sentry value to cause the monitor to die.
self.monitor_queue.put(None)
# Monolithic build...end of module: rocket/monitor.py
# Monolithic build...start of module: rocket/threadpool.py
# Import System Modules
import logging
# Import Package Modules
# package imports removed in monolithic build
# Setup Logging
log = logging.getLogger('Rocket.Errors.ThreadPool')
log.addHandler(NullHandler())
class ThreadPool:
"""The ThreadPool class is a container class for all the worker threads. It
manages the number of actively running threads."""
def __init__(self,
method,
app_info,
active_queue,
monitor_queue,
min_threads=DEFAULTS['MIN_THREADS'],
max_threads=DEFAULTS['MAX_THREADS'],
):
if __debug__:
log.debug("Initializing ThreadPool.")
self.check_for_dead_threads = 0
self.active_queue = active_queue
self.worker_class = method
self.min_threads = min_threads
self.max_threads = max_threads
self.monitor_queue = monitor_queue
self.stop_server = False
self.alive = False
# TODO - Optimize this based on some real-world usage data
self.grow_threshold = int(max_threads / 10) + 2
if not isinstance(app_info, dict):
app_info = dict()
if has_futures and app_info.get('futures'):
app_info['executor'] = WSGIExecutor(max([DEFAULTS['MIN_THREADS'],
2]))
app_info.update(max_threads=max_threads,
min_threads=min_threads)
self.min_threads = min_threads
self.app_info = app_info
self.threads = set()
def start(self):
self.stop_server = False
if __debug__:
log.debug("Starting threads.")
self.grow(self.min_threads)
self.alive = True
def stop(self):
self.alive = False
if __debug__:
log.debug("Stopping threads.")
self.stop_server = True
# Prompt the threads to die
self.shrink(len(self.threads))
# Stop futures initially
if has_futures and self.app_info.get('futures'):
if __debug__:
log.debug("Future executor is present. Python will not "
"exit until all jobs have finished.")
self.app_info['executor'].shutdown(wait=False)
# Give them the gun
#active_threads = [t for t in self.threads if t.isAlive()]
#while active_threads:
# t = active_threads.pop()
# t.kill()
# Wait until they pull the trigger
for t in self.threads:
if t.isAlive():
t.join()
# Clean up the mess
self.bring_out_your_dead()
def bring_out_your_dead(self):
# Remove dead threads from the pool
dead_threads = [t for t in self.threads if not t.isAlive()]
for t in dead_threads:
if __debug__:
log.debug("Removing dead thread: %s." % t.getName())
try:
# Py2.4 complains here so we put it in a try block
self.threads.remove(t)
except:
pass
self.check_for_dead_threads -= len(dead_threads)
def grow(self, amount=None):
if self.stop_server:
return
if not amount:
amount = self.max_threads
if self.alive:
amount = min([amount, self.max_threads - len(self.threads)])
if __debug__:
log.debug("Growing by %i." % amount)
for x in range(amount):
worker = self.worker_class(self.app_info,
self.active_queue,
self.monitor_queue)
worker.setDaemon(True)
self.threads.add(worker)
worker.start()
def shrink(self, amount=1):
if __debug__:
log.debug("Shrinking by %i." % amount)
self.check_for_dead_threads += amount
for x in range(amount):
self.active_queue.put(None)
def dynamic_resize(self):
if (self.max_threads > self.min_threads or self.max_threads == 0):
if self.check_for_dead_threads > 0:
self.bring_out_your_dead()
queueSize = self.active_queue.qsize()
threadCount = len(self.threads)
if __debug__:
log.debug("Examining ThreadPool. %i threads and %i Q'd conxions"
% (threadCount, queueSize))
if queueSize == 0 and threadCount > self.min_threads:
self.shrink()
elif queueSize > self.grow_threshold:
self.grow(queueSize)
# Monolithic build...end of module: rocket/threadpool.py
# Monolithic build...start of module: rocket/worker.py
# Import System Modules
import re
import sys
import socket
import logging
import traceback
from wsgiref.headers import Headers
from threading import Thread
from datetime import datetime
try:
from urllib import unquote
except ImportError:
from urllib.parse import unquote
try:
from io import StringIO
except ImportError:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
try:
from ssl import SSLError
except ImportError:
class SSLError(socket.error):
pass
# Import Package Modules
# package imports removed in monolithic build
# Define Constants
re_SLASH = re.compile('%2F', re.IGNORECASE)
re_REQUEST_LINE = re.compile(r"""^
(?P<method>OPTIONS|GET|HEAD|POST|PUT|DELETE|TRACE|CONNECT) # Request Method
\ # (single space)
(
(?P<scheme>[^:/]+) # Scheme
(://) #
(?P<host>[^/]+) # Host
)? #
(?P<path>(\*|/[^ \?]*)) # Path
(\? (?P<query_string>[^ ]*))? # Query String
\ # (single space)
(?P<protocol>HTTPS?/1\.[01]) # Protocol
$
""", re.X)
LOG_LINE = '%(client_ip)s - "%(request_line)s" - %(status)s %(size)s'
RESPONSE = '''\
%s %s
Content-Length: %i
Content-Type: %s
%s
'''
if IS_JYTHON:
HTTP_METHODS = set(['OPTIONS', 'GET', 'HEAD', 'POST', 'PUT',
'DELETE', 'TRACE', 'CONNECT'])
class Worker(Thread):
"""The Worker class is a base class responsible for receiving connections
and (a subclass) will run an application to process the the connection """
def __init__(self,
app_info,
active_queue,
monitor_queue,
*args,
**kwargs):
Thread.__init__(self, *args, **kwargs)
# Instance Variables
self.app_info = app_info
self.active_queue = active_queue
self.monitor_queue = monitor_queue
self.size = 0
self.status = "200 OK"
self.closeConnection = True
self.request_line = ""
self.protocol = 'HTTP/1.1'
# Request Log
self.req_log = logging.getLogger('Rocket.Requests')
self.req_log.addHandler(NullHandler())
# Error Log
self.err_log = logging.getLogger('Rocket.Errors.' + self.getName())
self.err_log.addHandler(NullHandler())
def _handleError(self, typ, val, tb):
if typ == SSLError:
if 'timed out' in str(val.args[0]):
typ = SocketTimeout
if typ == SocketTimeout:
if __debug__:
self.err_log.debug('Socket timed out')
self.monitor_queue.put(self.conn)
return True
if typ == SocketClosed:
self.closeConnection = True
if __debug__:
self.err_log.debug('Client closed socket')
return False
if typ == BadRequest:
self.closeConnection = True
if __debug__:
self.err_log.debug('Client sent a bad request')
return True
if typ == socket.error:
self.closeConnection = True
if val.args[0] in IGNORE_ERRORS_ON_CLOSE:
if __debug__:
self.err_log.debug('Ignorable socket Error received...'
'closing connection.')
return False
else:
self.status = "999 Utter Server Failure"
tb_fmt = traceback.format_exception(typ, val, tb)
self.err_log.error('Unhandled Error when serving '
'connection:\n' + '\n'.join(tb_fmt))
return False
self.closeConnection = True
tb_fmt = traceback.format_exception(typ, val, tb)
self.err_log.error('\n'.join(tb_fmt))
self.send_response('500 Server Error')
return False
def run(self):
if __debug__:
self.err_log.debug('Entering main loop.')
# Enter thread main loop
while True:
conn = self.active_queue.get()
if not conn:
# A non-client is a signal to die
if __debug__:
self.err_log.debug('Received a death threat.')
return conn
if isinstance(conn, tuple):
conn = Connection(*conn)
self.conn = conn
if conn.ssl != conn.secure:
self.err_log.info('Received HTTP connection on HTTPS port.')
self.send_response('400 Bad Request')
self.closeConnection = True
conn.close()
continue
else:
if __debug__:
self.err_log.debug('Received a connection.')
self.closeConnection = False
# Enter connection serve loop
while True:
if __debug__:
self.err_log.debug('Serving a request')
try:
self.run_app(conn)
except:
exc = sys.exc_info()
handled = self._handleError(*exc)
if handled:
break
finally:
if self.request_line:
log_info = dict(client_ip=conn.client_addr,
time=datetime.now().strftime('%c'),
status=self.status.split(' ')[0],
size=self.size,
request_line=self.request_line)
self.req_log.info(LOG_LINE % log_info)
if self.closeConnection:
try:
conn.close()
except:
self.err_log.error(str(traceback.format_exc()))
break
def run_app(self, conn):
# Must be overridden with a method reads the request from the socket
# and sends a response.
self.closeConnection = True
raise NotImplementedError('Overload this method!')
def send_response(self, status):
stat_msg = status.split(' ', 1)[1]
msg = RESPONSE % (self.protocol,
status,
len(stat_msg),
'text/plain',
stat_msg)
try:
self.conn.sendall(b(msg))
except socket.timeout:
self.closeConnection = True
msg = 'Tried to send "%s" to client but received timeout error'
self.err_log.error(msg % status)
except socket.error:
self.closeConnection = True
msg = 'Tried to send "%s" to client but received socket error'
self.err_log.error(msg % status)
def read_request_line(self, sock_file):
self.request_line = ''
try:
# Grab the request line
d = sock_file.readline()
if PY3K:
d = d.decode('ISO-8859-1')
if d == '\r\n':
# Allow an extra NEWLINE at the beginning per HTTP 1.1 spec
if __debug__:
self.err_log.debug('Client sent newline')
d = sock_file.readline()
if PY3K:
d = d.decode('ISO-8859-1')
except socket.timeout:
raise SocketTimeout('Socket timed out before request.')
except TypeError:
raise SocketClosed(
'SSL bug caused closure of socket. See '
'"https://groups.google.com/d/topic/web2py/P_Gw0JxWzCs".')
d = d.strip()
if not d:
if __debug__:
self.err_log.debug(
'Client did not send a recognizable request.')
raise SocketClosed('Client closed socket.')
self.request_line = d
# NOTE: I've replaced the traditional method of procedurally breaking
# apart the request line with a (rather unsightly) regular expression.
# However, Java's regexp support sucks so bad that it actually takes
# longer in Jython to process the regexp than procedurally. So I've
# left the old code here for Jython's sake...for now.
if IS_JYTHON:
return self._read_request_line_jython(d)
match = re_REQUEST_LINE.match(d)
if not match:
self.send_response('400 Bad Request')
raise BadRequest
req = match.groupdict()
for k, v in req.iteritems():
if not v:
req[k] = ""
if k == 'path':
req['path'] = r'%2F'.join(
[unquote(x) for x in re_SLASH.split(v)])
self.protocol = req['protocol']
return req
def _read_request_line_jython(self, d):
d = d.strip()
try:
method, uri, proto = d.split(' ')
if not proto.startswith('HTTP') or \
proto[-3:] not in ('1.0', '1.1') or \
method not in HTTP_METHODS:
self.send_response('400 Bad Request')
raise BadRequest
except ValueError:
self.send_response('400 Bad Request')
raise BadRequest
req = dict(method=method, protocol=proto)
scheme = ''
host = ''
if uri == '*' or uri.startswith('/'):
path = uri
elif '://' in uri:
scheme, rest = uri.split('://')
host, path = rest.split('/', 1)
path = '/' + path
else:
self.send_response('400 Bad Request')
raise BadRequest
query_string = ''
if '?' in path:
path, query_string = path.split('?', 1)
path = r'%2F'.join([unquote(x) for x in re_SLASH.split(path)])
req.update(path=path,
query_string=query_string,
scheme=scheme.lower(),
host=host)
return req
def read_headers(self, sock_file):
try:
headers = dict()
lname = None
lval = None
while True:
l = sock_file.readline()
if PY3K:
try:
l = str(l, 'ISO-8859-1')
except UnicodeDecodeError:
self.err_log.warning(
'Client sent invalid header: ' + repr(l))
if l.strip().replace('\0', '') == '':
break
if l[0] in ' \t' and lname:
# Some headers take more than one line
lval += ' ' + l.strip()
else:
# HTTP header values are latin-1 encoded
l = l.split(':', 1)
# HTTP header names are us-ascii encoded
lname = l[0].strip().upper().replace('-', '_')
lval = l[-1].strip()
headers[str(lname)] = str(lval)
except socket.timeout:
raise SocketTimeout("Socket timed out before request.")
return headers
class SocketTimeout(Exception):
"Exception for when a socket times out between requests."
pass
class BadRequest(Exception):
"Exception for when a client sends an incomprehensible request."
pass
class SocketClosed(Exception):
"Exception for when a socket is closed by the client."
pass
class ChunkedReader(object):
def __init__(self, sock_file):
self.stream = sock_file
self.chunk_size = 0
def _read_header(self):
chunk_len = ""
try:
while "" == chunk_len:
chunk_len = self.stream.readline().strip()
return int(chunk_len, 16)
except ValueError:
return 0
def read(self, size):
data = b('')
chunk_size = self.chunk_size
while size:
if not chunk_size:
chunk_size = self._read_header()
if size < chunk_size:
data += self.stream.read(size)
chunk_size -= size
break
else:
if not chunk_size:
break
data += self.stream.read(chunk_size)
size -= chunk_size
chunk_size = 0
self.chunk_size = chunk_size
return data
def readline(self):
data = b('')
c = self.read(1)
while c and c != b('\n'):
data += c
c = self.read(1)
data += c
return data
def readlines(self):
yield self.readline()
def get_method(method):
methods = dict(wsgi=WSGIWorker)
return methods[method.lower()]
# Monolithic build...end of module: rocket/worker.py
# Monolithic build...start of module: rocket/methods/__init__.py
# Monolithic build...end of module: rocket/methods/__init__.py
# Monolithic build...start of module: rocket/methods/wsgi.py
# Import System Modules
import sys
import socket
from wsgiref.headers import Headers
from wsgiref.util import FileWrapper
# Import Package Modules
# package imports removed in monolithic build
if PY3K:
from email.utils import formatdate
else:
# Caps Utils for Py2.4 compatibility
from email.Utils import formatdate
# Define Constants
NEWLINE = b('\r\n')
HEADER_RESPONSE = '''HTTP/1.1 %s\r\n%s'''
BASE_ENV = {'SERVER_NAME': SERVER_NAME,
'SCRIPT_NAME': '', # Direct call WSGI does not need a name
'wsgi.errors': sys.stderr,
'wsgi.version': (1, 0),
'wsgi.multiprocess': False,
'wsgi.run_once': False,
'wsgi.file_wrapper': FileWrapper
}
class WSGIWorker(Worker):
def __init__(self, *args, **kwargs):
"""Builds some instance variables that will last the life of the
thread."""
Worker.__init__(self, *args, **kwargs)
if isinstance(self.app_info, dict):
multithreaded = self.app_info.get('max_threads') != 1
else:
multithreaded = False
self.base_environ = dict(
{'SERVER_SOFTWARE': self.app_info['server_software'],
'wsgi.multithread': multithreaded,
})
self.base_environ.update(BASE_ENV)
# Grab our application
self.app = self.app_info.get('wsgi_app')
if not hasattr(self.app, "__call__"):
raise TypeError("The wsgi_app specified (%s) is not a valid WSGI application." % repr(self.app))
# Enable futures
if has_futures and self.app_info.get('futures'):
executor = self.app_info['executor']
self.base_environ.update({"wsgiorg.executor": executor,
"wsgiorg.futures": executor.futures})
def build_environ(self, sock_file, conn):
""" Build the execution environment. """
# Grab the request line
request = self.read_request_line(sock_file)
# Copy the Base Environment
environ = self.base_environ.copy()
# Grab the headers
for k, v in self.read_headers(sock_file).iteritems():
environ[str('HTTP_' + k)] = v
# Add CGI Variables
environ['REQUEST_METHOD'] = request['method']
environ['PATH_INFO'] = request['path']
environ['SERVER_PROTOCOL'] = request['protocol']
environ['SERVER_PORT'] = str(conn.server_port)
environ['REMOTE_PORT'] = str(conn.client_port)
environ['REMOTE_ADDR'] = str(conn.client_addr)
environ['QUERY_STRING'] = request['query_string']
if 'HTTP_CONTENT_LENGTH' in environ:
environ['CONTENT_LENGTH'] = environ['HTTP_CONTENT_LENGTH']
if 'HTTP_CONTENT_TYPE' in environ:
environ['CONTENT_TYPE'] = environ['HTTP_CONTENT_TYPE']
# Save the request method for later
self.request_method = environ['REQUEST_METHOD']
# Add Dynamic WSGI Variables
if conn.ssl:
environ['wsgi.url_scheme'] = 'https'
environ['HTTPS'] = 'on'
try:
peercert = conn.socket.getpeercert(binary_form=True)
environ['SSL_CLIENT_RAW_CERT'] = \
peercert and ssl.DER_cert_to_PEM_cert(peercert)
except Exception:
print sys.exc_info()[1]
else:
environ['wsgi.url_scheme'] = 'http'
if environ.get('HTTP_TRANSFER_ENCODING', '') == 'chunked':
environ['wsgi.input'] = ChunkedReader(sock_file)
else:
environ['wsgi.input'] = sock_file
return environ
def send_headers(self, data, sections):
h_set = self.header_set
# Does the app want us to send output chunked?
self.chunked = h_set.get('Transfer-Encoding', '').lower() == 'chunked'
# Add a Date header if it's not there already
if not 'Date' in h_set:
h_set['Date'] = formatdate(usegmt=True)
# Add a Server header if it's not there already
if not 'Server' in h_set:
h_set['Server'] = HTTP_SERVER_SOFTWARE
if 'Content-Length' in h_set:
self.size = int(h_set['Content-Length'])
else:
s = int(self.status.split(' ')[0])
if (s < 200 or s not in (204, 205, 304)) and not self.chunked:
if sections == 1 or self.protocol != 'HTTP/1.1':
# Add a Content-Length header because it's not there
self.size = len(data)
h_set['Content-Length'] = str(self.size)
else:
# If they sent us more than one section, we blow chunks
h_set['Transfer-Encoding'] = 'Chunked'
self.chunked = True
if __debug__:
self.err_log.debug('Adding header...'
'Transfer-Encoding: Chunked')
if 'Connection' not in h_set:
# If the application did not provide a connection header,
# fill it in
client_conn = self.environ.get('HTTP_CONNECTION', '').lower()
if self.environ['SERVER_PROTOCOL'] == 'HTTP/1.1':
# HTTP = 1.1 defaults to keep-alive connections
if client_conn:
h_set['Connection'] = client_conn
else:
h_set['Connection'] = 'keep-alive'
else:
# HTTP < 1.1 supports keep-alive but it's quirky
# so we don't support it
h_set['Connection'] = 'close'
# Close our connection if we need to.
self.closeConnection = h_set.get('Connection', '').lower() == 'close'
# Build our output headers
header_data = HEADER_RESPONSE % (self.status, str(h_set))
# Send the headers
if __debug__:
self.err_log.debug('Sending Headers: %s' % repr(header_data))
self.conn.sendall(b(header_data))
self.headers_sent = True
def write_warning(self, data, sections=None):
self.err_log.warning('WSGI app called write method directly. This is '
'deprecated behavior. Please update your app.')
return self.write(data, sections)
def write(self, data, sections=None):
""" Write the data to the output socket. """
if self.error[0]:
self.status = self.error[0]
data = b(self.error[1])
if not self.headers_sent:
self.send_headers(data, sections)
if self.request_method != 'HEAD':
try:
if self.chunked:
self.conn.sendall(b('%x\r\n%s\r\n' % (len(data), data)))
else:
self.conn.sendall(data)
except socket.timeout:
self.closeConnection = True
except socket.error:
# But some clients will close the connection before that
# resulting in a socket error.
self.closeConnection = True
def start_response(self, status, response_headers, exc_info=None):
""" Store the HTTP status and headers to be sent when self.write is
called. """
if exc_info:
try:
if self.headers_sent:
# Re-raise original exception if headers sent
# because this violates WSGI specification.
raise
finally:
exc_info = None
elif self.header_set:
raise AssertionError("Headers already set!")
if PY3K and not isinstance(status, str):
self.status = str(status, 'ISO-8859-1')
else:
self.status = status
# Make sure headers are bytes objects
try:
self.header_set = Headers(response_headers)
except UnicodeDecodeError:
self.error = ('500 Internal Server Error',
'HTTP Headers should be bytes')
self.err_log.error('Received HTTP Headers from client that contain'
' invalid characters for Latin-1 encoding.')
return self.write_warning
def run_app(self, conn):
self.size = 0
self.header_set = Headers([])
self.headers_sent = False
self.error = (None, None)
self.chunked = False
sections = None
output = None
if __debug__:
self.err_log.debug('Getting sock_file')
# Build our file-like object
if PY3K:
sock_file = conn.makefile(mode='rb', buffering=BUF_SIZE)
else:
sock_file = conn.makefile(BUF_SIZE)
try:
# Read the headers and build our WSGI environment
self.environ = environ = self.build_environ(sock_file, conn)
# Handle 100 Continue
if environ.get('HTTP_EXPECT', '') == '100-continue':
res = environ['SERVER_PROTOCOL'] + ' 100 Continue\r\n\r\n'
conn.sendall(b(res))
# Send it to our WSGI application
output = self.app(environ, self.start_response)
if not hasattr(output, '__len__') and not hasattr(output, '__iter__'):
self.error = ('500 Internal Server Error',
'WSGI applications must return a list or '
'generator type.')
if hasattr(output, '__len__'):
sections = len(output)
for data in output:
# Don't send headers until body appears
if data:
self.write(data, sections)
if self.chunked:
# If chunked, send our final chunk length
self.conn.sendall(b('0\r\n\r\n'))
elif not self.headers_sent:
# Send headers if the body was empty
self.send_headers('', sections)
# Don't capture exceptions here. The Worker class handles
# them appropriately.
finally:
if __debug__:
self.err_log.debug('Finally closing output and sock_file')
if hasattr(output, 'close'):
output.close()
sock_file.close()
# Monolithic build...end of module: rocket/methods/wsgi.py
| [
[
1,
0,
0.0043,
0.0005,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0048,
0.0005,
0,
0.66,
0.0108,
546,
0,
1,
0,
0,
546,
0,
0
],
[
1,
0,
0.0053,
0.0005,
0,
... | [
"import sys",
"import errno",
"import socket",
"import logging",
"import platform",
"VERSION = '1.2.6'",
"SERVER_NAME = socket.gethostname()",
"SERVER_SOFTWARE = 'Rocket %s' % VERSION",
"HTTP_SERVER_SOFTWARE = '%s Python/%s' % (\n SERVER_SOFTWARE, sys.version.split(' ')[0])",
"BUF_SIZE = 16384"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Functions required to execute app components
============================================
FOR INTERNAL USE ONLY
"""
from os import stat
import thread
import logging
from fileutils import read_file
cfs = {} # for speed-up
cfs_lock = thread.allocate_lock() # and thread safety
def getcfs(key, filename, filter=None):
"""
Caches the *filtered* file `filename` with `key` until the file is
modified.
:param key: the cache key
:param filename: the file to cache
:param filter: is the function used for filtering. Normally `filename` is a
.py file and `filter` is a function that bytecode compiles the file.
In this way the bytecode compiled file is cached. (Default = None)
This is used on Google App Engine since pyc files cannot be saved.
"""
try:
t = stat(filename).st_mtime
except OSError:
return filter() if callable(filter) else ''
cfs_lock.acquire()
item = cfs.get(key, None)
cfs_lock.release()
if item and item[0] == t:
return item[1]
if not callable(filter):
data = read_file(filename)
else:
data = filter()
cfs_lock.acquire()
cfs[key] = (t, data)
cfs_lock.release()
return data
| [
[
8,
0,
0.1604,
0.1887,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.283,
0.0189,
0,
0.66,
0.1429,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3019,
0.0189,
0,
0.66,... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\nFunctions required to execute app components\n============================================",
"from os import stat",
"import thread",
"i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
CONTENT_TYPE dictionary created against freedesktop.org' shared mime info
database version 1.1.
Deviations from official standards:
- '.md': 'application/x-genesis-rom' --> 'text/x-markdown'
- '.png': 'image/x-apple-ios-png' --> 'image/png'
Additions:
- '.load': 'text/html'
- '.json': 'application/json'
- '.jsonp': 'application/jsonp'
- '.pickle': 'application/python-pickle'
- '.w2p': 'application/w2p'
"""
__all__ = ['contenttype']
CONTENT_TYPE = {
'.123': 'application/vnd.lotus-1-2-3',
'.3ds': 'image/x-3ds',
'.3g2': 'video/3gpp2',
'.3ga': 'video/3gpp',
'.3gp': 'video/3gpp',
'.3gp2': 'video/3gpp2',
'.3gpp': 'video/3gpp',
'.3gpp2': 'video/3gpp2',
'.602': 'application/x-t602',
'.669': 'audio/x-mod',
'.7z': 'application/x-7z-compressed',
'.a': 'application/x-archive',
'.aac': 'audio/aac',
'.abw': 'application/x-abiword',
'.abw.crashed': 'application/x-abiword',
'.abw.gz': 'application/x-abiword',
'.ac3': 'audio/ac3',
'.ace': 'application/x-ace',
'.adb': 'text/x-adasrc',
'.ads': 'text/x-adasrc',
'.afm': 'application/x-font-afm',
'.ag': 'image/x-applix-graphics',
'.ai': 'application/illustrator',
'.aif': 'audio/x-aiff',
'.aifc': 'audio/x-aifc',
'.aiff': 'audio/x-aiff',
'.aiffc': 'audio/x-aifc',
'.al': 'application/x-perl',
'.alz': 'application/x-alz',
'.amr': 'audio/amr',
'.amz': 'audio/x-amzxml',
'.ani': 'application/x-navi-animation',
'.anim[1-9j]': 'video/x-anim',
'.anx': 'application/annodex',
'.ape': 'audio/x-ape',
'.apk': 'application/vnd.android.package-archive',
'.ar': 'application/x-archive',
'.arj': 'application/x-arj',
'.arw': 'image/x-sony-arw',
'.as': 'application/x-applix-spreadsheet',
'.asc': 'text/plain',
'.asf': 'video/x-ms-asf',
'.asp': 'application/x-asp',
'.ass': 'text/x-ssa',
'.asx': 'audio/x-ms-asx',
'.atom': 'application/atom+xml',
'.au': 'audio/basic',
'.avf': 'video/x-msvideo',
'.avi': 'video/x-msvideo',
'.aw': 'application/x-applix-word',
'.awb': 'audio/amr-wb',
'.awk': 'application/x-awk',
'.axa': 'audio/annodex',
'.axv': 'video/annodex',
'.bak': 'application/x-trash',
'.bcpio': 'application/x-bcpio',
'.bdf': 'application/x-font-bdf',
'.bdm': 'video/mp2t',
'.bdmv': 'video/mp2t',
'.bib': 'text/x-bibtex',
'.bin': 'application/octet-stream',
'.blend': 'application/x-blender',
'.blender': 'application/x-blender',
'.bmp': 'image/bmp',
'.bz': 'application/x-bzip',
'.bz2': 'application/x-bzip',
'.c': 'text/x-csrc',
'.c++': 'text/x-c++src',
'.cab': 'application/vnd.ms-cab-compressed',
'.cap': 'application/vnd.tcpdump.pcap',
'.cb7': 'application/x-cb7',
'.cbl': 'text/x-cobol',
'.cbr': 'application/x-cbr',
'.cbt': 'application/x-cbt',
'.cbz': 'application/x-cbz',
'.cc': 'text/x-c++src',
'.ccmx': 'application/x-ccmx',
'.cdf': 'application/x-netcdf',
'.cdr': 'application/vnd.corel-draw',
'.cer': 'application/pkix-cert',
'.cert': 'application/x-x509-ca-cert',
'.cgm': 'image/cgm',
'.chm': 'application/vnd.ms-htmlhelp',
'.chrt': 'application/x-kchart',
'.class': 'application/x-java',
'.clpi': 'video/mp2t',
'.cls': 'text/x-tex',
'.cmake': 'text/x-cmake',
'.cob': 'text/x-cobol',
'.cpi': 'video/mp2t',
'.cpio': 'application/x-cpio',
'.cpio.gz': 'application/x-cpio-compressed',
'.cpp': 'text/x-c++src',
'.cr2': 'image/x-canon-cr2',
'.crl': 'application/pkix-crl',
'.crt': 'application/x-x509-ca-cert',
'.crw': 'image/x-canon-crw',
'.cs': 'text/x-csharp',
'.csh': 'application/x-csh',
'.css': 'text/css',
'.cssl': 'text/css',
'.csv': 'text/csv',
'.cue': 'application/x-cue',
'.cur': 'image/x-win-bitmap',
'.cxx': 'text/x-c++src',
'.d': 'text/x-dsrc',
'.dar': 'application/x-dar',
'.dbf': 'application/x-dbf',
'.dc': 'application/x-dc-rom',
'.dcl': 'text/x-dcl',
'.dcm': 'application/dicom',
'.dcr': 'image/x-kodak-dcr',
'.dds': 'image/x-dds',
'.deb': 'application/x-deb',
'.der': 'application/x-x509-ca-cert',
'.desktop': 'application/x-desktop',
'.di': 'text/x-dsrc',
'.dia': 'application/x-dia-diagram',
'.diff': 'text/x-patch',
'.divx': 'video/x-msvideo',
'.djv': 'image/vnd.djvu',
'.djvu': 'image/vnd.djvu',
'.dmg': 'application/x-apple-diskimage',
'.dmp': 'application/vnd.tcpdump.pcap',
'.dng': 'image/x-adobe-dng',
'.doc': 'application/msword',
'.docbook': 'application/x-docbook+xml',
'.docm': 'application/vnd.ms-word.document.macroenabled.12',
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.dot': 'text/vnd.graphviz',
'.dotm': 'application/vnd.ms-word.template.macroenabled.12',
'.dotx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'.dsl': 'text/x-dsl',
'.dtd': 'application/xml-dtd',
'.dts': 'audio/vnd.dts',
'.dtshd': 'audio/vnd.dts.hd',
'.dtx': 'text/x-tex',
'.dv': 'video/dv',
'.dvi': 'application/x-dvi',
'.dvi.bz2': 'application/x-bzdvi',
'.dvi.gz': 'application/x-gzdvi',
'.dwg': 'image/vnd.dwg',
'.dxf': 'image/vnd.dxf',
'.e': 'text/x-eiffel',
'.egon': 'application/x-egon',
'.eif': 'text/x-eiffel',
'.el': 'text/x-emacs-lisp',
'.emf': 'image/x-emf',
'.eml': 'message/rfc822',
'.emp': 'application/vnd.emusic-emusic_package',
'.ent': 'application/xml-external-parsed-entity',
'.eps': 'image/x-eps',
'.eps.bz2': 'image/x-bzeps',
'.eps.gz': 'image/x-gzeps',
'.epsf': 'image/x-eps',
'.epsf.bz2': 'image/x-bzeps',
'.epsf.gz': 'image/x-gzeps',
'.epsi': 'image/x-eps',
'.epsi.bz2': 'image/x-bzeps',
'.epsi.gz': 'image/x-gzeps',
'.epub': 'application/epub+zip',
'.erl': 'text/x-erlang',
'.es': 'application/ecmascript',
'.etheme': 'application/x-e-theme',
'.etx': 'text/x-setext',
'.exe': 'application/x-ms-dos-executable',
'.exr': 'image/x-exr',
'.ez': 'application/andrew-inset',
'.f': 'text/x-fortran',
'.f4a': 'audio/mp4',
'.f4b': 'audio/x-m4b',
'.f4v': 'video/mp4',
'.f90': 'text/x-fortran',
'.f95': 'text/x-fortran',
'.fb2': 'application/x-fictionbook+xml',
'.fig': 'image/x-xfig',
'.fits': 'image/fits',
'.fl': 'application/x-fluid',
'.flac': 'audio/flac',
'.flc': 'video/x-flic',
'.fli': 'video/x-flic',
'.flv': 'video/x-flv',
'.flw': 'application/x-kivio',
'.fo': 'text/x-xslfo',
'.fodg': 'application/vnd.oasis.opendocument.graphics-flat-xml',
'.fodp': 'application/vnd.oasis.opendocument.presentation-flat-xml',
'.fods': 'application/vnd.oasis.opendocument.spreadsheet-flat-xml',
'.fodt': 'application/vnd.oasis.opendocument.text-flat-xml',
'.for': 'text/x-fortran',
'.fxm': 'video/x-javafx',
'.g3': 'image/fax-g3',
'.gb': 'application/x-gameboy-rom',
'.gba': 'application/x-gba-rom',
'.gcrd': 'text/vcard',
'.ged': 'application/x-gedcom',
'.gedcom': 'application/x-gedcom',
'.gem': 'application/x-tar',
'.gen': 'application/x-genesis-rom',
'.gf': 'application/x-tex-gf',
'.gg': 'application/x-sms-rom',
'.gif': 'image/gif',
'.glade': 'application/x-glade',
'.gml': 'application/gml+xml',
'.gmo': 'application/x-gettext-translation',
'.gnc': 'application/x-gnucash',
'.gnd': 'application/gnunet-directory',
'.gnucash': 'application/x-gnucash',
'.gnumeric': 'application/x-gnumeric',
'.gnuplot': 'application/x-gnuplot',
'.go': 'text/x-go',
'.gp': 'application/x-gnuplot',
'.gpg': 'application/pgp-encrypted',
'.gplt': 'application/x-gnuplot',
'.gra': 'application/x-graphite',
'.gsf': 'application/x-font-type1',
'.gsm': 'audio/x-gsm',
'.gtar': 'application/x-tar',
'.gv': 'text/vnd.graphviz',
'.gvp': 'text/x-google-video-pointer',
'.gz': 'application/gzip',
'.h': 'text/x-chdr',
'.h++': 'text/x-c++hdr',
'.h4': 'application/x-hdf',
'.h5': 'application/x-hdf',
'.hdf': 'application/x-hdf',
'.hdf4': 'application/x-hdf',
'.hdf5': 'application/x-hdf',
'.hh': 'text/x-c++hdr',
'.hlp': 'application/winhlp',
'.hp': 'text/x-c++hdr',
'.hpgl': 'application/vnd.hp-hpgl',
'.hpp': 'text/x-c++hdr',
'.hs': 'text/x-haskell',
'.htm': 'text/html',
'.html': 'text/html',
'.hwp': 'application/x-hwp',
'.hwt': 'application/x-hwt',
'.hxx': 'text/x-c++hdr',
'.ica': 'application/x-ica',
'.icb': 'image/x-tga',
'.icc': 'application/vnd.iccprofile',
'.icm': 'application/vnd.iccprofile',
'.icns': 'image/x-icns',
'.ico': 'image/vnd.microsoft.icon',
'.ics': 'text/calendar',
'.idl': 'text/x-idl',
'.ief': 'image/ief',
'.iff': 'image/x-ilbm',
'.ilbm': 'image/x-ilbm',
'.ime': 'text/x-imelody',
'.imy': 'text/x-imelody',
'.ins': 'text/x-tex',
'.iptables': 'text/x-iptables',
'.iso': 'application/x-cd-image',
'.iso9660': 'application/x-cd-image',
'.it': 'audio/x-it',
'.it87': 'application/x-it87',
'.j2k': 'image/jp2',
'.jad': 'text/vnd.sun.j2me.app-descriptor',
'.jar': 'application/x-java-archive',
'.java': 'text/x-java',
'.jceks': 'application/x-java-jce-keystore',
'.jks': 'application/x-java-keystore',
'.jng': 'image/x-jng',
'.jnlp': 'application/x-java-jnlp-file',
'.jp2': 'image/jp2',
'.jpc': 'image/jp2',
'.jpe': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.jpf': 'image/jp2',
'.jpg': 'image/jpeg',
'.jpr': 'application/x-jbuilder-project',
'.jpx': 'image/jp2',
'.js': 'application/javascript',
'.json': 'application/json',
'.jsonp': 'application/jsonp',
'.k25': 'image/x-kodak-k25',
'.kar': 'audio/midi',
'.karbon': 'application/x-karbon',
'.kdc': 'image/x-kodak-kdc',
'.kdelnk': 'application/x-desktop',
'.kexi': 'application/x-kexiproject-sqlite3',
'.kexic': 'application/x-kexi-connectiondata',
'.kexis': 'application/x-kexiproject-shortcut',
'.kfo': 'application/x-kformula',
'.kil': 'application/x-killustrator',
'.kino': 'application/smil',
'.kml': 'application/vnd.google-earth.kml+xml',
'.kmz': 'application/vnd.google-earth.kmz',
'.kon': 'application/x-kontour',
'.kpm': 'application/x-kpovmodeler',
'.kpr': 'application/x-kpresenter',
'.kpt': 'application/x-kpresenter',
'.kra': 'application/x-krita',
'.ks': 'application/x-java-keystore',
'.ksp': 'application/x-kspread',
'.kud': 'application/x-kugar',
'.kwd': 'application/x-kword',
'.kwt': 'application/x-kword',
'.la': 'application/x-shared-library-la',
'.latex': 'text/x-tex',
'.lbm': 'image/x-ilbm',
'.ldif': 'text/x-ldif',
'.lha': 'application/x-lha',
'.lhs': 'text/x-literate-haskell',
'.lhz': 'application/x-lhz',
'.load' : 'text/html',
'.log': 'text/x-log',
'.lrz': 'application/x-lrzip',
'.ltx': 'text/x-tex',
'.lua': 'text/x-lua',
'.lwo': 'image/x-lwo',
'.lwob': 'image/x-lwo',
'.lwp': 'application/vnd.lotus-wordpro',
'.lws': 'image/x-lws',
'.ly': 'text/x-lilypond',
'.lyx': 'application/x-lyx',
'.lz': 'application/x-lzip',
'.lzh': 'application/x-lha',
'.lzma': 'application/x-lzma',
'.lzo': 'application/x-lzop',
'.m': 'text/x-matlab',
'.m15': 'audio/x-mod',
'.m1u': 'video/vnd.mpegurl',
'.m2t': 'video/mp2t',
'.m2ts': 'video/mp2t',
'.m3u': 'application/vnd.apple.mpegurl',
'.m3u8': 'application/vnd.apple.mpegurl',
'.m4': 'application/x-m4',
'.m4a': 'audio/mp4',
'.m4b': 'audio/x-m4b',
'.m4u': 'video/vnd.mpegurl',
'.m4v': 'video/mp4',
'.mab': 'application/x-markaby',
'.mak': 'text/x-makefile',
'.man': 'application/x-troff-man',
'.manifest': 'text/cache-manifest',
'.markdown': 'text/x-markdown',
'.mbox': 'application/mbox',
'.md': 'text/x-markdown',
'.mdb': 'application/vnd.ms-access',
'.mdi': 'image/vnd.ms-modi',
'.me': 'text/x-troff-me',
'.med': 'audio/x-mod',
'.meta4': 'application/metalink4+xml',
'.metalink': 'application/metalink+xml',
'.mgp': 'application/x-magicpoint',
'.mht': 'application/x-mimearchive',
'.mhtml': 'application/x-mimearchive',
'.mid': 'audio/midi',
'.midi': 'audio/midi',
'.mif': 'application/x-mif',
'.minipsf': 'audio/x-minipsf',
'.mk': 'text/x-makefile',
'.mka': 'audio/x-matroska',
'.mkd': 'text/x-markdown',
'.mkv': 'video/x-matroska',
'.ml': 'text/x-ocaml',
'.mli': 'text/x-ocaml',
'.mm': 'text/x-troff-mm',
'.mmf': 'application/x-smaf',
'.mml': 'application/mathml+xml',
'.mng': 'video/x-mng',
'.mo': 'text/x-modelica',
'.mo3': 'audio/x-mo3',
'.mobi': 'application/x-mobipocket-ebook',
'.moc': 'text/x-moc',
'.mod': 'audio/x-mod',
'.mof': 'text/x-mof',
'.moov': 'video/quicktime',
'.mov': 'video/quicktime',
'.movie': 'video/x-sgi-movie',
'.mp+': 'audio/x-musepack',
'.mp2': 'video/mpeg',
'.mp3': 'audio/mpeg',
'.mp4': 'video/mp4',
'.mpc': 'audio/x-musepack',
'.mpe': 'video/mpeg',
'.mpeg': 'video/mpeg',
'.mpg': 'video/mpeg',
'.mpga': 'audio/mpeg',
'.mpl': 'video/mp2t',
'.mpls': 'video/mp2t',
'.mpp': 'audio/x-musepack',
'.mrl': 'text/x-mrml',
'.mrml': 'text/x-mrml',
'.mrw': 'image/x-minolta-mrw',
'.ms': 'text/x-troff-ms',
'.msi': 'application/x-msi',
'.msod': 'image/x-msod',
'.msx': 'application/x-msx-rom',
'.mtm': 'audio/x-mod',
'.mts': 'video/mp2t',
'.mup': 'text/x-mup',
'.mxf': 'application/mxf',
'.mxu': 'video/vnd.mpegurl',
'.n64': 'application/x-n64-rom',
'.nb': 'application/mathematica',
'.nc': 'application/x-netcdf',
'.nds': 'application/x-nintendo-ds-rom',
'.nef': 'image/x-nikon-nef',
'.nes': 'application/x-nes-rom',
'.nfo': 'text/x-nfo',
'.not': 'text/x-mup',
'.nsc': 'application/x-netshow-channel',
'.nsv': 'video/x-nsv',
'.nzb': 'application/x-nzb',
'.o': 'application/x-object',
'.obj': 'application/x-tgif',
'.ocl': 'text/x-ocl',
'.oda': 'application/oda',
'.odb': 'application/vnd.oasis.opendocument.database',
'.odc': 'application/vnd.oasis.opendocument.chart',
'.odf': 'application/vnd.oasis.opendocument.formula',
'.odg': 'application/vnd.oasis.opendocument.graphics',
'.odi': 'application/vnd.oasis.opendocument.image',
'.odm': 'application/vnd.oasis.opendocument.text-master',
'.odp': 'application/vnd.oasis.opendocument.presentation',
'.ods': 'application/vnd.oasis.opendocument.spreadsheet',
'.odt': 'application/vnd.oasis.opendocument.text',
'.oga': 'audio/ogg',
'.ogg': 'application/ogg',
'.ogm': 'video/x-ogm+ogg',
'.ogv': 'video/ogg',
'.ogx': 'application/ogg',
'.old': 'application/x-trash',
'.oleo': 'application/x-oleo',
'.ooc': 'text/x-ooc',
'.opml': 'text/x-opml+xml',
'.oprc': 'application/vnd.palm',
'.ora': 'image/openraster',
'.orf': 'image/x-olympus-orf',
'.otc': 'application/vnd.oasis.opendocument.chart-template',
'.otf': 'application/x-font-otf',
'.otg': 'application/vnd.oasis.opendocument.graphics-template',
'.oth': 'application/vnd.oasis.opendocument.text-web',
'.otp': 'application/vnd.oasis.opendocument.presentation-template',
'.ots': 'application/vnd.oasis.opendocument.spreadsheet-template',
'.ott': 'application/vnd.oasis.opendocument.text-template',
'.owl': 'application/rdf+xml',
'.oxps': 'application/oxps',
'.oxt': 'application/vnd.openofficeorg.extension',
'.p': 'text/x-pascal',
'.p10': 'application/pkcs10',
'.p12': 'application/x-pkcs12',
'.p7b': 'application/x-pkcs7-certificates',
'.p7c': 'application/pkcs7-mime',
'.p7m': 'application/pkcs7-mime',
'.p7s': 'application/pkcs7-signature',
'.p8': 'application/pkcs8',
'.pack': 'application/x-java-pack200',
'.pak': 'application/x-pak',
'.par2': 'application/x-par2',
'.pas': 'text/x-pascal',
'.patch': 'text/x-patch',
'.pbm': 'image/x-portable-bitmap',
'.pcap': 'application/vnd.tcpdump.pcap',
'.pcd': 'image/x-photo-cd',
'.pcf': 'application/x-cisco-vpn-settings',
'.pcf.gz': 'application/x-font-pcf',
'.pcf.z': 'application/x-font-pcf',
'.pcl': 'application/vnd.hp-pcl',
'.pct': 'image/x-pict',
'.pcx': 'image/x-pcx',
'.pdb': 'chemical/x-pdb',
'.pdc': 'application/x-aportisdoc',
'.pdf': 'application/pdf',
'.pdf.bz2': 'application/x-bzpdf',
'.pdf.gz': 'application/x-gzpdf',
'.pdf.xz': 'application/x-xzpdf',
'.pef': 'image/x-pentax-pef',
'.pem': 'application/x-x509-ca-cert',
'.perl': 'application/x-perl',
'.pfa': 'application/x-font-type1',
'.pfb': 'application/x-font-type1',
'.pfx': 'application/x-pkcs12',
'.pgm': 'image/x-portable-graymap',
'.pgn': 'application/x-chess-pgn',
'.pgp': 'application/pgp-encrypted',
'.php': 'application/x-php',
'.php3': 'application/x-php',
'.php4': 'application/x-php',
'.php5': 'application/x-php',
'.phps': 'application/x-php',
'.pict': 'image/x-pict',
'.pict1': 'image/x-pict',
'.pict2': 'image/x-pict',
'.pk': 'application/x-tex-pk',
'.pkipath': 'application/pkix-pkipath',
'.pkr': 'application/pgp-keys',
'.pl': 'application/x-perl',
'.pla': 'audio/x-iriver-pla',
'.pln': 'application/x-planperfect',
'.pls': 'audio/x-scpls',
'.pm': 'application/x-perl',
'.png': 'image/png',
'.pnm': 'image/x-portable-anymap',
'.pntg': 'image/x-macpaint',
'.po': 'text/x-gettext-translation',
'.por': 'application/x-spss-por',
'.pot': 'text/x-gettext-translation-template',
'.potm': 'application/vnd.ms-powerpoint.template.macroenabled.12',
'.potx': 'application/vnd.openxmlformats-officedocument.presentationml.template',
'.ppam': 'application/vnd.ms-powerpoint.addin.macroenabled.12',
'.ppm': 'image/x-portable-pixmap',
'.pps': 'application/vnd.ms-powerpoint',
'.ppsm': 'application/vnd.ms-powerpoint.slideshow.macroenabled.12',
'.ppsx': 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'.ppt': 'application/vnd.ms-powerpoint',
'.pptm': 'application/vnd.ms-powerpoint.presentation.macroenabled.12',
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'.ppz': 'application/vnd.ms-powerpoint',
'.pqa': 'application/vnd.palm',
'.prc': 'application/vnd.palm',
'.ps': 'application/postscript',
'.ps.bz2': 'application/x-bzpostscript',
'.ps.gz': 'application/x-gzpostscript',
'.psd': 'image/vnd.adobe.photoshop',
'.psf': 'audio/x-psf',
'.psf.gz': 'application/x-gz-font-linux-psf',
'.psflib': 'audio/x-psflib',
'.psid': 'audio/prs.sid',
'.psw': 'application/x-pocket-word',
'.pw': 'application/x-pw',
'.py': 'text/x-python',
'.pyc': 'application/x-python-bytecode',
'.pickle': 'application/python-pickle',
'.pyo': 'application/x-python-bytecode',
'.qif': 'image/x-quicktime',
'.qml': 'text/x-qml',
'.qt': 'video/quicktime',
'.qti': 'application/x-qtiplot',
'.qti.gz': 'application/x-qtiplot',
'.qtif': 'image/x-quicktime',
'.qtl': 'application/x-quicktime-media-link',
'.qtvr': 'video/quicktime',
'.ra': 'audio/vnd.rn-realaudio',
'.raf': 'image/x-fuji-raf',
'.ram': 'application/ram',
'.rar': 'application/x-rar',
'.ras': 'image/x-cmu-raster',
'.raw': 'image/x-panasonic-raw',
'.rax': 'audio/vnd.rn-realaudio',
'.rb': 'application/x-ruby',
'.rdf': 'application/rdf+xml',
'.rdfs': 'application/rdf+xml',
'.reg': 'text/x-ms-regedit',
'.rej': 'text/x-reject',
'.rgb': 'image/x-rgb',
'.rle': 'image/rle',
'.rm': 'application/vnd.rn-realmedia',
'.rmj': 'application/vnd.rn-realmedia',
'.rmm': 'application/vnd.rn-realmedia',
'.rms': 'application/vnd.rn-realmedia',
'.rmvb': 'application/vnd.rn-realmedia',
'.rmx': 'application/vnd.rn-realmedia',
'.rnc': 'application/relax-ng-compact-syntax',
'.rng': 'application/xml',
'.roff': 'text/troff',
'.rp': 'image/vnd.rn-realpix',
'.rpm': 'application/x-rpm',
'.rss': 'application/rss+xml',
'.rt': 'text/vnd.rn-realtext',
'.rtf': 'application/rtf',
'.rtx': 'text/richtext',
'.rv': 'video/vnd.rn-realvideo',
'.rvx': 'video/vnd.rn-realvideo',
'.rw2': 'image/x-panasonic-raw2',
'.s3m': 'audio/x-s3m',
'.sam': 'application/x-amipro',
'.sami': 'application/x-sami',
'.sav': 'application/x-spss-sav',
'.scala': 'text/x-scala',
'.scm': 'text/x-scheme',
'.sda': 'application/vnd.stardivision.draw',
'.sdc': 'application/vnd.stardivision.calc',
'.sdd': 'application/vnd.stardivision.impress',
'.sdp': 'application/sdp',
'.sds': 'application/vnd.stardivision.chart',
'.sdw': 'application/vnd.stardivision.writer',
'.sgf': 'application/x-go-sgf',
'.sgi': 'image/x-sgi',
'.sgl': 'application/vnd.stardivision.writer',
'.sgm': 'text/sgml',
'.sgml': 'text/sgml',
'.sh': 'application/x-shellscript',
'.shape': 'application/x-dia-shape',
'.shar': 'application/x-shar',
'.shn': 'application/x-shorten',
'.siag': 'application/x-siag',
'.sid': 'audio/prs.sid',
'.sik': 'application/x-trash',
'.sis': 'application/vnd.symbian.install',
'.sisx': 'x-epoc/x-sisx-app',
'.sit': 'application/x-stuffit',
'.siv': 'application/sieve',
'.sk': 'image/x-skencil',
'.sk1': 'image/x-skencil',
'.skr': 'application/pgp-keys',
'.sldm': 'application/vnd.ms-powerpoint.slide.macroenabled.12',
'.sldx': 'application/vnd.openxmlformats-officedocument.presentationml.slide',
'.slk': 'text/spreadsheet',
'.smaf': 'application/x-smaf',
'.smc': 'application/x-snes-rom',
'.smd': 'application/vnd.stardivision.mail',
'.smf': 'application/vnd.stardivision.math',
'.smi': 'application/x-sami',
'.smil': 'application/smil',
'.sml': 'application/smil',
'.sms': 'application/x-sms-rom',
'.snd': 'audio/basic',
'.so': 'application/x-sharedlib',
'.spc': 'application/x-pkcs7-certificates',
'.spd': 'application/x-font-speedo',
'.spec': 'text/x-rpm-spec',
'.spl': 'application/x-shockwave-flash',
'.spm': 'application/x-source-rpm',
'.spx': 'audio/x-speex',
'.sql': 'text/x-sql',
'.sr2': 'image/x-sony-sr2',
'.src': 'application/x-wais-source',
'.src.rpm': 'application/x-source-rpm',
'.srf': 'image/x-sony-srf',
'.srt': 'application/x-subrip',
'.ss': 'text/x-scheme',
'.ssa': 'text/x-ssa',
'.stc': 'application/vnd.sun.xml.calc.template',
'.std': 'application/vnd.sun.xml.draw.template',
'.sti': 'application/vnd.sun.xml.impress.template',
'.stm': 'audio/x-stm',
'.stw': 'application/vnd.sun.xml.writer.template',
'.sty': 'text/x-tex',
'.sub': 'text/x-subviewer',
'.sun': 'image/x-sun-raster',
'.sv': 'text/x-svsrc',
'.sv4cpio': 'application/x-sv4cpio',
'.sv4crc': 'application/x-sv4crc',
'.svg': 'image/svg+xml',
'.svgz': 'image/svg+xml-compressed',
'.svh': 'text/x-svhdr',
'.swf': 'application/x-shockwave-flash',
'.swm': 'application/x-ms-wim',
'.sxc': 'application/vnd.sun.xml.calc',
'.sxd': 'application/vnd.sun.xml.draw',
'.sxg': 'application/vnd.sun.xml.writer.global',
'.sxi': 'application/vnd.sun.xml.impress',
'.sxm': 'application/vnd.sun.xml.math',
'.sxw': 'application/vnd.sun.xml.writer',
'.sylk': 'text/spreadsheet',
'.t': 'text/troff',
'.t2t': 'text/x-txt2tags',
'.tar': 'application/x-tar',
'.tar.bz': 'application/x-bzip-compressed-tar',
'.tar.bz2': 'application/x-bzip-compressed-tar',
'.tar.gz': 'application/x-compressed-tar',
'.tar.lrz': 'application/x-lrzip-compressed-tar',
'.tar.lzma': 'application/x-lzma-compressed-tar',
'.tar.lzo': 'application/x-tzo',
'.tar.xz': 'application/x-xz-compressed-tar',
'.tar.z': 'application/x-tarz',
'.taz': 'application/x-tarz',
'.tb2': 'application/x-bzip-compressed-tar',
'.tbz': 'application/x-bzip-compressed-tar',
'.tbz2': 'application/x-bzip-compressed-tar',
'.tcl': 'text/x-tcl',
'.tex': 'text/x-tex',
'.texi': 'text/x-texinfo',
'.texinfo': 'text/x-texinfo',
'.tga': 'image/x-tga',
'.tgz': 'application/x-compressed-tar',
'.theme': 'application/x-theme',
'.themepack': 'application/x-windows-themepack',
'.tif': 'image/tiff',
'.tiff': 'image/tiff',
'.tk': 'text/x-tcl',
'.tlrz': 'application/x-lrzip-compressed-tar',
'.tlz': 'application/x-lzma-compressed-tar',
'.tnef': 'application/vnd.ms-tnef',
'.tnf': 'application/vnd.ms-tnef',
'.toc': 'application/x-cdrdao-toc',
'.torrent': 'application/x-bittorrent',
'.tpic': 'image/x-tga',
'.tr': 'text/troff',
'.ts': 'video/mp2t',
'.tsv': 'text/tab-separated-values',
'.tta': 'audio/x-tta',
'.ttc': 'application/x-font-ttf',
'.ttf': 'application/x-font-ttf',
'.ttx': 'application/x-font-ttx',
'.txt': 'text/plain',
'.txz': 'application/x-xz-compressed-tar',
'.tzo': 'application/x-tzo',
'.ufraw': 'application/x-ufraw',
'.ui': 'application/x-gtk-builder',
'.uil': 'text/x-uil',
'.ult': 'audio/x-mod',
'.uni': 'audio/x-mod',
'.url': 'application/x-mswinurl',
'.ustar': 'application/x-ustar',
'.uue': 'text/x-uuencode',
'.v': 'text/x-verilog',
'.vala': 'text/x-vala',
'.vapi': 'text/x-vala',
'.vcard': 'text/vcard',
'.vcf': 'text/vcard',
'.vcs': 'text/calendar',
'.vct': 'text/vcard',
'.vda': 'image/x-tga',
'.vhd': 'text/x-vhdl',
'.vhdl': 'text/x-vhdl',
'.viv': 'video/vivo',
'.vivo': 'video/vivo',
'.vlc': 'audio/x-mpegurl',
'.vob': 'video/mpeg',
'.voc': 'audio/x-voc',
'.vor': 'application/vnd.stardivision.writer',
'.vrm': 'model/vrml',
'.vrml': 'model/vrml',
'.vsd': 'application/vnd.visio',
'.vss': 'application/vnd.visio',
'.vst': 'image/x-tga',
'.vsw': 'application/vnd.visio',
'.vtt': 'text/vtt',
'.w2p': 'application/w2p',
'.wav': 'audio/x-wav',
'.wax': 'audio/x-ms-asx',
'.wb1': 'application/x-quattropro',
'.wb2': 'application/x-quattropro',
'.wb3': 'application/x-quattropro',
'.wbmp': 'image/vnd.wap.wbmp',
'.wcm': 'application/vnd.ms-works',
'.wdb': 'application/vnd.ms-works',
'.webm': 'video/webm',
'.wim': 'application/x-ms-wim',
'.wk1': 'application/vnd.lotus-1-2-3',
'.wk3': 'application/vnd.lotus-1-2-3',
'.wk4': 'application/vnd.lotus-1-2-3',
'.wks': 'application/vnd.ms-works',
'.wma': 'audio/x-ms-wma',
'.wmf': 'image/x-wmf',
'.wml': 'text/vnd.wap.wml',
'.wmls': 'text/vnd.wap.wmlscript',
'.wmv': 'video/x-ms-wmv',
'.wmx': 'audio/x-ms-asx',
'.woff': 'application/font-woff',
'.wp': 'application/vnd.wordperfect',
'.wp4': 'application/vnd.wordperfect',
'.wp5': 'application/vnd.wordperfect',
'.wp6': 'application/vnd.wordperfect',
'.wpd': 'application/vnd.wordperfect',
'.wpg': 'application/x-wpg',
'.wpl': 'application/vnd.ms-wpl',
'.wpp': 'application/vnd.wordperfect',
'.wps': 'application/vnd.ms-works',
'.wri': 'application/x-mswrite',
'.wrl': 'model/vrml',
'.wsgi': 'text/x-python',
'.wv': 'audio/x-wavpack',
'.wvc': 'audio/x-wavpack-correction',
'.wvp': 'audio/x-wavpack',
'.wvx': 'audio/x-ms-asx',
'.wwf': 'application/x-wwf',
'.x3f': 'image/x-sigma-x3f',
'.xac': 'application/x-gnucash',
'.xbel': 'application/x-xbel',
'.xbl': 'application/xml',
'.xbm': 'image/x-xbitmap',
'.xcf': 'image/x-xcf',
'.xcf.bz2': 'image/x-compressed-xcf',
'.xcf.gz': 'image/x-compressed-xcf',
'.xhtml': 'application/xhtml+xml',
'.xi': 'audio/x-xi',
'.xla': 'application/vnd.ms-excel',
'.xlam': 'application/vnd.ms-excel.addin.macroenabled.12',
'.xlc': 'application/vnd.ms-excel',
'.xld': 'application/vnd.ms-excel',
'.xlf': 'application/x-xliff',
'.xliff': 'application/x-xliff',
'.xll': 'application/vnd.ms-excel',
'.xlm': 'application/vnd.ms-excel',
'.xlr': 'application/vnd.ms-works',
'.xls': 'application/vnd.ms-excel',
'.xlsb': 'application/vnd.ms-excel.sheet.binary.macroenabled.12',
'.xlsm': 'application/vnd.ms-excel.sheet.macroenabled.12',
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'.xlt': 'application/vnd.ms-excel',
'.xltm': 'application/vnd.ms-excel.template.macroenabled.12',
'.xltx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'.xlw': 'application/vnd.ms-excel',
'.xm': 'audio/x-xm',
'.xmf': 'audio/x-xmf',
'.xmi': 'text/x-xmi',
'.xml': 'application/xml',
'.xpi': 'application/x-xpinstall',
'.xpm': 'image/x-xpixmap',
'.xps': 'application/oxps',
'.xsd': 'application/xml',
'.xsl': 'application/xslt+xml',
'.xslfo': 'text/x-xslfo',
'.xslt': 'application/xslt+xml',
'.xspf': 'application/xspf+xml',
'.xul': 'application/vnd.mozilla.xul+xml',
'.xwd': 'image/x-xwindowdump',
'.xyz': 'chemical/x-pdb',
'.xz': 'application/x-xz',
'.yaml': 'application/x-yaml',
'.yml': 'application/x-yaml',
'.z': 'application/x-compress',
'.zabw': 'application/x-abiword',
'.zip': 'application/zip',
'.zoo': 'application/x-zoo',
}
def contenttype(filename, default='text/plain'):
"""
Returns the Content-Type string matching extension of the given filename.
"""
i = filename.rfind('.')
if i >= 0:
default = CONTENT_TYPE.get(filename[i:].lower(), default)
j = filename.rfind('.', 0, i)
if j >= 0:
default = CONTENT_TYPE.get(filename[j:].lower(), default)
if default.startswith('text/'):
default += '; charset=utf-8'
return default
| [
[
8,
0,
0.0147,
0.0211,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.027,
0.0012,
0,
0.66,
0.3333,
272,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
0.5053,
0.9531,
0,
0.66,... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\nCONTENT_TYPE dictionary created against freedesktop.org' shared mime info\ndatabase version 1.1.",
"__all__ = ['contenttype']",
"CONTENT_... |
from test_http import *
from test_cache import *
from test_dal import *
from test_html import *
from test_is_url import *
from test_languages import *
from test_router import *
from test_routes import *
from test_storage import *
from test_template import *
from test_utils import *
from test_contribs import *
from test_web import *
import sys
if sys.version[:3] == '2.7':
from test_old_doctests import *
| [
[
1,
0,
0.0588,
0.0588,
0,
0.66,
0,
891,
0,
1,
0,
0,
891,
0,
0
],
[
1,
0,
0.1176,
0.0588,
0,
0.66,
0.0714,
215,
0,
1,
0,
0,
215,
0,
0
],
[
1,
0,
0.1765,
0.0588,
0,
... | [
"from test_http import *",
"from test_cache import *",
"from test_dal import *",
"from test_html import *",
"from test_is_url import *",
"from test_languages import *",
"from test_router import *",
"from test_routes import *",
"from test_storage import *",
"from test_template import *",
"from te... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
def handler(request, response, methods):
response.session_id = None # no sessions for xmlrpc
dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None)
for method in methods:
dispatcher.register_function(method)
dispatcher.register_introspection_functions()
response.headers['Content-Type'] = 'text/xml'
dispatch = getattr(dispatcher, '_dispatch', None)
return dispatcher._marshaled_dispatch(request.body.read(), dispatch)
| [
[
8,
0,
0.2857,
0.2381,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.4762,
0.0476,
0,
0.66,
0.5,
73,
0,
1,
0,
0,
73,
0,
0
],
[
2,
0,
0.8095,
0.4286,
0,
0.66,
... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\"\"\"",
"from SimpleXMLRPCServer import SimpleXMLRPCDispatcher",
"def handler(request, response, methods):\n response.session_id = None... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu> and
Limodou <limodou@gmail.com>.
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
This makes uses of the pywin32 package
(http://sourceforge.net/projects/pywin32/).
You do not need to install this package to use web2py.
"""
import time
import os
import sys
import traceback
try:
import win32serviceutil
import win32service
import win32event
except:
if os.name == 'nt':
print "Warning, winservice is unable to install the Mark Hammond Win32 extensions"
import servicemanager
import _winreg
from fileutils import up
__all__ = ['web2py_windows_service_handler']
class Service(win32serviceutil.ServiceFramework):
_svc_name_ = '_unNamed'
_svc_display_name_ = '_Service Template'
def __init__(self, *args):
win32serviceutil.ServiceFramework.__init__(self, *args)
self.stop_event = win32event.CreateEvent(None, 0, 0, None)
def log(self, msg):
servicemanager.LogInfoMsg(str(msg))
def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
try:
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.start()
win32event.WaitForSingleObject(self.stop_event,
win32event.INFINITE)
except:
self.log(traceback.format_exc(sys.exc_info))
self.SvcStop()
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
try:
self.stop()
except:
self.log(traceback.format_exc(sys.exc_info))
win32event.SetEvent(self.stop_event)
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
# to be overridden
def start(self):
pass
# to be overridden
def stop(self):
pass
class Web2pyService(Service):
_svc_name_ = 'web2py'
_svc_display_name_ = 'web2py Service'
_exe_args_ = 'options'
server = None
def chdir(self):
try:
h = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
r'SYSTEM\CurrentControlSet\Services\%s'
% self._svc_name_)
try:
cls = _winreg.QueryValue(h, 'PythonClass')
finally:
_winreg.CloseKey(h)
dir = os.path.dirname(cls)
os.chdir(dir)
from gluon.settings import global_settings
global_settings.gluon_parent = dir
return True
except:
self.log("Can't change to web2py working path; server is stopped")
return False
def start(self):
self.log('web2py server starting')
if not self.chdir():
return
if len(sys.argv) == 2:
opt_mod = sys.argv[1]
else:
opt_mod = self._exe_args_
options = __import__(opt_mod, [], [], '')
if True: # legacy support for old options files, which have only (deprecated) numthreads
if hasattr(options, 'numthreads') and not hasattr(options, 'minthreads'):
options.minthreads = options.numthreads
if not hasattr(options, 'minthreads'):
options.minthreads = None
if not hasattr(options, 'maxthreads'):
options.maxthreads = None
import main
self.server = main.HttpServer(
ip=options.ip,
port=options.port,
password=options.password,
pid_filename=options.pid_filename,
log_filename=options.log_filename,
profiler_filename=options.profiler_filename,
ssl_certificate=options.ssl_certificate,
ssl_private_key=options.ssl_private_key,
min_threads=options.minthreads,
max_threads=options.maxthreads,
server_name=options.server_name,
request_queue_size=options.request_queue_size,
timeout=options.timeout,
shutdown_timeout=options.shutdown_timeout,
path=options.folder
)
try:
from rewrite import load
load()
self.server.start()
except:
# self.server.stop()
self.server = None
raise
def stop(self):
self.log('web2py server stopping')
if not self.chdir():
return
if self.server:
self.server.stop()
time.sleep(1)
class Web2pyCronService(Web2pyService):
_svc_name_ = 'web2py_cron'
_svc_display_name_ = 'web2py Cron Service'
_exe_args_ = 'options'
def start(self):
import newcron
import global_settings
self.log('web2py server starting')
if not self.chdir():
return
if len(sys.argv) == 2:
opt_mod = sys.argv[1]
else:
opt_mod = self._exe_args_
options = __import__(opt_mod, [], [], '')
global_settings.global_settings.web2py_crontype = 'external'
if options.scheduler: # -K
apps = [app.strip() for app in options.scheduler.split(
',') if check_existent_app(options, app.strip())]
else:
apps = None
self.extcron = newcron.extcron(options.folder, apps=apps)
try:
self.extcron.start()
except:
# self.server.stop()
self.extcron = None
raise
def stop(self):
self.log('web2py cron stopping')
if not self.chdir():
return
if self.extcron:
self.extcron.join()
def register_service_handler(argv=None, opt_file='options', cls=Web2pyService):
path = os.path.dirname(__file__)
web2py_path = up(path)
if web2py_path.endswith('.zip'): # in case bianry distro 'library.zip'
web2py_path = os.path.dirname(web2py_path)
os.chdir(web2py_path)
classstring = os.path.normpath(
os.path.join(web2py_path, 'gluon.winservice.'+cls.__name__))
if opt_file:
cls._exe_args_ = opt_file
win32serviceutil.HandleCommandLine(
cls, serviceClassString=classstring, argv=['', 'install'])
win32serviceutil.HandleCommandLine(
cls, serviceClassString=classstring, argv=argv)
if __name__ == '__main__':
register_service_handler(cls=Web2pyService)
register_service_handler(cls=Web2pyCronService)
| [
[
8,
0,
0.0399,
0.0563,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0751,
0.0047,
0,
0.66,
0.0714,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.0798,
0.0047,
0,
0.66... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nDeveloped by Massimo Di Pierro <mdipierro@cs.depaul.edu> and\nLimodou <limodou@gmail.com>.\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\nThis makes uses of the pywin32 package\n(http://sourceforge.net/projects/pywin32/).",
"import time",
"imp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
import cgi
import os
import re
import copy
import types
import urllib
import base64
import sanitizer
import itertools
import decoder
import copy_reg
import cPickle
import marshal
from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint
from storage import Storage
from utils import web2py_uuid, simple_hash, compare
from highlight import highlight
regex_crlf = re.compile('\r|\n')
join = ''.join
# name2codepoint is incomplete respect to xhtml (and xml): 'apos' is missing.
entitydefs = dict(map(lambda (
k, v): (k, unichr(v).encode('utf-8')), name2codepoint.iteritems()))
entitydefs.setdefault('apos', u"'".encode('utf-8'))
__all__ = [
'A',
'B',
'BEAUTIFY',
'BODY',
'BR',
'BUTTON',
'CENTER',
'CAT',
'CODE',
'COL',
'COLGROUP',
'DIV',
'EM',
'EMBED',
'FIELDSET',
'FORM',
'H1',
'H2',
'H3',
'H4',
'H5',
'H6',
'HEAD',
'HR',
'HTML',
'I',
'IFRAME',
'IMG',
'INPUT',
'LABEL',
'LEGEND',
'LI',
'LINK',
'OL',
'UL',
'MARKMIN',
'MENU',
'META',
'OBJECT',
'ON',
'OPTION',
'P',
'PRE',
'SCRIPT',
'OPTGROUP',
'SELECT',
'SPAN',
'STRONG',
'STYLE',
'TABLE',
'TAG',
'TD',
'TEXTAREA',
'TH',
'THEAD',
'TBODY',
'TFOOT',
'TITLE',
'TR',
'TT',
'URL',
'XHTML',
'XML',
'xmlescape',
'embed64',
]
def xmlescape(data, quote=True):
"""
returns an escaped string of the provided data
:param data: the data to be escaped
:param quote: optional (default False)
"""
# first try the xml function
if hasattr(data, 'xml') and callable(data.xml):
return data.xml()
# otherwise, make it a string
if not isinstance(data, (str, unicode)):
data = str(data)
elif isinstance(data, unicode):
data = data.encode('utf8', 'xmlcharrefreplace')
# ... and do the escaping
data = cgi.escape(data, quote).replace("'", "'")
return data
def call_as_list(f,*a,**b):
if not isinstance(f, (list,tuple)):
f = [f]
for item in f:
item(*a,**b)
def truncate_string(text, length, dots='...'):
text = text.decode('utf-8')
if len(text) > length:
text = text[:length - len(dots)].encode('utf-8') + dots
return text
def URL(
a=None,
c=None,
f=None,
r=None,
args=None,
vars=None,
anchor='',
extension=None,
env=None,
hmac_key=None,
hash_vars=True,
salt=None,
user_signature=None,
scheme=None,
host=None,
port=None,
encode_embedded_slash=False,
url_encode=True
):
"""
generate a URL
example::
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':1, 'q':2}, anchor='1'))
'/a/c/f/x/y/z?p=1&q=2#1'
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':(1,3), 'q':2}, anchor='1'))
'/a/c/f/x/y/z?p=1&p=3&q=2#1'
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':(3,1), 'q':2}, anchor='1'))
'/a/c/f/x/y/z?p=3&p=1&q=2#1'
>>> str(URL(a='a', c='c', f='f', anchor='1+2'))
'/a/c/f#1%2B2'
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':(1,3), 'q':2}, anchor='1', hmac_key='key'))
'/a/c/f/x/y/z?p=1&p=3&q=2&_signature=a32530f0d0caa80964bb92aad2bedf8a4486a31f#1'
>>> str(URL(a='a', c='c', f='f', args=['w/x', 'y/z']))
'/a/c/f/w/x/y/z'
>>> str(URL(a='a', c='c', f='f', args=['w/x', 'y/z'], encode_embedded_slash=True))
'/a/c/f/w%2Fx/y%2Fz'
>>> str(URL(a='a', c='c', f='f', args=['%(id)d'], url_encode=False))
'/a/c/f/%(id)d'
>>> str(URL(a='a', c='c', f='f', args=['%(id)d'], url_encode=True))
'/a/c/f/%25%28id%29d'
>>> str(URL(a='a', c='c', f='f', vars={'id' : '%(id)d' }, url_encode=False))
'/a/c/f?id=%(id)d'
>>> str(URL(a='a', c='c', f='f', vars={'id' : '%(id)d' }, url_encode=True))
'/a/c/f?id=%25%28id%29d'
>>> str(URL(a='a', c='c', f='f', anchor='%(id)d', url_encode=False))
'/a/c/f#%(id)d'
>>> str(URL(a='a', c='c', f='f', anchor='%(id)d', url_encode=True))
'/a/c/f#%25%28id%29d'
generates a url '/a/c/f' corresponding to application a, controller c
and function f. If r=request is passed, a, c, f are set, respectively,
to r.application, r.controller, r.function.
The more typical usage is:
URL(r=request, f='index') that generates a url for the index function
within the present application and controller.
:param a: application (default to current if r is given)
:param c: controller (default to current if r is given)
:param f: function (default to current if r is given)
:param r: request (optional)
:param args: any arguments (optional)
:param vars: any variables (optional)
:param anchor: anchorname, without # (optional)
:param hmac_key: key to use when generating hmac signature (optional)
:param hash_vars: which of the vars to include in our hmac signature
True (default) - hash all vars, False - hash none of the vars,
iterable - hash only the included vars ['key1','key2']
:param scheme: URI scheme (True, 'http' or 'https', etc); forces absolute URL (optional)
:param host: string to force absolute URL with host (True means http_host)
:param port: optional port number (forces absolute URL)
:raises SyntaxError: when no application, controller or function is
available
:raises SyntaxError: when a CRLF is found in the generated url
"""
from rewrite import url_out # done here in case used not-in web2py
if args in (None, []):
args = []
vars = vars or {}
application = None
controller = None
function = None
if not isinstance(args, (list, tuple)):
args = [args]
if not r:
if a and not c and not f:
(f, a, c) = (a, c, f)
elif a and c and not f:
(c, f, a) = (a, c, f)
from globals import current
if hasattr(current, 'request'):
r = current.request
if r:
application = r.application
controller = r.controller
function = r.function
env = r.env
if extension is None and r.extension != 'html':
extension = r.extension
if a:
application = a
if c:
controller = c
if f:
if not isinstance(f, str):
if hasattr(f, '__name__'):
function = f.__name__
else:
raise SyntaxError(
'when calling URL, function or function name required')
elif '/' in f:
if f.startswith("/"):
f = f[1:]
items = f.split('/')
function = f = items[0]
args = items[1:] + args
else:
function = f
# if the url gets a static resource, don't force extention
if controller == 'static':
extension = None
if '.' in function:
function, extension = function.rsplit('.', 1)
function2 = '%s.%s' % (function, extension or 'html')
if not (application and controller and function):
raise SyntaxError('not enough information to build the url (%s %s %s)' % (application, controller, function))
if args:
if url_encode:
if encode_embedded_slash:
other = '/' + '/'.join([urllib.quote(str(
x), '') for x in args])
else:
other = args and urllib.quote(
'/' + '/'.join([str(x) for x in args]))
else:
other = args and ('/' + '/'.join([str(x) for x in args]))
else:
other = ''
if other.endswith('/'):
other += '/' # add trailing slash to make last trailing empty arg explicit
list_vars = []
for (key, vals) in sorted(vars.items()):
if key == '_signature':
continue
if not isinstance(vals, (list, tuple)):
vals = [vals]
for val in vals:
list_vars.append((key, val))
if user_signature:
from globals import current
if current.session.auth:
hmac_key = current.session.auth.hmac_key
if hmac_key:
# generate an hmac signature of the vars & args so can later
# verify the user hasn't messed with anything
h_args = '/%s/%s/%s%s' % (application, controller, function2, other)
# how many of the vars should we include in our hash?
if hash_vars is True: # include them all
h_vars = list_vars
elif hash_vars is False: # include none of them
h_vars = ''
else: # include just those specified
if hash_vars and not isinstance(hash_vars, (list, tuple)):
hash_vars = [hash_vars]
h_vars = [(k, v) for (k, v) in list_vars if k in hash_vars]
# re-assembling the same way during hash authentication
message = h_args + '?' + urllib.urlencode(sorted(h_vars))
sig = simple_hash(
message, hmac_key or '', salt or '', digest_alg='sha1')
# add the signature into vars
list_vars.append(('_signature', sig))
if list_vars:
if url_encode:
other += '?%s' % urllib.urlencode(list_vars)
else:
other += '?%s' % '&'.join(['%s=%s' % var[:2] for var in list_vars])
if anchor:
if url_encode:
other += '#' + urllib.quote(str(anchor))
else:
other += '#' + (str(anchor))
if extension:
function += '.' + extension
if regex_crlf.search(join([application, controller, function, other])):
raise SyntaxError('CRLF Injection Detected')
url = url_out(r, env, application, controller, function,
args, other, scheme, host, port)
return url
def verifyURL(request, hmac_key=None, hash_vars=True, salt=None, user_signature=None):
"""
Verifies that a request's args & vars have not been tampered with by the user
:param request: web2py's request object
:param hmac_key: the key to authenticate with, must be the same one previously
used when calling URL()
:param hash_vars: which vars to include in our hashing. (Optional)
Only uses the 1st value currently
True (or undefined) means all, False none,
an iterable just the specified keys
do not call directly. Use instead:
URL.verify(hmac_key='...')
the key has to match the one used to generate the URL.
>>> r = Storage()
>>> gv = Storage(p=(1,3),q=2,_signature='a32530f0d0caa80964bb92aad2bedf8a4486a31f')
>>> r.update(dict(application='a', controller='c', function='f', extension='html'))
>>> r['args'] = ['x', 'y', 'z']
>>> r['get_vars'] = gv
>>> verifyURL(r, 'key')
True
>>> verifyURL(r, 'kay')
False
>>> r.get_vars.p = (3, 1)
>>> verifyURL(r, 'key')
True
>>> r.get_vars.p = (3, 2)
>>> verifyURL(r, 'key')
False
"""
if not '_signature' in request.get_vars:
return False # no signature in the request URL
# check if user_signature requires
if user_signature:
from globals import current
if not current.session or not current.session.auth:
return False
hmac_key = current.session.auth.hmac_key
if not hmac_key:
return False
# get our sig from request.get_vars for later comparison
original_sig = request.get_vars._signature
# now generate a new hmac for the remaining args & vars
vars, args = request.get_vars, request.args
# remove the signature var since it was not part of our signed message
request.get_vars.pop('_signature')
# join all the args & vars into one long string
# always include all of the args
other = args and urllib.quote('/' + '/'.join([str(x) for x in args])) or ''
h_args = '/%s/%s/%s.%s%s' % (request.application,
request.controller,
request.function,
request.extension,
other)
# but only include those vars specified (allows more flexibility for use with
# forms or ajax)
list_vars = []
for (key, vals) in sorted(vars.items()):
if not isinstance(vals, (list, tuple)):
vals = [vals]
for val in vals:
list_vars.append((key, val))
# which of the vars are to be included?
if hash_vars is True: # include them all
h_vars = list_vars
elif hash_vars is False: # include none of them
h_vars = ''
else: # include just those specified
# wrap in a try - if the desired vars have been removed it'll fail
try:
if hash_vars and not isinstance(hash_vars, (list, tuple)):
hash_vars = [hash_vars]
h_vars = [(k, v) for (k, v) in list_vars if k in hash_vars]
except:
# user has removed one of our vars! Immediate fail
return False
# build the full message string with both args & vars
message = h_args + '?' + urllib.urlencode(sorted(h_vars))
# hash with the hmac_key provided
sig = simple_hash(message, str(hmac_key), salt or '', digest_alg='sha1')
# put _signature back in get_vars just in case a second call to URL.verify is performed
# (otherwise it'll immediately return false)
request.get_vars['_signature'] = original_sig
# return whether or not the signature in the request matched the one we just generated
# (I.E. was the message the same as the one we originally signed)
return compare(original_sig, sig)
URL.verify = verifyURL
ON = True
class XmlComponent(object):
"""
Abstract root for all Html components
"""
# TODO: move some DIV methods to here
def xml(self):
raise NotImplementedError
def __mul__(self, n):
return CAT(*[self for i in range(n)])
def __add__(self, other):
if isinstance(self, CAT):
components = self.components
else:
components = [self]
if isinstance(other, CAT):
components += other.components
else:
components += [other]
return CAT(*components)
def add_class(self, name):
""" add a class to _class attribute """
c = self['_class']
classes = (set(c.split()) if c else set()) | set(name.split())
self['_class'] = ' '.join(classes) if classes else None
return self
def remove_class(self, name):
""" remove a class from _class attribute """
c = self['_class']
classes = (set(c.split()) if c else set()) - set(name.split())
self['_class'] = ' '.join(classes) if classes else None
return self
class XML(XmlComponent):
"""
use it to wrap a string that contains XML/HTML so that it will not be
escaped by the template
example:
>>> XML('<h1>Hello</h1>').xml()
'<h1>Hello</h1>'
"""
def __init__(
self,
text,
sanitize=False,
permitted_tags=[
'a',
'b',
'blockquote',
'br/',
'i',
'li',
'ol',
'ul',
'p',
'cite',
'code',
'pre',
'img/',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'table', 'tr', 'td', 'div',
'strong','span',
],
allowed_attributes={
'a': ['href', 'title', 'target'],
'img': ['src', 'alt'],
'blockquote': ['type'],
'td': ['colspan'],
},
):
"""
:param text: the XML text
:param sanitize: sanitize text using the permitted tags and allowed
attributes (default False)
:param permitted_tags: list of permitted tags (default: simple list of
tags)
:param allowed_attributes: dictionary of allowed attributed (default
for A, IMG and BlockQuote).
The key is the tag; the value is a list of allowed attributes.
"""
if sanitize:
text = sanitizer.sanitize(text, permitted_tags,
allowed_attributes)
if isinstance(text, unicode):
text = text.encode('utf8', 'xmlcharrefreplace')
elif not isinstance(text, str):
text = str(text)
self.text = text
def xml(self):
return self.text
def __str__(self):
return self.text
def __add__(self, other):
return '%s%s' % (self, other)
def __radd__(self, other):
return '%s%s' % (other, self)
def __cmp__(self, other):
return cmp(str(self), str(other))
def __hash__(self):
return hash(str(self))
# why was this here? Break unpickling in sessions
# def __getattr__(self, name):
# return getattr(str(self), name)
def __getitem__(self, i):
return str(self)[i]
def __getslice__(self, i, j):
return str(self)[i:j]
def __iter__(self):
for c in str(self):
yield c
def __len__(self):
return len(str(self))
def flatten(self, render=None):
"""
return the text stored by the XML object rendered by the render function
"""
if render:
return render(self.text, None, {})
return self.text
def elements(self, *args, **kargs):
"""
to be considered experimental since the behavior of this method is questionable
another options could be TAG(self.text).elements(*args,**kargs)
"""
return []
### important to allow safe session.flash=T(....)
def XML_unpickle(data):
return marshal.loads(data)
def XML_pickle(data):
return XML_unpickle, (marshal.dumps(str(data)),)
copy_reg.pickle(XML, XML_pickle, XML_unpickle)
class DIV(XmlComponent):
"""
HTML helper, for easy generating and manipulating a DOM structure.
Little or no validation is done.
Behaves like a dictionary regarding updating of attributes.
Behaves like a list regarding inserting/appending components.
example::
>>> DIV('hello', 'world', _style='color:red;').xml()
'<div style=\"color:red;\">helloworld</div>'
all other HTML helpers are derived from DIV.
_something=\"value\" attributes are transparently translated into
something=\"value\" HTML attributes
"""
# name of the tag, subclasses should update this
# tags ending with a '/' denote classes that cannot
# contain components
tag = 'div'
def __init__(self, *components, **attributes):
"""
:param *components: any components that should be nested in this element
:param **attributes: any attributes you want to give to this element
:raises SyntaxError: when a stand alone tag receives components
"""
if self.tag[-1:] == '/' and components:
raise SyntaxError('<%s> tags cannot have components'
% self.tag)
if len(components) == 1 and isinstance(components[0], (list, tuple)):
self.components = list(components[0])
else:
self.components = list(components)
self.attributes = attributes
self._fixup()
# converts special attributes in components attributes
self.parent = None
for c in self.components:
self._setnode(c)
self._postprocessing()
def update(self, **kargs):
"""
dictionary like updating of the tag attributes
"""
for (key, value) in kargs.iteritems():
self[key] = value
return self
def append(self, value):
"""
list style appending of components
>>> a=DIV()
>>> a.append(SPAN('x'))
>>> print a
<div><span>x</span></div>
"""
self._setnode(value)
ret = self.components.append(value)
self._fixup()
return ret
def insert(self, i, value):
"""
list style inserting of components
>>> a=DIV()
>>> a.insert(0,SPAN('x'))
>>> print a
<div><span>x</span></div>
"""
self._setnode(value)
ret = self.components.insert(i, value)
self._fixup()
return ret
def __getitem__(self, i):
"""
gets attribute with name 'i' or component #i.
If attribute 'i' is not found returns None
:param i: index
if i is a string: the name of the attribute
otherwise references to number of the component
"""
if isinstance(i, str):
try:
return self.attributes[i]
except KeyError:
return None
else:
return self.components[i]
def __setitem__(self, i, value):
"""
sets attribute with name 'i' or component #i.
:param i: index
if i is a string: the name of the attribute
otherwise references to number of the component
:param value: the new value
"""
self._setnode(value)
if isinstance(i, (str, unicode)):
self.attributes[i] = value
else:
self.components[i] = value
def __delitem__(self, i):
"""
deletes attribute with name 'i' or component #i.
:param i: index
if i is a string: the name of the attribute
otherwise references to number of the component
"""
if isinstance(i, str):
del self.attributes[i]
else:
del self.components[i]
def __len__(self):
"""
returns the number of included components
"""
return len(self.components)
def __nonzero__(self):
"""
always return True
"""
return True
def _fixup(self):
"""
Handling of provided components.
Nothing to fixup yet. May be overridden by subclasses,
eg for wrapping some components in another component or blocking them.
"""
return
def _wrap_components(self, allowed_parents,
wrap_parent=None,
wrap_lambda=None):
"""
helper for _fixup. Checks if a component is in allowed_parents,
otherwise wraps it in wrap_parent
:param allowed_parents: (tuple) classes that the component should be an
instance of
:param wrap_parent: the class to wrap the component in, if needed
:param wrap_lambda: lambda to use for wrapping, if needed
"""
components = []
for c in self.components:
if isinstance(c, allowed_parents):
pass
elif wrap_lambda:
c = wrap_lambda(c)
else:
c = wrap_parent(c)
if isinstance(c, DIV):
c.parent = self
components.append(c)
self.components = components
def _postprocessing(self):
"""
Handling of attributes (normally the ones not prefixed with '_').
Nothing to postprocess yet. May be overridden by subclasses
"""
return
def _traverse(self, status, hideerror=False):
# TODO: docstring
newstatus = status
for c in self.components:
if hasattr(c, '_traverse') and callable(c._traverse):
c.vars = self.vars
c.request_vars = self.request_vars
c.errors = self.errors
c.latest = self.latest
c.session = self.session
c.formname = self.formname
c['hideerror'] = hideerror or \
self.attributes.get('hideerror', False)
newstatus = c._traverse(status, hideerror) and newstatus
# for input, textarea, select, option
# deal with 'value' and 'validation'
name = self['_name']
if newstatus:
newstatus = self._validate()
self._postprocessing()
elif 'old_value' in self.attributes:
self['value'] = self['old_value']
self._postprocessing()
elif name and name in self.vars:
self['value'] = self.vars[name]
self._postprocessing()
if name:
self.latest[name] = self['value']
return newstatus
def _validate(self):
"""
nothing to validate yet. May be overridden by subclasses
"""
return True
def _setnode(self, value):
if isinstance(value, DIV):
value.parent = self
def _xml(self):
"""
helper for xml generation. Returns separately:
- the component attributes
- the generated xml of the inner components
Component attributes start with an underscore ('_') and
do not have a False or None value. The underscore is removed.
A value of True is replaced with the attribute name.
:returns: tuple: (attributes, components)
"""
# get the attributes for this component
# (they start with '_', others may have special meanings)
attr = []
for key, value in self.attributes.iteritems():
if key[:1] != '_':
continue
name = key[1:]
if value is True:
value = name
elif value is False or value is None:
continue
attr.append((name, value))
data = self.attributes.get('data',{})
for key, value in data.iteritems():
name = 'data-' + key
value = data[key]
attr.append((name,value))
attr.sort()
fa = ''
for name,value in attr:
fa += ' %s="%s"' % (name, xmlescape(value, True))
# get the xml for the inner components
co = join([xmlescape(component) for component in
self.components])
return (fa, co)
def xml(self):
"""
generates the xml for this component.
"""
(fa, co) = self._xml()
if not self.tag:
return co
if self.tag[-1:] == '/':
# <tag [attributes] />
return '<%s%s />' % (self.tag[:-1], fa)
# else: <tag [attributes]> inner components xml </tag>
return '<%s%s>%s</%s>' % (self.tag, fa, co, self.tag)
def __str__(self):
"""
str(COMPONENT) returns equals COMPONENT.xml()
"""
return self.xml()
def flatten(self, render=None):
"""
return the text stored by the DIV object rendered by the render function
the render function must take text, tagname, and attributes
render=None is equivalent to render=lambda text, tag, attr: text
>>> markdown = lambda text,tag=None,attributes={}: \
{None: re.sub('\s+',' ',text), \
'h1':'#'+text+'\\n\\n', \
'p':text+'\\n'}.get(tag,text)
>>> a=TAG('<h1>Header</h1><p>this is a test</p>')
>>> a.flatten(markdown)
'#Header\\n\\nthis is a test\\n'
"""
text = ''
for c in self.components:
if isinstance(c, XmlComponent):
s = c.flatten(render)
elif render:
s = render(str(c))
else:
s = str(c)
text += s
if render:
text = render(text, self.tag, self.attributes)
return text
regex_tag = re.compile('^[\w\-\:]+')
regex_id = re.compile('#([\w\-]+)')
regex_class = re.compile('\.([\w\-]+)')
regex_attr = re.compile('\[([\w\-\:]+)=(.*?)\]')
def elements(self, *args, **kargs):
"""
find all component that match the supplied attribute dictionary,
or None if nothing could be found
All components of the components are searched.
>>> a = DIV(DIV(SPAN('x'),3,DIV(SPAN('y'))))
>>> for c in a.elements('span',first_only=True): c[0]='z'
>>> print a
<div><div><span>z</span>3<div><span>y</span></div></div></div>
>>> for c in a.elements('span'): c[0]='z'
>>> print a
<div><div><span>z</span>3<div><span>z</span></div></div></div>
It also supports a syntax compatible with jQuery
>>> a=TAG('<div><span><a id="1-1" u:v=$>hello</a></span><p class="this is a test">world</p></div>')
>>> for e in a.elements('div a#1-1, p.is'): print e.flatten()
hello
world
>>> for e in a.elements('#1-1'): print e.flatten()
hello
>>> a.elements('a[u:v=$]')[0].xml()
'<a id="1-1" u:v="$">hello</a>'
>>> a=FORM( INPUT(_type='text'), SELECT(range(1)), TEXTAREA() )
>>> for c in a.elements('input, select, textarea'): c['_disabled'] = 'disabled'
>>> a.xml()
'<form action="#" enctype="multipart/form-data" method="post"><input disabled="disabled" type="text" /><select disabled="disabled"><option value="0">0</option></select><textarea cols="40" disabled="disabled" rows="10"></textarea></form>'
Elements that are matched can also be replaced or removed by specifying
a "replace" argument (note, a list of the original matching elements
is still returned as usual).
>>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='abc'), SPAN('z', _class='abc'))))
>>> b = a.elements('span.abc', replace=P('x', _class='xyz'))
>>> print a
<div><div><p class="xyz">x</p><div><p class="xyz">x</p><p class="xyz">x</p></div></div></div>
"replace" can be a callable, which will be passed the original element and
should return a new element to replace it.
>>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='abc'), SPAN('z', _class='abc'))))
>>> b = a.elements('span.abc', replace=lambda el: P(el[0], _class='xyz'))
>>> print a
<div><div><p class="xyz">x</p><div><p class="xyz">y</p><p class="xyz">z</p></div></div></div>
If replace=None, matching elements will be removed completely.
>>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='abc'), SPAN('z', _class='abc'))))
>>> b = a.elements('span', find='y', replace=None)
>>> print a
<div><div><span class="abc">x</span><div><span class="abc">z</span></div></div></div>
If a "find_text" argument is specified, elements will be searched for text
components that match find_text, and any matching text components will be
replaced (find_text is ignored if "replace" is not also specified).
Like the "find" argument, "find_text" can be a string or a compiled regex.
>>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='abc'), SPAN('z', _class='abc'))))
>>> b = a.elements(find_text=re.compile('x|y|z'), replace='hello')
>>> print a
<div><div><span class="abc">hello</span><div><span class="abc">hello</span><span class="abc">hello</span></div></div></div>
If other attributes are specified along with find_text, then only components
that match the specified attributes will be searched for find_text.
>>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='efg'), SPAN('z', _class='abc'))))
>>> b = a.elements('span.efg', find_text=re.compile('x|y|z'), replace='hello')
>>> print a
<div><div><span class="abc">x</span><div><span class="efg">hello</span><span class="abc">z</span></div></div></div>
"""
if len(args) == 1:
args = [a.strip() for a in args[0].split(',')]
if len(args) > 1:
subset = [self.elements(a, **kargs) for a in args]
return reduce(lambda a, b: a + b, subset, [])
elif len(args) == 1:
items = args[0].split()
if len(items) > 1:
subset = [a.elements(' '.join(
items[1:]), **kargs) for a in self.elements(items[0])]
return reduce(lambda a, b: a + b, subset, [])
else:
item = items[0]
if '#' in item or '.' in item or '[' in item:
match_tag = self.regex_tag.search(item)
match_id = self.regex_id.search(item)
match_class = self.regex_class.search(item)
match_attr = self.regex_attr.finditer(item)
args = []
if match_tag:
args = [match_tag.group()]
if match_id:
kargs['_id'] = match_id.group(1)
if match_class:
kargs['_class'] = re.compile('(?<!\w)%s(?!\w)' %
match_class.group(1).replace('-', '\\-').replace(':', '\\:'))
for item in match_attr:
kargs['_' + item.group(1)] = item.group(2)
return self.elements(*args, **kargs)
# make a copy of the components
matches = []
# check if the component has an attribute with the same
# value as provided
check = True
tag = getattr(self, 'tag').replace('/', '')
if args and tag not in args:
check = False
for (key, value) in kargs.iteritems():
if key not in ['first_only', 'replace', 'find_text']:
if isinstance(value, (str, int)):
if self[key] != str(value):
check = False
elif key in self.attributes:
if not value.search(str(self[key])):
check = False
else:
check = False
if 'find' in kargs:
find = kargs['find']
is_regex = not isinstance(find, (str, int))
for c in self.components:
if (isinstance(c, str) and ((is_regex and find.search(c)) or
(str(find) in c))):
check = True
# if found, return the component
if check:
matches.append(self)
first_only = kargs.get('first_only', False)
replace = kargs.get('replace', False)
find_text = replace is not False and kargs.get('find_text', False)
is_regex = not isinstance(find_text, (str, int, bool))
find_components = not (check and first_only)
def replace_component(i):
if replace is None:
del self[i]
elif callable(replace):
self[i] = replace(self[i])
else:
self[i] = replace
# loop the components
if find_text or find_components:
for i, c in enumerate(self.components):
if check and find_text and isinstance(c, str) and \
((is_regex and find_text.search(c)) or (str(find_text) in c)):
replace_component(i)
if find_components and isinstance(c, XmlComponent):
child_matches = c.elements(*args, **kargs)
if len(child_matches):
if not find_text and replace is not False and child_matches[0] is c:
replace_component(i)
if first_only:
return child_matches
matches.extend(child_matches)
return matches
def element(self, *args, **kargs):
"""
find the first component that matches the supplied attribute dictionary,
or None if nothing could be found
Also the components of the components are searched.
"""
kargs['first_only'] = True
elements = self.elements(*args, **kargs)
if not elements:
# we found nothing
return None
return elements[0]
def siblings(self, *args, **kargs):
"""
find all sibling components that match the supplied argument list
and attribute dictionary, or None if nothing could be found
"""
sibs = [s for s in self.parent.components if not s == self]
matches = []
first_only = False
if 'first_only' in kargs:
first_only = kargs.pop('first_only')
for c in sibs:
try:
check = True
tag = getattr(c, 'tag').replace("/", "")
if args and tag not in args:
check = False
for (key, value) in kargs.iteritems():
if c[key] != value:
check = False
if check:
matches.append(c)
if first_only:
break
except:
pass
return matches
def sibling(self, *args, **kargs):
"""
find the first sibling component that match the supplied argument list
and attribute dictionary, or None if nothing could be found
"""
kargs['first_only'] = True
sibs = self.siblings(*args, **kargs)
if not sibs:
return None
return sibs[0]
class CAT(DIV):
tag = ''
def TAG_unpickler(data):
return cPickle.loads(data)
def TAG_pickler(data):
d = DIV()
d.__dict__ = data.__dict__
marshal_dump = cPickle.dumps(d)
return (TAG_unpickler, (marshal_dump,))
class __TAG__(XmlComponent):
"""
TAG factory example::
>>> print TAG.first(TAG.second('test'), _key = 3)
<first key=\"3\"><second>test</second></first>
"""
def __getitem__(self, name):
return self.__getattr__(name)
def __getattr__(self, name):
if name[-1:] == '_':
name = name[:-1] + '/'
if isinstance(name, unicode):
name = name.encode('utf-8')
class __tag__(DIV):
tag = name
copy_reg.pickle(__tag__, TAG_pickler, TAG_unpickler)
return lambda *a, **b: __tag__(*a, **b)
def __call__(self, html):
return web2pyHTMLParser(decoder.decoder(html)).tree
TAG = __TAG__()
class HTML(DIV):
"""
There are four predefined document type definitions.
They can be specified in the 'doctype' parameter:
-'strict' enables strict doctype
-'transitional' enables transitional doctype (default)
-'frameset' enables frameset doctype
-'html5' enables HTML 5 doctype
-any other string will be treated as user's own doctype
'lang' parameter specifies the language of the document.
Defaults to 'en'.
See also :class:`DIV`
"""
tag = 'html'
strict = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n'
transitional = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n'
frameset = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">\n'
html5 = '<!DOCTYPE HTML>\n'
def xml(self):
lang = self['lang']
if not lang:
lang = 'en'
self.attributes['_lang'] = lang
doctype = self['doctype']
if doctype is None:
doctype = self.transitional
elif doctype == 'strict':
doctype = self.strict
elif doctype == 'transitional':
doctype = self.transitional
elif doctype == 'frameset':
doctype = self.frameset
elif doctype == 'html5':
doctype = self.html5
elif doctype == '':
doctype = ''
else:
doctype = '%s\n' % doctype
(fa, co) = self._xml()
return '%s<%s%s>%s</%s>' % (doctype, self.tag, fa, co, self.tag)
class XHTML(DIV):
"""
This is XHTML version of the HTML helper.
There are three predefined document type definitions.
They can be specified in the 'doctype' parameter:
-'strict' enables strict doctype
-'transitional' enables transitional doctype (default)
-'frameset' enables frameset doctype
-any other string will be treated as user's own doctype
'lang' parameter specifies the language of the document and the xml document.
Defaults to 'en'.
'xmlns' parameter specifies the xml namespace.
Defaults to 'http://www.w3.org/1999/xhtml'.
See also :class:`DIV`
"""
tag = 'html'
strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n'
transitional = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n'
frameset = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">\n'
xmlns = 'http://www.w3.org/1999/xhtml'
def xml(self):
xmlns = self['xmlns']
if xmlns:
self.attributes['_xmlns'] = xmlns
else:
self.attributes['_xmlns'] = self.xmlns
lang = self['lang']
if not lang:
lang = 'en'
self.attributes['_lang'] = lang
self.attributes['_xml:lang'] = lang
doctype = self['doctype']
if doctype:
if doctype == 'strict':
doctype = self.strict
elif doctype == 'transitional':
doctype = self.transitional
elif doctype == 'frameset':
doctype = self.frameset
else:
doctype = '%s\n' % doctype
else:
doctype = self.transitional
(fa, co) = self._xml()
return '%s<%s%s>%s</%s>' % (doctype, self.tag, fa, co, self.tag)
class HEAD(DIV):
tag = 'head'
class TITLE(DIV):
tag = 'title'
class META(DIV):
tag = 'meta/'
class LINK(DIV):
tag = 'link/'
class SCRIPT(DIV):
tag = 'script'
def xml(self):
(fa, co) = self._xml()
# no escaping of subcomponents
co = '\n'.join([str(component) for component in
self.components])
if co:
# <script [attributes]><!--//--><![CDATA[//><!--
# script body
# //--><!]]></script>
# return '<%s%s><!--//--><![CDATA[//><!--\n%s\n//--><!]]></%s>' % (self.tag, fa, co, self.tag)
return '<%s%s><!--\n%s\n//--></%s>' % (self.tag, fa, co, self.tag)
else:
return DIV.xml(self)
class STYLE(DIV):
tag = 'style'
def xml(self):
(fa, co) = self._xml()
# no escaping of subcomponents
co = '\n'.join([str(component) for component in
self.components])
if co:
# <style [attributes]><!--/*--><![CDATA[/*><!--*/
# style body
# /*]]>*/--></style>
return '<%s%s><!--/*--><![CDATA[/*><!--*/\n%s\n/*]]>*/--></%s>' % (self.tag, fa, co, self.tag)
else:
return DIV.xml(self)
class IMG(DIV):
tag = 'img/'
class SPAN(DIV):
tag = 'span'
class BODY(DIV):
tag = 'body'
class H1(DIV):
tag = 'h1'
class H2(DIV):
tag = 'h2'
class H3(DIV):
tag = 'h3'
class H4(DIV):
tag = 'h4'
class H5(DIV):
tag = 'h5'
class H6(DIV):
tag = 'h6'
class P(DIV):
"""
Will replace ``\\n`` by ``<br />`` if the `cr2br` attribute is provided.
see also :class:`DIV`
"""
tag = 'p'
def xml(self):
text = DIV.xml(self)
if self['cr2br']:
text = text.replace('\n', '<br />')
return text
class STRONG(DIV):
tag = 'strong'
class B(DIV):
tag = 'b'
class BR(DIV):
tag = 'br/'
class HR(DIV):
tag = 'hr/'
class A(DIV):
tag = 'a'
def xml(self):
if not self.components and self['_href']:
self.append(self['_href'])
if self['delete']:
d = "jQuery(this).closest('%s').remove();" % self['delete']
else:
d = ''
if self['component']:
self['_onclick'] = "web2py_component('%s','%s');%sreturn false;" % \
(self['component'], self['target'] or '', d)
self['_href'] = self['_href'] or '#null'
elif self['callback']:
returnfalse = "var e = arguments[0] || window.event; e.cancelBubble=true; if (e.stopPropagation) {e.stopPropagation(); e.stopImmediatePropagation(); e.preventDefault();}"
if d and not self['noconfirm']:
self['_onclick'] = "if(confirm(w2p_ajax_confirm_message||'Are you sure you want to delete this object?')){ajax('%s',[],'%s');%s};%s" % \
(self['callback'], self['target'] or '', d, returnfalse)
else:
self['_onclick'] = "ajax('%s',[],'%s');%sreturn false" % \
(self['callback'], self['target'] or '', d)
self['_href'] = self['_href'] or '#null'
elif self['cid']:
pre = self['pre_call'] + ';' if self['pre_call'] else ''
self['_onclick'] = '%sweb2py_component("%s","%s");%sreturn false;' % \
(pre,self['_href'], self['cid'], d)
return DIV.xml(self)
class BUTTON(DIV):
tag = 'button'
class EM(DIV):
tag = 'em'
class EMBED(DIV):
tag = 'embed/'
class TT(DIV):
tag = 'tt'
class PRE(DIV):
tag = 'pre'
class CENTER(DIV):
tag = 'center'
class CODE(DIV):
"""
displays code in HTML with syntax highlighting.
:param attributes: optional attributes:
- language: indicates the language, otherwise PYTHON is assumed
- link: can provide a link
- styles: for styles
Example::
{{=CODE(\"print 'hello world'\", language='python', link=None,
counter=1, styles={}, highlight_line=None)}}
supported languages are \"python\", \"html_plain\", \"c\", \"cpp\",
\"web2py\", \"html\".
The \"html\" language interprets {{ and }} tags as \"web2py\" code,
\"html_plain\" doesn't.
if a link='/examples/global/vars/' is provided web2py keywords are linked to
the online docs.
the counter is used for line numbering, counter can be None or a prompt
string.
"""
def xml(self):
language = self['language'] or 'PYTHON'
link = self['link']
counter = self.attributes.get('counter', 1)
highlight_line = self.attributes.get('highlight_line', None)
context_lines = self.attributes.get('context_lines', None)
styles = self['styles'] or {}
return highlight(
join(self.components),
language=language,
link=link,
counter=counter,
styles=styles,
attributes=self.attributes,
highlight_line=highlight_line,
context_lines=context_lines,
)
class LABEL(DIV):
tag = 'label'
class LI(DIV):
tag = 'li'
class UL(DIV):
"""
UL Component.
If subcomponents are not LI-components they will be wrapped in a LI
see also :class:`DIV`
"""
tag = 'ul'
def _fixup(self):
self._wrap_components(LI, LI)
class OL(UL):
tag = 'ol'
class TD(DIV):
tag = 'td'
class TH(DIV):
tag = 'th'
class TR(DIV):
"""
TR Component.
If subcomponents are not TD/TH-components they will be wrapped in a TD
see also :class:`DIV`
"""
tag = 'tr'
def _fixup(self):
self._wrap_components((TD, TH), TD)
class THEAD(DIV):
tag = 'thead'
def _fixup(self):
self._wrap_components(TR, TR)
class TBODY(DIV):
tag = 'tbody'
def _fixup(self):
self._wrap_components(TR, TR)
class TFOOT(DIV):
tag = 'tfoot'
def _fixup(self):
self._wrap_components(TR, TR)
class COL(DIV):
tag = 'col'
class COLGROUP(DIV):
tag = 'colgroup'
class TABLE(DIV):
"""
TABLE Component.
If subcomponents are not TR/TBODY/THEAD/TFOOT-components
they will be wrapped in a TR
see also :class:`DIV`
"""
tag = 'table'
def _fixup(self):
self._wrap_components((TR, TBODY, THEAD, TFOOT, COL, COLGROUP), TR)
class I(DIV):
tag = 'i'
class IFRAME(DIV):
tag = 'iframe'
class INPUT(DIV):
"""
INPUT Component
examples::
>>> INPUT(_type='text', _name='name', value='Max').xml()
'<input name=\"name\" type=\"text\" value=\"Max\" />'
>>> INPUT(_type='checkbox', _name='checkbox', value='on').xml()
'<input checked=\"checked\" name=\"checkbox\" type=\"checkbox\" value=\"on\" />'
>>> INPUT(_type='radio', _name='radio', _value='yes', value='yes').xml()
'<input checked=\"checked\" name=\"radio\" type=\"radio\" value=\"yes\" />'
>>> INPUT(_type='radio', _name='radio', _value='no', value='yes').xml()
'<input name=\"radio\" type=\"radio\" value=\"no\" />'
the input helper takes two special attributes value= and requires=.
:param value: used to pass the initial value for the input field.
value differs from _value because it works for checkboxes, radio,
textarea and select/option too.
- for a checkbox value should be '' or 'on'.
- for a radio or select/option value should be the _value
of the checked/selected item.
:param requires: should be None, or a validator or a list of validators
for the value of the field.
"""
tag = 'input/'
def _validate(self):
# # this only changes value, not _value
name = self['_name']
if name is None or name == '':
return True
name = str(name)
request_vars_get = self.request_vars.get
if self['_type'] != 'checkbox':
self['old_value'] = self['value'] or self['_value'] or ''
value = request_vars_get(name, '')
self['value'] = value if not hasattr(value,'file') else None
else:
self['old_value'] = self['value'] or False
value = request_vars_get(name)
if isinstance(value, (tuple, list)):
self['value'] = self['_value'] in value
else:
self['value'] = self['_value'] == value
requires = self['requires']
if requires:
if not isinstance(requires, (list, tuple)):
requires = [requires]
for validator in requires:
(value, errors) = validator(value)
if not errors is None:
self.vars[name] = value
self.errors[name] = errors
break
if not name in self.errors:
self.vars[name] = value
return True
return False
def _postprocessing(self):
t = self['_type']
if not t:
t = self['_type'] = 'text'
t = t.lower()
value = self['value']
if self['_value'] is None or isinstance(self['_value'],cgi.FieldStorage):
_value = None
else:
_value = str(self['_value'])
if '_checked' in self.attributes and not 'value' in self.attributes:
pass
elif t == 'checkbox':
if not _value:
_value = self['_value'] = 'on'
if not value:
value = []
elif value is True:
value = [_value]
elif not isinstance(value, (list, tuple)):
value = str(value).split('|')
self['_checked'] = _value in value and 'checked' or None
elif t == 'radio':
if str(value) == str(_value):
self['_checked'] = 'checked'
else:
self['_checked'] = None
elif not t == 'submit':
if value is None:
self['value'] = _value
elif not isinstance(value, list):
self['_value'] = value
def xml(self):
name = self.attributes.get('_name', None)
if name and hasattr(self, 'errors') \
and self.errors.get(name, None) \
and self['hideerror'] != True:
self['_class'] = (self['_class'] and self['_class']
+ ' ' or '') + 'invalidinput'
return DIV.xml(self) + DIV(
DIV(
self.errors[name], _class='error',
errors=None, _id='%s__error' % name),
_class='error_wrapper').xml()
else:
if self['_class'] and self['_class'].endswith('invalidinput'):
self['_class'] = self['_class'][:-12]
if self['_class'] == '':
self['_class'] = None
return DIV.xml(self)
class TEXTAREA(INPUT):
"""
example::
TEXTAREA(_name='sometext', value='blah '*100, requires=IS_NOT_EMPTY())
'blah blah blah ...' will be the content of the textarea field.
"""
tag = 'textarea'
def _postprocessing(self):
if not '_rows' in self.attributes:
self['_rows'] = 10
if not '_cols' in self.attributes:
self['_cols'] = 40
if not self['value'] is None:
self.components = [self['value']]
elif self.components:
self['value'] = self.components[0]
class OPTION(DIV):
tag = 'option'
def _fixup(self):
if not '_value' in self.attributes:
self.attributes['_value'] = str(self.components[0])
class OBJECT(DIV):
tag = 'object'
class OPTGROUP(DIV):
tag = 'optgroup'
def _fixup(self):
components = []
for c in self.components:
if isinstance(c, OPTION):
components.append(c)
else:
components.append(OPTION(c, _value=str(c)))
self.components = components
class SELECT(INPUT):
"""
example::
>>> from validators import IS_IN_SET
>>> SELECT('yes', 'no', _name='selector', value='yes',
... requires=IS_IN_SET(['yes', 'no'])).xml()
'<select name=\"selector\"><option selected=\"selected\" value=\"yes\">yes</option><option value=\"no\">no</option></select>'
"""
tag = 'select'
def _fixup(self):
components = []
for c in self.components:
if isinstance(c, (OPTION, OPTGROUP)):
components.append(c)
else:
components.append(OPTION(c, _value=str(c)))
self.components = components
def _postprocessing(self):
component_list = []
for c in self.components:
if isinstance(c, OPTGROUP):
component_list.append(c.components)
else:
component_list.append([c])
options = itertools.chain(*component_list)
value = self['value']
if not value is None:
if not self['_multiple']:
for c in options: # my patch
if ((value is not None) and
(str(c['_value']) == str(value))):
c['_selected'] = 'selected'
else:
c['_selected'] = None
else:
if isinstance(value, (list, tuple)):
values = [str(item) for item in value]
else:
values = [str(value)]
for c in options: # my patch
if ((value is not None) and
(str(c['_value']) in values)):
c['_selected'] = 'selected'
else:
c['_selected'] = None
class FIELDSET(DIV):
tag = 'fieldset'
class LEGEND(DIV):
tag = 'legend'
class FORM(DIV):
"""
example::
>>> from validators import IS_NOT_EMPTY
>>> form=FORM(INPUT(_name=\"test\", requires=IS_NOT_EMPTY()))
>>> form.xml()
'<form action=\"#\" enctype=\"multipart/form-data\" method=\"post\"><input name=\"test\" type=\"text\" /></form>'
a FORM is container for INPUT, TEXTAREA, SELECT and other helpers
form has one important method::
form.accepts(request.vars, session)
if form is accepted (and all validators pass) form.vars contains the
accepted vars, otherwise form.errors contains the errors.
in case of errors the form is modified to present the errors to the user.
"""
tag = 'form'
def __init__(self, *components, **attributes):
DIV.__init__(self, *components, **attributes)
self.vars = Storage()
self.errors = Storage()
self.latest = Storage()
self.accepted = None # none for not submitted
def assert_status(self, status, request_vars):
return status
def accepts(
self,
request_vars,
session=None,
formname='default',
keepvalues=False,
onvalidation=None,
hideerror=False,
**kwargs
):
"""
kwargs is not used but allows to specify the same interface for FORM and SQLFORM
"""
if request_vars.__class__.__name__ == 'Request':
request_vars = request_vars.post_vars
self.errors.clear()
self.request_vars = Storage()
self.request_vars.update(request_vars)
self.session = session
self.formname = formname
self.keepvalues = keepvalues
# if this tag is a form and we are in accepting mode (status=True)
# check formname and formkey
status = True
changed = False
request_vars = self.request_vars
if session is not None:
formkey = session.get('_formkey[%s]' % formname, None)
# check if user tampering with form and void CSRF
if not formkey or formkey != request_vars._formkey:
status = False
if formname != request_vars._formname:
status = False
if status and session:
# check if editing a record that has been modified by the server
if hasattr(self, 'record_hash') and self.record_hash != formkey:
status = False
self.record_changed = changed = True
status = self._traverse(status, hideerror)
status = self.assert_status(status, request_vars)
if onvalidation:
if isinstance(onvalidation, dict):
onsuccess = onvalidation.get('onsuccess', None)
onfailure = onvalidation.get('onfailure', None)
onchange = onvalidation.get('onchange', None)
if [k for k in onvalidation if not k in (
'onsuccess','onfailure','onchange')]:
raise RuntimeError('Invalid key in onvalidate dict')
if onsuccess and status:
call_as_list(onsuccess,self)
if onfailure and request_vars and not status:
call_as_list(onfailure,self)
status = len(self.errors) == 0
if changed:
if onchange and self.record_changed and \
self.detect_record_change:
call_as_list(onchange,self)
elif status:
call_as_list(onvalidation, self)
if self.errors:
status = False
if not session is None:
if hasattr(self, 'record_hash'):
formkey = self.record_hash
else:
formkey = web2py_uuid()
self.formkey = session['_formkey[%s]' % formname] = formkey
if status and not keepvalues:
self._traverse(False, hideerror)
self.accepted = status
return status
def _postprocessing(self):
if not '_action' in self.attributes:
self['_action'] = '#'
if not '_method' in self.attributes:
self['_method'] = 'post'
if not '_enctype' in self.attributes:
self['_enctype'] = 'multipart/form-data'
def hidden_fields(self):
c = []
attr = self.attributes.get('hidden', {})
if 'hidden' in self.attributes:
c = [INPUT(_type='hidden', _name=key, _value=value)
for (key, value) in attr.iteritems()]
if hasattr(self, 'formkey') and self.formkey:
c.append(INPUT(_type='hidden', _name='_formkey',
_value=self.formkey))
if hasattr(self, 'formname') and self.formname:
c.append(INPUT(_type='hidden', _name='_formname',
_value=self.formname))
return DIV(c, _style="display:none;")
def xml(self):
newform = FORM(*self.components, **self.attributes)
hidden_fields = self.hidden_fields()
if hidden_fields.components:
newform.append(hidden_fields)
return DIV.xml(newform)
def validate(self, **kwargs):
"""
This function validates the form,
you can use it instead of directly form.accepts.
Usage:
In controller
def action():
form=FORM(INPUT(_name=\"test\", requires=IS_NOT_EMPTY()))
form.validate() #you can pass some args here - see below
return dict(form=form)
This can receive a bunch of arguments
onsuccess = 'flash' - will show message_onsuccess in response.flash
None - will do nothing
can be a function (lambda form: pass)
onfailure = 'flash' - will show message_onfailure in response.flash
None - will do nothing
can be a function (lambda form: pass)
onchange = 'flash' - will show message_onchange in response.flash
None - will do nothing
can be a function (lambda form: pass)
message_onsuccess
message_onfailure
message_onchange
next = where to redirect in case of success
any other kwargs will be passed for form.accepts(...)
"""
from gluon import current, redirect
kwargs['request_vars'] = kwargs.get(
'request_vars', current.request.post_vars)
kwargs['session'] = kwargs.get('session', current.session)
kwargs['dbio'] = kwargs.get('dbio', False)
# necessary for SQLHTML forms
onsuccess = kwargs.get('onsuccess', 'flash')
onfailure = kwargs.get('onfailure', 'flash')
onchange = kwargs.get('onchange', 'flash')
message_onsuccess = kwargs.get('message_onsuccess',
current.T("Success!"))
message_onfailure = kwargs.get('message_onfailure',
current.T("Errors in form, please check it out."))
message_onchange = kwargs.get('message_onchange',
current.T("Form consecutive submissions not allowed. " +
"Try re-submitting or refreshing the form page."))
next = kwargs.get('next', None)
for key in ('message_onsuccess', 'message_onfailure', 'onsuccess',
'onfailure', 'next', 'message_onchange', 'onchange'):
if key in kwargs:
del kwargs[key]
if self.accepts(**kwargs):
if onsuccess == 'flash':
if next:
current.session.flash = message_onsuccess
else:
current.response.flash = message_onsuccess
elif callable(onsuccess):
onsuccess(self)
if next:
if self.vars:
for key, value in self.vars.iteritems():
next = next.replace('[%s]' % key,
urllib.quote(str(value)))
if not next.startswith('/'):
next = URL(next)
redirect(next)
return True
elif self.errors:
if onfailure == 'flash':
current.response.flash = message_onfailure
elif callable(onfailure):
onfailure(self)
return False
elif hasattr(self, "record_changed"):
if self.record_changed and self.detect_record_change:
if onchange == 'flash':
current.response.flash = message_onchange
elif callable(onchange):
onchange(self)
return False
def process(self, **kwargs):
"""
Perform the .validate() method but returns the form
Usage in controllers:
# directly on return
def action():
#some code here
return dict(form=FORM(...).process(...))
You can use it with FORM, SQLFORM or FORM based plugins
Examples:
#response.flash messages
def action():
form = SQLFORM(db.table).process(message_onsuccess='Sucess!')
retutn dict(form=form)
# callback function
# callback receives True or False as first arg, and a list of args.
def my_callback(status, msg):
response.flash = "Success! "+msg if status else "Errors occured"
# after argument can be 'flash' to response.flash messages
# or a function name to use as callback or None to do nothing.
def action():
return dict(form=SQLFORM(db.table).process(onsuccess=my_callback)
"""
kwargs['dbio'] = kwargs.get('dbio', True)
# necessary for SQLHTML forms
self.validate(**kwargs)
return self
REDIRECT_JS = "window.location='%s';return false"
def add_button(self, value, url, _class=None):
submit = self.element('input[type=submit]')
submit.parent.append(
INPUT(_type="button", _value=value, _class=_class,
_onclick=self.REDIRECT_JS % url))
@staticmethod
def confirm(text='OK', buttons=None, hidden=None):
if not buttons:
buttons = {}
if not hidden:
hidden = {}
inputs = [INPUT(_type='button',
_value=name,
_onclick=FORM.REDIRECT_JS % link)
for name, link in buttons.iteritems()]
inputs += [INPUT(_type='hidden',
_name=name,
_value=value)
for name, value in hidden.iteritems()]
form = FORM(INPUT(_type='submit', _value=text), *inputs)
form.process()
return form
def as_dict(self, flat=False, sanitize=True):
"""EXPERIMENTAL
Sanitize is naive. It should catch any unsafe value
for client retrieval.
"""
SERIALIZABLE = (int, float, bool, basestring, long,
set, list, dict, tuple, Storage, type(None))
UNSAFE = ("PASSWORD", "CRYPT")
d = self.__dict__
def sanitizer(obj):
if isinstance(obj, dict):
for k in obj.keys():
if any([unsafe in str(k).upper() for
unsafe in UNSAFE]):
# erease unsafe pair
obj.pop(k)
else:
# not implemented
pass
return obj
def flatten(obj):
if isinstance(obj, (dict, Storage)):
newobj = obj.copy()
else:
newobj = obj
if sanitize:
newobj = sanitizer(newobj)
if flat:
if type(obj) in SERIALIZABLE:
if isinstance(newobj, (dict, Storage)):
for k in newobj:
newk = flatten(k)
newobj[newk] = flatten(newobj[k])
if k != newk:
newobj.pop(k)
return newobj
elif isinstance(newobj, (list, tuple, set)):
return [flatten(item) for item in newobj]
else:
return newobj
else: return str(newobj)
else: return newobj
return flatten(d)
def as_json(self, sanitize=True):
d = self.as_dict(flat=True, sanitize=sanitize)
from serializers import json
return json(d)
def as_yaml(self, sanitize=True):
d = self.as_dict(flat=True, sanitize=sanitize)
from serializers import yaml
return yaml(d)
def as_xml(self, sanitize=True):
d = self.as_dict(flat=True, sanitize=sanitize)
from serializers import xml
return xml(d)
class BEAUTIFY(DIV):
"""
example::
>>> BEAUTIFY(['a', 'b', {'hello': 'world'}]).xml()
'<div><table><tr><td><div>a</div></td></tr><tr><td><div>b</div></td></tr><tr><td><div><table><tr><td style="font-weight:bold;vertical-align:top">hello</td><td valign="top">:</td><td><div>world</div></td></tr></table></div></td></tr></table></div>'
turns any list, dictionary, etc into decent looking html.
Two special attributes are
:sorted: a function that takes the dict and returned sorted keys
:keyfilter: a funciton that takes a key and returns its representation
or None if the key is to be skipped. By default key[:1]=='_' is skipped.
"""
tag = 'div'
@staticmethod
def no_underscore(key):
if key[:1] == '_':
return None
return key
def __init__(self, component, **attributes):
self.components = [component]
self.attributes = attributes
sorter = attributes.get('sorted', sorted)
keyfilter = attributes.get('keyfilter', BEAUTIFY.no_underscore)
components = []
attributes = copy.copy(self.attributes)
level = attributes['level'] = attributes.get('level', 6) - 1
if '_class' in attributes:
attributes['_class'] += 'i'
if level == 0:
return
for c in self.components:
if hasattr(c, 'value') and not callable(c.value):
if c.value:
components.append(c.value)
if hasattr(c, 'xml') and callable(c.xml):
components.append(c)
continue
elif hasattr(c, 'keys') and callable(c.keys):
rows = []
try:
keys = (sorter and sorter(c)) or c
for key in keys:
if isinstance(key, (str, unicode)) and keyfilter:
filtered_key = keyfilter(key)
else:
filtered_key = str(key)
if filtered_key is None:
continue
value = c[key]
if isinstance(value, types.LambdaType):
continue
rows.append(
TR(
TD(filtered_key, _style='font-weight:bold;vertical-align:top'),
TD(':', _valign='top'),
TD(BEAUTIFY(value, **attributes))))
components.append(TABLE(*rows, **attributes))
continue
except:
pass
if isinstance(c, str):
components.append(str(c))
elif isinstance(c, unicode):
components.append(c.encode('utf8'))
elif isinstance(c, (list, tuple)):
items = [TR(TD(BEAUTIFY(item, **attributes)))
for item in c]
components.append(TABLE(*items, **attributes))
elif isinstance(c, cgi.FieldStorage):
components.append('FieldStorage object')
else:
components.append(repr(c))
self.components = components
class MENU(DIV):
"""
Used to build menus
Optional arguments
_class: defaults to 'web2py-menu web2py-menu-vertical'
ul_class: defaults to 'web2py-menu-vertical'
li_class: defaults to 'web2py-menu-expand'
li_first: defaults to 'web2py-menu-first'
li_last: defaults to 'web2py-menu-last'
Example:
menu = MENU([['name', False, URL(...), [submenu]], ...])
{{=menu}}
"""
tag = 'ul'
def __init__(self, data, **args):
self.data = data
self.attributes = args
self.components = []
if not '_class' in self.attributes:
self['_class'] = 'web2py-menu web2py-menu-vertical'
if not 'ul_class' in self.attributes:
self['ul_class'] = 'web2py-menu-vertical'
if not 'li_class' in self.attributes:
self['li_class'] = 'web2py-menu-expand'
if not 'li_first' in self.attributes:
self['li_first'] = 'web2py-menu-first'
if not 'li_last' in self.attributes:
self['li_last'] = 'web2py-menu-last'
if not 'li_active' in self.attributes:
self['li_active'] = 'web2py-menu-active'
if not 'mobile' in self.attributes:
self['mobile'] = False
def serialize(self, data, level=0):
if level == 0:
ul = UL(**self.attributes)
else:
ul = UL(_class=self['ul_class'])
for item in data:
if isinstance(item,LI):
ul.append(item)
else:
(name, active, link) = item[:3]
if isinstance(link, DIV):
li = LI(link)
elif 'no_link_url' in self.attributes and self['no_link_url'] == link:
li = LI(DIV(name))
elif isinstance(link,dict):
li = LI(A(name, **link))
elif link:
li = LI(A(name, _href=link))
elif not link and isinstance(name, A):
li = LI(name)
else:
li = LI(A(name, _href='#',
_onclick='javascript:void(0);return false;'))
if level == 0 and item == data[0]:
li['_class'] = self['li_first']
elif level == 0 and item == data[-1]:
li['_class'] = self['li_last']
if len(item) > 3 and item[3]:
li['_class'] = self['li_class']
li.append(self.serialize(item[3], level + 1))
if active or ('active_url' in self.attributes and self['active_url'] == link):
if li['_class']:
li['_class'] = li['_class'] + ' ' + self['li_active']
else:
li['_class'] = self['li_active']
if len(item) <= 4 or item[4] == True:
ul.append(li)
return ul
def serialize_mobile(self, data, select=None, prefix=''):
if not select:
select = SELECT(**self.attributes)
for item in data:
if len(item) <= 4 or item[4] == True:
select.append(OPTION(CAT(prefix, item[0]),
_value=item[2], _selected=item[1]))
if len(item) > 3 and len(item[3]):
self.serialize_mobile(
item[3], select, prefix=CAT(prefix, item[0], '/'))
select['_onchange'] = 'window.location=this.value'
return select
def xml(self):
if self['mobile']:
return self.serialize_mobile(self.data, 0).xml()
else:
return self.serialize(self.data, 0).xml()
def embed64(
filename=None,
file=None,
data=None,
extension='image/gif',
):
"""
helper to encode the provided (binary) data into base64.
:param filename: if provided, opens and reads this file in 'rb' mode
:param file: if provided, reads this file
:param data: if provided, uses the provided data
"""
if filename and os.path.exists(file):
fp = open(filename, 'rb')
data = fp.read()
fp.close()
data = base64.b64encode(data)
return 'data:%s;base64,%s' % (extension, data)
def test():
"""
Example:
>>> from validators import *
>>> print DIV(A('click me', _href=URL(a='a', c='b', f='c')), BR(), HR(), DIV(SPAN(\"World\"), _class='unknown')).xml()
<div><a href=\"/a/b/c\">click me</a><br /><hr /><div class=\"unknown\"><span>World</span></div></div>
>>> print DIV(UL(\"doc\",\"cat\",\"mouse\")).xml()
<div><ul><li>doc</li><li>cat</li><li>mouse</li></ul></div>
>>> print DIV(UL(\"doc\", LI(\"cat\", _class='feline'), 18)).xml()
<div><ul><li>doc</li><li class=\"feline\">cat</li><li>18</li></ul></div>
>>> print TABLE(['a', 'b', 'c'], TR('d', 'e', 'f'), TR(TD(1), TD(2), TD(3))).xml()
<table><tr><td>a</td><td>b</td><td>c</td></tr><tr><td>d</td><td>e</td><td>f</td></tr><tr><td>1</td><td>2</td><td>3</td></tr></table>
>>> form=FORM(INPUT(_type='text', _name='myvar', requires=IS_EXPR('int(value)<10')))
>>> print form.xml()
<form action=\"#\" enctype=\"multipart/form-data\" method=\"post\"><input name=\"myvar\" type=\"text\" /></form>
>>> print form.accepts({'myvar':'34'}, formname=None)
False
>>> print form.xml()
<form action="#" enctype="multipart/form-data" method="post"><input class="invalidinput" name="myvar" type="text" value="34" /><div class="error_wrapper"><div class="error" id="myvar__error">invalid expression</div></div></form>
>>> print form.accepts({'myvar':'4'}, formname=None, keepvalues=True)
True
>>> print form.xml()
<form action=\"#\" enctype=\"multipart/form-data\" method=\"post\"><input name=\"myvar\" type=\"text\" value=\"4\" /></form>
>>> form=FORM(SELECT('cat', 'dog', _name='myvar'))
>>> print form.accepts({'myvar':'dog'}, formname=None, keepvalues=True)
True
>>> print form.xml()
<form action=\"#\" enctype=\"multipart/form-data\" method=\"post\"><select name=\"myvar\"><option value=\"cat\">cat</option><option selected=\"selected\" value=\"dog\">dog</option></select></form>
>>> form=FORM(INPUT(_type='text', _name='myvar', requires=IS_MATCH('^\w+$', 'only alphanumeric!')))
>>> print form.accepts({'myvar':'as df'}, formname=None)
False
>>> print form.xml()
<form action="#" enctype="multipart/form-data" method="post"><input class="invalidinput" name="myvar" type="text" value="as df" /><div class="error_wrapper"><div class="error" id="myvar__error">only alphanumeric!</div></div></form>
>>> session={}
>>> form=FORM(INPUT(value=\"Hello World\", _name=\"var\", requires=IS_MATCH('^\w+$')))
>>> isinstance(form.as_dict(), dict)
True
>>> form.as_dict(flat=True).has_key("vars")
True
>>> isinstance(form.as_json(), basestring) and len(form.as_json(sanitize=False)) > 0
True
>>> if form.accepts({}, session,formname=None): print 'passed'
>>> if form.accepts({'var':'test ', '_formkey': session['_formkey[None]']}, session, formname=None): print 'passed'
"""
pass
class web2pyHTMLParser(HTMLParser):
"""
obj = web2pyHTMLParser(text) parses and html/xml text into web2py helpers.
obj.tree contains the root of the tree, and tree can be manipulated
>>> str(web2pyHTMLParser('hello<div a="b" c=3>wor<ld<span>xxx</span>y<script/>yy</div>zzz').tree)
'hello<div a="b" c="3">wor<ld<span>xxx</span>y<script></script>yy</div>zzz'
>>> str(web2pyHTMLParser('<div>a<span>b</div>c').tree)
'<div>a<span>b</span></div>c'
>>> tree = web2pyHTMLParser('hello<div a="b">world</div>').tree
>>> tree.element(_a='b')['_c']=5
>>> str(tree)
'hello<div a="b" c="5">world</div>'
"""
def __init__(self, text, closed=('input', 'link')):
HTMLParser.__init__(self)
self.tree = self.parent = TAG['']()
self.closed = closed
self.tags = [x for x in __all__ if isinstance(eval(x), DIV)]
self.last = None
self.feed(text)
def handle_starttag(self, tagname, attrs):
if tagname.upper() in self.tags:
tag = eval(tagname.upper())
else:
if tagname in self.closed:
tagname += '/'
tag = TAG[tagname]()
for key, value in attrs:
tag['_' + key] = value
tag.parent = self.parent
self.parent.append(tag)
if not tag.tag.endswith('/'):
self.parent = tag
else:
self.last = tag.tag[:-1]
def handle_data(self, data):
if not isinstance(data, unicode):
try:
data = data.decode('utf8')
except:
data = data.decode('latin1')
self.parent.append(data.encode('utf8', 'xmlcharref'))
def handle_charref(self, name):
if name.startswith('x'):
self.parent.append(unichr(int(name[1:], 16)).encode('utf8'))
else:
self.parent.append(unichr(int(name)).encode('utf8'))
def handle_entityref(self, name):
self.parent.append(entitydefs[name])
def handle_endtag(self, tagname):
# this deals with unbalanced tags
if tagname == self.last:
return
while True:
try:
parent_tagname = self.parent.tag
self.parent = self.parent.parent
except:
raise RuntimeError("unable to balance tag %s" % tagname)
if parent_tagname[:len(tagname)] == tagname: break
def markdown_serializer(text, tag=None, attr=None):
attr = attr or {}
if tag is None:
return re.sub('\s+', ' ', text)
if tag == 'br':
return '\n\n'
if tag == 'h1':
return '#' + text + '\n\n'
if tag == 'h2':
return '#' * 2 + text + '\n\n'
if tag == 'h3':
return '#' * 3 + text + '\n\n'
if tag == 'h4':
return '#' * 4 + text + '\n\n'
if tag == 'p':
return text + '\n\n'
if tag == 'b' or tag == 'strong':
return '**%s**' % text
if tag == 'em' or tag == 'i':
return '*%s*' % text
if tag == 'tt' or tag == 'code':
return '`%s`' % text
if tag == 'a':
return '[%s](%s)' % (text, attr.get('_href', ''))
if tag == 'img':
return '' % (attr.get('_alt', ''), attr.get('_src', ''))
return text
def markmin_serializer(text, tag=None, attr=None):
attr = attr or {}
# if tag is None: return re.sub('\s+',' ',text)
if tag == 'br':
return '\n\n'
if tag == 'h1':
return '# ' + text + '\n\n'
if tag == 'h2':
return '#' * 2 + ' ' + text + '\n\n'
if tag == 'h3':
return '#' * 3 + ' ' + text + '\n\n'
if tag == 'h4':
return '#' * 4 + ' ' + text + '\n\n'
if tag == 'p':
return text + '\n\n'
if tag == 'li':
return '\n- ' + text.replace('\n', ' ')
if tag == 'tr':
return text[3:].replace('\n', ' ') + '\n'
if tag in ['table', 'blockquote']:
return '\n-----\n' + text + '\n------\n'
if tag in ['td', 'th']:
return ' | ' + text
if tag in ['b', 'strong', 'label']:
return '**%s**' % text
if tag in ['em', 'i']:
return "''%s''" % text
if tag in ['tt']:
return '``%s``' % text.strip()
if tag in ['code']:
return '``\n%s``' % text
if tag == 'a':
return '[[%s %s]]' % (text, attr.get('_href', ''))
if tag == 'img':
return '[[%s %s left]]' % (attr.get('_alt', 'no title'), attr.get('_src', ''))
return text
class MARKMIN(XmlComponent):
"""
For documentation: http://web2py.com/examples/static/markmin.html
"""
def __init__(self, text, extra=None, allowed=None, sep='p',
url=None, environment=None, latex='google',
autolinks='default',
protolinks='default',
class_prefix='',
id_prefix='markmin_'):
self.text = text
self.extra = extra or {}
self.allowed = allowed or {}
self.sep = sep
self.url = URL if url == True else url
self.environment = environment
self.latex = latex
self.autolinks = autolinks
self.protolinks = protolinks
self.class_prefix = class_prefix
self.id_prefix = id_prefix
def xml(self):
"""
calls the gluon.contrib.markmin render function to convert the wiki syntax
"""
from contrib.markmin.markmin2html import render
return render(self.text, extra=self.extra,
allowed=self.allowed, sep=self.sep, latex=self.latex,
URL=self.url, environment=self.environment,
autolinks=self.autolinks, protolinks=self.protolinks,
class_prefix=self.class_prefix, id_prefix=self.id_prefix)
def __str__(self):
return self.xml()
def flatten(self, render=None):
"""
return the text stored by the MARKMIN object rendered by the render function
"""
return self.text
def elements(self, *args, **kargs):
"""
to be considered experimental since the behavior of this method is questionable
another options could be TAG(self.text).elements(*args,**kargs)
"""
return [self.text]
if __name__ == '__main__':
import doctest
doctest.testmod()
| [
[
8,
0,
0.0022,
0.0018,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0037,
0.0004,
0,
0.66,
0.0097,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.0041,
0.0004,
0,
0.66... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\"\"\"",
"import cgi",
"import os",
"import re",
"import copy",
"import types",
"import urllib",
"import base64",
"import sanit... |
# -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
"Pythonic simple JSON RPC Client implementation"
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2011 Mariano Reingart"
__license__ = "LGPL 3.0"
__version__ = "0.05"
import urllib
from xmlrpclib import Transport, SafeTransport
from cStringIO import StringIO
import random
import sys
try:
import gluon.contrib.simplejson as json # try web2py json serializer
except ImportError:
try:
import json # try stdlib (py2.6)
except:
import simplejson as json # try external module
class JSONRPCError(RuntimeError):
"Error object for remote procedure call fail"
def __init__(self, code, message, data=None):
value = "%s: %s\n%s" % (code, message, '\n'.join(data))
RuntimeError.__init__(self, value)
self.code = code
self.message = message
self.data = data
class JSONDummyParser:
"json wrapper for xmlrpclib parser interfase"
def __init__(self):
self.buf = StringIO()
def feed(self, data):
self.buf.write(data)
def close(self):
return self.buf.getvalue()
class JSONTransportMixin:
"json wrapper for xmlrpclib transport interfase"
def send_content(self, connection, request_body):
connection.putheader("Content-Type", "application/json")
connection.putheader("Content-Length", str(len(request_body)))
connection.endheaders()
if request_body:
connection.send(request_body)
# todo: add gzip compression
def getparser(self):
# get parser and unmarshaller
parser = JSONDummyParser()
return parser, parser
class JSONTransport(JSONTransportMixin, Transport):
pass
class JSONSafeTransport(JSONTransportMixin, SafeTransport):
pass
class ServerProxy(object):
"JSON RPC Simple Client Service Proxy"
def __init__(self, uri, transport=None, encoding=None, verbose=0):
self.location = uri # server location (url)
self.trace = verbose # show debug messages
self.exceptions = True # raise errors? (JSONRPCError)
self.timeout = None
self.json_request = self.json_response = ''
type, uri = urllib.splittype(uri)
if type not in ("http", "https"):
raise IOError("unsupported JSON-RPC protocol")
self.__host, self.__handler = urllib.splithost(uri)
if transport is None:
if type == "https":
transport = JSONSafeTransport()
else:
transport = JSONTransport()
self.__transport = transport
self.__encoding = encoding
self.__verbose = verbose
def __getattr__(self, attr):
"pseudo method that can be called"
return lambda *args: self.call(attr, *args)
def call(self, method, *args):
"JSON RPC communication (method invocation)"
# build data sent to the service
request_id = random.randint(0, sys.maxint)
data = {'id': request_id, 'method': method, 'params': args, }
request = json.dumps(data)
# make HTTP request (retry if connection is lost)
response = self.__transport.request(
self.__host,
self.__handler,
request,
verbose=self.__verbose
)
# store plain request and response for further debugging
self.json_request = request
self.json_response = response
# parse json data coming from service
# {'version': '1.1', 'id': id, 'result': result, 'error': None}
response = json.loads(response)
if response['id'] != request_id:
raise JSONRPCError(0, "JSON Request ID != Response ID")
self.error = response.get('error', {})
if self.error and self.exceptions:
raise JSONRPCError(self.error.get('code', 0),
self.error.get('message', ''),
self.error.get('data', None))
return response.get('result')
ServiceProxy = ServerProxy
if __name__ == "__main__":
# basic tests:
location = "http://www.web2py.com.ar/webservices/sample/call/jsonrpc"
client = ServerProxy(location, verbose='--verbose' in sys.argv,)
print client.add(1, 2)
| [
[
8,
0,
0.0789,
0.0066,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.0921,
0.0066,
0,
0.66,
0.0556,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0987,
0.0066,
0,
0.66... | [
"\"Pythonic simple JSON RPC Client implementation\"",
"__author__ = \"Mariano Reingart (reingart@gmail.com)\"",
"__copyright__ = \"Copyright (C) 2011 Mariano Reingart\"",
"__license__ = \"LGPL 3.0\"",
"__version__ = \"0.05\"",
"import urllib",
"from xmlrpclib import Transport, SafeTransport",
"from cS... |
#!/usr/bin/env python
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Attention: Requires Chrome or Safari. For IE of Firefox you need https://github.com/gimite/web-socket-js
1) install tornado (requires Tornado 2.1)
easy_install tornado
2) start this app:
python gluon/contrib/websocket_messaging.py -k mykey -p 8888
3) from any web2py app you can post messages with
from gluon.contrib.websocket_messaging import websocket_send
websocket_send('http://127.0.0.1:8888','Hello World','mykey','mygroup')
4) from any template you can receive them with
<script>
$(document).ready(function(){
if(!web2py_websocket('ws://127.0.0.1:8888/realtime/mygroup',function(e){alert(e.data)}))
alert("html5 websocket not supported by your browser, try Google Chrome");
});
</script>
When the server posts a message, all clients connected to the page will popup an alert message
Or if you want to send json messages and store evaluated json in a var called data:
<script>
$(document).ready(function(){
var data;
web2py_websocket('ws://127.0.0.1:8888/realtime/mygroup',function(e){data=eval('('+e.data+')')});
});
</script>
- All communications between web2py and websocket_messaging will be digitally signed with hmac.
- All validation is handled on the web2py side and there is no need to modify websocket_messaging.py
- Multiple web2py instances can talk with one or more websocket_messaging servers.
- "ws://127.0.0.1:8888/realtime/" must be contain the IP of the websocket_messaging server.
- Via group='mygroup' name you can support multiple groups of clients (think of many chat-rooms)
Here is a complete sample web2py action:
def index():
form=LOAD('default','ajax_form',ajax=True)
script=SCRIPT('''
jQuery(document).ready(function(){
var callback=function(e){alert(e.data)};
if(!web2py_websocket('ws://127.0.0.1:8888/realtime/mygroup',callback))
alert("html5 websocket not supported by your browser, try Google Chrome");
});
''')
return dict(form=form, script=script)
def ajax_form():
form=SQLFORM.factory(Field('message'))
if form.accepts(request,session):
from gluon.contrib.websocket_messaging import websocket_send
websocket_send(
'http://127.0.0.1:8888',form.vars.message,'mykey','mygroup')
return form
Acknowledgements:
Tornado code inspired by http://thomas.pelletier.im/2010/08/websocket-tornado-redis/
"""
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import hmac
import sys
import optparse
import urllib
import time
listeners = {}
names = {}
tokens = {}
def websocket_send(url, message, hmac_key=None, group='default'):
sig = hmac_key and hmac.new(hmac_key, message).hexdigest() or ''
params = urllib.urlencode(
{'message': message, 'signature': sig, 'group': group})
f = urllib.urlopen(url, params)
data = f.read()
f.close()
return data
class PostHandler(tornado.web.RequestHandler):
"""
only authorized parties can post messages
"""
def post(self):
if hmac_key and not 'signature' in self.request.arguments:
return 'false'
if 'message' in self.request.arguments:
message = self.request.arguments['message'][0]
group = self.request.arguments.get('group', ['default'])[0]
print '%s:MESSAGE to %s:%s' % (time.time(), group, message)
if hmac_key:
signature = self.request.arguments['signature'][0]
if not hmac.new(hmac_key, message).hexdigest() == signature:
return 'false'
for client in listeners.get(group, []):
client.write_message(message)
return 'true'
return 'false'
class TokenHandler(tornado.web.RequestHandler):
"""
if running with -t post a token to allow a client to join using the token
the message here is the token (any uuid)
allows only authorized parties to joins, for example, a chat
"""
def post(self):
if hmac_key and not 'message' in self.request.arguments:
return 'false'
if 'message' in self.request.arguments:
message = self.request.arguments['message'][0]
if hmac_key:
signature = self.request.arguments['signature'][0]
if not hmac.new(hmac_key, message).hexdigest() == signature:
return 'false'
tokens[message] = None
return 'true'
return 'false'
class DistributeHandler(tornado.websocket.WebSocketHandler):
def open(self, params):
group, token, name = params.split('/') + [None, None]
self.group = group or 'default'
self.token = token or 'none'
self.name = name or 'anonymous'
# only authorized parties can join
if DistributeHandler.tokens:
if not self.token in tokens or not token[self.token] is None:
self.close()
else:
tokens[self.token] = self
if not self.group in listeners:
listeners[self.group] = []
# notify clients that a member has joined the groups
for client in listeners.get(self.group, []):
client.write_message('+' + self.name)
listeners[self.group].append(self)
names[self] = self.name
print '%s:CONNECT to %s' % (time.time(), self.group)
def on_message(self, message):
pass
def on_close(self):
if self.group in listeners:
listeners[self.group].remove(self)
del names[self]
# notify clients that a member has left the groups
for client in listeners.get(self.group, []):
client.write_message('-' + self.name)
print '%s:DISCONNECT from %s' % (time.time(), self.group)
if __name__ == "__main__":
usage = __doc__
version = ""
parser = optparse.OptionParser(usage, None, optparse.Option, version)
parser.add_option('-p',
'--port',
default='8888',
dest='port',
help='socket')
parser.add_option('-l',
'--listen',
default='0.0.0.0',
dest='address',
help='listener address')
parser.add_option('-k',
'--hmac_key',
default='',
dest='hmac_key',
help='hmac_key')
parser.add_option('-t',
'--tokens',
action='store_true',
default=False,
dest='tokens',
help='require tockens to join')
(options, args) = parser.parse_args()
hmac_key = options.hmac_key
DistributeHandler.tokens = options.tokens
urls = [
(r'/', PostHandler),
(r'/token', TokenHandler),
(r'/realtime/(.*)', DistributeHandler)]
application = tornado.web.Application(urls, auto_reload=True)
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(int(options.port), address=options.address)
tornado.ioloop.IOLoop.instance().start()
| [
[
8,
0,
0.1763,
0.3382,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3527,
0.0048,
0,
0.66,
0.0588,
17,
0,
1,
0,
0,
17,
0,
0
],
[
1,
0,
0.3575,
0.0048,
0,
0.66,
... | [
"\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\nAttention: Requires Chrome or Safari. For IE of Firefox you need https://github.com/gimite/web-socket-js\n\n1) install tornado (requires Torn... |
#!/usr/bin/env python
# coding: utf8
"""
RPX Authentication for web2py
Developed by Nathan Freeze (Copyright © 2009)
Email <nathan@freezable.com>
Modified by Massimo Di Pierro
This file contains code to allow using RPXNow.com (now Jainrain.com)
services with web2py
"""
import os
import re
import urllib
from gluon import *
from gluon.tools import fetch
from gluon.storage import Storage
import gluon.contrib.simplejson as json
class RPXAccount(object):
"""
from gluon.contrib.login_methods.rpx_account import RPXAccount
auth.settings.actions_disabled=['register','change_password',
'request_reset_password']
auth.settings.login_form = RPXAccount(request,
api_key="...",
domain="...",
url = "http://localhost:8000/%s/default/user/login" % request.application)
"""
def __init__(self,
request,
api_key="",
domain="",
url="",
embed=True,
auth_url="https://rpxnow.com/api/v2/auth_info",
language="en",
prompt='rpx',
on_login_failure=None,
):
self.request = request
self.api_key = api_key
self.embed = embed
self.auth_url = auth_url
self.domain = domain
self.token_url = url
self.language = language
self.profile = None
self.prompt = prompt
self.on_login_failure = on_login_failure
self.mappings = Storage()
dn = {'givenName': '', 'familyName': ''}
self.mappings.Facebook = lambda profile, dn=dn:\
dict(registration_id=profile.get("identifier", ""),
username=profile.get("preferredUsername", ""),
email=profile.get("email", ""),
first_name=profile.get("name", dn).get("givenName", ""),
last_name=profile.get("name", dn).get("familyName", ""))
self.mappings.Google = lambda profile, dn=dn:\
dict(registration_id=profile.get("identifier", ""),
username=profile.get("preferredUsername", ""),
email=profile.get("email", ""),
first_name=profile.get("name", dn).get("givenName", ""),
last_name=profile.get("name", dn).get("familyName", ""))
self.mappings.default = lambda profile:\
dict(registration_id=profile.get("identifier", ""),
username=profile.get("preferredUsername", ""),
email=profile.get("email", ""),
first_name=profile.get("preferredUsername", ""),
last_name='')
def get_user(self):
request = self.request
if request.vars.token:
user = Storage()
data = urllib.urlencode(
dict(apiKey=self.api_key, token=request.vars.token))
auth_info_json = fetch(self.auth_url + '?' + data)
auth_info = json.loads(auth_info_json)
if auth_info['stat'] == 'ok':
self.profile = auth_info['profile']
provider = re.sub('[^\w\-]', '', self.profile['providerName'])
user = self.mappings.get(
provider, self.mappings.default)(self.profile)
return user
elif self.on_login_failure:
redirect(self.on_login_failure)
return None
def login_form(self):
request = self.request
args = request.args
if self.embed:
JANRAIN_URL = \
"https://%s.rpxnow.com/openid/embed?token_url=%s&language_preference=%s"
rpxform = IFRAME(
_src=JANRAIN_URL % (
self.domain, self.token_url, self.language),
_scrolling="no",
_frameborder="no",
_style="width:400px;height:240px;")
else:
JANRAIN_URL = \
"https://%s.rpxnow.com/openid/v2/signin?token_url=%s"
rpxform = DIV(SCRIPT(_src="https://rpxnow.com/openid/v2/widget",
_type="text/javascript"),
SCRIPT("RPXNOW.overlay = true;",
"RPXNOW.language_preference = '%s';" % self.language,
"RPXNOW.realm = '%s';" % self.domain,
"RPXNOW.token_url = '%s';" % self.token_url,
"RPXNOW.show();",
_type="text/javascript"))
return rpxform
def use_janrain(auth, filename='private/janrain.key', **kwargs):
path = os.path.join(current.request.folder, filename)
if os.path.exists(path):
request = current.request
domain, key = open(path, 'r').read().strip().split(':')
host = current.request.env.http_host
url = URL('default', 'user', args='login', scheme=True)
auth.settings.actions_disabled = \
['register', 'change_password', 'request_reset_password']
auth.settings.login_form = RPXAccount(
request, api_key=key, domain=domain, url=url, **kwargs)
| [
[
8,
0,
0.0597,
0.0672,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1045,
0.0075,
0,
0.66,
0.1111,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1119,
0.0075,
0,
0.66... | [
"\"\"\"\n RPX Authentication for web2py\n Developed by Nathan Freeze (Copyright © 2009)\n Email <nathan@freezable.com>\n Modified by Massimo Di Pierro\n\n This file contains code to allow using RPXNow.com (now Jainrain.com)\n services with web2py",
"import os",
"import re",
"import urllib",
"fro... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of web2py Web Framework (Copyrighted, 2007-2009).
Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>.
License: GPL v2
Thanks to Hans Donner <hans.donner@pobox.com> for GaeGoogleAccount.
"""
from google.appengine.api import users
class GaeGoogleAccount(object):
"""
Login will be done via Google's Appengine login object, instead of web2py's
login form.
Include in your model (eg db.py)::
from gluon.contrib.login_methods.gae_google_account import \
GaeGoogleAccount
auth.settings.login_form=GaeGoogleAccount()
"""
def login_url(self, next="/"):
return users.create_login_url(next)
def logout_url(self, next="/"):
return users.create_logout_url(next)
def get_user(self):
user = users.get_current_user()
if user:
return dict(nickname=user.nickname(), email=user.email(),
user_id=user.user_id(), source="google account")
| [
[
8,
0,
0.1842,
0.1842,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3158,
0.0263,
0,
0.66,
0.5,
279,
0,
1,
0,
0,
279,
0,
0
],
[
3,
0,
0.6974,
0.6316,
0,
0.66,
... | [
"\"\"\"\nThis file is part of web2py Web Framework (Copyrighted, 2007-2009).\nDeveloped by Massimo Di Pierro <mdipierro@cs.depaul.edu>.\nLicense: GPL v2\n\nThanks to Hans Donner <hans.donner@pobox.com> for GaeGoogleAccount.\n\"\"\"",
"from google.appengine.api import users",
"class GaeGoogleAccount(object):\n ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of web2py Web Framework (Copyrighted, 2007-2009).
Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>.
License: GPL v2
Thanks to Hans Donner <hans.donner@pobox.com> for GaeGoogleAccount.
"""
from gluon.http import HTTP
try:
import linkedin
except ImportError:
raise HTTP(400, "linkedin module not found")
class LinkedInAccount(object):
"""
Login will be done via Google's Appengine login object, instead of web2py's
login form.
Include in your model (eg db.py)::
from gluon.contrib.login_methods.linkedin_account import LinkedInAccount
auth.settings.login_form=LinkedInAccount(request,KEY,SECRET,RETURN_URL)
"""
def __init__(self, request, key, secret, return_url):
self.request = request
self.api = linkedin.LinkedIn(key, secret, return_url)
self.token = result = self.api.requestToken()
def login_url(self, next="/"):
return self.api.getAuthorizeURL(self.token)
def logout_url(self, next="/"):
return ''
def get_user(self):
result = self.request.vars.verifier and self.api.accessToken(
verifier=self.request.vars.verifier)
if result:
profile = self.api.GetProfile()
profile = self.api.GetProfile(
profile).public_url = "http://www.linkedin.com/in/ozgurv"
return dict(first_name=profile.first_name,
last_name=profile.last_name,
username=profile.id)
| [
[
8,
0,
0.1373,
0.1373,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2353,
0.0196,
0,
0.66,
0.3333,
453,
0,
1,
0,
0,
453,
0,
0
],
[
7,
0,
0.2843,
0.0784,
0,
0.66... | [
"\"\"\"\nThis file is part of web2py Web Framework (Copyrighted, 2007-2009).\nDeveloped by Massimo Di Pierro <mdipierro@cs.depaul.edu>.\nLicense: GPL v2\n\nThanks to Hans Donner <hans.donner@pobox.com> for GaeGoogleAccount.\n\"\"\"",
"from gluon.http import HTTP",
"try:\n import linkedin\nexcept ImportError:... |
#!/usr/bin/env python
# coding: utf8
"""
Dropbox Authentication for web2py
Developed by Massimo Di Pierro (2012)
Same License as Web2py License
"""
# mind here session is dropbox session, not current.session
import os
import re
import urllib
from dropbox import client, rest, session
from gluon import *
from gluon.tools import fetch
from gluon.storage import Storage
import gluon.contrib.simplejson as json
class DropboxAccount(object):
"""
from gluon.contrib.login_methods.dropbox_account import DropboxAccount
auth.settings.actions_disabled=['register','change_password',
'request_reset_password']
auth.settings.login_form = DropboxAccount(request,
key="...",
secret="...",
access_type="...",
login_url = "http://localhost:8000/%s/default/user/login" % request.application)
when logged in
client = auth.settings.login_form.client
"""
def __init__(self,
request,
key="",
secret="",
access_type="app_folder",
login_url="",
on_login_failure=None,
):
self.request = request
self.key = key
self.secret = secret
self.access_type = access_type
self.login_url = login_url
self.on_login_failure = on_login_failure
self.sess = session.DropboxSession(
self.key, self.secret, self.access_type)
def get_user(self):
request = self.request
if not current.session.dropbox_request_token:
return None
elif not current.session.dropbox_access_token:
request_token = current.session.dropbox_request_token
self.sess.set_request_token(request_token[0], request_token[1])
access_token = self.sess.obtain_access_token(self.sess.token)
current.session.dropbox_access_token = \
(access_token.key, access_token.secret)
else:
access_token = current.session.dropbox_access_token
self.sess.set_token(access_token[0], access_token[1])
user = Storage()
self.client = client.DropboxClient(self.sess)
data = self.client.account_info()
display_name = data.get('display_name', '').split(' ', 1)
user = dict(email=data.get('email', None),
first_name=display_name[0],
last_name=display_name[-1],
registration_id=data.get('uid', None))
if not user['registration_id'] and self.on_login_failure:
redirect(self.on_login_failure)
return user
def login_form(self):
request_token = self.sess.obtain_request_token()
current.session.dropbox_request_token = \
(request_token.key, request_token.secret)
dropbox_url = self.sess.build_authorize_url(request_token,
self.login_url)
redirect(dropbox_url)
form = IFRAME(_src=dropbox_url,
_scrolling="no",
_frameborder="no",
_style="width:400px;height:240px;")
return form
def logout_url(self, next="/"):
self.sess.unlink()
current.session.auth = None
return next
def get_client(self):
access_token = current.session.dropbox_access_token
self.sess.set_token(access_token[0], access_token[1])
self.client = client.DropboxClient(self.sess)
def put(self, filename, file):
if not hasattr(self,'client'): self.get_client()
return self.client.put_file(filename, file)['bytes']
def get(self, filename):
if not hasattr(self,'client'): self.get_client()
return self.client.get_file(filename)
def dir(self, path):
if not hasattr(self,'client'): self.get_client()
return self.client.metadata(path)
def use_dropbox(auth, filename='private/dropbox.key', **kwargs):
path = os.path.join(current.request.folder, filename)
if os.path.exists(path):
request = current.request
key, secret, access_type = open(path, 'r').read().strip().split(':')
host = current.request.env.http_host
login_url = "http://%s/%s/default/user/login" % \
(host, request.application)
auth.settings.actions_disabled = \
['register', 'change_password', 'request_reset_password']
auth.settings.login_form = DropboxAccount(
request, key=key, secret=secret, access_type=access_type,
login_url=login_url, **kwargs)
| [
[
8,
0,
0.0458,
0.0382,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0916,
0.0076,
0,
0.66,
0.1,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0992,
0.0076,
0,
0.66,
... | [
"\"\"\"\nDropbox Authentication for web2py\nDeveloped by Massimo Di Pierro (2012)\nSame License as Web2py License\n\"\"\"",
"import os",
"import re",
"import urllib",
"from dropbox import client, rest, session",
"from gluon import *",
"from gluon.tools import fetch",
"from gluon.storage import Storage... |
#!/usr/bin/env python
# coding: utf8
"""
Oneall Authentication for web2py
Developed by Nathan Freeze (Copyright © 2013)
Email <nathan@freezable.com>
This file contains code to allow using onall.com
authentication services with web2py
"""
import os
import base64
from gluon import *
from gluon.storage import Storage
from gluon.contrib.simplejson import JSONDecodeError
from gluon.tools import fetch
import gluon.contrib.simplejson as json
class OneallAccount(object):
"""
from gluon.contrib.login_methods.oneall_account import OneallAccount
auth.settings.actions_disabled=['register','change_password',
'request_reset_password']
auth.settings.login_form = OneallAccount(request,
public_key="...",
private_key="...",
domain="...",
url = "http://localhost:8000/%s/default/user/login" % request.application)
"""
def __init__(self, request, public_key="", private_key="", domain="",
url=None, providers=None, on_login_failure=None):
self.request = request
self.public_key = public_key
self.private_key = private_key
self.url = url
self.domain = domain
self.profile = None
self.on_login_failure = on_login_failure
self.providers = providers or ["facebook", "google", "yahoo", "openid"]
self.mappings = Storage()
def defaultmapping(profile):
name = profile.get('name',{})
dname = name.get('formatted',profile.get('displayName'))
email=profile.get('emails', [{}])[0].get('value')
reg_id=profile.get('identity_token','')
username=profile.get('preferredUsername',email)
first_name=name.get('givenName', dname.split(' ')[0])
last_name=profile.get('familyName',dname.split(' ')[1])
return dict(registration_id=reg_id,username=username,email=email,
first_name=first_name,last_name=last_name)
self.mappings.default = defaultmapping
def get_user(self):
request = self.request
user = None
if request.vars.connection_token:
auth_url = "https://%s.api.oneall.com/connections/%s.json" % \
(self.domain, request.vars.connection_token)
auth_pw = "%s:%s" % (self.public_key,self.private_key)
auth_pw = base64.b64encode(auth_pw)
headers = dict(Authorization="Basic %s" % auth_pw)
try:
auth_info_json = fetch(auth_url,headers=headers)
auth_info = json.loads(auth_info_json)
data = auth_info['response']['result']['data']
if data['plugin']['key'] == 'social_login':
if data['plugin']['data']['status'] == 'success':
userdata = data['user']
self.profile = userdata['identity']
source = self.profile['source']['key']
mapping = self.mappings.get(source,self.mappings['default'])
user = mapping(self.profile)
except (JSONDecodeError, KeyError):
pass
if user is None and self.on_login_failure:
redirect(self.on_login_failure)
return user
def login_form(self):
scheme = self.request.env.wsgi_url_scheme
oneall_url = scheme + "://%s.api.oneall.com/socialize/library.js" % self.domain
oneall_lib = SCRIPT(_src=oneall_url,_type='text/javascript')
container = DIV(_id="oa_social_login_container")
widget = SCRIPT('oneall.api.plugins.social_login.build("oa_social_login_container",',
'{providers : %s,' % self.providers,
'callback_uri: "%s"});' % self.url,
_type="text/javascript")
form = DIV(oneall_lib,container,widget)
return form
def use_oneall(auth, filename='private/oneall.key', **kwargs):
path = os.path.join(current.request.folder, filename)
if os.path.exists(path):
request = current.request
domain, public_key, private_key = open(path, 'r').read().strip().split(':')
url = URL('default', 'user', args='login', scheme=True)
auth.settings.actions_disabled =\
['register', 'change_password', 'request_reset_password']
auth.settings.login_form = OneallAccount(
request, public_key=public_key,private_key=private_key,
domain=domain, url=url, **kwargs)
| [
[
8,
0,
0.0701,
0.0748,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1215,
0.0093,
0,
0.66,
0.1111,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1308,
0.0093,
0,
0.66... | [
"\"\"\"\n Oneall Authentication for web2py\n Developed by Nathan Freeze (Copyright © 2013)\n Email <nathan@freezable.com>\n\n This file contains code to allow using onall.com\n authentication services with web2py\n\"\"\"",
"import os",
"import base64",
"from gluon import *",
"from gluon.storage im... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
BrowserID Authentication for web2py
developed by Madhukar R Pai (Copyright 2012)
Email <madspai@gmail.com>
License : LGPL
thanks and credits to the web2py community
This custom authenticator allows web2py to authenticate using browserid (https://browserid.org/)
BrowserID is a project by Mozilla Labs (http://mozillalabs.com/)
to Know how browserid works please visit http://identity.mozilla.com/post/7616727542/introducing-browserid-a-better-way-to-sign-in
bottom line BrowserID provides a free, secure, de-centralized, easy to use(for users and developers) login solution.
You can use any email id as your login id. Browserid just verifys the email id and lets you login with that id.
credits for the doPost jquery function - itsadok (http://stackoverflow.com/users/7581/itsadok)
"""
import time
from gluon import *
from gluon.storage import Storage
from gluon.tools import fetch
import gluon.contrib.simplejson as json
class BrowserID(object):
"""
from gluon.contrib.login_methods.browserid_account import BrowserID
auth.settings.login_form = BrowserID(request,
audience = "http://127.0.0.1:8000"
assertion_post_url = "http://127.0.0.1:8000/%s/default/user/login" % request.application)
"""
def __init__(self,
request,
audience="",
assertion_post_url="",
prompt="BrowserID Login",
issuer="browserid.org",
verify_url="https://browserid.org/verify",
browserid_js="https://browserid.org/include.js",
browserid_button="https://browserid.org/i/sign_in_red.png",
crypto_js="https://crypto-js.googlecode.com/files/2.2.0-crypto-md5.js",
on_login_failure=None,
):
self.request = request
self.audience = audience
self.assertion_post_url = assertion_post_url
self.prompt = prompt
self.issuer = issuer
self.verify_url = verify_url
self.browserid_js = browserid_js
self.browserid_button = browserid_button
self.crypto_js = crypto_js
self.on_login_failure = on_login_failure
self.asertion_js = """
(function($){$.extend({doPost:function(url,params){var $form=$("<form method='POST'>").attr("action",url);
$.each(params,function(name,value){$("<input type='hidden'>").attr("name",name).attr("value",value).appendTo($form)});
$form.appendTo("body");$form.submit()}})})(jQuery);
function gotVerifiedEmail(assertion){if(assertion !== null){$.doPost('%s',{'assertion':assertion});}}""" % self.assertion_post_url
def get_user(self):
request = self.request
if request.vars.assertion:
audience = self.audience
issuer = self.issuer
assertion = XML(request.vars.assertion, sanitize=True)
verify_data = {'assertion': assertion, 'audience': audience}
auth_info_json = fetch(self.verify_url, data=verify_data)
j = json.loads(auth_info_json)
epoch_time = int(time.time() * 1000) # we need 13 digit epoch time
if j["status"] == "okay" and j["audience"] == audience and j['issuer'] == issuer and j['expires'] >= epoch_time:
return dict(email=j['email'])
elif self.on_login_failure:
redirect('http://google.com')
else:
redirect('http://google.com')
return None
def login_form(self):
request = self.request
onclick = "javascript:navigator.id.getVerifiedEmail(gotVerifiedEmail) ; return false"
form = DIV(SCRIPT(_src=self.browserid_js, _type="text/javascript"),
SCRIPT(_src=self.crypto_js, _type="text/javascript"),
A(IMG(_src=self.browserid_button, _alt=self.prompt), _href="#", _onclick=onclick, _class="browserid", _title="Login With BrowserID"),
SCRIPT(self.asertion_js))
return form
| [
[
8,
0,
0.1374,
0.1978,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2418,
0.011,
0,
0.66,
0.1667,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.2527,
0.011,
0,
0.66,
... | [
"\"\"\"\n BrowserID Authentication for web2py\n developed by Madhukar R Pai (Copyright 2012)\n Email <madspai@gmail.com>\n License : LGPL\n\n thanks and credits to the web2py community",
"import time",
"from gluon import *",
"from gluon.storage import Storage",
"from gluon.tools import fetch"... |
#!/usr/bin/env python
# coding: utf8
"""
ExtendedLoginForm is used to extend normal login form in web2py with one more login method.
So user can choose the built-in login or extended login methods.
"""
from gluon import current, DIV
class ExtendedLoginForm(object):
"""
Put extended_login_form under web2py/gluon/contrib/login_methods folder.
Then inside your model where defines the auth:
auth = Auth(globals(),db) # authentication/authorization
...
auth.define_tables() # You might like to put the code after auth.define_tables
... # if the alt_login_form deals with tables of auth.
alt_login_form = RPXAccount(request,
api_key="...",
domain="...",
url = "http://localhost:8000/%s/default/user/login" % request.application)
extended_login_form = ExtendedLoginForm(
auth, alt_login_form, signals=['token'])
auth.settings.login_form = extended_login_form
Note:
Since rpx_account doesn't create the password for the user, you
might need to provide a way for user to create password to do
normal login.
"""
def __init__(self,
auth,
alt_login_form,
signals=[],
login_arg='login'
):
self.auth = auth
self.alt_login_form = alt_login_form
self.signals = signals
self.login_arg = login_arg
def get_user(self):
"""
Delegate the get_user to alt_login_form.get_user.
"""
if hasattr(self.alt_login_form, 'get_user'):
return self.alt_login_form.get_user()
return None # let gluon.tools.Auth.get_or_create_user do the rest
def login_url(self, next):
"""
Optional implement for alt_login_form.
In normal case, this should be replaced by get_user, and never get called.
"""
if hasattr(self.alt_login_form, 'login_url'):
return self.alt_login_form.login_url(next)
return self.auth.settings.login_url
def logout_url(self, next):
"""
Optional implement for alt_login_form.
Called if bool(alt_login_form.get_user) is True.
If alt_login_form implemented logout_url function, it will return that function call.
"""
if hasattr(self.alt_login_form, 'logout_url'):
return self.alt_login_form.logout_url(next)
return next
def login_form(self):
"""
Combine the auth() form with alt_login_form.
If signals are set and a parameter in request matches any signals,
it will return the call of alt_login_form.login_form instead.
So alt_login_form can handle some particular situations, for example,
multiple steps of OpenID login inside alt_login_form.login_form.
Otherwise it will render the normal login form combined with
alt_login_form.login_form.
"""
request = current.request
args = request.args
if (self.signals and
any([True for signal in self.signals if signal in request.vars])
):
return self.alt_login_form.login_form()
self.auth.settings.login_form = self.auth
form = DIV(self.auth())
self.auth.settings.login_form = self
form.components.append(self.alt_login_form.login_form())
return form
| [
[
8,
0,
0.0524,
0.0381,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0857,
0.0095,
0,
0.66,
0.5,
826,
0,
2,
0,
0,
826,
0,
0
],
[
3,
0,
0.5571,
0.8952,
0,
0.66,
... | [
"\"\"\"\nExtendedLoginForm is used to extend normal login form in web2py with one more login method.\nSo user can choose the built-in login or extended login methods.\n\"\"\"",
"from gluon import current, DIV",
"class ExtendedLoginForm(object):\n \"\"\"\n Put extended_login_form under web2py/gluon/contrib... |
import urllib
import urllib2
import base64
def basic_auth(server="http://127.0.0.1"):
"""
to use basic login with a different server
from gluon.contrib.login_methods.basic_auth import basic_auth
auth.settings.login_methods.append(basic_auth('http://server'))
"""
def basic_login_aux(username,
password,
server=server):
key = base64.b64encode(username + ':' + password)
headers = {'Authorization': 'Basic ' + key}
request = urllib2.Request(server, None, headers)
try:
urllib2.urlopen(request)
return True
except (urllib2.URLError, urllib2.HTTPError):
return False
return basic_login_aux
| [
[
1,
0,
0.0417,
0.0417,
0,
0.66,
0,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0833,
0.0417,
0,
0.66,
0.3333,
345,
0,
1,
0,
0,
345,
0,
0
],
[
1,
0,
0.125,
0.0417,
0,
0... | [
"import urllib",
"import urllib2",
"import base64",
"def basic_auth(server=\"http://127.0.0.1\"):\n \"\"\"\n to use basic login with a different server\n from gluon.contrib.login_methods.basic_auth import basic_auth\n auth.settings.login_methods.append(basic_auth('http://server'))\n \"\"\"\n\n ... |
#!/usr/bin/env python
import time
from hashlib import md5
from gluon.dal import DAL
def motp_auth(db=DAL('sqlite://storage.sqlite'),
time_offset=60):
"""
motp allows you to login with a one time password(OTP) generated on a motp client,
motp clients are available for practically all platforms.
to know more about OTP visit http://en.wikipedia.org/wiki/One-time_password
to know more visit http://motp.sourceforge.net
Written by Madhukar R Pai (madspai@gmail.com)
License : MIT or GPL v2
thanks and credits to the web2py community
to use motp_auth:
motp_auth.py has to be located in gluon/contrib/login_methods/ folder
first auth_user has to have 2 extra fields - motp_secret and motp_pin
for that define auth like shown below:
## after auth = Auth(db)
db.define_table(
auth.settings.table_user_name,
Field('first_name', length=128, default=''),
Field('last_name', length=128, default=''),
Field('email', length=128, default='', unique=True), # required
Field('password', 'password', length=512, # required
readable=False, label='Password'),
Field('motp_secret',length=512,default='',
label='MOTP Seceret'),
Field('motp_pin',length=128,default='',
label='MOTP PIN'),
Field('registration_key', length=512, # required
writable=False, readable=False, default=''),
Field('reset_password_key', length=512, # required
writable=False, readable=False, default=''),
Field('registration_id', length=512, # required
writable=False, readable=False, default=''))
##validators
custom_auth_table = db[auth.settings.table_user_name]
# get the custom_auth_table
custom_auth_table.first_name.requires = \
IS_NOT_EMPTY(error_message=auth.messages.is_empty)
custom_auth_table.last_name.requires = \
IS_NOT_EMPTY(error_message=auth.messages.is_empty)
custom_auth_table.password.requires = CRYPT()
custom_auth_table.email.requires = [
IS_EMAIL(error_message=auth.messages.invalid_email),
IS_NOT_IN_DB(db, custom_auth_table.email)]
auth.settings.table_user = custom_auth_table # tell auth to use custom_auth_table
## before auth.define_tables()
##after that:
from gluon.contrib.login_methods.motp_auth import motp_auth
auth.settings.login_methods.append(motp_auth(db=db))
##Instructions for using MOTP
- after configuring motp for web2py, Install a MOTP client on your phone (android,IOS, java, windows phone, etc)
- initialize the motp client (to reset a motp secret type in #**#),
During user creation enter the secret generated during initialization into the motp_secret field in auth_user and
similarly enter a pre-decided pin into the motp_pin
- done.. to login, just generate a fresh OTP by typing in the pin and use the OTP as password
###To Dos###
- both motp_secret and pin are stored in plain text! need to have some way of encrypting
- web2py stores the password in db on successful login (should not happen)
- maybe some utility or page to check the otp would be useful
- as of now user field is hardcoded to email. Some way of selecting user table and user field.
"""
def verify_otp(otp, pin, secret, offset=60):
epoch_time = int(time.time())
time_start = int(str(epoch_time - offset)[:-1])
time_end = int(str(epoch_time + offset)[:-1])
for t in range(time_start - 1, time_end + 1):
to_hash = str(t) + secret + pin
hash = md5(to_hash).hexdigest()[:6]
if otp == hash:
return True
return False
def motp_auth_aux(email,
password,
db=db,
offset=time_offset):
if db:
user_data = db(db.auth_user.email == email).select().first()
if user_data:
if user_data['motp_secret'] and user_data['motp_pin']:
motp_secret = user_data['motp_secret']
motp_pin = user_data['motp_pin']
otp_check = verify_otp(
password, motp_pin, motp_secret, offset=offset)
if otp_check:
return True
else:
return False
else:
return False
return False
return motp_auth_aux
| [
[
1,
0,
0.027,
0.009,
0,
0.66,
0,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.036,
0.009,
0,
0.66,
0.3333,
154,
0,
1,
0,
0,
154,
0,
0
],
[
1,
0,
0.045,
0.009,
0,
0.66,
... | [
"import time",
"from hashlib import md5",
"from gluon.dal import DAL",
"def motp_auth(db=DAL('sqlite://storage.sqlite'),\n time_offset=60):\n\n \"\"\"\n motp allows you to login with a one time password(OTP) generated on a motp client,\n motp clients are available for practically all pla... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Written by Michele Comitini <mcm@glisco.it>
License: GPL v3
Adds support for x509 authentication.
"""
from gluon.globals import current
from gluon.storage import Storage
from gluon.http import HTTP, redirect
#requires M2Crypto
from M2Crypto import X509
class X509Auth(object):
"""
Login using x509 cert from client.
from gluon.contrib.login_methods.x509_auth import X509Account
auth.settings.actions_disabled=['register','change_password',
'request_reset_password','profile']
auth.settings.login_form = X509Auth()
"""
def __init__(self):
self.request = current.request
self.ssl_client_raw_cert = self.request.env.ssl_client_raw_cert
# rebuild the certificate passed by the env
# this is double work, but it is the only way
# since we cannot access the web server ssl engine directly
if self.ssl_client_raw_cert:
x509 = X509.load_cert_string(
self.ssl_client_raw_cert, X509.FORMAT_PEM)
# extract it from the cert
self.serial = self.request.env.ssl_client_serial or (
'%x' % x509.get_serial_number()).upper()
subject = x509.get_subject()
# Reordering the subject map to a usable Storage map
# this allows us a cleaner syntax:
# cn = self.subject.cn
self.subject = Storage(filter(None,
map(lambda x:
(x, map(lambda y:
y.get_data(
).as_text(),
subject.get_entries_by_nid(subject.nid[x]))),
subject.nid.keys())))
def login_form(self, **args):
raise HTTP(403, 'Login not allowed. No valid x509 crentials')
def login_url(self, next="/"):
raise HTTP(403, 'Login not allowed. No valid x509 crentials')
def logout_url(self, next="/"):
return next
def get_user(self):
'''Returns the user info contained in the certificate.
'''
# We did not get the client cert?
if not self.ssl_client_raw_cert:
return None
# Try to reconstruct some useful info for web2py auth machinery
p = profile = dict()
username = p['username'] = reduce(lambda a, b: '%s | %s' % (
a, b), self.subject.CN or self.subject.commonName)
p['first_name'] = reduce(lambda a, b: '%s | %s' % (a, b),
self.subject.givenName or username)
p['last_name'] = reduce(
lambda a, b: '%s | %s' % (a, b), self.subject.surname)
p['email'] = reduce(lambda a, b: '%s | %s' % (
a, b), self.subject.Email or self.subject.emailAddress)
# IMPORTANT WE USE THE CERT SERIAL AS UNIQUE KEY FOR THE USER
p['registration_id'] = self.serial
# If the auth table has a field certificate it will be used to
# save a PEM encoded copy of the user certificate.
p['certificate'] = self.ssl_client_raw_cert
return profile
| [
[
8,
0,
0.0714,
0.0714,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1224,
0.0102,
0,
0.66,
0.2,
703,
0,
1,
0,
0,
703,
0,
0
],
[
1,
0,
0.1327,
0.0102,
0,
0.66,
... | [
"\"\"\"\nWritten by Michele Comitini <mcm@glisco.it>\nLicense: GPL v3\n\nAdds support for x509 authentication.\n\n\"\"\"",
"from gluon.globals import current",
"from gluon.storage import Storage",
"from gluon.http import HTTP, redirect",
"from M2Crypto import X509",
"class X509Auth(object):\n \"\"\"\n ... |
from gluon.contrib.pam import authenticate
def pam_auth():
"""
to use pam_login:
from gluon.contrib.login_methods.pam_auth import pam_auth
auth.settings.login_methods.append(pam_auth())
or
auth.settings.actions_disabled=[
'register','change_password','request_reset_password']
auth.settings.login_methods=[pam_auth()]
The latter method will not store the user password in auth_user.
"""
def pam_auth_aux(username, password):
return authenticate(username, password)
return pam_auth_aux
| [
[
1,
0,
0.0455,
0.0455,
0,
0.66,
0,
109,
0,
1,
0,
0,
109,
0,
0
],
[
2,
0,
0.5909,
0.8636,
0,
0.66,
1,
1,
0,
0,
1,
0,
0,
0,
1
],
[
8,
1,
0.5,
0.5909,
1,
0.62,
0,... | [
"from gluon.contrib.pam import authenticate",
"def pam_auth():\n \"\"\"\n to use pam_login:\n from gluon.contrib.login_methods.pam_auth import pam_auth\n auth.settings.login_methods.append(pam_auth())\n\n or",
" \"\"\"\n to use pam_login:\n from gluon.contrib.login_methods.pam_auth impor... |
#!/usr/bin/env python
# coding: utf8
"""
LoginRadius Authentication for web2py
Developed by Nathan Freeze (Copyright © 2013)
Email <nathan@freezable.com>
This file contains code to allow using loginradius.com
authentication services with web2py
"""
import os
from gluon import *
from gluon.storage import Storage
from gluon.contrib.simplejson import JSONDecodeError
from gluon.tools import fetch
import gluon.contrib.simplejson as json
class LoginRadiusAccount(object):
"""
from gluon.contrib.login_methods.loginradius_account import LoginRadiusAccount
auth.settings.actions_disabled=['register','change_password',
'request_reset_password']
auth.settings.login_form = LoginRadiusAccount(request,
api_key="...",
api_secret="...",
url = "http://localhost:8000/%s/default/user/login" % request.application)
"""
def __init__(self, request, api_key="", api_secret="",
url=None, on_login_failure=None):
self.request = request
self.api_key = api_key
self.api_secret = api_secret
self.url = url
self.auth_base_url = "https://hub.loginradius.com/UserProfile.ashx/"
self.profile = None
self.on_login_failure = on_login_failure
self.mappings = Storage()
def defaultmapping(profile):
first_name = profile.get('FirstName')
last_name = profile.get('LastName')
email = profile.get('Email', [{}])[0].get('Value')
reg_id = profile.get('ID', '')
username = profile.get('ProfileName', email)
return dict(registration_id=reg_id, username=username, email=email,
first_name=first_name, last_name=last_name)
self.mappings.default = defaultmapping
def get_user(self):
request = self.request
user = None
if request.vars.token:
try:
auth_url = self.auth_base_url + self.api_secret + "/" + request.vars.token
json_data = fetch(auth_url, headers={'User-Agent': "LoginRadius - Python - SDK"})
self.profile = json.loads(json_data)
provider = self.profile['Provider']
mapping = self.mappings.get(provider, self.mappings['default'])
user = mapping(self.profile)
except (JSONDecodeError, KeyError):
pass
if user is None and self.on_login_failure:
redirect(self.on_login_failure)
return user
def login_form(self):
loginradius_url = "https://hub.loginradius.com/include/js/LoginRadius.js"
loginradius_lib = SCRIPT(_src=loginradius_url, _type='text/javascript')
container = DIV(_id="interfacecontainerdiv", _class='interfacecontainerdiv')
widget = SCRIPT("""var options={}; options.login=true;
LoginRadius_SocialLogin.util.ready(function () {
$ui = LoginRadius_SocialLogin.lr_login_settings;
$ui.interfacesize = "";$ui.apikey = "%s";
$ui.callback=""; $ui.lrinterfacecontainer ="interfacecontainerdiv";
LoginRadius_SocialLogin.init(options); });""" % self.api_key)
form = DIV(container, loginradius_lib, widget)
return form
def use_loginradius(auth, filename='private/loginradius.key', **kwargs):
path = os.path.join(current.request.folder, filename)
if os.path.exists(path):
request = current.request
domain, public_key, private_key = open(path, 'r').read().strip().split(':')
url = URL('default', 'user', args='login', scheme=True)
auth.settings.actions_disabled = \
['register', 'change_password', 'request_reset_password']
auth.settings.login_form = LoginRadiusAccount(
request, api_key=public_key, api_secret=private_key,
url=url, **kwargs)
| [
[
8,
0,
0.0773,
0.0825,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.134,
0.0103,
0,
0.66,
0.125,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1443,
0.0103,
0,
0.66,
... | [
"\"\"\"\n LoginRadius Authentication for web2py\n Developed by Nathan Freeze (Copyright © 2013)\n Email <nathan@freezable.com>\n\n This file contains code to allow using loginradius.com\n authentication services with web2py\n\"\"\"",
"import os",
"from gluon import *",
"from gluon.storage import Sto... |
import smtplib
import logging
def email_auth(server="smtp.gmail.com:587",
domain="@gmail.com",
tls_mode=None):
"""
to use email_login:
from gluon.contrib.login_methods.email_auth import email_auth
auth.settings.login_methods.append(email_auth("smtp.gmail.com:587",
"@gmail.com"))
"""
def email_auth_aux(email,
password,
server=server,
domain=domain,
tls_mode=tls_mode):
if domain:
if not isinstance(domain, (list, tuple)):
domain = [str(domain)]
if not [d for d in domain if email[-len(d):] == d]:
return False
(host, port) = server.split(':')
if tls_mode is None: # then auto detect
tls_mode = port == '587'
try:
server = None
server = smtplib.SMTP(host, port)
server.ehlo()
if tls_mode:
server.starttls()
server.ehlo()
server.login(email, password)
server.quit()
return True
except:
logging.exception('email_auth() failed')
if server:
try:
server.quit()
except: # server might already close connection after error
pass
return False
return email_auth_aux
| [
[
1,
0,
0.0217,
0.0217,
0,
0.66,
0,
389,
0,
1,
0,
0,
389,
0,
0
],
[
1,
0,
0.0435,
0.0217,
0,
0.66,
0.5,
715,
0,
1,
0,
0,
715,
0,
0
],
[
2,
0,
0.5543,
0.913,
0,
0.66... | [
"import smtplib",
"import logging",
"def email_auth(server=\"smtp.gmail.com:587\",\n domain=\"@gmail.com\",\n tls_mode=None):\n \"\"\"\n to use email_login:\n from gluon.contrib.login_methods.email_auth import email_auth\n auth.settings.login_methods.append(email_auth(\"s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of web2py Web Framework (Copyrighted, 2007-2009).
Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>.
License: GPL v2
Tinkered by Szabolcs Gyuris < szimszo n @ o regpreshaz dot eu>
"""
from gluon import current, redirect
class CasAuth(object):
"""
Login will be done via Web2py's CAS application, instead of web2py's
login form.
Include in your model (eg db.py)::
from gluon.contrib.login_methods.cas_auth import CasAuth
auth.define_tables(username=True)
auth.settings.login_form=CasAuth(
urlbase = "https://[your CAS provider]/app/default/user/cas",
actions=['login','validate','logout'])
where urlbase is the actual CAS server url without the login,logout...
Enjoy.
###UPDATE###
if you want to connect to a CAS version 2 JASIG Server use this:
auth.settings.login_form=CasAuth(
urlbase = "https://[Your CAS server]/cas",
actions = ['login','serviceValidate','logout'],
casversion = 2,
casusername = "cas:user")
where casusername is the xml node returned by CAS server which contains
user's username.
"""
def __init__(self, g=None, # g for backward compatibility ###
urlbase="https://web2py.com/cas/cas",
actions=['login', 'validate', 'logout'],
maps=dict(username=lambda v: v.get('username', v['user']),
email=lambda v: v.get('email', None),
user_id=lambda v: v['user']),
casversion=1,
casusername='cas:user'
):
self.urlbase = urlbase
self.cas_login_url = "%s/%s" % (self.urlbase, actions[0])
self.cas_check_url = "%s/%s" % (self.urlbase, actions[1])
self.cas_logout_url = "%s/%s" % (self.urlbase, actions[2])
self.maps = maps
self.casversion = casversion
self.casusername = casusername
http_host = current.request.env.http_x_forwarded_host
if not http_host:
http_host = current.request.env.http_host
if current.request.env.wsgi_url_scheme in ['https', 'HTTPS']:
scheme = 'https'
else:
scheme = 'http'
self.cas_my_url = '%s://%s%s' % (
scheme, http_host, current.request.env.path_info)
def login_url(self, next="/"):
current.session.token = self._CAS_login()
return next
def logout_url(self, next="/"):
current.session.token = None
current.session.auth = None
self._CAS_logout()
return next
def get_user(self):
user = current.session.token
if user:
d = {'source': 'web2py cas'}
for key in self.maps:
d[key] = self.maps[key](user)
return d
return None
def _CAS_login(self):
"""
exposed as CAS.login(request)
returns a token on success, None on failed authentication
"""
import urllib
self.ticket = current.request.vars.ticket
if not current.request.vars.ticket:
redirect("%s?service=%s" % (self.cas_login_url,
self.cas_my_url))
else:
url = "%s?service=%s&ticket=%s" % (self.cas_check_url,
self.cas_my_url,
self.ticket)
data = urllib.urlopen(url).read()
if data.startswith('yes') or data.startswith('no'):
data = data.split('\n')
if data[0] == 'yes':
if ':' in data[1]: # for Compatibility with Custom CAS
items = data[1].split(':')
a = items[0]
b = len(items) > 1 and items[1] or a
c = len(items) > 2 and items[2] or b
else:
a = b = c = data[1]
return dict(user=a, email=b, username=c)
return None
import xml.dom.minidom as dom
import xml.parsers.expat as expat
try:
dxml = dom.parseString(data)
envelop = dxml.getElementsByTagName(
"cas:authenticationSuccess")
if len(envelop) > 0:
res = dict()
for x in envelop[0].childNodes:
if x.nodeName.startswith('cas:') and len(x.childNodes):
key = x.nodeName[4:].encode('utf8')
value = x.childNodes[0].nodeValue.encode('utf8')
if not key in res:
res[key] = value
else:
if not isinstance(res[key], list):
res[key] = [res[key]]
res[key].append(value)
return res
except expat.ExpatError:
pass
return None # fallback
def _CAS_logout(self):
"""
exposed CAS.logout()
redirects to the CAS logout page
"""
import urllib
redirect("%s?service=%s" % (self.cas_logout_url, self.cas_my_url))
| [
[
8,
0,
0.0486,
0.0486,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0833,
0.0069,
0,
0.66,
0.5,
826,
0,
2,
0,
0,
826,
0,
0
],
[
3,
0,
0.5521,
0.9028,
0,
0.66,
... | [
"\"\"\"\nThis file is part of web2py Web Framework (Copyrighted, 2007-2009).\nDeveloped by Massimo Di Pierro <mdipierro@cs.depaul.edu>.\nLicense: GPL v2\n\nTinkered by Szabolcs Gyuris < szimszo n @ o regpreshaz dot eu>\n\"\"\"",
"from gluon import current, redirect",
"class CasAuth(object):\n \"\"\"\n Log... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Loginza.ru authentication for web2py
Developed by Vladimir Dronnikov (Copyright © 2011)
Email <dronnikov@gmail.com>
"""
import urllib
from gluon.html import *
from gluon.tools import fetch
from gluon.storage import Storage
import gluon.contrib.simplejson as json
class Loginza(object):
"""
from gluon.contrib.login_methods.loginza import Loginza
auth.settings.login_form = Loginza(request,
url = "http://localhost:8000/%s/default/user/login" % request.application)
"""
def __init__(self,
request,
url="",
embed=True,
auth_url="http://loginza.ru/api/authinfo",
language="en",
prompt="loginza",
on_login_failure=None,
):
self.request = request
self.token_url = url
self.embed = embed
self.auth_url = auth_url
self.language = language
self.prompt = prompt
self.profile = None
self.on_login_failure = on_login_failure
self.mappings = Storage()
# TODO: profile.photo is the URL to the picture
# Howto download and store it locally?
# FIXME: what if email is unique=True
self.mappings["http://twitter.com/"] = lambda profile:\
dict(registration_id=profile.get("identity", ""),
username=profile.get("nickname", ""),
email=profile.get("email", ""),
last_name=profile.get("name", "").get("full_name", ""),
#avatar = profile.get("photo",""),
)
self.mappings["https://www.google.com/accounts/o8/ud"] = lambda profile:\
dict(registration_id=profile.get("identity", ""),
username=profile.get("name", "").get("full_name", ""),
email=profile.get("email", ""),
first_name=profile.get("name", "").get("first_name", ""),
last_name=profile.get("name", "").get("last_name", ""),
#avatar = profile.get("photo",""),
)
self.mappings["http://vkontakte.ru/"] = lambda profile:\
dict(registration_id=profile.get("identity", ""),
username=profile.get("name", "").get("full_name", ""),
email=profile.get("email", ""),
first_name=profile.get("name", "").get("first_name", ""),
last_name=profile.get("name", "").get("last_name", ""),
#avatar = profile.get("photo",""),
)
self.mappings.default = lambda profile:\
dict(registration_id=profile.get("identity", ""),
username=profile.get("name", "").get("full_name"),
email=profile.get("email", ""),
first_name=profile.get("name", "").get("first_name", ""),
last_name=profile.get("name", "").get("last_name", ""),
#avatar = profile.get("photo",""),
)
def get_user(self):
request = self.request
if request.vars.token:
user = Storage()
data = urllib.urlencode(dict(token=request.vars.token))
auth_info_json = fetch(self.auth_url + '?' + data)
#print auth_info_json
auth_info = json.loads(auth_info_json)
if auth_info["identity"] is not None:
self.profile = auth_info
provider = self.profile["provider"]
user = self.mappings.get(
provider, self.mappings.default)(self.profile)
#user["password"] = ???
#user["avatar"] = ???
return user
elif self.on_login_failure:
redirect(self.on_login_failure)
return None
def login_form(self):
request = self.request
args = request.args
LOGINZA_URL = "https://loginza.ru/api/widget?lang=%s&token_url=%s&overlay=loginza"
if self.embed:
form = IFRAME(_src=LOGINZA_URL % (self.language, self.token_url),
_scrolling="no",
_frameborder="no",
_style="width:359px;height:300px;")
else:
form = DIV(
A(self.prompt, _href=LOGINZA_URL % (
self.language, self.token_url), _class="loginza"),
SCRIPT(_src="https://s3-eu-west-1.amazonaws.com/s1.loginza.ru/js/widget.js", _type="text/javascript"))
return form
| [
[
8,
0,
0.0522,
0.0435,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.087,
0.0087,
0,
0.66,
0.1667,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0957,
0.0087,
0,
0.66,... | [
"\"\"\"\n Loginza.ru authentication for web2py\n Developed by Vladimir Dronnikov (Copyright © 2011)\n Email <dronnikov@gmail.com>\n\"\"\"",
"import urllib",
"from gluon.html import *",
"from gluon.tools import fetch",
"from gluon.storage import Storage",
"import gluon.contrib.simplejson as json",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Written by Michele Comitini <mcm@glisco.it>
License: GPL v3
Adds support for OAuth1.0a authentication to web2py.
Dependencies:
- python-oauth2 (http://github.com/simplegeo/python-oauth2)
"""
import oauth2 as oauth
import cgi
from urllib import urlencode
from gluon import current
class OAuthAccount(object):
"""
Login will be done via OAuth Framework, instead of web2py's
login form.
Include in your model (eg db.py)::
# define the auth_table before call to auth.define_tables()
auth_table = db.define_table(
auth.settings.table_user_name,
Field('first_name', length=128, default=""),
Field('last_name', length=128, default=""),
Field('username', length=128, default="", unique=True),
Field('password', 'password', length=256,
readable=False, label='Password'),
Field('registration_key', length=128, default= "",
writable=False, readable=False))
auth_table.username.requires = IS_NOT_IN_DB(db, auth_table.username)
.
.
.
auth.define_tables()
.
.
.
CLIENT_ID=\"<put your fb application id here>\"
CLIENT_SECRET=\"<put your fb application secret here>\"
AUTH_URL="..."
TOKEN_URL="..."
ACCESS_TOKEN_URL="..."
from gluon.contrib.login_methods.oauth10a_account import OAuthAccount
auth.settings.login_form=OAuthAccount(globals(
),CLIENT_ID,CLIENT_SECRET, AUTH_URL, TOKEN_URL, ACCESS_TOKEN_URL)
"""
def __redirect_uri(self, next=None):
"""Build the uri used by the authenticating server to redirect
the client back to the page originating the auth request.
Appends the _next action to the generated url so the flows continues.
"""
r = self.request
http_host = r.env.http_host
url_scheme = r.env.wsgi_url_scheme
if next:
path_info = next
else:
path_info = r.env.path_info
uri = '%s://%s%s' % (url_scheme, http_host, path_info)
if r.get_vars and not next:
uri += '?' + urlencode(r.get_vars)
return uri
def accessToken(self):
"""Return the access token generated by the authenticating server.
If token is already in the session that one will be used.
Otherwise the token is fetched from the auth server.
"""
if self.session.access_token:
# return the token (TODO: does it expire?)
return self.session.access_token
if self.session.request_token:
# Exchange the request token with an authorization token.
token = self.session.request_token
self.session.request_token = None
# Build an authorized client
# OAuth1.0a put the verifier!
token.set_verifier(self.request.vars.oauth_verifier)
client = oauth.Client(self.consumer, token)
resp, content = client.request(self.access_token_url, "POST")
if str(resp['status']) != '200':
self.session.request_token = None
self.globals['redirect'](self.globals[
'URL'](f='user', args='logout'))
self.session.access_token = oauth.Token.from_string(content)
return self.session.access_token
self.session.access_token = None
return None
def __init__(self, g, client_id, client_secret, auth_url, token_url, access_token_url):
self.globals = g
self.client_id = client_id
self.client_secret = client_secret
self.code = None
self.request = current.request
self.session = current.session
self.auth_url = auth_url
self.token_url = token_url
self.access_token_url = access_token_url
# consumer init
self.consumer = oauth.Consumer(self.client_id, self.client_secret)
def login_url(self, next="/"):
self.__oauth_login(next)
return next
def logout_url(self, next="/"):
self.session.request_token = None
self.session.access_token = None
return next
def get_user(self):
'''Get user data.
Since OAuth does not specify what a user
is, this function must be implemented for the specific
provider.
'''
raise NotImplementedError("Must override get_user()")
def __oauth_login(self, next):
'''This method redirects the user to the authenticating form
on authentication server if the authentication code
and the authentication token are not available to the
application yet.
Once the authentication code has been received this method is
called to set the access token into the session by calling
accessToken()
'''
if not self.accessToken():
# setup the client
client = oauth.Client(self.consumer, None)
# Get a request token.
# oauth_callback *is REQUIRED* for OAuth1.0a
# putting it in the body seems to work.
callback_url = self.__redirect_uri(next)
data = urlencode(dict(oauth_callback=callback_url))
resp, content = client.request(self.token_url, "POST", body=data)
if resp['status'] != '200':
self.session.request_token = None
self.globals['redirect'](self.globals[
'URL'](f='user', args='logout'))
# Store the request token in session.
request_token = self.session.request_token = oauth.Token.from_string(content)
# Redirect the user to the authentication URL and pass the callback url.
data = urlencode(dict(oauth_token=request_token.key,
oauth_callback=callback_url))
auth_request_url = self.auth_url + '?' + data
HTTP = self.globals['HTTP']
raise HTTP(302,
"You are not authenticated: you are being redirected to the <a href='" + auth_request_url + "'> authentication server</a>",
Location=auth_request_url)
return None
| [
[
8,
0,
0.0464,
0.0546,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.082,
0.0055,
0,
0.66,
0.2,
311,
0,
1,
0,
0,
311,
0,
0
],
[
1,
0,
0.0874,
0.0055,
0,
0.66,
... | [
"\"\"\"\nWritten by Michele Comitini <mcm@glisco.it>\nLicense: GPL v3\n\nAdds support for OAuth1.0a authentication to web2py.\n\nDependencies:\n - python-oauth2 (http://github.com/simplegeo/python-oauth2)",
"import oauth2 as oauth",
"import cgi",
"from urllib import urlencode",
"from gluon import current",... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of web2py Web Framework (Copyrighted, 2007-2009).
Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu> and
Robin B <robi123@gmail.com>.
License: GPL v2
"""
__all__ = ['MEMDB', 'Field']
import re
import sys
import os
import types
import datetime
import thread
import cStringIO
import csv
import copy
import gluon.validators as validators
from gluon.storage import Storage
from gluon import SQLTABLE
import random
SQL_DIALECTS = {'memcache': {
'boolean': bool,
'string': unicode,
'text': unicode,
'password': unicode,
'blob': unicode,
'upload': unicode,
'integer': long,
'double': float,
'date': datetime.date,
'time': datetime.time,
'datetime': datetime.datetime,
'id': int,
'reference': int,
'lower': None,
'upper': None,
'is null': 'IS NULL',
'is not null': 'IS NOT NULL',
'extract': None,
'left join': None,
}}
def cleanup(text):
if re.compile('[^0-9a-zA-Z_]').findall(text):
raise SyntaxError('Can\'t cleanup \'%s\': only [0-9a-zA-Z_] allowed in table and field names' % text)
return text
def assert_filter_fields(*fields):
for field in fields:
if isinstance(field, (Field, Expression)) and field.type\
in ['text', 'blob']:
raise SyntaxError('AppEngine does not index by: %s'
% field.type)
def dateobj_to_datetime(object):
# convert dates,times to datetimes for AppEngine
if isinstance(object, datetime.date):
object = datetime.datetime(object.year, object.month,
object.day)
if isinstance(object, datetime.time):
object = datetime.datetime(
1970,
1,
1,
object.hour,
object.minute,
object.second,
object.microsecond,
)
return object
def sqlhtml_validators(field_type, length):
v = {
'boolean': [],
'string': validators.IS_LENGTH(length),
'text': [],
'password': validators.IS_LENGTH(length),
'blob': [],
'upload': [],
'double': validators.IS_FLOAT_IN_RANGE(-1e100, 1e100),
'integer': validators.IS_INT_IN_RANGE(-1e100, 1e100),
'date': validators.IS_DATE(),
'time': validators.IS_TIME(),
'datetime': validators.IS_DATETIME(),
'reference': validators.IS_INT_IN_RANGE(0, 1e100),
}
try:
return v[field_type[:9]]
except KeyError:
return []
class DALStorage(dict):
"""
a dictionary that let you do d['a'] as well as d.a
"""
def __getattr__(self, key):
return self[key]
def __setattr__(self, key, value):
if key in self:
raise SyntaxError(
'Object \'%s\'exists and cannot be redefined' % key)
self[key] = value
def __repr__(self):
return '<DALStorage ' + dict.__repr__(self) + '>'
class SQLCallableList(list):
def __call__(self):
return copy.copy(self)
class MEMDB(DALStorage):
"""
an instance of this class represents a database connection
Example::
db=MEMDB(Client())
db.define_table('tablename',Field('fieldname1'),
Field('fieldname2'))
"""
def __init__(self, client):
self._dbname = 'memdb'
self['_lastsql'] = ''
self.tables = SQLCallableList()
self._translator = SQL_DIALECTS['memcache']
self.client = client
def define_table(
self,
tablename,
*fields,
**args
):
tablename = cleanup(tablename)
if tablename in dir(self) or tablename[0] == '_':
raise SyntaxError('invalid table name: %s' % tablename)
if not tablename in self.tables:
self.tables.append(tablename)
else:
raise SyntaxError('table already defined: %s' % tablename)
t = self[tablename] = Table(self, tablename, *fields)
t._create()
return t
def __call__(self, where=''):
return Set(self, where)
class SQLALL(object):
def __init__(self, table):
self.table = table
class Table(DALStorage):
"""
an instance of this class represents a database table
Example::
db=MEMDB(Client())
db.define_table('users',Field('name'))
db.users.insert(name='me')
"""
def __init__(
self,
db,
tablename,
*fields
):
self._db = db
self._tablename = tablename
self.fields = SQLCallableList()
self._referenced_by = []
fields = list(fields)
fields.insert(0, Field('id', 'id'))
for field in fields:
self.fields.append(field.name)
self[field.name] = field
field._tablename = self._tablename
field._table = self
field._db = self._db
self.ALL = SQLALL(self)
def _create(self):
fields = []
myfields = {}
for k in self.fields:
field = self[k]
attr = {}
if not field.type[:9] in ['id', 'reference']:
if field.notnull:
attr = dict(required=True)
if field.type[:2] == 'id':
continue
if field.type[:9] == 'reference':
referenced = field.type[10:].strip()
if not referenced:
raise SyntaxError('Table %s: reference \'%s\' to nothing!' % (
self._tablename, k))
if not referenced in self._db:
raise SyntaxError(
'Table: table %s does not exist' % referenced)
referee = self._db[referenced]
ftype = \
self._db._translator[field.type[:9]](
self._db[referenced]._tableobj)
if self._tablename in referee.fields: # ## THIS IS OK
raise SyntaxError('Field: table \'%s\' has same name as a field '
'in referenced table \'%s\'' % (
self._tablename, referenced))
self._db[referenced]._referenced_by.append((self._tablename,
field.name))
elif not field.type in self._db._translator\
or not self._db._translator[field.type]:
raise SyntaxError('Field: unkown field type %s' % field.type)
self._tableobj = self._db.client
return None
def create(self):
# nothing to do, here for backward compatility
pass
def drop(self):
# nothing to do, here for backward compatibility
self._db(self.id > 0).delete()
def insert(self, **fields):
id = self._create_id()
if self.update(id, **fields):
return long(id)
else:
return None
def get(self, id):
val = self._tableobj.get(self._id_to_key(id))
if val:
return Storage(val)
else:
return None
def update(self, id, **fields):
for field in fields:
if not field in fields and self[field].default\
is not None:
fields[field] = self[field].default
if field in fields:
fields[field] = obj_represent(fields[field],
self[field].type, self._db)
return self._tableobj.set(self._id_to_key(id), fields)
def delete(self, id):
return self._tableobj.delete(self._id_to_key(id))
def _shard_key(self, shard):
return self._id_to_key('s/%s' % shard)
def _id_to_key(self, id):
return '__memdb__/t/%s/k/%s' % (self._tablename, str(id))
def _create_id(self):
shard = random.randint(10, 99)
shard_id = self._shard_key(shard)
id = self._tableobj.incr(shard_id)
if not id:
if self._tableobj.set(shard_id, '0'):
id = 0
else:
raise Exception('cannot set memcache')
return long(str(shard) + str(id))
def __str__(self):
return self._tablename
class Expression(object):
def __init__(
self,
name,
type='string',
db=None,
):
(self.name, self.type, self._db) = (name, type, db)
def __str__(self):
return self.name
def __or__(self, other): # for use in sortby
assert_filter_fields(self, other)
return Expression(self.name + '|' + other.name, None, None)
def __invert__(self):
assert_filter_fields(self)
return Expression('-' + self.name, self.type, None)
# for use in Query
def __eq__(self, value):
return Query(self, '=', value)
def __ne__(self, value):
return Query(self, '!=', value)
def __lt__(self, value):
return Query(self, '<', value)
def __le__(self, value):
return Query(self, '<=', value)
def __gt__(self, value):
return Query(self, '>', value)
def __ge__(self, value):
return Query(self, '>=', value)
# def like(self,value): return Query(self,' LIKE ',value)
# def belongs(self,value): return Query(self,' IN ',value)
# for use in both Query and sortby
def __add__(self, other):
return Expression('%s+%s' % (self, other), 'float', None)
def __sub__(self, other):
return Expression('%s-%s' % (self, other), 'float', None)
def __mul__(self, other):
return Expression('%s*%s' % (self, other), 'float', None)
def __div__(self, other):
return Expression('%s/%s' % (self, other), 'float', None)
class Field(Expression):
"""
an instance of this class represents a database field
example::
a = Field(name, 'string', length=32, required=False,
default=None, requires=IS_NOT_EMPTY(), notnull=False,
unique=False, uploadfield=True)
to be used as argument of GQLDB.define_table
allowed field types:
string, boolean, integer, double, text, blob,
date, time, datetime, upload, password
strings must have a length or 512 by default.
fields should have a default or they will be required in SQLFORMs
the requires argument are used to validate the field input in SQLFORMs
"""
def __init__(
self,
fieldname,
type='string',
length=None,
default=None,
required=False,
requires=sqlhtml_validators,
ondelete='CASCADE',
notnull=False,
unique=False,
uploadfield=True,
):
self.name = cleanup(fieldname)
if fieldname in dir(Table) or fieldname[0] == '_':
raise SyntaxError('Field: invalid field name: %s' % fieldname)
if isinstance(type, Table):
type = 'reference ' + type._tablename
if not length:
length = 512
self.type = type # 'string', 'integer'
self.length = length # the length of the string
self.default = default # default value for field
self.required = required # is this field required
self.ondelete = ondelete.upper() # this is for reference fields only
self.notnull = notnull
self.unique = unique
self.uploadfield = uploadfield
if requires == sqlhtml_validators:
requires = sqlhtml_validators(type, length)
elif requires is None:
requires = []
self.requires = requires # list of validators
def formatter(self, value):
if value is None or not self.requires:
return value
if not isinstance(self.requires, (list, tuple)):
requires = [self.requires]
else:
requires = copy.copy(self.requires)
requires.reverse()
for item in requires:
if hasattr(item, 'formatter'):
value = item.formatter(value)
return value
def __str__(self):
return '%s.%s' % (self._tablename, self.name)
MEMDB.Field = Field # ## required by gluon/globals.py session.connect
def obj_represent(object, fieldtype, db):
if object is not None:
if fieldtype == 'date' and not isinstance(object,
datetime.date):
(y, m, d) = [int(x) for x in str(object).strip().split('-')]
object = datetime.date(y, m, d)
elif fieldtype == 'time' and not isinstance(object, datetime.time):
time_items = [int(x) for x in str(object).strip().split(':')[:3]]
if len(time_items) == 3:
(h, mi, s) = time_items
else:
(h, mi, s) = time_items + [0]
object = datetime.time(h, mi, s)
elif fieldtype == 'datetime' and not isinstance(object,
datetime.datetime):
(y, m, d) = [int(x) for x in
str(object)[:10].strip().split('-')]
time_items = [int(x) for x in
str(object)[11:].strip().split(':')[:3]]
if len(time_items) == 3:
(h, mi, s) = time_items
else:
(h, mi, s) = time_items + [0]
object = datetime.datetime(
y,
m,
d,
h,
mi,
s,
)
elif fieldtype == 'integer' and not isinstance(object, long):
object = long(object)
return object
class QueryException:
def __init__(self, **a):
self.__dict__ = a
class Query(object):
"""
A query object necessary to define a set.
It can be stored or can be passed to GQLDB.__call__() to obtain a Set
Example:
query=db.users.name=='Max'
set=db(query)
records=set.select()
"""
def __init__(
self,
left,
op=None,
right=None,
):
if isinstance(right, (Field, Expression)):
raise SyntaxError(
'Query: right side of filter must be a value or entity')
if isinstance(left, Field) and left.name == 'id':
if op == '=':
self.get_one = \
QueryException(tablename=left._tablename,
id=long(right))
return
else:
raise SyntaxError('only equality by id is supported')
raise SyntaxError('not supported')
def __str__(self):
return str(self.left)
class Set(object):
"""
As Set represents a set of records in the database,
the records are identified by the where=Query(...) object.
normally the Set is generated by GQLDB.__call__(Query(...))
given a set, for example
set=db(db.users.name=='Max')
you can:
set.update(db.users.name='Massimo')
set.delete() # all elements in the set
set.select(orderby=db.users.id,groupby=db.users.name,limitby=(0,10))
and take subsets:
subset=set(db.users.id<5)
"""
def __init__(self, db, where=None):
self._db = db
self._tables = []
self.filters = []
if hasattr(where, 'get_all'):
self.where = where
self._tables.insert(0, where.get_all)
elif hasattr(where, 'get_one') and isinstance(where.get_one,
QueryException):
self.where = where.get_one
else:
# find out which tables are involved
if isinstance(where, Query):
self.filters = where.left
self.where = where
self._tables = [field._tablename for (field, op, val) in
self.filters]
def __call__(self, where):
if isinstance(self.where, QueryException) or isinstance(where,
QueryException):
raise SyntaxError('neither self.where nor where can be a QueryException instance')
if self.where:
return Set(self._db, self.where & where)
else:
return Set(self._db, where)
def _get_table_or_raise(self):
tablenames = list(set(self._tables)) # unique
if len(tablenames) < 1:
raise SyntaxError('Set: no tables selected')
if len(tablenames) > 1:
raise SyntaxError('Set: no join in appengine')
return self._db[tablenames[0]]._tableobj
def _getitem_exception(self):
(tablename, id) = (self.where.tablename, self.where.id)
fields = self._db[tablename].fields
self.colnames = ['%s.%s' % (tablename, t) for t in fields]
item = self._db[tablename].get(id)
return (item, fields, tablename, id)
def _select_except(self):
(item, fields, tablename, id) = self._getitem_exception()
if not item:
return []
new_item = []
for t in fields:
if t == 'id':
new_item.append(long(id))
else:
new_item.append(getattr(item, t))
r = [new_item]
return Rows(self._db, r, *self.colnames)
def select(self, *fields, **attributes):
"""
Always returns a Rows object, even if it may be empty
"""
if isinstance(self.where, QueryException):
return self._select_except()
else:
raise SyntaxError('select arguments not supported')
def count(self):
return len(self.select())
def delete(self):
if isinstance(self.where, QueryException):
(item, fields, tablename, id) = self._getitem_exception()
if not item:
return
self._db[tablename].delete(id)
else:
raise Exception('deletion not implemented')
def update(self, **update_fields):
if isinstance(self.where, QueryException):
(item, fields, tablename, id) = self._getitem_exception()
if not item:
return
for (key, value) in update_fields.items():
setattr(item, key, value)
self._db[tablename].update(id, **item)
else:
raise Exception('update not implemented')
def update_record(
t,
s,
id,
a,
):
item = s.get(id)
for (key, value) in a.items():
t[key] = value
setattr(item, key, value)
s.update(id, **item)
class Rows(object):
"""
A wrapper for the return value of a select. It basically represents a table.
It has an iterator and each row is represented as a dictionary.
"""
# ## this class still needs some work to care for ID/OID
def __init__(
self,
db,
response,
*colnames
):
self._db = db
self.colnames = colnames
self.response = response
def __len__(self):
return len(self.response)
def __getitem__(self, i):
if i >= len(self.response) or i < 0:
raise SyntaxError('Rows: no such row: %i' % i)
if len(self.response[0]) != len(self.colnames):
raise SyntaxError('Rows: internal error')
row = DALStorage()
for j in xrange(len(self.colnames)):
value = self.response[i][j]
if isinstance(value, unicode):
value = value.encode('utf-8')
packed = self.colnames[j].split('.')
try:
(tablename, fieldname) = packed
except:
if not '_extra' in row:
row['_extra'] = DALStorage()
row['_extra'][self.colnames[j]] = value
continue
table = self._db[tablename]
field = table[fieldname]
if not tablename in row:
row[tablename] = DALStorage()
if field.type[:9] == 'reference':
referee = field.type[10:].strip()
rid = value
row[tablename][fieldname] = rid
elif field.type == 'boolean' and value is not None:
# row[tablename][fieldname]=Set(self._db[referee].id==rid)
if value == True or value == 'T':
row[tablename][fieldname] = True
else:
row[tablename][fieldname] = False
elif field.type == 'date' and value is not None\
and not isinstance(value, datetime.date):
(y, m, d) = [int(x) for x in
str(value).strip().split('-')]
row[tablename][fieldname] = datetime.date(y, m, d)
elif field.type == 'time' and value is not None\
and not isinstance(value, datetime.time):
time_items = [int(x) for x in
str(value).strip().split(':')[:3]]
if len(time_items) == 3:
(h, mi, s) = time_items
else:
(h, mi, s) = time_items + [0]
row[tablename][fieldname] = datetime.time(h, mi, s)
elif field.type == 'datetime' and value is not None\
and not isinstance(value, datetime.datetime):
(y, m, d) = [int(x) for x in
str(value)[:10].strip().split('-')]
time_items = [int(x) for x in
str(value)[11:].strip().split(':')[:3]]
if len(time_items) == 3:
(h, mi, s) = time_items
else:
(h, mi, s) = time_items + [0]
row[tablename][fieldname] = datetime.datetime(
y,
m,
d,
h,
mi,
s,
)
else:
row[tablename][fieldname] = value
if fieldname == 'id':
id = row[tablename].id
row[tablename].update_record = lambda t = row[tablename], \
s = self._db[tablename], id = id, **a: update_record(t,
s, id, a)
for (referee_table, referee_name) in \
table._referenced_by:
s = self._db[referee_table][referee_name]
row[tablename][referee_table] = Set(self._db, s
== id)
if len(row.keys()) == 1:
return row[row.keys()[0]]
return row
def __iter__(self):
"""
iterator over records
"""
for i in xrange(len(self)):
yield self[i]
def __str__(self):
"""
serializes the table into a csv file
"""
s = cStringIO.StringIO()
writer = csv.writer(s)
writer.writerow(self.colnames)
c = len(self.colnames)
for i in xrange(len(self)):
row = [self.response[i][j] for j in xrange(c)]
for k in xrange(c):
if isinstance(row[k], unicode):
row[k] = row[k].encode('utf-8')
writer.writerow(row)
return s.getvalue()
def xml(self):
"""
serializes the table using SQLTABLE (if present)
"""
return SQLTABLE(self).xml()
def test_all():
"""
How to run from web2py dir:
export PYTHONPATH=.:YOUR_PLATFORMS_APPENGINE_PATH
python gluon/contrib/memdb.py
Setup the UTC timezone and database stubs
>>> import os
>>> os.environ['TZ'] = 'UTC'
>>> import time
>>> if hasattr(time, 'tzset'):
... time.tzset()
>>>
>>> from google.appengine.api import apiproxy_stub_map
>>> from google.appengine.api.memcache import memcache_stub
>>> apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
>>> apiproxy_stub_map.apiproxy.RegisterStub('memcache', memcache_stub.MemcacheServiceStub())
Create a table with all possible field types
>>> from google.appengine.api.memcache import Client
>>> db=MEMDB(Client())
>>> tmp=db.define_table('users', Field('stringf','string',length=32,required=True), Field('booleanf','boolean',default=False), Field('passwordf','password',notnull=True), Field('blobf','blob'), Field('uploadf','upload'), Field('integerf','integer',unique=True), Field('doublef','double',unique=True,notnull=True), Field('datef','date',default=datetime.date.today()), Field('timef','time'), Field('datetimef','datetime'), migrate='test_user.table')
Insert a field
>>> user_id = db.users.insert(stringf='a',booleanf=True,passwordf='p',blobf='0A', uploadf=None, integerf=5,doublef=3.14, datef=datetime.date(2001,1,1), timef=datetime.time(12,30,15), datetimef=datetime.datetime(2002,2,2,12,30,15))
>>> user_id != None
True
Select all
# >>> all = db().select(db.users.ALL)
Drop the table
# >>> db.users.drop()
Select many entities
>>> tmp = db.define_table(\"posts\", Field('body','text'), Field('total','integer'), Field('created_at','datetime'))
>>> many = 20 #2010 # more than 1000 single fetch limit (it can be slow)
>>> few = 5
>>> most = many - few
>>> 0 < few < most < many
True
>>> for i in range(many):
... f=db.posts.insert(body='', total=i,created_at=datetime.datetime(2008, 7, 6, 14, 15, 42, i))
>>>
# test timezones
>>> class TZOffset(datetime.tzinfo):
... def __init__(self,offset=0):
... self.offset = offset
... def utcoffset(self, dt): return datetime.timedelta(hours=self.offset)
... def dst(self, dt): return datetime.timedelta(0)
... def tzname(self, dt): return 'UTC' + str(self.offset)
...
>>> SERVER_OFFSET = -8
>>>
>>> stamp = datetime.datetime(2008, 7, 6, 14, 15, 42, 828201)
>>> post_id = db.posts.insert(created_at=stamp,body='body1')
>>> naive_stamp = db(db.posts.id==post_id).select()[0].created_at
>>> utc_stamp=naive_stamp.replace(tzinfo=TZOffset())
>>> server_stamp = utc_stamp.astimezone(TZOffset(SERVER_OFFSET))
>>> stamp == naive_stamp
True
>>> utc_stamp == server_stamp
True
>>> rows = db(db.posts.id==post_id).select()
>>> len(rows) == 1
True
>>> rows[0].body == 'body1'
True
>>> db(db.posts.id==post_id).delete()
>>> rows = db(db.posts.id==post_id).select()
>>> len(rows) == 0
True
>>> id = db.posts.insert(total='0') # coerce str to integer
>>> rows = db(db.posts.id==id).select()
>>> len(rows) == 1
True
>>> rows[0].total == 0
True
Examples of insert, select, update, delete
>>> tmp=db.define_table('person', Field('name'), Field('birth','date'), migrate='test_person.table')
>>> marco_id=db.person.insert(name=\"Marco\",birth='2005-06-22')
>>> person_id=db.person.insert(name=\"Massimo\",birth='1971-12-21')
>>> me=db(db.person.id==person_id).select()[0] # test select
>>> me.name
'Massimo'
>>> db(db.person.id==person_id).update(name='massimo') # test update
>>> me = db(db.person.id==person_id).select()[0]
>>> me.name
'massimo'
>>> str(me.birth)
'1971-12-21'
# resave date to ensure it comes back the same
>>> me=db(db.person.id==person_id).update(birth=me.birth) # test update
>>> me = db(db.person.id==person_id).select()[0]
>>> me.birth
datetime.date(1971, 12, 21)
>>> db(db.person.id==marco_id).delete() # test delete
>>> len(db(db.person.id==marco_id).select())
0
Update a single record
>>> me.update_record(name=\"Max\")
>>> me.name
'Max'
>>> me = db(db.person.id == person_id).select()[0]
>>> me.name
'Max'
"""
SQLField = Field
SQLTable = Table
SQLXorable = Expression
SQLQuery = Query
SQLSet = Set
SQLRows = Rows
SQLStorage = DALStorage
if __name__ == '__main__':
import doctest
doctest.testmod()
| [
[
8,
0,
0.0072,
0.0066,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.0121,
0.0011,
0,
0.66,
0.0238,
272,
0,
0,
0,
0,
0,
5,
0
],
[
1,
0,
0.0143,
0.0011,
0,
0.66,... | [
"\"\"\"\nThis file is part of web2py Web Framework (Copyrighted, 2007-2009).\nDeveloped by Massimo Di Pierro <mdipierro@cs.depaul.edu> and\nRobin B <robi123@gmail.com>.\nLicense: GPL v2\n\"\"\"",
"__all__ = ['MEMDB', 'Field']",
"import re",
"import sys",
"import os",
"import types",
"import datetime",
... |
# Only Python 2.6 and up, because of NamedTuple.
import time
from collections import namedtuple
Score = namedtuple('Score', ['tag', 'stamp'])
class TimeCollector(object):
def __init__(self):
'''The first time stamp is created here'''
self.scores = [Score(tag='start', stamp=time.clock())]
def addStamp(self, description):
'''Adds a new time stamp, with a description.'''
self.scores.append(Score(tag=description, stamp=time.clock()))
def _stampDelta(self, index1, index2):
'''Private utility function to clean up this common calculation.'''
return self.scores[index1].stamp - self.scores[index2].stamp
def getReportItems(self, orderByCost=True):
'''Returns a list of dicts. Each dict has
start (ms),
end (ms),
delta (ms),
perc (%),
tag (str)
'''
self.scores.append(Score(tag='finish', stamp=time.clock()))
total_time = self._stampDelta(-1, 0)
data = []
for i in range(1, len(self.scores)):
delta = self._stampDelta(i, i - 1)
if abs(total_time) < 1e-6:
perc = 0
else:
perc = delta / total_time * 100
data.append(
dict(
start=self._stampDelta(i - 1, 0) * 1000,
end=self._stampDelta(i, 0) * 1000,
delta=delta * 1000,
perc=perc,
tag=self.scores[i].tag
)
)
if orderByCost:
data.sort(key=lambda x: x['perc'], reverse=True)
return data
def getReportLines(self, orderByCost=True):
'''Produces a report of logged time-stamps as a list of strings.
if orderByCost is False, then the order of the stamps is
chronological.'''
data = self.getReportItems(orderByCost)
headerTemplate = '%10s | %10s | %10s | %11s | %-30s'
headerData = ('Start(ms)', 'End(ms)', 'Delta(ms)', 'Time Cost',
'Description')
bodyTemplate = '%(start)10.0f | %(end)10.0f | %(delta)10.0f |' \
+ ' %(perc)10.0f%% | %(tag)-30s'
return [headerTemplate % headerData] + [bodyTemplate % d for d in data]
def getReportText(self, **kwargs):
return '\n'.join(self.getReportLines(**kwargs))
def restart(self):
self.scores = [Score(tag='start', stamp=time.clock())]
if __name__ == '__main__':
print('')
print('Testing:')
print('')
# First create the collector
t = TimeCollector()
x = [i for i in range(1000)]
# Every time some work gets done, add a stamp
t.addStamp('Initialization Section')
x = [i for i in range(10000)]
t.addStamp('A big loop')
x = [i for i in range(100000)]
t.addStamp('calling builder function')
# Finally, obtain the results
print('')
print(t.getReportText())
# If you want to measure something else in the same scope, you can
# restart the collector.
t.restart()
x = [i for i in range(1000000)]
t.addStamp('Part 2')
x = [i for i in range(1000000)]
t.addStamp('Cleanup')
# And once again report results
print('')
print(t.getReportText())
t.restart()
for y in range(1, 200, 20):
x = [i for i in range(10000) * y]
t.addStamp('Iteration when y = ' + str(y))
print('')
# You can turn off ordering of results
print(t.getReportText(orderByCost=False))
| [
[
1,
0,
0.0196,
0.0098,
0,
0.66,
0,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.0294,
0.0098,
0,
0.66,
0.25,
193,
0,
1,
0,
0,
193,
0,
0
],
[
14,
0,
0.0392,
0.0098,
0,
0... | [
"import time",
"from collections import namedtuple",
"Score = namedtuple('Score', ['tag', 'stamp'])",
"class TimeCollector(object):\n def __init__(self):\n '''The first time stamp is created here'''\n self.scores = [Score(tag='start', stamp=time.clock())]\n\n def addStamp(self, description... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.