code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
__all__ = 'LOCATIONS',
LOCATIONS = {
'Ocarina': {
'type': 'area',
'link': {
'West Lower Mount Hebra': [('nosettings', 'inverted')],
'East Light World': [('nosettings', 'inverted')],
'Kakariko': [('nosettings', 'inverted')],
'South Light World': [('nosettings', 'inverted')],
'East Light World': [('nosettings', 'inverted')],
'Desert Portal (LW)': [('nosettings', 'inverted')],
'Southern Shores': [('nosettings', 'inverted')],
'West Lower Death Mountain': [('settings', 'inverted')],
'River Shop Area': [('settings', 'inverted')],
"Thieves' Town Surface": [('settings', 'inverted')],
'South Dark World': [('settings', 'inverted')],
'East Dark World': [('settings', 'inverted')],
'Desert Portal (DW)': [('settings', 'inverted')],
'Eastern Shores': [('settings', 'inverted')],
}
},
'Light Bottle Ocarina': {
'type': 'area',
'link': {
'West Lower Mount Hebra': [('and', [
('glitch', 'major'), ('item', 'bottle')])],
'East Light World': [('and', [
('glitch', 'major'), ('item', 'bottle')])],
'Kakariko': [('and', [
('glitch', 'major'), ('item', 'bottle')])],
'South Light World': [('and', [
('glitch', 'major'), ('item', 'bottle')])],
'East Light World': [('and', [
('glitch', 'major'), ('item', 'bottle')])],
'Desert Portal (LW)': [('and', [
('glitch', 'major'), ('item', 'bottle')])],
'Southern Shores': [('and', [
('glitch', 'major'), ('item', 'bottle')])]}
},
'Dark Bottle Ocarina': {
'type': 'area',
'link': {
'West Lower Death Mountain': [('and', [
('glitch', 'major'), ('item', 'bottle')])],
'River Shop Area': [('and', [
('glitch', 'major'), ('item', 'bottle')])],
"Thieves' Town Surface": [('and', [
('glitch', 'major'), ('item', 'bottle')])],
'South Dark World': [('and', [
('glitch', 'major'), ('item', 'bottle')])],
'East Dark World': [('and', [
('glitch', 'major'), ('item', 'bottle')])],
'Desert Portal (DW)': [('and', [
('glitch', 'major'), ('item', 'bottle')])],
'Eastern Shores': [('and', [
('glitch', 'major'), ('item', 'bottle')])]}
},
} | z3-tracker | /z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/ocarina.py | ocarina.py |
__all__ = 'LOCATIONS',
LOCATIONS = {
'Castle Dungeons': {
'type': 'drop', 'map': 'light', 'coord': (332, 290),
'keypools': [],
'link': {
"Zelda's Treasure": []}
},
'East Palace': {
'type': 'dungeon', 'map': 'light', 'coord': (636, 251),
'keypools': [],
'link': {}
},
'Desert Palace': {
'type': 'dungeon', 'map': 'light', 'coord': (49, 528),
'keypools': [
{'type': 'small', 'settings': (), 'keys': 1,
'chests': ('Desert Palace Map', 'Desert Palace Small Key')},
{'type': 'big', 'settings': (),
'chests': (
'Desert Palace Compass', 'Desert Palace Big Key',
'Desert Palace Map', 'Desert Palace Small Key')}],
'link': {}
},
'Mountain Tower': {
'type': 'dungeon', 'map': 'light', 'coord': (372, 14),
'keypools': [
{'type': 'small', 'settings': (), 'keys': 1,
'chests': ('Mountain Tower Small Key', 'Mountain Tower Map')},
{'type': 'big', 'settings': (),
'chests': (
'Mountain Tower Small Key', 'Mountain Tower Map',
'Mountain Tower Big Key')}],
'link': {}
},
'Castle Tower': {
'type': 'dungeon', 'map': 'light', 'coord': (332, 244),
'keypools': [
{'type': 'small', 'settings': (), 'keys': 1,
'chests': ('Castle Tower First Chest',)},
{'type': 'small', 'settings': (), 'keys': 1,
'chests': (
'Castle Tower First Chest', 'Castle Tower Seconds Chest')}],
'link': {}
},
'Dark Palace': {
'type': 'dungeon', 'map': 'dark', 'coord': (629, 241),
'keypools': [
{'type': 'small', 'settings': (), 'keys': 4,
'chests': (
'Dark Palace First Key', 'Dark Palace Key With A View',
'Dark Palace Map', 'Dark Palace Big Key',
'Dark Palace Stalfos Key', 'Dark Palace Targetting Chest')},
{'type': 'small', 'settings': (), 'keys': 2,
'chests': (
'Dark Palace First Key', 'Dark Palace Key With A View',
'Dark Palace Map', 'Dark Palace Big Key',
'Dark Palace Stalfos Key', 'Dark Palace Targetting Chest',
'Dark Palace Treasury Left Chest',
'Dark Palace Treasury Right Chest','Dark Palace Compass')}],
'link': {}
},
'Swamp Palace': {
'type': 'dungeon', 'map': 'dark', 'coord': (304, 600),
'keypools': [
{'type': 'small', 'settings': (), 'keys': 1,
'chests': ('Swamp Palace Key',)}],
'link': {}
},
'Skull Woods': {
'type': 'dungeon', 'map': 'dark', 'coord': (20, 22),
'keypools': [],
'link': {}
},
"Thieves' Town": {
'type': 'dungeon', 'map': 'dark', 'coord': (77, 301),
'keypools': [],
'link': {}
},
'Ice Palace': {
'type': 'dungeon', 'map': 'dark', 'coord': (523, 552),
'keypools': [],
'link': {}
},
'Misery Mire': {
'type': 'dungeon', 'map': 'dark', 'coord': (43, 532),
'keypools': [],
'link': {}
},
'Turtle Rock': {
'type': 'dungeon', 'map': 'dark', 'coord': (618, 33),
'keypools': [
{'type': 'small', 'settings': ('open',), 'keys': 1,
'chests': (
'Turtle Rock Compass', 'Turtle Rock Map',
'Turtle Rock Map Key')},
{'type': 'small', 'settings': ('open',), 'keys': 1,
'chests': (
'Turtle Rock Compass', 'Turtle Rock Map',
'Turtle Rock Map Key', 'Turtle Rock Chain Chomp Key')},
{'type': 'small', 'settings': ('open',), 'keys': 1,
'chests': (
'Turtle Rock Compass', 'Turtle Rock Map',
'Turtle Rock Map Key', 'Turtle Rock Chain Chomp Key',
'Turtle Rock Big Key', 'Turtle Rock Treasure',
'Turtle Rock Switch Key')},
{'type': 'small', 'settings': ('open',), 'keys': 1,
'chests': (
'Turtle Rock Compass', 'Turtle Rock Map',
'Turtle Rock Map Key', 'Turtle Rock Chain Chomp Key',
'Turtle Rock Big Key', 'Turtle Rock Treasure',
'Turtle Rock Switch Key', 'Turtle Rock Treasury Chest 1',
'Turtle Rock Treasury Chest 2', 'Turtle Rock Treasury Chest 3',
'Turtle Rock Treasury Chest 4')},
{'type': 'big', 'settings': ('open',),
'chests': (
'Turtle Rock Compass', 'Turtle Rock Map',
'Turtle Rock Map Key', 'Turtle Rock Chain Chomp Key',
'Turtle Rock Big Key')}],
'link': {}
},
"Ganon's Tower": {
'type': 'dungeon', 'map': 'dark', 'coord': (367, 14),
'keypools': [
{'type': 'small', 'settings': (), 'keys': 2,
'chests': (
"Ganon's Tower Torch Key",
"Ganon's Tower Stalfos Room Chest 1",
"Ganon's Tower Stalfos Room Chest 2",
"Ganon's Tower Stalfos Room Chest 3",
"Ganon's Tower Stalfos Room Chest 4",
"Ganon's Tower Trap Chest 1", "Ganon's Tower Trap Chest 2",
"Ganon's Tower Tile Room")},
{'type': 'small', 'settings': (), 'keys': 1,
'chests': (
"Ganon's Tower Torch Key",
"Ganon's Tower Stalfos Room Chest 1",
"Ganon's Tower Stalfos Room Chest 2",
"Ganon's Tower Stalfos Room Chest 3",
"Ganon's Tower Stalfos Room Chest 4",
"Ganon's Tower Map", "Ganon's Tower Trap Chest 1",
"Ganon's Tower Trap Chest 2", "Ganon's Tower Tile Room")},
{'type': 'small', 'settings': (), 'keys': 1,
'chests': (
"Ganon's Tower Torch Key",
"Ganon's Tower Stalfos Room Chest 1",
"Ganon's Tower Stalfos Room Chest 2",
"Ganon's Tower Stalfos Room Chest 3",
"Ganon's Tower Stalfos Room Chest 4",
"Ganon's Tower Map", "Ganon's Tower Winder Room Key",
"Ganon's Tower Trap Chest 1", "Ganon's Tower Trap Chest 2",
"Ganon's Tower Tile Room")}],
'link': {}
},
} | z3-tracker | /z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/dungeons.py | dungeons.py |
__all__ = 'LOCATIONS',
LOCATIONS = {
'Desert': {
'type': 'area',
'link': {
'Misery Mire Surface': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'Light Bottle Ocarina': [],
'Southern Shores': [],
"Aginah's Cave Entrance (E)": [],
'Desert Cave Valley': [
('settings', 'inverted'),
('glitch', 'major'),
('and', [
('glitch', 'overworld'), ('item', 'pegasus')])],
'Desert Palace Stairs': [('item', 'mudora')],
'Desert Portal (LW)': [('and', [
('glitch', 'overworld'), ('item', 'pegasus')])],
'Desert Ridge': [('and', [
('glitch', 'overworld'), ('item', 'pegasus')])]},
'visible': {"Vulture's Heart": []}
},
"Aginah's Cave Entrance (E)": {
'type': 'entrance_unique', 'map': 'light', 'coord': (132, 546),
'link': {
'Desert': [],
"Aginah's Cave Entrance (I)": []}
},
"Aginah's Cave Entrance (I)": {
'type': 'interior',
'link': {
"Aginah's Cave Entrance (E)": [],
"Aginah's Cave Interior": []}
},
"Aginah's Cave Interior": {
'type': 'area',
'link': {
"Aginah's Cave Entrance (I)": [],
"Aginah's Cave": [('item', 'bombs')]}
},
"Aginah's Cave": {
'type': 'cave', 'map': 'light', 'coord': (132, 546),
'link': {
"Aginah's Cave Interior": []}
},
'Desert Cave Valley': {
'type': 'area',
'link': {
'Misery Mire Surface': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'Desert': [],
'Desert Cave Entrance (E)': [('item', 'powerglove')]}
},
'Desert Cave Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (116, 515),
'link': {
'Desert Cave Valley': [],
'Desert Cave Entrance (I)': []}
},
'Desert Cave Entrance (I)': {
'type': 'interior',
'link': {
'Desert Cave Entrance (E)': [],
'Desert Cave': []}
},
'Desert Cave': {
'type': 'drop', 'map': 'light', 'coord': (116, 515),
'link': {
'Desert Cave Entrance (I)': []}
},
'Desert Portal (LW)': {
'type': 'area',
'link': {
'Desert Portal (DW)': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'Desert Portal': [('item', 'titansmitts')],
'Desert': []}
},
'Desert Portal': {
'type': 'area',
'link': {
'Desert Portal (DW)': [('and', [
('nosettings', 'inverted'), ('state', 'rabbit')])],
'Desert Portal (LW)': [('and', [
('settings', 'inverted'), ('state', 'rabbit')])]}
},
'Desert Palace Stairs': {
'type': 'area',
'link': {
'Misery Mire Surface': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'Desert Palace Main Entrance Entrance (E)': []}
},
'Desert Palace Main Entrance Entrance (E)': {
'type': 'entrance_dungeon', 'map': 'light', 'coord': (49, 549),
'link': {
'Desert Palace Stairs': [],
'Desert Palace Main Entrance Entrance (I)': []}
},
'Desert Palace Main Entrance Entrance (I)': {
'type': 'interior',
'link': {
'Desert Palace Main Entrance Entrance (E)': [],
'Desert Palace Lobby': []}
},
'Desert Palace Lobby': {
'type': 'area', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Interior': [('and', [
('rabbitbarrier', None),
('or', [('nosettings', 'majoronly'), ('item', 'pegasus')])])]}
},
'Desert Palace Side Entrance Entrance (I)': {
'type': 'interior',
'link': {
'Desert Palace Side Entrance Entrance (E)': [],
'Desert Palace Interior': [('or', [
('nosettings', 'majoronly'), ('item', 'pegasus')])]}
},
'Desert Palace Side Entrance Entrance (E)': {
'type': 'entrance_dungeon', 'map': 'light', 'coord': (75, 527),
'link': {
'Desert': [],
'Desert Palace Side Entrance Entrance (I)': []}
},
'Desert Palace Interior': {
'type': 'area', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Lobby': [('rabbitbarrier', None)],
'Desert Palace Side Entrance Entrance (I)': [],
'Desert Palace Back Entrance Entrance (I)': [],
'Desert Palace Compass Room': [('smallkey', 'Desert Palace')],
'Desert Palace Map': [('rabbitbarrier', None)],
'Desert Palace Small Key': [('item', 'pegasus')],
'Desert Palace Treasure Lobby': [('rabbitbarrier', None)]}
},
'Desert Palace Compass Room': {
'type': 'area', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Compass': [('rabbitbarrier', None)],
'Desert Palace Big Key': [('rabbitbarrier', None)],
'Desert Palace Interior': []}
},
'Desert Palace Compass': {
'type': 'dungeonchest', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Compass Room': []}
},
'Desert Palace Big Key': {
'type': 'dungeonchest', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Compass Room': []}
},
'Desert Palace Map': {
'type': 'dungeonchest', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Interior': []}
},
'Desert Palace Small Key': {
'type': 'dungeonchest', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Interior': []}
},
'Desert Palace Treasure Lobby': {
'type': 'area', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Treasure': [('bigkey', 'Desert Palace')],
'Desert Palace Interior': []}
},
'Desert Palace Treasure': {
'type': 'dungeonchest', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Treasure Lobby': []}
},
'Desert Palace Back Entrance Entrance (I)': {
'type': 'interior',
'link': {
'Desert Palace Back Entrance Entrance (E)': [],
'Desert Palace Interior': [('or', [
('nosettings', 'majoronly'), ('item', 'pegasus')])]}
},
'Desert Palace Back Entrance Entrance (E)': {
'type': 'entrance_dungeon', 'map': 'light', 'coord': (23, 527),
'link': {
'Desert Ridge': [],
'Desert Palace Back Entrance Entrance (I)': []}
},
'Desert Ridge': {
'type': 'area',
'link': {
'Misery Mire Surface': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'Desert Palace Back Entrance Entrance (E)': [],
'Desert': [],
"Vulture's Heart": [],
'Desert Palace Gauntlet Entrance': [('item', 'powerglove')]}
},
"Vulture's Heart": {
'type': 'item', 'map': 'light', 'coord': (16, 606),
'link': {
'Desert Ridge': []}
},
'Desert Palace Gauntlet Entrance': {
'type': 'area',
'link': {
'Misery Mire Surface': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'Desert Ridge': [('item', 'powerglove')],
'Desert Palace Gauntlet Entrance (E)': []}
},
'Desert Palace Gauntlet Entrance (E)': {
'type': 'entrance_dungeon', 'map': 'light', 'coord': (49, 507),
'link': {
'Desert Palace Gauntlet Entrance': [],
'Desert Palace Gauntlet Entrance (I)': []}
},
'Desert Palace Gauntlet Entrance (I)': {
'type': 'interior',
'link': {
'Desert Palace Gauntlet Entrance (E)': [],
'Desert Palace Trap Room 1': [('rabbitbarrier', None)]}
},
'Desert Palace Trap Room 1': {
'type': 'area', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Gauntlet Entrance (I)': [],
'Desert Palace Hidden Key 1': [],
'Desert Palace Trap Room 2': [('smallkey', 'Desert Palace')]}
},
'Desert Palace Hidden Key 1': {
'type': 'dungeonkey', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Trap Room 1': []}
},
'Desert Palace Trap Room 2': {
'type': 'area', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Trap Room 1': [],
'Desert Palace Hidden Key 2': [],
'Desert Palace Torch Room': [('smallkey', 'Desert Palace')]}
},
'Desert Palace Hidden Key 2': {
'type': 'dungeonkey', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Trap Room 2': []}
},
'Desert Palace Torch Room': {
'type': 'area', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Trap Room 2': [],
'Desert Palace Boss Door': [
('item', 'lantern'), ('item', 'firerod')]}
},
'Desert Palace Boss Door': {
'type': 'area', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Torch Room': [],
'Desert Palace Boss': [('bigkey', 'Desert Palace')]}
},
'Desert Palace Boss': {
'type': 'dungeonboss', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Boss Item': [
('item', 'sword'), ('item', 'hammer'), ('item', 'bow'),
('item', 'firerod'), ('item', 'icerod'), ('item', 'byrna'),
('item', 'somaria')]}
},
'Desert Palace Boss Item': {
'type': 'dungeonchest_nokey', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Reward': []}
},
'Desert Palace Reward': {
'type': 'dungeonreward', 'dungeon': 'Desert Palace',
'link': {
'Desert Palace Main Entrance Entrance (I)': []}
},
} | z3-tracker | /z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/desert.py | desert.py |
__all__ = 'LOCATIONS',
LOCATIONS = {
'Hebra Ascent': {
'type': 'area',
'link': {
'Hebra Ascent (Bottom) Entrance (I)': [('item', 'lantern')],
'Finding The Lost Man': [('item', 'lantern')],
'Hebra Ascent (Top) Entrance (I)': [('item', 'lantern')]}
},
'Finding The Lost Man': {
'type': 'area',
'link': {
'Hebra Ascent': [],
"Lost Man's Cave Front Entrance Entrance (I)": [
('access', "Lost Man's Cave Front Entrance Entrance (E)")]}
},
'Hebra Ascent (Top) Entrance (I)': {
'type': 'interior',
'link': {
'Hebra Ascent': [],
'Hebra Ascent (Top) Entrance (E)': [('nosettings', 'inverted')],
'West Death Mountain Fairy Entrance (E)': [
('settings', 'inverted')]}
},
'Hebra Ascent (Top) Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (269, 125),
'link': {
'Hebra Ascent (Top) Entrance (I)': [('nosettings', 'inverted')],
'West Death Mountain Fairy Entrance (I)': [
('settings', 'inverted')],
'West Lower Mount Hebra': []}
},
'West Lower Mount Hebra': {
'type': 'area',
'link': {
'West Lower Death Mountain': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'Light Bottle Ocarina': [],
'Hebra Ascent (Top) Entrance (E)': [],
"Lost Man's Cave Front Entrance Entrance (E)": [],
"Lost Man's Cave Back Entrance Entrance (E)": [],
'East Lower Mount Hebra': [
('item', 'hookshot'),
('glitch', 'major'),
('and', [
('glitch', 'overworld'),
('or', [
('item', 'mirror'), ('item', 'pegasus')])])],
'Hebra Descent (Top) Entrance (E)': [],
'Heart Rock Cave Top Entrance Entrance (E)': [],
'West Hebra Fairy Cave Entrance (E)': [],
'Heart Rock Cave Bottom Entrance Entrance (E)': [],
'Hebra Portal': [],
'Pyramid Fairy Entrance (E)': [('and', [
('glitch', 'overworld'), ('item', 'mirror'),
('item', 'pegasus'),
('or', [
('item', 'sword'), ('item', 'hookshot')])])],
'Heart Rock': [
('and', [
('glitch', 'overworld'), ('item', 'pegasus')]),
('glitch', 'major')],
"King's Tomb Entrance (E)": [('and', [
('glitch', 'overworld'), ('item', 'pegasus')])]},
'visible': {'Heart Rock': []}
},
"Lost Man's Cave Front Entrance Entrance (E)": {
'type': 'entrance_unique', 'map': 'light', 'coord': (298, 155),
'link': {
'West Lower Mount Hebra': [],
"Lost Man's Cave Front Entrance Entrance (I)": []}
},
"Lost Man's Cave Front Entrance Entrance (I)": {
'type': 'interior',
'link': {
"Lost Man's Cave Front Entrance Entrance (E)": [],
"Lost Man's Cave Front": []}
},
"Lost Man's Cave Front": {
'type': 'area',
'link': {
"Lost Man's Cave Front Entrance Entrance (I)": [],
'Lost Man': [('access', 'Finding The Lost Man')],
"Lost Man's Cave Back": [('item', 'lantern')]}
},
'Lost Man': {
'type': 'chest', 'map': 'light', 'coord': (298, 150),
'link': {
"Lost Man's Cave Front": []}
},
"Lost Man's Cave Back": {
'type': 'area',
'link': {
"Lost Man's Cave Front": [],
"Lost Man's Cave Back Entrance Entrance (I)": []}
},
"Lost Man's Cave Back Entrance Entrance (I)": {
'type': 'interior',
'link': {
"Lost Man's Cave Front": [('item', 'lantern')],
"Lost Man's Cave Back Entrance Entrance (E)": []}
},
"Lost Man's Cave Back Entrance Entrance (E)": {
'type': 'entrance_unique', 'map': 'light', 'coord': (355, 106),
'link': {
"Lost Man's Cave Back Entrance Entrance (I)": [],
'West Lower Mount Hebra': []}
},
'Hebra Descent (Top) Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (262, 91),
'link': {
'West Lower Mount Hebra': [],
'Hebra Descent (Top) Entrance (I)': []}
},
'Hebra Descent (Top) Entrance (I)': {
'type': 'interior',
'link': {
'Hebra Descent (Top) Entrance (E)': [],
'Hebra Descent': []}
},
'Hebra Descent': {
'type': 'area',
'link': {
'Hebra Descent (Bottom) Entrance (I)': [],
'Hebra Descent (Top) Entrance (I)': []}
},
'Heart Rock Cave Top Entrance Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (324, 68),
'link': {
'West Lower Mount Hebra': [],
'Heart Rock Cave Top Entrance Entrance (I)': []}
},
'Heart Rock Cave Top Entrance Entrance (I)': {
'type': 'interior',
'link': {
'Heart Rock Cave Top Entrance Entrance (E)': [],
'Heart Rock Cave Top': []}
},
'Heart Rock Cave Top': {
'type': 'area',
'link': {
'Heart Rock Cave Top Entrance Entrance (I)': [],
'West Hebra Fairy Cave': []}
},
'West Hebra Fairy Cave Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (302, 91),
'link': {
'West Lower Mount Hebra': [],
'West Hebra Fairy Cave Entrance (I)': []}
},
'West Hebra Fairy Cave Entrance (I)': {
'type': 'interior',
'link': {
'West Hebra Fairy Cave Entrance (E)': [],
'West Hebra Fairy Cave': []}
},
'West Hebra Fairy Cave': {
'type': 'area',
'link': {
'West Hebra Fairy Cave Entrance (I)': []}
},
'Heart Rock Cave Bottom Entrance Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (324, 96),
'link': {
'West Lower Mount Hebra': [],
'Heart Rock Cave Bottom Entrance Entrance (I)': []}
},
'Heart Rock Cave Bottom Entrance Entrance (I)': {
'type': 'interior',
'link': {
'Heart Rock Cave Bottom Entrance Entrance (E)': [],
'Heart Rock Cave Bottom': []}
},
'Heart Rock Cave Bottom': {
'type': 'area',
'link': {
'Heart Rock Cave Bottom Entrance Entrance (I)': [],
'Heart Rock Cave Heart': [],
'West Hebra Fairy Cave': []}
},
'Heart Rock Cave Heart': {
'type': 'cave', 'map': 'light', 'coord': (324, 88),
'link': {
'Heart Rock Cave Bottom': []}
},
'Hebra Portal': {
'type': 'area',
'link': {
'West Lower Death Mountain': [('and', [
('nosettings', 'inverted'), ('state', 'rabbit')])],
'West Lower Mount Hebra': [('and', [
('settings', 'inverted'), ('state', 'rabbit')])]}
},
'Heart Rock': {
'type': 'item', 'map': 'light', 'coord': (337, 55),
'link': {
'West Lower Death Mountain': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'West Lower Mount Hebra': [],
'West Upper Mount Hebra': []}
},
'West Upper Mount Hebra': {
'type': 'area',
'link': {
'West Upper Death Mountain': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'West Lower Mount Hebra': [],
'Heart Rock': [('settings', 'inverted')],
'Ether Rock': [('mudora', 'take')],
'Mountain Tower Entrance (E)': [],
'East Upper Mount Hebra': [('item', 'hammer')]},
'visible': {'Heart Rock': [], 'Ether Rock': [('item', 'mudora')]}
},
'Ether Rock': {
'type': 'item', 'map': 'light', 'coord': (278, 13),
'link': {
'West Upper Mount Hebra': []}
},
'East Lower Mount Hebra': {
'type': 'area',
'link': {
'West Lower Death Mountain': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'West Lower Mount Hebra': [('item', 'hookshot')],
'Spiral Cave Bottom Entrance Entrance (E)': [],
'Fairy Maze Bottom Entrance Entrance (E)': [
('item', 'titansmitts')],
'East Hebra Fairy Cave Entrance Entrance (E)': [],
'Hebra Shop Cave Entrance (E)': [],
'East Hebra Portal': [('item', 'titansmitts')],
'East Hebra Cave Bottom Entrance Entrance (E)': []}
},
'Spiral Cave Bottom Entrance Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (530, 86),
'link': {
'East Lower Mount Hebra': [],
'Spiral Cave Bottom Entrance Entrance (I)': []}
},
'Spiral Cave Bottom Entrance Entrance (I)': {
'type': 'interior',
'link': {
'Spiral Cave Bottom Entrance Entrance (E)': [],
'Spiral Cave Bottom': []}
},
'Spiral Cave Bottom': {
'type': 'area',
'link': {
'Spiral Cave Bottom Entrance Entrance (I)': []}
},
'Fairy Maze Bottom Entrance Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (544, 91),
'link': {
'East Lower Mount Hebra': [],
'Fairy Maze Bottom Entrance Entrance (I)': []}
},
'Fairy Maze Bottom Entrance Entrance (I)': {
'type': 'interior',
'link': {
'Fairy Maze Bottom Entrance Entrance (E)': [],
'Fairy Maze Top Entrance Entrance (I)': []}
},
'East Hebra Fairy Cave Entrance Entrance (E)': {
'type': 'entrance', 'map': 'light', 'coord': (558, 96),
'link': {
'East Lower Mount Hebra': [],
'East Hebra Fairy Cave Entrance Entrance (I)': []}
},
'East Hebra Fairy Cave Entrance Entrance (I)': {
'type': 'interior',
'link': {
'East Hebra Fairy Cave Entrance Entrance (E)': []}
},
'Hebra Shop Cave Entrance (E)': {
'type': 'entrance_shop', 'map': 'light', 'coord': (572, 96),
'link': {
'East Lower Mount Hebra': [],
'Hebra Shop Cave Entrance (I)': []}
},
'Hebra Shop Cave Entrance (I)': {
'type': 'interior',
'link': {
'Hebra Shop Cave Entrance (E)': [],
'Hebra Shop Cave': []}
},
'Hebra Shop Cave': {
'type': 'area',
'link': {
'Hebra Shop Cave Entrance (I)': []}
},
'East Hebra Portal': {
'type': 'area',
'link': {
'East Lower Death Mountain': [('and', [
('nosettings', 'inverted'), ('state', 'rabbit')])],
'East Lower Mount Hebra': [('and', [
('settings', 'inverted'), ('state', 'rabbit')])]}
},
'East Hebra Cave Bottom Entrance Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (573, 142),
'link': {
'East Lower Mount Hebra': [],
'East Hebra Cave Bottom Entrance Entrance (I)': []}
},
'East Hebra Cave Bottom Entrance Entrance (I)': {
'type': 'interior',
'link': {
'East Hebra Cave Bottom Entrance Entrance (E)': [],
'East Hebra Cave (area)': []}
},
'East Hebra Cave (area)': {
'type': 'area',
'link': {
'East Hebra Cave Bottom Entrance Entrance (I)': [],
'Hebra Shop Cave': [('rabbitbarrier', None)],
'East Hebra Cave': [('item', 'bombs')],
'East Hebra Cave Top Entrance Entrance (I)': []}
},
'East Hebra Cave': {
'type': 'cave', 'map': 'light', 'coord': (573, 142),
'link': {
'Hebra Shop Cave': []}
},
'East Hebra Cave Top Entrance Entrance (I)': {
'type': 'interior',
'link': {
'East Hebra Cave (area)': [],
'East Hebra Cave Top Entrance Entrance (E)': []}
},
'East Hebra Cave Top Entrance Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (569, 41),
'link': {
'East Hebra Cave (area)': [],
'East Upper Mount Hebra': []}
},
'East Upper Mount Hebra': {
'type': 'area',
'link': {
'East Upper Death Mountain': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'Turtle Rock Balcony': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'Turtle Rock Fairy Exit': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'Light Bottle Ocarina': [],
'West Upper Mount Hebra': [('item', 'hammer')],
'East Lower Mount Hebra': [],
'Spiral Cave Top Entrance Entrance (E)': [],
'Fairy Maze Top Entrance Entrance (E)': [],
'Goriya Cave Entrance (E)': [('settings', 'inverted')],
'East Hebra Cave Top Entrance Entrance (E)': [],
'Heart Peak': [
('settings', 'inverted'),
('and', [
('glitch', 'overworld'), ('item', 'mirror')])],
'Turtle Rock Portal (LW)': [('item', 'titansmitts')]},
'visible': {'Heart Peak': []}
},
'Spiral Cave Top Entrance Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (529, 59),
'link': {
'East Lower Mount Hebra': [],
'Spiral Cave Top Entrance Entrance (I)': []}
},
'Spiral Cave Top Entrance Entrance (I)': {
'type': 'interior',
'link': {
'Spiral Cave Top Entrance Entrance (E)': [],
'Spiral Cave Top': []}
},
'Spiral Cave Top': {
'type': 'area',
'link': {
'Spiral Cave Top Entrance Entrance (I)': [],
'Spiral Cave': [('rabbitbarrier', None)]}
},
'Spiral Cave': {
'type': 'cave', 'map': 'light', 'coord': (529, 59),
'link': {
'Spiral Cave Bottom': []}
},
'Fairy Maze Top Entrance Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (544, 75),
'link': {
'East Lower Mount Hebra': [],
'Fairy Maze Top Entrance Entrance (I)': [],
'Fairy Maze Bottom Entrance Entrance (E)': []}
},
'Fairy Maze Top Entrance Entrance (I)': {
'type': 'interior',
'link': {
'Fairy Maze Top Entrance Entrance (E)': [],
'Fairy Maze Bottom Entrance Entrance (I)': []}
},
'Goriya Cave Entrance (E)': {
'type': 'entrance_unique', 'map': 'light', 'coord': (559, 59),
'link': {
'East Lower Mount Hebra': [],
'Goriya Cave Entrance (I)': []}
},
'Goriya Cave Entrance (I)': {
'type': 'interior',
'link': {
'Goriya Cave Entrance (E)': [],
'Goriya Cave': [('item', 'hammer')]}
},
'Goriya Cave': {
'type': 'cave', 'map': 'light', 'coord': (559, 59),
'link': {
'Goriya Cave Entrance (I)': [('item', 'hammer')]}
},
'Heart Peak': {
'type': 'item', 'map': 'light', 'coord': (539, 14),
'link': {
'Pit Cave Peak': [
('nosettings', 'inverted'),
('item', 'mirror')],
'East Upper Mount Hebra': [('settings', 'inverted')]}
},
'Turtle Rock Portal (LW)': {
'type': 'area',
'link': {
'Turtle Rock Portal (DW)': [('and', [
('settings', 'inverted'), ('item', 'mirror')])],
'East Upper Mount Hebra': [
('nosettings', 'inverted'), ('item', 'hammer')],
'Turtle Rock Portal': [('item', 'hammer')]}
},
'Turtle Rock Portal': {
'type': 'area',
'link': {
'Turtle Rock Portal (DW)': [('and', [
('nosettings', 'inverted'), ('state', 'rabbit')])],
'Turtle Rock Portal (LW)': [('and', [
('settings', 'inverted'), ('state', 'rabbit')])]}
},
} | z3-tracker | /z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/hebra.py | hebra.py |
__all__ = 'LOCATIONS',
LOCATIONS = {
'South Dark World': {
'type': 'area',
'link': {
'South Light World': [('and', [
('nosettings', 'inverted'), ('item', 'mirror')])],
'Southern Shores': [('and', [
('nosettings', 'inverted'), ('item', 'mirror')])],
'Running Game': [('and', [
('nosettings', 'inverted'), ('item', 'mirror')])],
'Cave Near Haunted Grove Entrance (E)': [('and', [
('nosettings', 'inverted'), ('item', 'mirror')])],
'Bombos Stone Mountain': [('and', [
('nosettings', 'inverted'), ('item', 'mirror')])],
'Dark Bottle Ocarina': [],
'Digging Game': [('rabbitbarrier', None)],
'Shooting Game Entrance (E)': [],
"Thieves' Town Surface": [('item', 'titansmitts')],
'Ocarina Boy': [('rabbitbarrier', None)],
'Fairy Pond Under Rocks (DW) Entrance (E)': [('item', 'pegasus')],
'Portal Ersatz': [('and', [
('settings', 'inverted'), ('access', 'Castle Tower Reward'),
('rabbitbarrier', None)])],
'Bomb Shop Entrance (E)': [],
'East Dark World': [('item', 'hammer')],
'Frozen Lake Shop Entrance (E)': [],
'Frozen Lake': [('item', 'flippers')],
'South Portal (DW)': [('item', 'hammer')],
'Hiding Thief Cave Entrance (E)': [('item', 'bombs')],
'Swamp Palace Entrance (E)': [],
'Misery Mire Surface': [('and', [
('glitch', 'overworld'), ('item', 'pegasus')])]}
},
'Digging Game': {
'type': 'item', 'map': 'dark', 'coord': (32, 459),
'link': {
'South Dark World': []}
},
'Shooting Game Entrance (E)': {
'type': 'entrance', 'map': 'dark', 'coord': (137, 464),
'link': {
'South Dark World': [],
'Shooting Game Entrance (I)': []}
},
'Shooting Game Entrance (I)': {
'type': 'interior',
'link': {
'Shooting Game Entrance (E)': []}
},
'Ocarina Boy': {
'type': 'item', 'map': 'dark', 'coord': (199, 452),
'link': {
'South Dark World': []}
},
'Fairy Pond Under Rocks (DW) Entrance (E)': {
'type': 'entrance', 'map': 'dark', 'coord': (307, 433),
'link': {
'South Dark World': [],
'Fairy Pond Under Rocks (DW) Entrance (I)': []}
},
'Fairy Pond Under Rocks (DW) Entrance (I)': {
'type': 'interior',
'link': {
'Fairy Pond Under Rocks (DW) Entrance (E)': []}
},
'Portal Ersatz': {
'type': 'area',
'link': {
'South Light World': [('state', 'rabbit')]}
},
'Bomb Shop Entrance (E)': {
'type': 'entrance_unique', 'map': 'dark', 'coord': (363, 456),
'link': {
'South Dark World': [],
'Bomb Shop Entrance (I)': [('nosettings', 'inverted')],
"Link's House Entrance (I)": [('settings', 'inverted')]}
},
'Bomb Shop Entrance (I)': {
'type': 'interior',
'link': {
'Bomb Shop Entrance (E)': [('nosettings', 'inverted')],
"Link's House Entrance (E)": [('settings', 'inverted')]}
},
'Frozen Lake Shop Entrance (E)': {
'type': 'entrance_shop', 'map': 'dark', 'coord': (424, 532),
'link': {
'South Dark World': [],
'Frozen Lake Shop Entrance (I)': []}
},
'Frozen Lake Shop Entrance (I)': {
'type': 'interior',
'link': {
'Frozen Lake Shop Entrance (E)': []}
},
'South Portal (DW)': {
'type': 'area',
'link': {
'South Portal (LW)': [('and', [
('nosettings', 'inverted'), ('item', 'mirror')])],
'South Dark World': [('item', 'hammer')],
'South Portal': [('item', 'powerglove')]}
},
'Hiding Thief Cave Entrance (E)': {
'type': 'entrance_unique', 'map': 'dark', 'coord': (391, 515),
'link': {
'South Dark World': [],
'Hiding Thief Cave Entrance (I)': []}
},
'Hiding Thief Cave Entrance (I)': {
'type': 'interior',
'link': {
'Hiding Thief Cave Entrance (E)': [],
'Hiding Thief Cave': []}
},
'Hiding Thief Cave': {
'type': 'cave', 'map': 'dark', 'coord': (391, 515),
'link': {
'Hiding Thief Cave Entrance (I)': []}
},
'Frozen Lake': {
'type': 'area',
'link': {
'Lake Hylia': [('and', [
('nosettings', 'inverted'), ('item', 'mirror')])],
'Small Lake Hylia Island': [('and', [
('nosettings', 'inverted'), ('item', 'mirror')])],
'Ice Palace Exterior': [('settings', 'inverted')],
'East Dark World': [],
'Dark World Waterway': [],
'Eastern Shores': []}
},
'Ice Palace Exterior': {
'type': 'area',
'link': {
'Large Lake Hylia Island': [('and', [
('nosettings', 'inverted'), ('item', 'mirror')])],
'Ice Palace Portal': [('item', 'titansmitts')],
'Frozen Lake': [('and', [
('settings', 'inverted'), ('item', 'flippers')])],
'Ice Palace Entrance (E)': []}
},
'Dark World Waterway': {
'type': 'area',
'link': {
'Frozen Lake': [],
'Dark River': []}
},
'Eastern Shores': {
'type': 'area',
'link': {
'Southern Shores': [('and', [
('nosettings', 'inverted'), ('item', 'mirror')])],
'Frozen Lake': [('item', 'flippers')],
'Eastern Shores Under Rock Entrance (E)': [('item', 'powerglove')],
'Eastern Shores Fairy Entrance (E)': [('item', 'bombs')],
'Eastern Shores Cave Entrance (E)': []}
},
'Eastern Shores Under Rock Entrance (E)': {
'type': 'entrance', 'map': 'dark', 'coord': (592, 521),
'link': {
'Eastern Shores': [],
'Eastern Shores Under Rock Entrance (I)': []}
},
'Eastern Shores Under Rock Entrance (I)': {
'type': 'interior',
'link': {
'Eastern Shores Under Rock Entrance (I)': []}
},
'Eastern Shores Fairy Entrance (E)': {
'type': 'entrance', 'map': 'dark', 'coord': (588, 507),
'link': {
'Eastern Shores': [],
'Eastern Shores Fairy Entrance (I)': []}
},
'Eastern Shores Fairy Entrance (I)': {
'type': 'interior',
'link': {
'Eastern Shores Fairy Entrance (E)': []}
},
'Eastern Shores Cave Entrance (E)': {
'type': 'entrance', 'map': 'dark', 'coord': (600, 507),
'link': {
'Eastern Shores': [],
'Eastern Shores Cave Entrance (I)': []}
},
'Eastern Shores Cave Entrance (I)': {
'type': 'interior',
'link': {
'Eastern Shores Cave Entrance (E)': []}
},
} | z3-tracker | /z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/darkworld_south.py | darkworld_south.py |
import importlib
import typing
from .major import MAJORLOCATIONS
LOCATIONIMPORTS = (
'castle', 'darkpalace', 'darkworld_east', 'darkworld_north',
'darkworld_south', 'deathmountain', 'desert', 'dungeons', 'ganonstower',
'hebra', 'icepalace', 'kakariko', 'lightworld_east', 'lightworld_north',
'lightworld_south', 'miserymire', 'mountaintower', 'ocarina', 'swamppalace',
'skullwoods', 'thievestown', 'turtlerock')
LOCATIONS = {}
for locimp in LOCATIONIMPORTS:
addloc = importlib.import_module(
'.{0:s}'.format(locimp), package=__package__)
LOCATIONS.update(addloc.LOCATIONS)
del addloc, locimp
__all__ = 'Ruleset', 'MAJORLOCATIONS'
class Ruleset(dict):
'''
Placement ruleset
'''
def __init__(self):
super().__init__()
self.dungeons = {}
self.parse_locations()
def parse_locations(self) -> None:
'''
Create location database.
'''
for loc in LOCATIONS:
self[loc] = Location(LOCATIONS[loc])
if 'dungeon' in LOCATIONS[loc]:
if self[loc].dungeon not in self.dungeons:
self.dungeons[self[loc].dungeon] = Dungeon()
self.dungeons[self[loc].dungeon][loc] = self[loc]
assert all(loc in self for loc in MAJORLOCATIONS)
def locations(self, gametype: str, maptype: str, majoronly: bool) -> dict:
'''
Return a list of locations to be displayed on a map.
Args:
gametype: 'item', 'item_shop', 'item_retro' or 'entrance'
maptype: 'light' or 'dark'
majoronly: only return major item locations
Returns:
dict: {
'location name': {'map': str, 'coord': (int, int), 'type': str}}
'''
assert gametype in ('item', 'item_shop', 'item_retro', 'entrance')
assert maptype in ('light', 'dark')
if gametype == 'item':
valid = 'chest', 'item', 'cave', 'drop', 'dungeon', 'ganon'
elif gametype == 'item_shop':
valid = (
'chest', 'item', 'cave', 'drop', 'dungeon', 'ganon',
'entrance_shop')
elif gametype == 'item_retro':
valid = (
'chest', 'item', 'cave', 'drop', 'dungeon', 'ganon', 'entrance',
'entrance_shop')
else:
valid = ('entrance', 'entrance_unique', 'entrance_shop',
'entrance_drop', 'entrance_dungeon', 'item', 'dungeon',
'ganon')
ret = {}
for loc in self:
majorcheck = (
not majoronly or loc in MAJORLOCATIONS or
self[loc].type in (
'item_retro', 'ganon', 'entrance', 'entrance_shop',
'entrance_dungeon', 'dungeon'))
displaycheck = (
self[loc].type in valid and self[loc].map == maptype and
majorcheck)
if displaycheck:
ret[loc] = {
'map': self[loc].map, 'coord': self[loc].coord,
'type': self[loc].type}
return ret
def disconnect_entrances(self) -> None:
'''
Disconnect all entrances from each other.
'''
for loc in self:
for link in tuple(self[loc].link.keys()):
if ((self[loc].type.startswith('entrance') and
self[link].type == 'interior') or
(self[loc].type == 'interior' and
self[link].type.startswith('entrance'))):
del self[loc].link[link]
class Location(object):
'''
Location object
Instance variables:
type:
- 'chest': chest in house or in the open
- 'interior': interior connector; always has 'entrance' counterpart
- 'entrance': exterior connector shuffable by entrance randomiser
- 'entrance_unique': like entrance, but no take-any cave
- 'area': generic area linking other locations
- 'item': item in the open (or semi-hidden, e.g. buried)
- 'cave': open or chested item in a cave
- 'drop': drophole or downstairs cave
- 'dungeonchest': generic randomised item found in dungeon
- 'dungeonchest_nokey': can't hold a key
- 'dungeonkey': fixed small key found in dungeon
- 'dungeonboss': dungeon boss
- 'dungeonreward': pendant or crystal
- 'dungeon': the overall dungeon itself
- 'ganon': only used for the final bossfight
map: map on which location is displayed (not for 'area' or 'interior')
coord: coordinates of location on map (not for 'area' or 'interior')
keypools: key distribution in dungeon
dungeon: parent dungeon (only for dungeon locations)
link: locations to which this location connects, following the format
{'linked location': {'requirement type': 'requirement', ...}};
possible requirements are:
- 'settings': required settings
- 'nosettings': only if given setting is not active
- 'item': item in possession
- 'access': name of another location which needs to be available
- 'medallion': dynamic medallion requirement for two dungeons
- 'pendant': pendant in posession
- 'crystals': certain crystals in posession
- 'smallkeys': given number of dungeon chests being available
- 'bigkey': all dungeon chests being available
- 'macro': more complex requirements
visible: list of locations visible from here
checked: boolean always set to False or None
'''
def __init__(self, location: dict):
'''
Args:
location: location info; if None then object is uninitialised
'''
assert location['type'] in (
'chest', 'interior', 'entrance', 'entrance_unique', 'entrance_shop',
'entrance_drop', 'entrance_dungeon', 'area', 'item', 'cave', 'drop',
'dungeonchest', 'dungeonchest_nokey', 'dungeonkey', 'dungeonboss',
'dungeonreward', 'dungeon', 'ganon')
self.type = location['type']
if (
self.type not in ('area', 'interior') and
not self.type.startswith('dungeon')):
self.map = location['map']
self.coord = location['coord']
if self.type == 'dungeon':
self.map = location['map']
self.coord = location['coord']
self.keypools = location['keypools']
if self.type.startswith('dungeon') and len(self.type) > 7:
self.dungeon = location['dungeon']
if self.type == 'area' and 'dungeon' in location:
self.dungeon = location['dungeon']
self.link = location['link'].copy()
self.visible = (
location['visible'].copy() if 'visible' in location else {})
if self.type not in ('area', 'interior'):
self.checked = False
else:
self.checked = None
class Dungeon(dict):
'''
Dungeon object
'''
def keylocations(self) -> dict:
'''
Retrieve list of locations possibly holding a small key.
Returns:
dict: {'location name': location object}
'''
ret = {}
for loc in self:
if self[loc].type == 'dungeonchest':
ret[loc] = self[loc]
return ret | z3-tracker | /z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/ruleset.py | ruleset.py |
# z3 [](https://travis-ci.org/PressLabs/z3)
# Welcome to z3
z3 is a ZFS to S3 backup tool. This is basically plumbing around `zfs send` and `zfs receive`
so you should have at least a basic understanding of what those commands do.
z3 was developed by the awesome engineering team at [Presslabs](https://www.presslabs.com/),
a Managed WordPress Hosting provider.
For more open-source projects, check [Presslabs Code](https://www.presslabs.org/).
## Usage
`z3 status` will show you the current state, what snapshots you have on S3 and on the local
zfs dataset.
`z3 backup` perform full or incremental backups of your dataset.
`z3 restore` restores your dataset to a certain snapshot.
See `zfs SUBCOMMAND --help` for more info.
### Installing
`pip install z3`
z3 is tested on python 2.7 with latest boto 2 and boto 2.2.2 (python-boto version on Ubuntu 12.04).
#### Optional dependencies
```
# Install pv to get some progress indication while uploading.
apt-get install pv
# Install pigz to provide the pigz compressors.
apt-get install pigz
```
### Configuring
Most options can be configured as command line flags, environment variables or in a config file,
in that order of precedence.
The config file is read from `/etc/z3_backup/z3.conf` if it exists, some defaults are provided by the tool.
BUCKET `S3_KEY_ID` and `S3_SECRET` can't be provided on the command line.
For a list of all options see `z3/sample.conf`.
You'll usually want z3 to only backup certain snapshots (hourly/daily/weekly).
To do that you can specify a `SNAPSHOT_PREFIX` (defaults to `zfs-auto-snap:daily`).
Defaults for `SNAPSHOT_PREFIX` and `COMPRESSOR` can be set per filesystem like so:
```
[fs:tank/spam]
SNAPSHOT_PREFIX=delicious-daily-spam
COMPRESSOR=pigz4
[fs:tank/ham]
SNAPSHOT_PREFIX=weekly-non-spam
```
### Dataset Size, Concurrency and Memory Usage
Since the data is streamed from `zfs send` it gets read in to memory in chunks.
Z3 estimates a good chunk size for you: no smaller than 5MB and large enough
to produce at most 9999 chunks. These are S3 limitation for multipart uploads.
Here are some example chunk sizes for different datasets:
* 50 GiB: 5 MiB
* 500 GIB: 53 MiB
* 1 TiB: 110 MiB
* 2 TiB: 220 MiB
Multiply that by `CONCURRENCY` to know how much memory your upload will use.
### Usage Examples
#### Status
```
# show global options
z3 --help
# show status of backups for default dataset
z3 status
# show status for other dataset; only snapshots named daily-spam-*
z3 --dataset tank/spam --snapshot-prefix daily-spam- status
```
#### Backup
```
# show backup options
z3 backup --help
# perform incremental backup the latest snapshot; use pigz4 compressor
z3 backup --compressor pigz4 --dry-run
# inspect the commands that would be executed
z3 backup --compressor pigz4
# perform full backup of a specific snapshot
z3 backup --full --snapshot the-part-after-the-at-sign --dry-run
# inspect the commands that would be executed
z3 backup --full --snapshot the-part-after-the-at-sign
```
#### Restore
```
# see restore options
z3 restore --help
# restore a dataset to a certain snapshot
z3 restore the-part-after-the-at-sign --dry-run
# inspect the commands that would be executed
z3 restore the-part-after-the-at-sign
# force rollback of filesystem (zfs recv -F)
z3 restore the-part-after-the-at-sign --force
```
### Other Commands
Other command line tools are provided.
`pput` reads a stream from standard in and uploads the data to S3.
`z3_ssh_sync` a convenience tool to allow you to push zfs snapshots to another host.
If you need replication you should checkout zrep. This exists because we've already
got zrep between 2 nodes and needed a way to push backups to a 3rd machine.
`z3_get` called by `z3 restore` to download a backup.
## Development Overview
### Running the tests
The test suite uses pytest.
Some of the tests upload data to S3, so you need to setup the following environment:
```
export S3_KEY_ID=""
export S3_SECRET=""
export BUCKET="mytestbucket"
```
To skip tests that use S3:
```
py.test --capture=no --tb=native _tests/ -k "not with_s3"
```
### The Data
Snapshots are obtained using `zfs send`, optionally piped trough a compressor (pigz by default),
and finally piped to `pput`.
Incremental snapshots are always handled individually, so if you have multiple snapshots to send
since the last time you've performed a backup they get exported as individual snapshots
(multiple calls to `zfs send -i dataset@snapA dataset@snapB`).
Your snapshots end up as individual keys in an s3 bucket, with a configurable prefix (`S3_PREFIX`).
S3 key metadata is used to identify if a snapshot is full (`isfull="true"`) or incremental.
The parent of an incremental snapshot is identified with the `parent` attribute.
S3 and ZFS snapshots are matched by name.
### Health checks
The S3 health checks are very rudimentary, basically if a snapshot is incremental check
that the parent exists and is healthy. Full backups are always assumed healthy.
If backup/restore encounter unhealthy snapshots they abort execution.
### pput
pput is a simple tool with one job, read data from stdin and upload it to S3.
It's usually invoked by z3.
Consistency is important, it's better to fail hard when something goes wrong
than silently upload inconsistent or partial data.
There are few anticipated errors (if a part fails to upload, retry MAX_RETRY times).
Any other problem is unanticipated, so just let the tool crash.
TL;DR Fail early, fail hard.
| z3 | /z3-0.2.0.tar.gz/z3-0.2.0/README.md | README.md |
import sys
from zExceptions import Redirect
from ZPublisher.mapply import mapply
from ZPublisher.Publish import (call_object, missing_name, dont_publish_class,
get_module_info, Retry)
from zope.publisher.browser import setDefaultSkin
from zope.security.management import newInteraction, endInteraction
from z3c.amf.interfaces import IAMFRequest
from z3c.amf.amfgateway import AMFResponse
import pyamf
def publish(request, module_name, after_list, debug=0,
call_object=call_object,
missing_name=missing_name,
dont_publish_class=dont_publish_class,
mapply=mapply,
):
(bobo_before, bobo_after, object, realm, debug_mode, err_hook,
validated_hook, transactions_manager)= get_module_info(module_name)
parents=None
response=None
try:
# TODO pass request here once BaseRequest implements IParticipation
newInteraction()
request.processInputs()
request_get=request.get
response=request.response
# First check for "cancel" redirect:
if request_get('SUBMIT', '').strip().lower()=='cancel':
cancel=request_get('CANCEL_ACTION', '')
if cancel:
raise Redirect(cancel)
after_list[0]=bobo_after
if debug_mode:
response.debug_mode=debug_mode
if realm and not request.get('REMOTE_USER', None):
response.realm=realm
if bobo_before is not None:
bobo_before()
# Get the path list.
# According to RFC1738 a trailing space in the path is valid.
path=request_get('PATH_INFO')
request['PARENTS']=parents=[object]
if transactions_manager:
transactions_manager.begin()
object=request.traverse(path, validated_hook=validated_hook)
if transactions_manager:
transactions_manager.recordMetaData(object, request)
result=mapply(object, request.args, request,
call_object, 1,
missing_name,
dont_publish_class,
request, bind=1)
if result is not response:
response.setBody(result)
if transactions_manager:
transactions_manager.commit()
endInteraction()
return response
except:
# DM: provide nicer error message for FTP
sm = None
if response is not None:
sm = getattr(response, "setMessage", None)
if sm is not None:
from asyncore import compact_traceback
cl, val= sys.exc_info()[:2]
sm('%s: %s %s' % (
getattr(cl, '__name__', cl), val,
debug_mode and compact_traceback()[-1] or ''))
if IAMFRequest.providedBy(request):
if transactions_manager:
transactions_manager.abort()
endInteraction()
if response is None:
response = AMFResponse(request.response)
response._amfVersion = pyamf.AMF0
response._clientType = pyamf.AMF0
response._name = '/1'
response.exception()
return response
if err_hook is not None:
if parents:
parents=parents[0]
try:
try:
return err_hook(parents, request,
sys.exc_info()[0],
sys.exc_info()[1],
sys.exc_info()[2],
)
except Retry:
if not request.supports_retry():
return err_hook(parents, request,
sys.exc_info()[0],
sys.exc_info()[1],
sys.exc_info()[2],
)
finally:
if transactions_manager:
transactions_manager.abort()
endInteraction()
# Only reachable if Retry is raised and request supports retry.
newrequest=request.retry()
request.close() # Free resources held by the request.
# Set the default layer/skin on the newly generated request
setDefaultSkin(newrequest)
try:
return publish(newrequest, module_name, after_list, debug)
finally:
newrequest.close()
else:
if transactions_manager:
transactions_manager.abort()
endInteraction()
raise
import ZPublisher.Publish
ZPublisher.Publish.publish = publish
from Products.PluggableAuthService.plugins.CookieAuthHelper import CookieAuthHelper
from urllib import quote
def unauthorized(self):
req = self.REQUEST
resp = req['RESPONSE']
# If we set the auth cookie before, delete it now.
if self.cookie_name in resp.cookies:
del resp.cookies[self.cookie_name]
# Redirect if desired.
url = self.getLoginURL()
if IAMFRequest.providedBy(req):
#no need to redirect if it's an amf request
return 0
if url is not None:
came_from = req.get('came_from', None)
if came_from is None:
came_from = req.get('URL', '')
query = req.get('QUERY_STRING')
if query:
if not query.startswith('?'):
query = '?' + query
came_from = came_from + query
else:
# If came_from contains a value it means the user
# must be coming through here a second time
# Reasons could be typos when providing credentials
# or a redirect loop (see below)
req_url = req.get('URL', '')
if req_url and req_url == url:
# Oops... The login_form cannot be reached by the user -
# it might be protected itself due to misconfiguration -
# the only sane thing to do is to give up because we are
# in an endless redirect loop.
return 0
url = url + '?came_from=%s' % quote(came_from)
resp.redirect(url, lock=1)
return 1
# Could not challenge.
return 0
CookieAuthHelper.unauthorized = unauthorized | z3c.amf | /z3c.amf-0.2.tar.gz/z3c.amf-0.2/z3c/amf/patch.py | patch.py |
AMF/Flash Support in Zope 2
===========================
Introduction
------------
This package allows you to query Zope 2 from a flash using Flex with
Actionscript 2 or Actionscript 3 throught AMF0 or AMF3.
We are just providing here the Zope layer. The lower layer has been done
using the PyAMF package (see http://pyamf.org).
Let's write a simple AMF view that echoes various types of input:
>>> from Products.Five import BrowserView
>>> from datetime import datetime
>>> import elementtree.ElementTree as etree
>>> class EchoView(BrowserView):
...
... def echoString(self, value):
... return "%s" % value
...
... def echoProtectedString(self, value):
... return "%s" % value
...
... def echoList(self, value):
... return list(value)
...
... def echoDict(self, value):
... return dict(value)
...
... def echoVoid(self, value):
... pass
...
... def echoTuple(self, value):
... return tuple(value)
...
... def echoParams(self, value1, value2):
... return "%s-%s" % (value1, value2)
...
... def echoDate(self):
... return datetime(2008, 11, 17, 11, 11)
...
... def echoXML(self, value):
... root = etree.Element("html")
... body = etree.SubElement(root, 'body')
... body.text = value
... return root
Now we'll register it as a Flash view. For now we'll just register the
view for folder objects and call it on the default folder of the user:
>>> from zope.configuration import xmlconfig
>>> ignored = xmlconfig.string("""
... <configure
... xmlns="http://namespaces.zope.org/zope"
... xmlns:browser="http://namespaces.zope.org/browser"
... xmlns:flash="http://namespaces.zope.org/flash"
... >
...
... <include package="z3c.amf" file="meta.zcml" />
... <include package="Products.Five" file="meta.zcml" />
... <include package="z3c.amf" />
...
... <flash:view
... for="OFS.interfaces.IFolder"
... methods="echoString echoList echoDict echoVoid echoTuple
... echoDate echoXML echoParams"
... class="z3c.amf.README.EchoView"
... permission="zope.Public"
... />
...
... <flash:view
... for="OFS.interfaces.IFolder"
... methods="echoProtectedString"
... class="z3c.amf.README.EchoView"
... permission="zope2.FlashAccess"
... />
...
... </configure>
... """)
We create some helper functions.
For Requests:
>>> def createAMFRequest(target, body, username=None, password=None, multiParameters=False):
... envelope = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9)
... if username is not None and password is not None:
... envelope.headers['Credentials'] = dict(userid=unicode(username),
... password=unicode(password))
... if multiParameters:
... request = remoting.Request(target, body, envelope)
... else:
... request = remoting.Request(target, [body], envelope)
... envelope[u'/1'] = request
... amfRequest = remoting.encode(envelope)
... amfRequest.seek(0)
... return amfRequest.read()
For Responses:
>>> import pyamf
>>> from pyamf import remoting
>>> def printAMFResponse(response):
... context = pyamf.amf0.Context
... requests = remoting.decode(response.body, context())
... for name, value in requests.items():
... print (name, value, type(value.body))
Basic Types
-----------
String
>>> amfRequest = createAMFRequest(target='echoString', body='Hello World!')
>>> amfRequest
'\x00\x03\x00\x00\x00\x01\x00\nechoString\x00\x02/1\x00\x00\x00\x00\n\x00\x00\x00\x01\x02\x00\x0cHello World!'
>>> response = http(r"""
... POST /test_folder_1_ HTTP/1.0
... Content-Length: 102
... Content-Type: application/x-amf
...
... %s""" % amfRequest)
>>> printAMFResponse(response)
(u'/1', <Response status=/onResult>Hello World!</Response>, <type 'unicode'>)
List
>>> amfRequest = createAMFRequest(target='echoList', body=[u'Hé', u'Ho'])
>>> response = http(r"""
... POST /test_folder_1_ HTTP/1.0
... Content-Length: 102
... Content-Type: application/x-amf
...
... %s""" % amfRequest)
>>> printAMFResponse(response)
(u'/1', <Response status=/onResult>[u'H\xc3\xa9', u'Ho']</Response>,
<type 'list'>)
Dictionary
>>> amfRequest = createAMFRequest(target='echoDict',
... body={'fruit': 'orange'})
>>> response = http(r"""
... POST /test_folder_1_ HTTP/1.0
... Content-Length: 102
... Content-Type: application/x-amf
...
... %s""" % amfRequest)
>>> printAMFResponse(response)
(u'/1', <Response status=/onResult>{u'fruit': u'orange'}</Response>,
<class 'pyamf.ASObject'>)
Without return
>>> amfRequest = createAMFRequest(target='echoVoid', body='Hello World!')
>>> response = http(r"""
... POST /test_folder_1_ HTTP/1.0
... Content-Length: 102
... Content-Type: application/x-amf
...
... %s""" % amfRequest)
>>> printAMFResponse(response)
(u'/1', <Response status=/onResult>None</Response>, <type 'NoneType'>)
Tuple
>>> amfRequest = createAMFRequest(target='echoTuple', body=['foo', 'bar'])
>>> response = http(r"""
... POST /test_folder_1_ HTTP/1.0
... Content-Length: 102
... Content-Type: application/x-amf
...
... %s""" % amfRequest)
>>> printAMFResponse(response)
(u'/1', <Response status=/onResult>[u'foo', u'bar']</Response>,
<type 'list'>)
Datetime
>>> amfRequest = createAMFRequest(target='echoDate', body=None)
>>> response = http(r"""
... POST /test_folder_1_ HTTP/1.0
... Content-Length: 102
... Content-Type: application/x-amf
...
... %s""" % amfRequest)
>>> printAMFResponse(response)
(u'/1', <Response status=/onResult>2008-11-17 11:11:00</Response>,
<type 'datetime.datetime'>)
XML
>>> amfRequest = createAMFRequest(target='echoXML', body='It works!')
>>> response = http(r"""
... POST /test_folder_1_ HTTP/1.0
... Content-Length: 102
... Content-Type: application/x-amf
...
... %s""" % amfRequest)
>>> printAMFResponse(response)
(u'/1', <Response status=/onResult><Element html at ...></Response>,
<type 'instance'>)
Multi Parameters
----------------
>>> amfRequest = createAMFRequest(target='echoParams', body=['foo', 'bar'],
... multiParameters=True)
>>> response = http(r"""
... POST /test_folder_1_ HTTP/1.0
... Content-Length: 102
... Content-Type: application/x-amf
...
... %s""" % amfRequest)
>>> printAMFResponse(response)
(u'/1', <Response status=/onResult>foo-bar</Response>, <type 'unicode'>)
Errors
------
>>> amfRequest = createAMFRequest(target='echoUnknown', body=['foo', 'bar'])
>>> response = http(r"""
... POST /test_folder_1_ HTTP/1.0
... Content-Length: 102
... Content-Type: application/x-amf
...
... %s""" % amfRequest)
>>> printAMFResponse(response)
(u'/1', <Response status=/onStatus><ErrorFault level=error code=NotFound type=Resource not found...
...
User authentication
-------------------
Try to access our protected view without providing login/pass in flash:
>>> amfRequest = createAMFRequest(target='echoProtectedString',
... body='It works!')
>>> response = http(r"""
... POST /test_folder_1_ HTTP/1.0
... Content-Length: 102
... Content-Type: application/x-amf
...
... %s""" % amfRequest)
>>> printAMFResponse(response)
(u'/1', <Response status=/onStatus><ErrorFault level=error code=zExceptions.unauthorized.Unauthorized type=Not authorized></Response>,
<class 'pyamf.remoting.ErrorFault'>)
Now try to access with login/pass:
>>> from Testing.ZopeTestCase import user_name, user_password
>>> amfRequest = createAMFRequest(target='echoProtectedString',
... body="Hello World!", username=user_name,
... password=user_password)
>>> response = http(r"""
... POST /test_folder_1_ HTTP/1.0
... Content-Length: 200
... Content-Type: application/x-amf
...
... %s""" % amfRequest)
>>> printAMFResponse(response)
(u'/1', <Response status=/onResult>Hello World!</Response>, <type 'unicode'>)
Path in service
---------------
>>> amfRequest = createAMFRequest(target='test_folder_1_.echoProtectedString',
... body='It works!', username=user_name,
... password=user_password)
>>> response = http(r"""
... POST / HTTP/1.0
... Content-Length: 200
... Content-Type: application/x-amf
...
... %s""" % amfRequest)
>>> printAMFResponse(response)
(u'/1', <Response status=/onResult>It works!</Response>, <type 'unicode'>)
| z3c.amf | /z3c.amf-0.2.tar.gz/z3c.amf-0.2/z3c/amf/README.txt | README.txt |
import re
from cgi import FieldStorage, escape
from ZPublisher.HTTPRequest import *
from ZPublisher.Converters import get_converter
from copy import deepcopy
from ZPublisher.TaintedString import TaintedString
from zope.interface import directlyProvides
from z3c.amf.interfaces import IAMFRequest
xmlrpc=None # Placeholder for module that we'll import if we have to.
amfgateway=None
def processInputs(
self,
# "static" variables that we want to be local for speed
SEQUENCE=1,
DEFAULT=2,
RECORD=4,
RECORDS=8,
REC=12, # RECORD|RECORDS
EMPTY=16,
CONVERTED=32,
hasattr=hasattr,
getattr=getattr,
setattr=setattr,
search_type=re.compile('(:[a-zA-Z][-a-zA-Z0-9_]+|\\.[xy])$').search,
):
"""Process request inputs
We need to delay input parsing so that it is done under
publisher control for error handling purposes.
"""
response=self.response
environ=self.environ
method=environ.get('REQUEST_METHOD','GET')
if method != 'GET': fp=self.stdin
else: fp=None
form=self.form
other=self.other
taintedform=self.taintedform
meth=None
fs=FieldStorage(fp=fp,environ=environ,keep_blank_values=1)
if not hasattr(fs,'list') or fs.list is None:
# Hm, maybe it's an XML-RPC
if (fs.headers.has_key('content-type') and
'text/xml' in fs.headers['content-type'] and
method == 'POST'):
# Ye haaa, XML-RPC!
global xmlrpc
if xmlrpc is None: from ZPublisher import xmlrpc
meth, self.args = xmlrpc.parse_input(fs.value)
response=xmlrpc.response(response)
other['RESPONSE']=self.response=response
self.maybe_webdav_client = 0
elif (fs.headers.has_key('content-type') and
'application/x-amf' in fs.headers['content-type']):
global amfgateway
directlyProvides(self, IAMFRequest)
if amfgateway is None: import amfgateway
aparser = amfgateway.AMFParser(fs.value)
aparser.parse()
meth = aparser.method
self.args = aparser.args
if aparser.paths:
splitedPath = environ['PATH_INFO'].split('/')
splitedPath.extend(aparser.paths)
environ['PATH_INFO'] = "/".join(splitedPath)
response = amfgateway.AMFResponse(response)
response._amfVersion = aparser.amfVersion
response._clientType = aparser.clientType
response._method = meth
response._name = aparser.name
auth = aparser.auth
if auth:
import base64
response._auth = 1
authString = "%s:%s" % (auth.get('userid'),
auth.get('password'))
self._auth = "Basic %s" % base64.encodestring(authString)
self._auth = self._auth.replace('\n','')
other['RESPONSE'] = self.response = response
other['REQUEST_METHOD'] = method
self.maybe_webdav_client = 0
else:
self._file=fs.file
else:
fslist=fs.list
tuple_items={}
lt=type([])
CGI_name=isCGI_NAME
defaults={}
tainteddefaults={}
converter=None
for item in fslist:
isFileUpload = 0
key=item.name
if (hasattr(item,'file') and hasattr(item,'filename')
and hasattr(item,'headers')):
if (item.file and
(item.filename is not None
# RFC 1867 says that all fields get a content-type.
# or 'content-type' in map(lower, item.headers.keys())
)):
item=FileUpload(item)
isFileUpload = 1
else:
item=item.value
flags=0
character_encoding = ''
# Variables for potentially unsafe values.
tainted = None
converter_type = None
# Loop through the different types and set
# the appropriate flags
# We'll search from the back to the front.
# We'll do the search in two steps. First, we'll
# do a string search, and then we'll check it with
# a re search.
l=key.rfind(':')
if l >= 0:
mo = search_type(key,l)
if mo: l=mo.start(0)
else: l=-1
while l >= 0:
type_name=key[l+1:]
key=key[:l]
c=get_converter(type_name, None)
if c is not None:
converter=c
converter_type = type_name
flags=flags|CONVERTED
elif type_name == 'list':
flags=flags|SEQUENCE
elif type_name == 'tuple':
tuple_items[key]=1
flags=flags|SEQUENCE
elif (type_name == 'method' or type_name == 'action'):
if l: meth=key
else: meth=item
elif (type_name == 'default_method' or type_name == \
'default_action'):
if not meth:
if l: meth=key
else: meth=item
elif type_name == 'default':
flags=flags|DEFAULT
elif type_name == 'record':
flags=flags|RECORD
elif type_name == 'records':
flags=flags|RECORDS
elif type_name == 'ignore_empty':
if not item: flags=flags|EMPTY
elif has_codec(type_name):
character_encoding = type_name
l=key.rfind(':')
if l < 0: break
mo=search_type(key,l)
if mo: l = mo.start(0)
else: l = -1
# Filter out special names from form:
if CGI_name(key) or key[:5]=='HTTP_': continue
# If the key is tainted, mark it so as well.
tainted_key = key
if '<' in key:
tainted_key = TaintedString(key)
if flags:
# skip over empty fields
if flags&EMPTY: continue
#Split the key and its attribute
if flags&REC:
key=key.split(".")
key, attr=".".join(key[:-1]), key[-1]
# Update the tainted_key if necessary
tainted_key = key
if '<' in key:
tainted_key = TaintedString(key)
# Attributes cannot hold a <.
if '<' in attr:
raise ValueError(
"%s is not a valid record attribute name" %
escape(attr))
# defer conversion
if flags&CONVERTED:
try:
if character_encoding:
# We have a string with a specified character encoding.
# This gets passed to the converter either as unicode, if it can
# handle it, or crunched back down to latin-1 if it can not.
item = unicode(item,character_encoding)
if hasattr(converter,'convert_unicode'):
item = converter.convert_unicode(item)
else:
item = converter(item.encode(default_encoding))
else:
item=converter(item)
# Flag potentially unsafe values
if converter_type in ('string', 'required', 'text',
'ustring', 'utext'):
if not isFileUpload and '<' in item:
tainted = TaintedString(item)
elif converter_type in ('tokens', 'lines',
'utokens', 'ulines'):
is_tainted = 0
tainted = item[:]
for i in range(len(tainted)):
if '<' in tainted[i]:
is_tainted = 1
tainted[i] = TaintedString(tainted[i])
if not is_tainted:
tainted = None
except:
if (not item and not (flags&DEFAULT) and
defaults.has_key(key)):
item = defaults[key]
if flags&RECORD:
item=getattr(item,attr)
if flags&RECORDS:
item = getattr(item[-1], attr)
if tainteddefaults.has_key(tainted_key):
tainted = tainteddefaults[tainted_key]
if flags&RECORD:
tainted = getattr(tainted, attr)
if flags&RECORDS:
tainted = getattr(tainted[-1], attr)
else:
raise
elif not isFileUpload and '<' in item:
# Flag potentially unsafe values
tainted = TaintedString(item)
# If the key is tainted, we need to store stuff in the
# tainted dict as well, even if the value is safe.
if '<' in tainted_key and tainted is None:
tainted = item
#Determine which dictionary to use
if flags&DEFAULT:
mapping_object = defaults
tainted_mapping = tainteddefaults
else:
mapping_object = form
tainted_mapping = taintedform
#Insert in dictionary
if mapping_object.has_key(key):
if flags&RECORDS:
#Get the list and the last record
#in the list. reclist is mutable.
reclist = mapping_object[key]
x = reclist[-1]
if tainted:
# Store a tainted copy as well
if not tainted_mapping.has_key(tainted_key):
tainted_mapping[tainted_key] = deepcopy(
reclist)
treclist = tainted_mapping[tainted_key]
lastrecord = treclist[-1]
if not hasattr(lastrecord, attr):
if flags&SEQUENCE: tainted = [tainted]
setattr(lastrecord, attr, tainted)
else:
if flags&SEQUENCE:
getattr(lastrecord,
attr).append(tainted)
else:
newrec = record()
setattr(newrec, attr, tainted)
treclist.append(newrec)
elif tainted_mapping.has_key(tainted_key):
# If we already put a tainted value into this
# recordset, we need to make sure the whole
# recordset is built.
treclist = tainted_mapping[tainted_key]
lastrecord = treclist[-1]
copyitem = item
if not hasattr(lastrecord, attr):
if flags&SEQUENCE: copyitem = [copyitem]
setattr(lastrecord, attr, copyitem)
else:
if flags&SEQUENCE:
getattr(lastrecord,
attr).append(copyitem)
else:
newrec = record()
setattr(newrec, attr, copyitem)
treclist.append(newrec)
if not hasattr(x,attr):
#If the attribute does not
#exist, setit
if flags&SEQUENCE: item=[item]
setattr(x,attr,item)
else:
if flags&SEQUENCE:
# If the attribute is a
# sequence, append the item
# to the existing attribute
y = getattr(x, attr)
y.append(item)
setattr(x, attr, y)
else:
# Create a new record and add
# it to the list
n=record()
setattr(n,attr,item)
mapping_object[key].append(n)
elif flags&RECORD:
b=mapping_object[key]
if flags&SEQUENCE:
item=[item]
if not hasattr(b,attr):
# if it does not have the
# attribute, set it
setattr(b,attr,item)
else:
# it has the attribute so
# append the item to it
setattr(b,attr,getattr(b,attr)+item)
else:
# it is not a sequence so
# set the attribute
setattr(b,attr,item)
# Store a tainted copy as well if necessary
if tainted:
if not tainted_mapping.has_key(tainted_key):
tainted_mapping[tainted_key] = deepcopy(
mapping_object[key])
b = tainted_mapping[tainted_key]
if flags&SEQUENCE:
seq = getattr(b, attr, [])
seq.append(tainted)
setattr(b, attr, seq)
else:
setattr(b, attr, tainted)
elif tainted_mapping.has_key(tainted_key):
# If we already put a tainted value into this
# record, we need to make sure the whole record
# is built.
b = tainted_mapping[tainted_key]
if flags&SEQUENCE:
seq = getattr(b, attr, [])
seq.append(item)
setattr(b, attr, seq)
else:
setattr(b, attr, item)
else:
# it is not a record or list of records
found=mapping_object[key]
if tainted:
# Store a tainted version if necessary
if not tainted_mapping.has_key(tainted_key):
copied = deepcopy(found)
if isinstance(copied, lt):
tainted_mapping[tainted_key] = copied
else:
tainted_mapping[tainted_key] = [copied]
tainted_mapping[tainted_key].append(tainted)
elif tainted_mapping.has_key(tainted_key):
# We may already have encountered a tainted
# value for this key, and the tainted_mapping
# needs to hold all the values.
tfound = tainted_mapping[tainted_key]
if isinstance(tfound, lt):
tainted_mapping[tainted_key].append(item)
else:
tainted_mapping[tainted_key] = [tfound,
item]
if type(found) is lt:
found.append(item)
else:
found=[found,item]
mapping_object[key]=found
else:
# The dictionary does not have the key
if flags&RECORDS:
# Create a new record, set its attribute
# and put it in the dictionary as a list
a = record()
if flags&SEQUENCE: item=[item]
setattr(a,attr,item)
mapping_object[key]=[a]
if tainted:
# Store a tainted copy if necessary
a = record()
if flags&SEQUENCE: tainted = [tainted]
setattr(a, attr, tainted)
tainted_mapping[tainted_key] = [a]
elif flags&RECORD:
# Create a new record, set its attribute
# and put it in the dictionary
if flags&SEQUENCE: item=[item]
r = mapping_object[key]=record()
setattr(r,attr,item)
if tainted:
# Store a tainted copy if necessary
if flags&SEQUENCE: tainted = [tainted]
r = tainted_mapping[tainted_key] = record()
setattr(r, attr, tainted)
else:
# it is not a record or list of records
if flags&SEQUENCE: item=[item]
mapping_object[key]=item
if tainted:
# Store a tainted copy if necessary
if flags&SEQUENCE: tainted = [tainted]
tainted_mapping[tainted_key] = tainted
else:
# This branch is for case when no type was specified.
mapping_object = form
if not isFileUpload and '<' in item:
tainted = TaintedString(item)
elif '<' in key:
tainted = item
#Insert in dictionary
if mapping_object.has_key(key):
# it is not a record or list of records
found=mapping_object[key]
if tainted:
# Store a tainted version if necessary
if not taintedform.has_key(tainted_key):
copied = deepcopy(found)
if isinstance(copied, lt):
taintedform[tainted_key] = copied
else:
taintedform[tainted_key] = [copied]
elif not isinstance(taintedform[tainted_key], lt):
taintedform[tainted_key] = [
taintedform[tainted_key]]
taintedform[tainted_key].append(tainted)
elif taintedform.has_key(tainted_key):
# We may already have encountered a tainted value
# for this key, and the taintedform needs to hold
# all the values.
tfound = taintedform[tainted_key]
if isinstance(tfound, lt):
taintedform[tainted_key].append(item)
else:
taintedform[tainted_key] = [tfound, item]
if type(found) is lt:
found.append(item)
else:
found=[found,item]
mapping_object[key]=found
else:
mapping_object[key]=item
if tainted:
taintedform[tainted_key] = tainted
#insert defaults into form dictionary
if defaults:
for key, value in defaults.items():
tainted_key = key
if '<' in key: tainted_key = TaintedString(key)
if not form.has_key(key):
# if the form does not have the key,
# set the default
form[key]=value
if tainteddefaults.has_key(tainted_key):
taintedform[tainted_key] = \
tainteddefaults[tainted_key]
else:
#The form has the key
tdefault = tainteddefaults.get(tainted_key, value)
if isinstance(value, record):
# if the key is mapped to a record, get the
# record
r = form[key]
# First deal with tainted defaults.
if taintedform.has_key(tainted_key):
tainted = taintedform[tainted_key]
for k, v in tdefault.__dict__.items():
if not hasattr(tainted, k):
setattr(tainted, k, v)
elif tainteddefaults.has_key(tainted_key):
# Find out if any of the tainted default
# attributes needs to be copied over.
missesdefault = 0
for k, v in tdefault.__dict__.items():
if not hasattr(r, k):
missesdefault = 1
break
if missesdefault:
tainted = deepcopy(r)
for k, v in tdefault.__dict__.items():
if not hasattr(tainted, k):
setattr(tainted, k, v)
taintedform[tainted_key] = tainted
for k, v in value.__dict__.items():
# loop through the attributes and value
# in the default dictionary
if not hasattr(r, k):
# if the form dictionary doesn't have
# the attribute, set it to the default
setattr(r,k,v)
form[key] = r
elif isinstance(value, lt):
# the default value is a list
l = form[key]
if not isinstance(l, lt):
l = [l]
# First deal with tainted copies
if taintedform.has_key(tainted_key):
tainted = taintedform[tainted_key]
if not isinstance(tainted, lt):
tainted = [tainted]
for defitem in tdefault:
if isinstance(defitem, record):
for k, v in defitem.__dict__.items():
for origitem in tainted:
if not hasattr(origitem, k):
setattr(origitem, k, v)
else:
if not defitem in tainted:
tainted.append(defitem)
taintedform[tainted_key] = tainted
elif tainteddefaults.has_key(tainted_key):
missesdefault = 0
for defitem in tdefault:
if isinstance(defitem, record):
try:
for k, v in \
defitem.__dict__.items():
for origitem in l:
if not hasattr(origitem, k):
missesdefault = 1
raise NestedLoopExit
except NestedLoopExit:
break
else:
if not defitem in l:
missesdefault = 1
break
if missesdefault:
tainted = deepcopy(l)
for defitem in tdefault:
if isinstance(defitem, record):
for k, v in defitem.__dict__.items():
for origitem in tainted:
if not hasattr(origitem, k):
setattr(origitem, k, v)
else:
if not defitem in tainted:
tainted.append(defitem)
taintedform[tainted_key] = tainted
for x in value:
# for each x in the list
if isinstance(x, record):
# if the x is a record
for k, v in x.__dict__.items():
# loop through each
# attribute and value in
# the record
for y in l:
# loop through each
# record in the form
# list if it doesn't
# have the attributes
# in the default
# dictionary, set them
if not hasattr(y, k):
setattr(y, k, v)
else:
# x is not a record
if not x in l:
l.append(x)
form[key] = l
else:
# The form has the key, the key is not mapped
# to a record or sequence so do nothing
pass
# Convert to tuples
if tuple_items:
for key in tuple_items.keys():
# Split the key and get the attr
k=key.split( ".")
k,attr='.'.join(k[:-1]), k[-1]
a = attr
new = ''
# remove any type_names in the attr
while not a=='':
a=a.split( ":")
a,new=':'.join(a[:-1]), a[-1]
attr = new
if form.has_key(k):
# If the form has the split key get its value
tainted_split_key = k
if '<' in k: tainted_split_key = TaintedString(k)
item =form[k]
if isinstance(item, record):
# if the value is mapped to a record, check if it
# has the attribute, if it has it, convert it to
# a tuple and set it
if hasattr(item,attr):
value=tuple(getattr(item,attr))
setattr(item,attr,value)
else:
# It is mapped to a list of records
for x in item:
# loop through the records
if hasattr(x, attr):
# If the record has the attribute
# convert it to a tuple and set it
value=tuple(getattr(x,attr))
setattr(x,attr,value)
# Do the same for the tainted counterpart
if taintedform.has_key(tainted_split_key):
tainted = taintedform[tainted_split_key]
if isinstance(item, record):
seq = tuple(getattr(tainted, attr))
setattr(tainted, attr, seq)
else:
for trec in tainted:
if hasattr(trec, attr):
seq = getattr(trec, attr)
seq = tuple(seq)
setattr(trec, attr, seq)
else:
# the form does not have the split key
tainted_key = key
if '<' in key: tainted_key = TaintedString(key)
if form.has_key(key):
# if it has the original key, get the item
# convert it to a tuple
item=form[key]
item=tuple(form[key])
form[key]=item
if taintedform.has_key(tainted_key):
tainted = tuple(taintedform[tainted_key])
taintedform[tainted_key] = tainted
if meth:
if environ.has_key('PATH_INFO'):
path=environ['PATH_INFO']
while path[-1:]=='/': path=path[:-1]
else: path=''
other['PATH_INFO']=path="%s/%s" % (path,meth)
self._hacked_path=1
HTTPRequest.processInputs = processInputs
import logging
logger = logging.getLogger('Zope')
logger.info("z3c.amf: modified ZPublisher.HTTPRequest.processInputs") | z3c.amf | /z3c.amf-0.2.tar.gz/z3c.amf-0.2/z3c/amf/HTTPRequest.py | HTTPRequest.py |
import logging
import sys
import traceback
import types
from z3c.amf.interfaces import IAMFResponse
from zExceptions import Unauthorized, NotFound
from zope.interface import implements
import pyamf
from pyamf import remoting
from pyamf.remoting import amf0
class AMFParser(object):
"""
Parse the request
"""
def __init__(self, data):
context = pyamf.get_context(pyamf.AMF0)
self.requests = remoting.decode(data, context)
self.auth = None
self.paths = None
def parse(self):
name, request = self.requests.items()[0]
if self.requests.headers:
self.auth = self.requests.headers.get(u'Credentials')
self.method = request.target
if '.' in self.method:
paths = self.method.split('.')
self.method = paths[-1]
self.paths = paths[:-1]
params = request.body
if len(params) == 0 or params[0] is None:
self.args = tuple()
else:
self.args = tuple(params)
self.amfVersion = self.requests.amfVersion
self.clientType = self.requests.clientType
self.name = name
def parse_input(data):
parser = AMFParser(data)
return parser.parse()
class AMFResponse:
"""Customized Response that handles AMF-specific details.
We override setBody to marhsall Python objects into AMF. We
also override exception to convert errors to AMF faults.
"""
implements(IAMFResponse)
_contentType = remoting.CONTENT_TYPE
# Because we can't predict what kind of thing we're customizing,
# we have to use delegation, rather than inheritence to do the
# customization.
def __init__(self, real):
self.__dict__['_real']=real
def __getattr__(self, name):
return getattr(self._real, name)
def __setattr__(self, name, v):
return setattr(self._real, name, v)
def __delattr__(self, name):
return delattr(self._real, name)
def setBody(self, body, title='', is_error=0, bogus_str_search=None):
responseBody = remoting.Envelope(self._amfVersion,
self._clientType)
context = pyamf.get_context(pyamf.AMF0)
proc = amf0.RequestProcessor(self)
if isinstance(body, remoting.BaseFault):
amfResponse = remoting.Response(body,
status=remoting.STATUS_ERROR)
else:
amfResponse = remoting.Response(body)
responseBody[self._name] = amfResponse
body = remoting.encode(responseBody, context)
body.seek(0)
self._real.setBody(body.read())
self._setHeader()
return self
def exception(self, fatal=0, info=None,
absuri_match=None, tag_search=None):
if isinstance(info, tuple) and len(info)==3:
t, v, tb = info
else:
t, v, tb = sys.exc_info()
content = "".join(traceback.format_tb(tb))
logger = logging.getLogger('Zope')
logger.info('AMF Exception: %s' % content)
f=None
self._real.setStatus(200)
if t == 'Unauthorized' or t == Unauthorized or (
isinstance(t, types.ClassType) and issubclass(t, Unauthorized)):
# 401
f = remoting.ErrorFault(code=str(t), type='Not authorized')
elif isinstance(v, NotFound): # 404
f = remoting.ErrorFault(code='NotFound',
type='Resource not found',
description=str(v))
elif not isinstance(v, pyamf.BaseError): # 500
f = remoting.ErrorFault(code=str(t), type=str(v),
description=content)
self.setBody(f)
return tb
def _setHeader(self):
self.setHeader('content-length', len(self._real.body))
self._real.setHeader('content-type', self._contentType) | z3c.amf | /z3c.amf-0.2.tar.gz/z3c.amf-0.2/z3c/amf/amfgateway.py | amfgateway.py |
import zope.configuration.fields
from zope.security.zcml import Permission
from zope.interface import Interface
from zope.schema import TextLine
class IViewDirective(Interface):
"""View Directive for AMF methods."""
for_ = zope.configuration.fields.GlobalObject(
title=u"Published Object Type",
description=u"""The types of objects to be published via AMF
This can be expressed with either a class or an interface
""",
required=True)
interface = zope.configuration.fields.Tokens(
title=u"Interface to be published.",
required=False,
value_type=zope.configuration.fields.GlobalInterface())
methods = zope.configuration.fields.Tokens(
title=u"Methods (or attributes) to be published",
required=False,
value_type=zope.configuration.fields.PythonIdentifier())
class_ = zope.configuration.fields.GlobalObject(
title=u"Class",
description=u"A class that provides attributes used by the view.",
required=False)
permission = Permission(
title=u"Permission",
description=u"""The permission needed to use the view.
If this option is used and a name is given for the view, then
the names defined by the given methods or interfaces will be
under the given permission.
If a name is not given for the view, then, this option is
required and the the given permission is required to call the
individual views defined by the given interface and methods.
(See the name attribute.)
If no permission is given, then permissions should be declared
for the view using other means, such as the class directive.
""",
required=False, )
name = TextLine(
title=u"The name of the view.",
description=u"""
If a name is given, then rpc methods are accessed by
traversing the name and then accessing the methods. In this
case, the class should implement
zope.pubisher.interfaces.IPublishTraverse.
If no name is provided, then the names given by the attributes
and interfaces are published directly as callable views.
""",
required=False,
) | z3c.amf | /z3c.amf-0.2.tar.gz/z3c.amf-0.2/z3c/amf/metadirectives.py | metadirectives.py |
from zope.interface import Interface
from zope.security.checker import CheckerPublic
from zope.component.interface import provideInterface
from Products.Five.security import protectClass, protectName
from zope.app.publisher.browser.viewmeta import _handle_for
# XXX handler is non-public. Should call directives instead
from zope.app.component.metaconfigure import handler
from inspect import ismethod
from z3c.amf.interfaces import IAMFRequest
from Globals import InitializeClass as initializeClass
from Products.Five.security import getSecurityInfo
from Products.Five.metaclass import makeClass
from Products.Five.browser import BrowserView
from Products.Five.browser.metaconfigure import ViewMixinForAttributes
from Products.Five.security import CheckerPrivateId
def view(_context, for_=None, interface=None, methods=None,
class_=None, permission=None, name=None):
interface = interface or []
methods = methods or []
# If there were special permission settings provided, then use them
if permission == 'zope.Public':
permission = CheckerPublic
require = {}
for attr_name in methods:
require[attr_name] = permission
if interface:
for iface in interface:
for field_name in iface:
require[field_name] = permission
_context.action(
discriminator = None,
callable = provideInterface,
args = ('', for_))
cdict = getSecurityInfo(class_)
if name:
cdict['__name__'] = name
new_class = makeClass(class_.__name__,
(class_, BrowserView), cdict)
_handle_for(_context, for_)
# Register the new view.
_context.action(
discriminator = ('view', (for_, ), name, IAMFRequest),
callable = handler,
args = ('registerAdapter',
new_class, (for_, IAMFRequest),
Interface, name,
_context.info)
)
_context.action(
discriminator = ('five:protectClass', new_class),
callable = protectClass,
args = (new_class, permission))
for name in require:
_context.action(
discriminator = ('five:protectName', new_class, name),
callable = protectName,
args = (new_class, name, permission))
#else its private:
allowed = require
private_attrs = [name for name in dir(new_class)
if (not name.startswith('_')) and
(name not in allowed) and
ismethod(getattr(new_class, name))]
for attr in private_attrs:
_context.action(
discriminator = ('five:protectName', new_class, attr),
callable = protectName,
args = (new_class, attr, CheckerPrivateId))
else:
for name in require:
cdict.update({'__page_attribute__': name,
'__name__': name})
new_class = makeClass(class_.__name__,
(class_, ViewMixinForAttributes),
cdict)
func = getattr(new_class, name)
if not func.__doc__:
# cannot test for MethodType/UnboundMethod here
# because of ExtensionClass
if hasattr(func, 'im_func'):
# you can only set a docstring on functions, not
# on method objects
func = func.im_func
func.__doc__ = "Stub docstring to make ZPublisher work"
_context.action(
discriminator = ('view', (for_, ), name, IAMFRequest),
callable = handler,
args = ('registerAdapter',
new_class,
(for_, IAMFRequest), Interface, name,
_context.info))
_context.action(
discriminator = ('five:protectClass', new_class),
callable = protectClass,
args = (new_class, permission))
_context.action(
discriminator = ('five:protectName', new_class, name),
callable = protectName,
args = (new_class, name, permission))
_context.action(
discriminator = ('five:initialize:class', new_class),
callable = initializeClass,
args = (new_class, )
)
# Register the used interfaces with the interface service
if for_ is not None:
_context.action(
discriminator = None,
callable = provideInterface,
args = ('', for_)) | z3c.amf | /z3c.amf-0.2.tar.gz/z3c.amf-0.2/z3c/amf/metaconfigure.py | metaconfigure.py |
Introduction
============
This package provides a method to configure an application via standard
``.ini`` files. This is convenient for site admins since they are more
likely to be familiar with ini files than with ZCML.
Creating config files
=====================
There are two ways to tell a Zope instance which configuration files to
load: zcml statements and the APPCONFIG environment variable. zcml statements
are processed first, making it possible to override standard configuration.
The zcml syntax looks like this::
<configure xmlns="http://namespaces.zope.org/zope">
<include package="z3c.appconfig" file="meta.zcml"/>
<appconfig file="default.ini" />
</configure>
This will load the contents of ``default.ini`` and merge it into the
application configuration.
If an APPCONFIG environment variable is set and points to a file
its contents will be merged into the application configuration. This is done
last, allowing you to override application defined defaults. For example::
$ APPCONFIG=etc/mysite.ini bin/instance fg
Accessing configuration
=======================
The configuration data can be accessed from your code via a IAppConfig utility.
This utility is essentially a standard python dictionary which stores all
configuration data. For example lets use a very simple configuration file::
[site]
title = My lovely site
You can access the title from python with code like this::
from zope.component import getUtility
from z3c.appconfig.interfaces import IAppConfig
appconfig=getUtility(IAppConfig)
print "Site title is: %s" % appconfig["site"]["title"]
| z3c.appconfig | /z3c.appconfig-1.0b1.tar.gz/z3c.appconfig-1.0b1/README.txt | README.txt |
"""Events
"""
import zope.interface
from z3c.authenticator import interfaces
# principal events
@zope.interface.implementer(interfaces.IAuthenticatedPrincipalCreated)
class AuthenticatedPrincipalCreated:
"""
>>> from zope.interface.verify import verifyObject
>>> event = AuthenticatedPrincipalCreated('authentication', 'principal',
... 'request')
>>> verifyObject(interfaces.IAuthenticatedPrincipalCreated, event)
True
"""
def __init__(self, authentication, principal, request):
self.authentication = authentication
self.principal = principal
self.request = request
@zope.interface.implementer(interfaces.IUnauthenticatedPrincipalCreated)
class UnauthenticatedPrincipalCreated:
"""
>>> from zope.interface.verify import verifyObject
>>> event = UnauthenticatedPrincipalCreated('authentication', 'principal')
>>> verifyObject(interfaces.IUnauthenticatedPrincipalCreated, event)
True
"""
def __init__(self, authentication, principal):
self.authentication = authentication
self.principal = principal
@zope.interface.implementer(interfaces.IFoundPrincipalCreated)
class FoundPrincipalCreated:
"""
>>> from zope.interface.verify import verifyObject
>>> event = FoundPrincipalCreated('authentication', 'principal')
>>> verifyObject(interfaces.IFoundPrincipalCreated, event)
True
"""
def __init__(self, authentication, principal):
self.authentication = authentication
self.principal = principal
# group events
@zope.interface.implementer(interfaces.IGroupAdded)
class GroupAdded:
"""Group added event
>>> from zope.interface.verify import verifyObject
>>> event = GroupAdded(u'group')
>>> verifyObject(interfaces.IGroupAdded, event)
True
"""
def __init__(self, group):
self.group = group
def __repr__(self):
return "<GroupAdded %r>" % self.group.__name__
class AbstractUsersChanged:
def __init__(self, principal_ids, group_id):
self.principal_ids = principal_ids
self.group_id = group_id
def __repr__(self):
return "<{} {!r} {!r}>".format(
self.__class__.__name__, sorted(self.principal_ids), self.group_id)
@zope.interface.implementer(interfaces.IPrincipalsAddedToGroup)
class PrincipalsAddedToGroup(AbstractUsersChanged):
pass
@zope.interface.implementer(interfaces.IPrincipalsRemovedFromGroup)
class PrincipalsRemovedFromGroup(AbstractUsersChanged):
pass | z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/event.py | event.py |
"""Credential Plugins
"""
import base64
import persistent
import transaction
import zope.interface
from zope.component import hooks
from zope.container import contained
from zope.publisher.interfaces.http import IHTTPRequest
from zope.session.interfaces import ISession
from zope.traversing.browser.absoluteurl import absoluteURL
from z3c.authenticator import interfaces
@zope.interface.implementer(interfaces.IHTTPBasicAuthCredentialsPlugin)
class HTTPBasicAuthCredentialsPlugin(persistent.Persistent,
contained.Contained):
realm = 'Zope Application Management'
protocol = 'http auth'
def extractCredentials(self, request):
"""Extracts HTTP basic auth credentials from a request.
First we need to create a request that contains some credentials.
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest(
... environ={'HTTP_AUTHORIZATION': 'Basic bWdyOm1ncnB3'})
Now create the plugin and get the credentials.
>>> plugin = HTTPBasicAuthCredentialsPlugin()
>>> sorted(plugin.extractCredentials(request).items())
[('login', 'mgr'), ('password', 'mgrpw')]
Make sure we return `None`, if no authentication header has been
specified.
>>> print(plugin.extractCredentials(TestRequest()))
None
Also, this plugin can *only* handle basic authentication.
>>> request = TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'})
>>> print(plugin.extractCredentials(TestRequest()))
None
This plugin only works with HTTP requests.
>>> from zope.publisher.base import TestRequest
>>> print(plugin.extractCredentials(TestRequest('/')))
None
"""
if not IHTTPRequest.providedBy(request):
return None
if request._auth:
if request._auth.lower().startswith('basic '):
credentials = request._auth.split()[-1]
if isinstance(credentials, str):
credentials = credentials.encode('utf-8')
login, password = base64.decodebytes(credentials).split(b':')
return {'login': login.decode('utf-8'),
'password': password.decode('utf-8')}
return None
def challenge(self, request):
"""Issues an HTTP basic auth challenge for credentials.
The challenge is issued by setting the appropriate response headers.
To illustrate, we'll create a plugin:
>>> plugin = HTTPBasicAuthCredentialsPlugin()
The plugin adds its challenge to the HTTP response.
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> response = request.response
>>> plugin.challenge(request)
True
>>> response._status
401
>>> response.getHeader('WWW-Authenticate', literal=True)
'basic realm="Zope Application Management"'
Notice that the realm is quoted, as per RFC 2617.
The plugin only works with HTTP requests.
>>> from zope.publisher.base import TestRequest
>>> request = TestRequest('/')
>>> response = request.response
>>> print(plugin.challenge(request))
False
"""
if not IHTTPRequest.providedBy(request):
return False
request.response.setHeader("WWW-Authenticate",
'basic realm="%s"' % self.realm,
literal=True)
request.response.setStatus(401)
return True
def logout(self, request):
"""Always returns False as logout is not supported by basic auth.
>>> plugin = HTTPBasicAuthCredentialsPlugin()
>>> from zope.publisher.browser import TestRequest
>>> plugin.logout(TestRequest())
False
"""
return False
@zope.interface.implementer(interfaces.ISessionCredentials)
class SessionCredentials:
"""Credentials class for use with sessions.
A session credential is created with a login and a password:
>>> cred = SessionCredentials('scott', 'tiger')
Logins are read using getLogin:
>>> cred.getLogin()
'scott'
and passwords with getPassword:
>>> cred.getPassword()
'tiger'
"""
def __init__(self, login, password):
self.login = login
self.password = password
def getLogin(self):
return self.login
def getPassword(self):
return self.password
def __str__(self):
return self.getLogin() + ':' + self.getPassword()
@zope.interface.implementer(interfaces.ISessionCredentialsPlugin)
class SessionCredentialsPlugin(persistent.Persistent, contained.Contained):
"""A credentials plugin that uses Zope sessions to get/store credentials.
To illustrate how a session plugin works, we'll first setup some session
machinery:
>>> from z3c.authenticator.testing import sessionSetUp
>>> sessionSetUp()
This lets us retrieve the same session info from any test request, which
simulates what happens when a user submits a session ID as a cookie.
We also need a session plugin:
>>> plugin = SessionCredentialsPlugin()
A session plugin uses an ISession component to store the last set of
credentials it gets from a request. Credentials can be retrieved from
subsequent requests using the session-stored credentials.
If the given extractCredentials argument doesn't provide IHTTPRequest the
result will always be None:
>>> print(plugin.extractCredentials(None))
None
Our test environment is initially configured without credentials:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> print(plugin.extractCredentials(request))
None
We must explicitly provide credentials once so the plugin can store
them in a session:
>>> request = TestRequest(form=dict(login='scott', password='tiger'))
>>> sorted(plugin.extractCredentials(request).items())
[('login', 'scott'), ('password', 'tiger')]
Subsequent requests now have access to the credentials even if they're
not explicitly in the request:
>>> sorted(plugin.extractCredentials(request).items())
[('login', 'scott'), ('password', 'tiger')]
We can always provide new credentials explicitly in the request:
>>> sorted(plugin.extractCredentials(TestRequest(
... login='harry', password='hirsch')).items())
[('login', 'harry'), ('password', 'hirsch')]
and these will be used on subsequent requests:
>>> sorted(plugin.extractCredentials(TestRequest()).items())
[('login', 'harry'), ('password', 'hirsch')]
We can also change the fields from which the credentials are extracted:
>>> plugin.loginfield = "my_new_login_field"
>>> plugin.passwordfield = "my_new_password_field"
Now we build a request that uses the new fields:
>>> request = TestRequest(my_new_login_field='luke',
... my_new_password_field='the_force')
The plugin now extracts the credentials information from these new fields:
>>> sorted(plugin.extractCredentials(request).items())
[('login', 'luke'), ('password', 'the_force')]
We can also set prefixes for the fields from which the credentials are
extracted:
>>> plugin.loginfield = "login"
>>> plugin.passwordfield = "password"
>>> plugin.prefixes = ['form.widgets.']
Now we build a request that uses the new fields. Note that we need a
browser request which provides a form for this test since we can't setup
our prefixes.
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest(form={'form.widgets.login':'harry',
... 'form.widgets.password':'potter'})
The plugin now extracts the credentials information from these new fields:
>>> sorted(plugin.extractCredentials(request).items())
[('login', 'harry'), ('password', 'potter')]
Finally, we clear the session credentials using the logout method.
If the given logout argument doesn't provide IHTTPRequest the
result will always be False:
>>> plugin.logout(None)
False
Now try to logout with the correct argument:
>>> plugin.logout(TestRequest())
True
After logout we can not logaout again:
>>> print(plugin.extractCredentials(TestRequest()))
None
"""
challengeProtocol = None
prefixes = []
loginpagename = 'loginForm.html'
loginfield = 'login'
passwordfield = 'password'
def extractCredentials(self, request):
"""Extracts credentials from a session if they exist."""
if not IHTTPRequest.providedBy(request):
return None
session = ISession(request, None)
sessionData = session.get('z3c.authenticator.credential.session')
login = request.get(self.loginfield, None)
password = request.get(self.passwordfield, None)
# support z3c.form prefixes
for prefix in self.prefixes:
login = request.get(prefix + self.loginfield, login)
password = request.get(prefix + self.passwordfield, password)
credentials = None
if login and password:
credentials = SessionCredentials(login, password)
elif not sessionData:
return None
sessionData = session['z3c.authenticator.credential.session']
if credentials:
sessionData['credentials'] = credentials
else:
credentials = sessionData.get('credentials', None)
if not credentials:
return None
return {'login': credentials.getLogin(),
'password': credentials.getPassword()}
def challenge(self, request):
"""Challenges by redirecting to a login form.
To illustrate how a session plugin works, we'll first setup some
session machinery:
>>> from z3c.authenticator.testing import sessionSetUp
>>> sessionSetUp()
and we'll create a test request:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
and confirm its response's initial status and 'location' header:
>>> request.response.getStatus()
599
>>> request.response.getHeader('location')
When we issue a challenge using a session plugin:
>>> plugin = SessionCredentialsPlugin()
>>> plugin.challenge(request)
True
we get a redirect:
>>> request.response.getStatus()
302
>>> request.response.getHeader('location')
'http://127.0.0.1/@@loginForm.html'
and the camefrom session contains the camefrom url which is our
application root by default:
>>> session = ISession(request, None)
>>> sessionData = session['z3c.authenticator.credential.session']
>>> sessionData['camefrom']
'/'
The plugin redirects to the page defined by the loginpagename
attribute:
>>> plugin.loginpagename = 'mylogin.html'
>>> plugin.challenge(request)
True
>>> request.response.getHeader('location')
'http://127.0.0.1/@@mylogin.html'
and the camefrom session contains the camefrom url which is our
application root by default:
>>> session = ISession(request, None)
>>> sessionData = session['z3c.authenticator.credential.session']
>>> sessionData['camefrom']
'/'
It also provides the request URL as a 'camefrom' GET style parameter.
To illustrate, we'll pretend we've traversed a couple names:
>>> env = {
... 'REQUEST_URI': '/foo/bar/folder/page%201.html?q=value',
... 'QUERY_STRING': 'q=value'
... }
>>> request = TestRequest(environ=env)
>>> request._traversed_names = ['foo', 'bar']
>>> request._traversal_stack = ['page 1.html', 'folder']
>>> request['REQUEST_URI']
'/foo/bar/folder/page%201.html?q=value'
When we challenge:
>>> plugin.challenge(request)
True
We see the url points to the login form URL:
>>> request.response.getHeader('location') # doctest: +ELLIPSIS
'http://127.0.0.1/@@mylogin.html'
and the camefrom session contains the camefrom url:
>>> session = ISession(request, None)
>>> sessionData = session['z3c.authenticator.credential.session']
>>> sessionData['camefrom']
'/foo/bar/folder/page%201.html?q=value'
If the given challenge argument doesn't provide IHTTPRequest the
result will always be False:
>>> plugin.challenge(None)
False
This can be used by the login form to redirect the user back to the
originating URL upon successful authentication.
"""
if not IHTTPRequest.providedBy(request):
return False
site = hooks.getSite()
# We need the traversal stack to complete the 'camefrom' parameter
stack = request.getTraversalStack()
stack.reverse()
# Better to add the query string, if present
query = request.get('QUERY_STRING')
camefrom = '/'.join([request.getURL(path_only=True)] + stack)
if query:
camefrom = camefrom + '?' + query
url = '{}/@@{}'.format(absoluteURL(site, request), self.loginpagename)
# only redirect to the login form
request.response.redirect(url)
# and store the camefrom url into a session variable, then this url
# should not get exposed in the login form url.
session = ISession(request, None)
sessionData = session['z3c.authenticator.credential.session']
# XXX: this might be problematic with non-ASCII html page names
sessionData['camefrom'] = camefrom.replace(' ', '%20')
return True
def logout(self, request):
"""Performs logout by clearing session data credentials."""
if not IHTTPRequest.providedBy(request):
return False
sessionData = ISession(request)['z3c.authenticator.credential.session']
sessionData['credentials'] = None
sessionData['camefrom'] = None
transaction.commit()
return True | z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/credential.py | credential.py |
import base64
import zope.component
import zope.dublincore.interfaces
import zope.i18n
import zope.interface
from zope.schema import vocabulary
from zope.schema.interfaces import IVocabularyFactory
from z3c.authenticator import interfaces
from z3c.authenticator.interfaces import _
UTILITY_TITLE = _(
'z3c.authenticator.vocabulary-utility-plugin-title',
'${name} (a utility)')
CONTAINED_TITLE = _(
'z3c.authenticator.vocabulary-contained-plugin-title',
'${name} (in contents)')
MISSING_TITLE = _(
'z3c.authenticator.vocabulary-missing-plugin-title',
'${name} (not found; deselecting will remove)')
def mktok(s):
tok = base64.encodebytes(s.encode('utf-8')).decode('utf-8')
return tok.strip()
def _pluginVocabulary(context, interface, attr_name):
"""Vocabulary that provides names of plugins of a specified interface.
Given an interface, the options should include the unique names of all of
the plugins that provide the specified interface for the current context--
which is expected to be a pluggable authentication utility, hereafter
referred to as a Authenticator).
These plugins may be objects contained within the Authenticator
("contained plugins"), or may be utilities registered for the specified
interface, found in the context of the Authenticator
("utility plugins"). Contained plugins mask utility plugins of the same
name.
The vocabulary also includes the current values of the
Authenticator even if they do not correspond to a contained or
utility plugin.
"""
terms = {}
auth = interfaces.IAuthenticator.providedBy(context)
if auth:
for k, v in context.items():
if interface.providedBy(v):
dc = zope.dublincore.interfaces.IDCDescriptiveProperties(
v, None)
if dc is not None and dc.title:
title = dc.title
else:
title = k
terms[k] = vocabulary.SimpleTerm(
k, mktok(k), zope.i18n.Message(
CONTAINED_TITLE, mapping={'name': title}))
utils = zope.component.getUtilitiesFor(interface, context)
for nm, util in utils:
if nm not in terms:
terms[nm] = vocabulary.SimpleTerm(
nm, mktok(nm), zope.i18n.Message(
UTILITY_TITLE, mapping={'name': nm}))
if auth:
for nm in set(getattr(context, attr_name)):
if nm not in terms:
terms[nm] = vocabulary.SimpleTerm(
nm, mktok(nm), zope.i18n.Message(
MISSING_TITLE, mapping={'name': nm}))
return vocabulary.SimpleVocabulary(
[term for nm, term in sorted(terms.items())])
def authenticatorPlugins(context):
return _pluginVocabulary(
context, interfaces.IAuthenticatorPlugin, 'authenticatorPlugins')
zope.interface.alsoProvides(authenticatorPlugins, IVocabularyFactory)
def credentialsPlugins(context):
return _pluginVocabulary(
context, interfaces.ICredentialsPlugin, 'credentialsPlugins')
zope.interface.alsoProvides(credentialsPlugins, IVocabularyFactory) | z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/vocabulary.py | vocabulary.py |
"""Interfaces
"""
import zope.deprecation
import zope.interface
import zope.schema
import zope.security.interfaces
from zope.authentication.interfaces import ILogout
from zope.authentication.principal import PrincipalSource
from zope.container.constraints import containers
from zope.container.constraints import contains
from zope.container.interfaces import IContainer
from zope.i18nmessageid import MessageFactory
_ = MessageFactory('z3c')
class IPlugin(zope.interface.Interface):
"""A plugin for IAuthenticator component."""
# authenticator interfaces
class IAuthenticatorPlugin(IPlugin):
"""Authenticates and provides a principal using credentials."""
containers('z3c.authenticator.interfaces.IAuthenticator')
def authenticateCredentials(credentials):
"""Authenticates credentials and return a IPrincipal object.
If the credentials can be authenticated, return an object that provides
IPrincipal. If the plugin cannot authenticate the credentials,
returns None.
"""
def queryPrincipal(id, default=None):
"""Returns an IPrincipal object for the given principal id or default.
If the plugin cannot find information for the id, returns None.
"""
class IPrincipalRegistryAuthenticatorPlugin(IAuthenticatorPlugin):
"""Principal registry authenticator plugin.
This plugin is a little bit special since principals get returned from
a IAuthentication source next to the root then any other IAuthenticator.
By defaut this utility returns global principals and the IAuthenticator
forces to wrap then within a IFoundPrincipal. This allows us to apply
local groups to gloal defined principals.
You can trun of this feature by set allowQueryPrincipal to False.
Anyway, this is just an optional plugin, you don't have to use it.
"""
allowQueryPrincipal = zope.schema.Bool(
title=_('Allow query principal'),
description=_('Allow query principal. This is useful if an '
'authenticator plugin manages principals for another '
'authenticator.'),
default=True,
)
class ICredentialsPlugin(IPlugin):
"""Handles credentials extraction and challenges per request."""
containers('z3c.authenticator.interfaces.IAuthenticator')
challengeProtocol = zope.interface.Attribute(
"""A challenge protocol used by the plugin.
If a credentials plugin works with other credentials pluggins, it
and the other cooperating plugins should specify a common (non-None)
protocol. If a plugin returns True from its challenge method, then
other credentials plugins will be called only if they have the same
protocol.
""")
def extractCredentials(request):
"""Ties to extract credentials from a request.
A return value of None indicates that no credentials could be found.
Any other return value is treated as valid credentials.
"""
def challenge(request):
"""Possibly issues a challenge.
This is typically done in a protocol-specific way.
If a challenge was issued, return True, otherwise return False.
"""
def logout(request):
"""Possibly logout.
If a logout was performed, return True, otherwise return False.
"""
class ISearchable(zope.interface.Interface):
"""An interface for searching using schema-constrained input."""
def search(query, start=None, batch_size=None):
"""Returns an iteration of principal IDs matching the query.
query is a mapping of name/value pairs for fields specified by the
schema.
If the start argument is provided, then it should be an
integer and the given number of initial items should be
skipped.
If the batch_size argument is provided, then it should be an
integer and no more than the given number of items should be
returned.
"""
class IAuthenticator(ILogout, IContainer):
"""Authentication utility.
The Authenticator supports NOT IAuthenticatorPlugin plugins defined
in zope.app.authentication.interfaces. Because they use and return a
IPrincipalInfo object in the authenticateCredentials method.
Note: you have to write your own authenticator plugins because we do not
use the IPrincipalInfo implementation in this authentication module.
"""
contains(IPlugin)
includeNextUtilityForAuthenticate = zope.schema.Bool(
title=_('Include next utility for authenticate'),
description=_('Include next utility for authenticate'),
default=True,
)
credentialsPlugins = zope.schema.List(
title=_('Credentials Plugins'),
description=_("""Used for extracting credentials.
Names may be of ids of non-utility ICredentialsPlugins contained in
the IAuthenticator, or names of registered
ICredentialsPlugins utilities. Contained non-utility ids mask
utility names."""),
value_type=zope.schema.Choice(vocabulary='Z3CCredentialsPlugins'),
default=[],
)
authenticatorPlugins = zope.schema.List(
title=_('Authenticator Plugins'),
description=_("""Used for converting credentials to principals.
Names may be of ids of non-utility IAuthenticatorPlugins contained in
the IAuthenticator, or names of registered
IAuthenticatorPlugins utilities. Contained non-utility ids mask
utility names."""),
value_type=zope.schema.Choice(vocabulary='Z3CAuthenticatorPlugins'),
default=[],
)
def getCredentialsPlugins():
"""Return iterable of (plugin name, actual credentials plugin) pairs.
Looks up names in credentialsPlugins as contained ids of non-utility
ICredentialsPlugins first, then as registered ICredentialsPlugin
utilities. Names that do not resolve are ignored.
"""
def getAuthenticatorPlugins():
"""Return iterable of (plugin name, actual authenticator plugin) pairs.
Looks up names in authenticatorPlugins as contained ids of non-utility
IAuthenticatorPlugins first, then as registered IAuthenticatorPlugin
utilities. Names that do not resolve are ignored.
"""
def logout(request):
"""Performs a logout by delegating to its authenticator plugins."""
# user interfaces
class IUser(zope.interface.Interface):
"""User"""
containers('z3c.authenticator.interfaces.IUserContainer')
login = zope.schema.TextLine(
title=_("Login"),
description=_("The Login/Username of the principal. "
"This value can change."))
password = zope.schema.Password(
title=_("Password"),
description=_("The password for the principal."))
passwordManagerName = zope.schema.Choice(
title=_("Password Manager"),
vocabulary="Password Manager Names",
description=_("The password manager will be used"
" for encode/check the password"),
default="Plain Text",
# TODO: The password manager name may get changed if the password get
# changed!
readonly=True
)
title = zope.schema.TextLine(
title=_("Title"),
description=_("Provides a title for the principal."))
description = zope.schema.Text(
title=_("Description"),
description=_("Provides a description for the principal."),
required=False,
missing_value='',
default='')
class ISourceSearchCriteria(zope.interface.Interface):
"""Search Interface for this Principal Provider"""
search = zope.schema.TextLine(
title=_("Search String"),
description=_("A Search String"),
required=False,
default='',
missing_value='')
class IUserContainer(IContainer, IAuthenticatorPlugin, ISearchable):
"""Principal container."""
contains(IUser)
def add(user):
"""Add a user and returns a the assigned token (principal id)."""
def getUserByLogin(login):
"""Return the User object by looking it up by it's login"""
# principal interfaces
class IFoundPrincipal(zope.security.interfaces.IGroupClosureAwarePrincipal):
"""Provides found principal returned by IAuthenticator.getPrincipal.
The only goal of this adapter is to provide a none persistent object which
we can apply our group of group ids at runtime.
This is needed because there is no way to keep the group of group info
in sync if we whould store them in a IGroup implementation as persistent
information.
A found principal gets also created by the IAuthenticators search method
for users matching the search critaria.
"""
id = zope.interface.Attribute("The principal id.")
title = zope.interface.Attribute("The principal title.")
description = zope.interface.Attribute("A description of the principal.")
groups = zope.schema.List(
title=_("Groups"),
description=_(
"""Ids of groups to which the user directly belongs.
Plugins may append to this list. Mutating the list only affects
the life of the principal object, and does not persist (so
persistently adding groups to a principal should be done by working
with a plugin that mutates this list every time the principal is
created, like the group container in this package.)
"""),
value_type=zope.schema.TextLine(),
required=False)
class IAuthenticatedPrincipal(
zope.security.interfaces.IGroupClosureAwarePrincipal):
"""A factory adapting IInternalPrincipal and offering read access to the
principal.
A authenticated principal gets created by the IAuthenticators
authenticateCredentials method for principals matching the credential
criteria.
"""
id = zope.interface.Attribute("The principal id.")
title = zope.interface.Attribute("The principal title.")
description = zope.interface.Attribute("A description of the principal.")
groups = zope.schema.List(
title=_("Groups"),
description=_(
"""Ids of groups to which the user directly belongs.
Plugins may append to this list. Mutating the list only affects
the life of the principal object, and does not persist (so
persistently adding groups to a principal should be done by working
with a plugin that mutates this list every time the principal is
created, like the group container in this package.)
"""),
value_type=zope.schema.TextLine(),
required=False)
# group interfaces
class IGroup(zope.security.interfaces.IGroup):
"""IGroup provides the zope.security.interfaces.IGroup.
This let us use such IGroups as local registered IEveryoneGroup or
IAuthenticatedGroup utilities.
Note zope.security.interfaces.IGroup implementations are used for store
IPrincipal ids of other IPrincipal or IGroup objects.
zope.security.interfaces.IGroup implemenations are not used for store
group of group informations. Group of gorup information are collected
at runtime by the IAuthentication.getPrincipal method via an adapter
called IFoundPrincipal. I really hope this is understandable.
"""
containers('z3c.authenticato.interfaces.IGroupContainer')
id = zope.schema.TextLine(
title=_("Id"),
description=_("The unique identification of the principal."),
required=True,
readonly=True)
title = zope.schema.TextLine(
title=_("Title"),
description=_("Provides a title for the permission."),
required=True)
description = zope.schema.Text(
title=_("Description"),
description=_("Provides a description for the permission."),
required=False)
principals = zope.schema.List(
title=_('Group Principals'),
description=_("List of ids of principals which belong to the group"),
value_type=zope.schema.Choice(
title=_('Group Principals'),
description=_('Group Principals'),
source=PrincipalSource()),
required=False)
class IGroupContainer(IContainer, IAuthenticatorPlugin, ISearchable):
contains(IGroup)
prefix = zope.schema.TextLine(
title=_('Prefix'),
description=_("Prefix added to IDs of groups in this container"),
default='',
required=True,
readonly=True,
)
def getGroupsForPrincipal(principalid):
"""Get groups the given principal belongs to"""
def getPrincipalsForGroup(groupid):
"""Get principals which belong to the group"""
class IFoundGroup(IFoundPrincipal, zope.security.interfaces.IGroup):
"""IFoundGroup acts as a IFoundPrincipal representing a group.
This group principal is used as IFoundPrincipal adapter which we adhoc
apply our inherited groups incouding groups of groups. See IFoundPrincipal
for more information.
This means both interface z3c.authenticator.interfaces.IGroupPrincipal and
z3c.authenticator.interfaces.IGroup provide
zope.security.interfaces.IGroup.
"""
# members = zope.interface.Attribute('an iterable of members of the group')
# TODO: deprecate and remove later
IGroupPrincipal = IFoundGroup
zope.deprecation.deprecated(
'IGroupPrincipal',
'The IGroupPrincipal interface get replaced by IFoundGroup')
# principal event interfaces
class IPrincipalCreated(zope.interface.Interface):
"""A principal has been created."""
principal = zope.interface.Attribute("The principal that was created")
authentication = zope.interface.Attribute(
"The authentication utility that created the principal")
class IAuthenticatedPrincipalCreated(IPrincipalCreated):
"""A principal has been created by way of an authentication operation."""
request = zope.interface.Attribute(
"The request the user was authenticated against")
class IUnauthenticatedPrincipalCreated(IPrincipalCreated):
"""A unauthenticated principal has been created."""
class IFoundPrincipalCreated(IPrincipalCreated):
"""A principal has been created by way of a search operation."""
# group event interfaces
class IGroupAdded(zope.interface.Interface):
"""A group has been added."""
group = zope.interface.Attribute("""The group that was defined""")
class IPrincipalsAddedToGroup(zope.interface.Interface):
group_id = zope.interface.Attribute(
'the id of the group to which the principal was added')
principal_ids = zope.interface.Attribute(
'an iterable of one or more ids of principals added')
class IPrincipalsRemovedFromGroup(zope.interface.Interface):
group_id = zope.interface.Attribute(
'the id of the group from which the principal was removed')
principal_ids = zope.interface.Attribute(
'an iterable of one or more ids of principals removed')
# credential
class IHTTPBasicAuthRealm(zope.interface.Interface):
"""HTTP Basic Auth Realm
Represents the realm string that is used during basic HTTP authentication
"""
realm = zope.schema.TextLine(
title='Realm',
description='HTTP Basic Authentication Realm',
required=True,
default='ZAM')
class ISessionCredentials(zope.interface.Interface):
""" Interface for storing and accessing credentials in a session.
We use a real class with interface here to prevent unauthorized
access to the credentials.
"""
def getLogin():
"""Return login name."""
def getPassword():
"""Return password."""
class IBrowserFormChallenger(zope.interface.Interface):
"""A challenger that uses a browser form to collect user credentials."""
prefixes = zope.schema.List(
title='Form prefixes',
description='List of prefixes used in different login forms',
value_type=zope.schema.TextLine(
title='Form prefix',
description='Form prefix',
missing_value='',
required=True),
default=[])
loginpagename = zope.schema.TextLine(
title='Loginpagename',
description="""Name of the login form used by challenger.
The form must provide 'login' and 'password' input fields.
""",
default='loginForm.html')
loginfield = zope.schema.TextLine(
title='Loginfield',
description=(
"Field of the login page in which is looked for the login user"
" name."),
default="login")
passwordfield = zope.schema.TextLine(
title='Passwordfield',
description=(
"Field of the login page in which is looked for the password."),
default="password")
class IHTTPBasicAuthCredentialsPlugin(ICredentialsPlugin, IHTTPBasicAuthRealm):
"""BAsic authentication credential plugin."""
class ISessionCredentialsPlugin(ICredentialsPlugin, IBrowserFormChallenger):
"""Session credential plugin."""
class ILoginSchema(zope.interface.Interface):
"""The subscription form."""
login = zope.schema.TextLine(
title=_('Login'),
description=_('Your login name.'),
required=True)
password = zope.schema.Password(
title=_('Password'),
description=_('Your password.'))
# queriable search interfaces
class IQueriableAuthenticator(ISearchable):
"""Indicates the authenticator provides a search UI for principals.""" | z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/interfaces.py | interfaces.py |
"""Principal
"""
import zope.component
import zope.interface
from zope.authentication.interfaces import IAuthentication
from zope.security.interfaces import IPrincipal
from z3c.authenticator import interfaces
class PrincipalBase:
"""Base class for IAuthenticatedPrincipal and IFoundPrincipal principals.
"""
title = None
def __init__(self, principal):
"""We offer no access to the principal object itself."""
self.id = principal.__name__
self.title = principal.title
self.description = principal.description
self.groups = []
@property
def allGroups(self):
"""This method is not used in zope by default, but nice to have it."""
if self.groups:
seen = set()
auth = zope.component.getUtility(IAuthentication)
stack = [iter(self.groups)]
while stack:
try:
group_id = next(stack[-1])
except StopIteration:
stack.pop()
else:
if group_id not in seen:
yield group_id
seen.add(group_id)
group = auth.getPrincipal(group_id)
stack.append(iter(group.groups))
def __repr__(self):
return "<{} {}>".format(self.__class__.__name__, self.id)
@zope.component.adapter(interfaces.IUser)
@zope.interface.implementer(interfaces.IAuthenticatedPrincipal)
class AuthenticatedPrincipal(PrincipalBase):
"""Default IAuthenticatedPrincipal principal."""
@zope.component.adapter(interfaces.IUser)
@zope.interface.implementer(interfaces.IFoundPrincipal)
class FoundPrincipal(PrincipalBase):
"""Default IFoundPrincipal principal."""
@zope.component.adapter(IPrincipal)
@zope.interface.implementer(interfaces.IAuthenticatedPrincipal)
class AuthenticatedPrincipalForPrincipal(PrincipalBase):
"""IAuthenticatedPrincipal principal for IPrincipal."""
@zope.component.adapter(IPrincipal)
@zope.interface.implementer(interfaces.IFoundPrincipal)
class FoundPrincipalForPrincipal(PrincipalBase):
"""IFoundPrincipal principal for IPrincipal."""
@zope.interface.implementer(interfaces.IFoundGroup)
@zope.component.adapter(zope.security.interfaces.IGroup)
class FoundGroup:
def __init__(self, group):
self.id = group.__name__
self._group = group
self.groups = []
@property
def allGroups(self):
if self.groups:
seen = set()
auth = zope.component.getUtility(IAuthentication)
stack = [iter(self.groups)]
while stack:
try:
group_id = stack[-1].next()
except StopIteration:
stack.pop()
else:
if group_id not in seen:
yield group_id
seen.add(group_id)
group = auth.getPrincipal(group_id)
stack.append(iter(group.groups))
@property
def title(self):
return self._group.title
@property
def description(self):
return self._group.description
def __repr__(self):
return "<{} {}>".format(self.__class__.__name__, self.id) | z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/principal.py | principal.py |
"""Principal Source Widget Implementation
"""
import zope.component
import zope.i18n
import zope.interface
import zope.schema
import zope.schema.interfaces
from z3c.form import button
from z3c.form import converter
from z3c.form import field
from z3c.form.browser import text
from z3c.form.browser import widget
from z3c.form.i18n import MessageFactory as _
from z3c.form.interfaces import IFieldWidget
from z3c.form.interfaces import IFormLayer
from z3c.form.interfaces import ISequenceWidget
from z3c.form.interfaces import ITerms
from z3c.form.widget import FieldWidget
from z3c.form.widget import SequenceWidget
from z3c.formui import form
from z3c.template.template import getLayoutTemplate
from zope.authentication.interfaces import IAuthentication
from zope.authentication.interfaces import IPrincipalSource
from zope.traversing import api
from z3c.authenticator import interfaces
class IPrincipalSourceWidget(IFieldWidget):
"""SourceWidget."""
def addValue(value):
"""Add and render value as sequence item."""
class ISourceResultWidget(ISequenceWidget):
"""Search form result widget."""
def addValue(value):
"""Add and render value as sequence item."""
class ISourceSearchForm(zope.interface.Interface):
"""Search schema."""
# TODO: remove this if we have a fixed version of z3c.form
class PrincipalSourceDataConverter(converter.CollectionSequenceDataConverter):
"""A special converter between collections and sequence widgets."""
zope.component.adapts(zope.schema.interfaces.IList, IPrincipalSourceWidget)
def toWidgetValue(self, value):
widget = self.widget
if widget.terms is None:
widget.updateTerms()
return [widget.terms.getTerm(entry).token for entry in value]
def toFieldValue(self, value):
widget = self.widget
# bugfix, avoid to call lenght on terms
# if not widget.terms:
if widget.terms is None:
widget.updateTerms()
collectionType = self.field._type
if isinstance(collectionType, tuple):
collectionType = collectionType[-1]
return collectionType([widget.terms.getValue(token)
for token in value])
# TODO: remove this if we have a fixed version of z3c.form
class SourceSearchDataConverter(converter.CollectionSequenceDataConverter):
"""A special converter between collections and sequence widgets."""
zope.component.adapts(zope.schema.interfaces.IList, ISourceResultWidget)
def toWidgetValue(self, value):
widget = self.widget
if widget.terms is None:
widget.updateTerms()
return [widget.terms.getTerm(entry).token for entry in value]
def toFieldValue(self, value):
widget = self.widget
# bugfix, avoid to call lenght on terms
# if not widget.terms:
if widget.terms is None:
widget.updateTerms()
collectionType = self.field._type
if isinstance(collectionType, tuple):
collectionType = collectionType[-1]
return collectionType([widget.terms.getValue(token)
for token in value])
class PrincipalTerm:
def __init__(self, token, title):
self.token = token
self.title = title
@zope.interface.implementer(ITerms)
@zope.component.adapter(
zope.interface.Interface,
IFormLayer,
zope.interface.Interface,
zope.schema.interfaces.IList,
IPrincipalSourceWidget)
class PrincipalTerms:
def __init__(self, context, request, form, field, widget):
self.context = context
self.request = request
self.form = form
self.field = field
self.widget = widget
self.source = field.value_type.bind(self.context).vocabulary
def getTerm(self, pid):
if pid not in self.source:
raise LookupError(pid)
auth = zope.component.getUtility(IAuthentication)
principal = auth.getPrincipal(pid)
if principal is None:
raise LookupError(pid)
return PrincipalTerm(pid.encode('base64').strip().replace('=', '_'),
principal.title)
def getTermByToken(self, token):
pid = token.replace('_', '=').decode('base64')
return self.getTerm(pid)
def getValue(self, token):
return token.replace('_', '=').decode('base64')
def __contains__(self, pid):
if pid in self.source:
return True
return False
def __iter__(self):
raise NotImplementedError('Source queriable is not iterable.')
def __len__(self):
raise NotImplementedError('Source queriable does not provide lenght.')
class ISearchFormResultsField(zope.schema.interfaces.IList):
"""Search form results field.
Marker for the right widget.
"""
@zope.interface.implementer(ISearchFormResultsField)
class SearchFormResultsField(zope.schema.List):
"""Search form results field."""
@zope.interface.implementer(ISourceResultWidget)
class SourceResultWidget(widget.HTMLInputWidget, SequenceWidget):
"""Knows how to catch the right terms."""
klass = 'search-form-widget checkbox-widget'
searchResults = []
value = []
items = []
def isChecked(self, term):
return term.token in self.value
def addValue(self, value):
term = self.terms.getTerm(value)
checked = self.isChecked(term)
label = zope.i18n.translate(term.title, context=self.request,
default=term.title)
id = '{}-{}'.format(self.id, term.token)
item = {'id': id, 'name': self.name + ':list', 'value': term.token,
'label': label, 'checked': checked}
if item not in self.items:
self.items.append(item)
def updateTerms(self):
self.terms = self.form.terms
return self.terms
def extract(self, default=[]):
"""See z3c.form.interfaces.IWidget."""
tokens = super().extract(default)
for value in self.searchResults:
token = self.terms.getTerm(value).token
if token not in tokens:
tokens.append(token)
return tokens
def update(self):
"""See z3c.form.interfaces.IWidget."""
super().update()
widget.addFieldClass(self)
# update search forms
self.items = []
# append existing items
for token in self.value:
value = self.terms.getValue(token)
self.addValue(value)
def getSourceResultWidget(field, request):
"""IFieldWidget factory for CheckBoxWidget."""
return FieldWidget(field, SourceResultWidget(request))
class SourceSearchWidget(text.TextWidget):
"""Source search widget."""
style = 'border-color: gray; width:100px;'
@property
def label(self):
txt = _('search in: ')
prefix = zope.i18n.translate(txt, context=self.request, default=txt)
return '{}{}'.format(prefix, self.form.title)
@label.setter
def label(self, value):
pass
def getSourceSearchWidget(field, request):
"""IFieldWidget factory for TextWidget."""
return FieldWidget(field, SourceSearchWidget(request))
class ISearchResult(zope.interface.Interface):
"""Search value."""
results = SearchFormResultsField(
title=_('Principals'),
description=_("Principal ids"),
default=[],
required=False
)
# conditions
def hasResults(form):
return bool(form.widgets['search'].value)
@zope.interface.implementer(ISourceSearchForm)
class SearchFormMixin(form.Form):
"""Source Query View search form."""
layout = getLayoutTemplate('subform')
formErrorsMessage = _('Search error')
ignoreContext = True
terms = None
def __init__(self, context, request):
self.context = context
self.request = request
@property
def title(self):
if hasattr(self.context, 'title'):
return self.context.title
return api.getName(self.context)
def search(self, data):
raise NotImplementedError('Subform must implement search')
@button.buttonAndHandler(_('Search'))
def handleSearch(self, action):
"""Set search result"""
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
value = self.search(data)
self.widgets['results'].searchResults = value
self.widgets['results'].update()
@button.buttonAndHandler(_('Add'), condition=hasResults)
def handleAdd(self, action):
"""Set search result"""
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
for value in data.get('results', []):
self.__parent__.addValue(value)
class AuthenticatorSearchForm(SearchFormMixin):
"""Source search form for ISourceSearchCriteria."""
fields = field.Fields(interfaces.ISourceSearchCriteria).select('search')
fields += field.Fields(ISearchResult)
fields['results'].widgetFactory = getSourceResultWidget
fields['search'].widgetFactory = getSourceSearchWidget
def search(self, data):
# avoid empty search strings
value = []
if data.get('search'):
value = self.context.search(data) or []
return value
class PrincipalRegistrySearchForm(SearchFormMixin):
"""Source Query View search form for global PrincipalRegistry."""
fields = field.Fields(interfaces.ISourceSearchCriteria).select('search')
fields += field.Fields(ISearchResult)
fields['results'].widgetFactory = getSourceResultWidget
fields['search'].widgetFactory = getSourceSearchWidget
@property
def title(self):
return 'principals.zcml'
def search(self, data):
# avoid empty search strings
if data.get('search'):
searchStr = data.get('search')
value = [principal.id
for principal in self.context.getPrincipals(searchStr)]
return value
@zope.interface.implementer_only(IPrincipalSourceWidget)
@zope.component.adapter(zope.interface.Interface,
IPrincipalSource, zope.interface.Interface)
class PrincipalSourceWidget(widget.HTMLInputWidget, SequenceWidget):
"""Select widget implementation."""
klass = 'principal-source-widget checkbox-widget'
value = []
items = []
def __init__(self, field, source, request):
self.field = field
self.source = source
self.request = request
def isChecked(self, term):
return term.token in self.value
def addValue(self, value):
term = self.terms.getTerm(value)
checked = self.isChecked(term)
label = zope.i18n.translate(term.title, context=self.request,
default=term.title)
id = '{}-{}'.format(self.id, term.token)
item = {'id': id, 'name': self.name + ':list', 'value': term.token,
'label': label, 'checked': checked}
if item not in self.items:
self.items.append(item)
def update(self):
"""See z3c.form.interfaces.IWidget."""
super().update()
widget.addFieldClass(self)
# update serach forms
self.items = []
self.updateSearchForms()
# append existing items
for token in self.value:
value = self.terms.getValue(token)
self.addValue(value)
def updateSearchForms(self):
queriables = zope.schema.interfaces.ISourceQueriables(
self.source, None)
if queriables is None:
# treat the source itself as a queriable
queriables = ((self.name + '.query', self.source), )
else:
queriables = [
(self.name + '.' +
str(i).encode('base64').strip().replace('=', '_'),
s)
for (i, s) in queriables.getQueriables()]
self.searchForms = []
append = self.searchForms.append
for (name, source) in queriables:
searchForm = zope.component.getMultiAdapter((source, self.request),
ISourceSearchForm)
# ignore views which do not follow the update/render pattern
if hasattr(searchForm, 'update'):
searchForm.prefix = name
searchForm.__parent__ = self
searchForm.__name__ = name
# set the same terms for this form
searchForm.terms = self.terms
searchForm.update()
append(searchForm)
def getSearchForms(self):
return self.searchForms
def getSourceInputWidget(field, request):
"""Sequence IFieldWidget factory for ISource."""
source = field.value_type.vocabulary
widget = zope.component.getMultiAdapter((field, source, request),
IFieldWidget)
return widget | z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/widget.py | widget.py |
=======================
IAuthentication Utility
=======================
The Authenticator package provides a framework for authenticating principals
and associating information with them. It uses plugins and subscribers to get
its work done.
For a simple authentication utility to be used, it should be registered as a
utility providing the `zope.authentication.interfaces.IAuthentication` interface.
Our target is to support a handy IAuthentication utility which offers a simple
API for custom IUser implementations and does not depend on the default
zope.app.authentication implementation.
Security
--------
The Authenticator supports unique id tokens for principals. This means
principal that get deleted and again added with the same id, login etc. do
not have the same id again. We support this by generate a user id token
generated by the host id, timestamp, a random string and the login attribute.
What's different from PluggableAuthentication
---------------------------------------------
We use a different pattern for IAuthenticatorPlugins in this implementation
than used in PluggableAuthentication from zope.app.authentication,
because the pluggable authentication is not very handy when it comes to
implementing custom principal information. The IPrincipalInfo hook supporting
not propagate the password of a IInternalPrincipal is droped in this
implementation.
In our implementation we offer a IFoundPrincipal and IAuthenticatedPrincipal
which are implemented as adapters for a IUser. These adapters do not offer
their context which is the real IUser.
The Authenticator doesn't use a prefix. The usage of a prefix is only
implemented in the IGroupContainer.
We do not use a prefix in the IUserContainer because of the used unique user
id tokens. This will make sure that the same principal id doesn't get used at
a later time (common criteria). There is a ``add`` method which creates
this id for you based on the login. The __setitem__ should not get used
directly for adding IUser instances anymore. We heavily restricted the
usage of this method. See the inline doc tests in __setitem__ for more info.
Authentication
==============
The primary job of Authenticator is to authenticate principals. It uses
two types of plug-ins in its work:
- Credentials Plugins
- Authenticator Plugins
Credentials plugins are responsible for extracting user credentials from a
request. A credentials plugin may in some cases issue a 'challenge' to obtain
credentials. For example, a 'session' credentials plugin reads credentials
from a session (the "extraction"). If it cannot find credentials, it will
redirect the user to a login form in order to provide them (the "challenge").
Authenticator plugins are responsible for authenticating the credentials
extracted by a credentials plugin. They are also typically able to create
principal objects for credentials they successfully authenticate.
Given a request object, the Authenticator returns a principal object, if it
can. The Authenticator utility does this by first iterating through its
credentials plugins to obtain a set of credentials. If it gets credentials, it
iterates through its authenticator plugins to authenticate them.
If an authenticator succeeds in authenticating a set of credentials, the
Authenticator uses the authenticator to create a principal
corresponding to the credentials. The authenticator notifies subscribers if
an authenticated principal is created. Subscribers are responsible for adding
data, especially groups, to the principal. Typically, if a subscriber adds
data, it should also add corresponding interface declarations.
FAQ
---
Here some useful hints:
How should I set permission for principals?
You can apply roles to groups
and apply permissions to roles. Or you can directly apply local permisssions
to groups or to principals. After setting up these mappings you can grant roles to
groups. I always recommend a principal - group and permission - role mapping,
this gives you the most possible abstraction which is useful if it comes
to managing permissions and principals without directly invoking principals and
permissions themselves. But of course you can grant permissions to groups or the
worst thing, directly to principals. Granting permissions to principals is only
useful if it comes to selective local permission settings for selected
principals, e.g. an ownership-like permission setup.
How can I set permissions for all principals?
You can register one
group as IEveryone utility. This IGroup utility get applied to all principals.
Can I apply local groups to unauthenticated principals?
Yes this will work.
Since the last refactoring I refactored the IGroup implementation which makes
it compatible with the principalregistry API. This means you can now register
one local group as an unnamed IUnauthenticatedGroup. You can also register one
local group as an unnamed IAuthenticatedGroup utility which will get applied
to every authenticated principal or an unnamed utility for
IUnauthenticatedGroup.
Can I apply a local group to every principal?
Yes, this is possible if you
register a local unnamed utility providing IEveryoneGroup.
Principal
---------
First we create a principal:
>>> from z3c.authenticator import interfaces
>>> from z3c.authenticator.user import User
>>> login = 'bob'
>>> password = 'secret'
>>> title = 'Bob'
>>> p = User(login, password, title)
Such a principal provides the following attributes be default
>>> p.login
'bob'
>>> p.password.decode('utf-8')
'secret'
>>> p.title
'Bob'
and IUser:
>>> interfaces.IUser.providedBy(p)
True
Authenticator Plugin
--------------------
First set up a UserContainer which will store the principals:
>>> from z3c.authenticator.user import UserContainer
>>> authPlugin = UserContainer()
Now we have a UserContainer that provides an IUserContainer:
>>> interfaces.IUserContainer.providedBy(authPlugin)
True
Now we will add the created principal to the principal container using the
container's ``add`` method:
>>> uid, user = authPlugin.add(p)
The method returns the user id and the user object. The id gets generated
from the host IP address, the time, a random string and the user login attr.
This token should be unique and guaranteed that it will never get generated twice.
This allows us to add, delete and add the same user again without having such a
user inheriting existing permissions. We can test this token by comparing it
only with the __name__ of the object in this test since the token will be
different every test run.
>>> user.__name__ == uid
True
The returned user is still our previous added IUser
>>> user is p
True
>>> len(user.__name__)
32
>>> user.login
'bob'
>>> user.password.decode('utf-8')
'secret'
>>> user.title
'Bob'
Let's register the UserContainer as a named IAuthenticatorPlugin utility:
>>> import zope.component
>>> zope.component.provideUtility(authPlugin,
... provides=interfaces.IAuthenticatorPlugin,
... name='My Authenticator Plugin')
Credentials Plugin
------------------
After seting up the user and user container, we'll create a simple credentials
plugin:
>>> import zope.interface
>>> import zope.component
>>> @zope.interface.implementer(interfaces.ICredentialsPlugin)
... class MyCredentialsPlugin(object):
...
...
... def extractCredentials(self, request):
... return {'login': request.get('login', ''),
... 'password': request.get('password', '')}
...
... def challenge(self, request):
... pass # challenge is a no-op for this plugin
...
... def logout(self, request):
... pass # logout is a no-op for this plugin
As a plugin, MyCredentialsPlugin needs to be registered as a named utility or
it could be stored in the Authenticator attribute credentialsPlugins.
Use the first and register the plugina utility:
>>> myCredentialsPlugin = MyCredentialsPlugin()
>>> zope.component.provideUtility(myCredentialsPlugin,
... name='My Credentials Plugin')
AuthenticatedPrincipal and FoundPrincipal
-----------------------------------------
While authenticator plugins provide users, they are not responsible for
creating principals. This function is performed by the Authenticator:
>>> from z3c.authenticator.principal import AuthenticatedPrincipal
>>> from z3c.authenticator.principal import FoundPrincipal
>>> zope.component.provideAdapter(AuthenticatedPrincipal,
... provides=interfaces.IAuthenticatedPrincipal)
>>> zope.component.provideAdapter(FoundPrincipal,
... provides=interfaces.IFoundPrincipal)
Configuring the Authenticator
-----------------------------
Finally, we'll create the Authenticator itself:
>>> from z3c.authenticator import authentication
>>> auth = authentication.Authenticator()
and configure it with the two plugins:
>>> auth.credentialsPlugins = ('My Credentials Plugin', )
>>> auth.authenticatorPlugins = ('My Authenticator Plugin', )
Authenticate
------------
We can now use the Authenticator to authenticate a sample request:
>>> from zope.publisher.browser import TestRequest
>>> print(auth.authenticate(TestRequest()))
None
In this case, we cannot authenticate an empty request. In the same way, we
will not be able to authenticate a request with the wrong credentials:
>>> request = TestRequest(form={'login': 'let me in!', 'password': 'secret'})
>>> print(auth.authenticate(request))
None
However, if we provide the proper credentials:
>>> request = TestRequest(form={'login': 'bob', 'password': 'secret'})
>>> bob = auth.authenticate(request)
>>> bob
<AuthenticatedPrincipal...>
>>> interfaces.IAuthenticatedPrincipal.providedBy(bob)
True
we get an authenticated principal.
Changing login names
--------------------
Changing the login (i.e. username) of a principal is always a critical task because such a
login together with a password is the key to our implemenation. Let's try to
change the login and check if everything is correct. We can do this by getting the
principal from the UserContainer and changing the login on the IUser
implementation:
>>> internal = authPlugin[bob.id]
>>> internal.login = 'bob2'
Now we should be able to login with the new login:
>>> request = TestRequest(form={'login': 'bob2', 'password': 'secret'})
>>> bob2 = auth.authenticate(request)
>>> bob2
<AuthenticatedPrincipal ...>
>>> bob2.title
'Bob'
But not with the old one:
>>> request = TestRequest(form={'login': 'bob', 'password': 'secret'})
>>> auth.authenticate(request) == None
True
The user bob has still the same id as bob2 since the user id token doesn't
get changed by changing the login:
>>> bob.id == bob2.id
True
Events
------
Authenticating a principal will create events.
>>> from zope.component.eventtesting import getEvents
>>> from zope.component.eventtesting import clearEvents
We can verify that the appropriate event was published:
>>> clearEvents()
>>> request = TestRequest(form={'login': 'bob2', 'password': 'secret'})
>>> bobAgain = auth.authenticate(request)
And the principal attribute in the event provides the authenticated principal:
>>> [event] = getEvents(interfaces.IAuthenticatedPrincipalCreated)
>>> event.principal is bobAgain
True
>>> event.principal
<AuthenticatedPrincipal ...>
>>> event.request is request
True
The principal has the id, title, and description.
>>> event.principal.title
'Bob'
>>> event.principal.id == uid
True
>>> event.principal.description
''
We provide subscribers to these events that can be used for doing custom
processing. Note, the principal attibute provides an IAuthenticatedPrincipal:
>>> def addInfo(event):
... id = event.principal.id
... event.principal.description = 'Description for: %s' % id
>>> zope.component.provideHandler(addInfo,
... [interfaces.IAuthenticatedPrincipalCreated])
Now, if we authenticate a principal, its description is set:
>>> principal = auth.authenticate(request)
>>> principal.description
'Description for: ...'
Customization
-------------
Let's show you how the existing pattern can get used in a real use case. In
the next sample we'd like to provide an additional email attribute for principals.
First we have to define the interfaces declaring the email attribute:
>>> class IMyEmail(zope.interface.Interface):
... email = zope.schema.TextLine(
... title='EMail',
... description='The EMail')
>>> class IMyUser(IMyEmail, interfaces.IUser):
... """Custom IUser interface."""
>>> class IMyFoundPrincipal(IMyEmail, interfaces.IFoundPrincipal):
... """Custom IIMyFoundrincipal interface."""
>>> class IMyAuthenticatedPrincipal(IMyEmail,
... interfaces.IAuthenticatedPrincipal):
... """Custom IAuthenticatedPrincipal interface."""
After the schema, we define a custom principal implementation implementing
this interface:
>>> @zope.interface.implementer(IMyUser)
... class MyUser(User):
... def __init__(self, login, password, title, description, email):
... super(MyUser, self).__init__(login, password, title,
... description)
... self.email = email
Now we have to define the AuthenticatedPrincipal for MyUser:
>>> @zope.interface.implementer(IMyAuthenticatedPrincipal)
... class MyAuthenticatedPrincipal(AuthenticatedPrincipal):
... def __init__(self, principal):
... super(MyAuthenticatedPrincipal, self).__init__(principal)
... self.email = principal.email
And we have to define the FoundPrincipal for MyUser:
>>> @zope.interface.implementer(IMyFoundPrincipal)
... class MyFoundPrincipal(FoundPrincipal):
... def __init__(self, principal):
... super(MyFoundPrincipal, self).__init__(principal)
... self.email = principal.email
Note that you can provide different attributes for the found and authenticated
principals if needed. That's up to you what you like to do with these attributes
later.
Now we need to register our custom authenticated and found principal
adapters:
>>> zope.component.provideAdapter(MyAuthenticatedPrincipal,
... provides=interfaces.IAuthenticatedPrincipal)
>>> zope.component.provideAdapter(MyFoundPrincipal,
... provides=interfaces.IFoundPrincipal)
Now we can use them without any other event subscribers or other registration
in our principal container. Let's add a principal to this container:
>>> p = MyUser('max', 'password', 'Max', '', '[email protected]')
>>> token, max = authPlugin.add(p)
>>> len(token)
32
>>> max.__name__ == token
True
>>> max.password.decode('utf-8')
'password'
>>> max.title
'Max'
>>> max.email
'[email protected]'
Let's try to authenticate...
>>> request = TestRequest(form={'login': 'max', 'password': 'password'})
>>> authenticated = auth.authenticate(request)
and check your authenticated principal:
>>> interfaces.IAuthenticatedPrincipal.providedBy(authenticated)
True
>>> authenticated
<MyAuthenticatedPrincipal ...>
>>> authenticated.id == token
True
>>> authenticated.email
'[email protected]'
Check getUserByLogin:
>>> max = authPlugin.getUserByLogin('max')
>>> max.__class__.__name__
'MyUser'
>>> authPlugin.getUserByLogin('max').login
'max'
>>> authPlugin.getUserByLogin('max').__name__ == token
True
A handy feature for migration is that you can set your own ``token``.
Usually in z.a.authentication the ``token`` == login and we want to keep it
that way, unless you want to iterate through all permissions and whatever.
Note, the __name__ and the id in the container must be the *SAME* object.
>>> login = 'migrateduser'
>>> p = User(login, 'password', 'John')
Preset the ``token``
>>> p.__name__ = login
Watch out, we use __setitem__ instead of add(), because add() would kill off
the preset ``token`` in __name__.
>>> authPlugin[login] = p
Here we are, the user is set with the non-generated token.
>>> 'migrateduser' in authPlugin.keys()
True
>>> authPlugin['migrateduser']
<z3c.authenticator.user.User object at ...>
>>> authPlugin.getUserByLogin('migrateduser')
<z3c.authenticator.user.User object at ...>
Edge cases
----------
We can have Users with text logins, as we allow this with TextLine in IUser.
>>> p = User('bob'+chr(233), 'password', 'title')
Adding it should not fail:
>>> uid, user = authPlugin.add(p)
| z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/README.txt | README.txt |
"""Group Folders
"""
import BTrees.OOBTree
import persistent
import zope.component
import zope.event
import zope.interface
from zope.authentication.interfaces import IAuthenticatedGroup
from zope.authentication.interfaces import IAuthentication
from zope.authentication.interfaces import IEveryoneGroup
from zope.authentication.interfaces import IUnauthenticatedGroup
from zope.authentication.interfaces import IUnauthenticatedPrincipal
from zope.container import btree
from zope.container import contained
from zope.security.interfaces import IGroup
from zope.security.interfaces import IGroupAwarePrincipal
from z3c.authenticator import event
from z3c.authenticator import interfaces
@zope.interface.implementer(interfaces.IGroup)
class Group(persistent.Persistent, contained.Contained):
"""An implementation of IGroup used by the group container."""
_principals = ()
def __init__(self, title='', description=''):
self.title = title
self.description = description
@property
def id(self):
"""Id is the name which includes the container prefix (readonly)."""
return self.__name__
def setPrincipals(self, prinlist, check=True):
# method is not a part of the interface
parent = self.__parent__
old = self._principals
self._principals = tuple(prinlist)
oldset = set(old)
new = set(prinlist)
gid = self.__name__
removed = oldset - new
added = new - oldset
try:
parent._removePrincipalsFromGroup(removed, gid)
except AttributeError:
removed = None
try:
parent._addPrincipalsToGroup(added, gid)
except AttributeError:
added = None
if check:
try:
auth = zope.component.getUtility(IAuthentication)
nocycles(new, [], auth.getPrincipal)
except GroupCycle:
# abort
self.setPrincipals(old, False)
raise
# now that we've gotten past the checks, fire the events.
if removed:
zope.event.notify(
event.PrincipalsRemovedFromGroup(removed, gid))
if added:
zope.event.notify(
event.PrincipalsAddedToGroup(added, gid))
principals = property(lambda self: self._principals, setPrincipals)
def __repr__(self):
return "<{} {}>".format(self.__class__.__name__, self.__name__)
@zope.interface.implementer(interfaces.IGroupContainer)
class GroupContainer(btree.BTreeContainer):
def __init__(self, prefix=''):
self.prefix = prefix
super().__init__()
# __inversemapping is used to map principals to groups
self.__inverseMapping = BTrees.OOBTree.OOBTree()
def __setitem__(self, name, group):
"""Add a IGroup object within a correct id.
Create a GroupContainer
>>> gc = GroupContainer('groups')
Try to add something not providing IGroup
>>> try:
... gc.__setitem__(u'groups.members', object())
... except Exception as e:
... print(e)
Group does not support IGroup!
Create a group and add them with a wrong prefix:
>>> group = Group(u'users')
>>> try:
... gc.__setitem__(u'123', group)
... except Exception as e:
... print(e)
'Wrong prefix used in group id!'
Add a login attr since __setitem__ is in need of one
>>> gc.__setitem__(u'groups.users', group)
"""
# check if we store correct groups
if not interfaces.IGroup.providedBy(group):
raise TypeError('Group does not support IGroup!')
# check if the given id provides the used prefix
if not name.startswith(self.prefix):
raise KeyError('Wrong prefix used in group id!')
super().__setitem__(name, group)
gid = group.__name__
self._addPrincipalsToGroup(group.principals, gid)
if group.principals:
zope.event.notify(
event.PrincipalsAddedToGroup(group.principals, gid))
zope.event.notify(event.GroupAdded(group))
def addGroup(self, id, group):
id = self.prefix + id
self[id] = group
return id, self[id]
def __delitem__(self, gid):
group = self[gid]
self._removePrincipalsFromGroup(group.principals, gid)
if group.principals:
zope.event.notify(
event.PrincipalsRemovedFromGroup(group.principals, gid))
super().__delitem__(gid)
def _addPrincipalsToGroup(self, pids, gid):
for pid in pids:
self.__inverseMapping[pid] = (
self.__inverseMapping.get(pid, ()) + (gid,))
def _removePrincipalsFromGroup(self, pids, gid):
for pid in pids:
groups = self.__inverseMapping.get(pid)
if groups is None:
return
new = tuple([id for id in groups if id != gid])
if new:
self.__inverseMapping[pid] = new
else:
del self.__inverseMapping[pid]
def getGroupsForPrincipal(self, pid):
"""Get groups the given principal belongs to"""
return self.__inverseMapping.get(pid, ())
def getPrincipalsForGroup(self, gid):
"""Get principals which belong to the group"""
return self[gid].principals
def search(self, query, start=None, batch_size=None):
""" Search for groups"""
search = query.get('search')
if search is not None:
n = 0
search = search.lower()
for i, (id, groupinfo) in enumerate(self.items()):
if (search in groupinfo.title.lower() or
(groupinfo.description and
search in groupinfo.description.lower())):
if not ((start is not None and i < start) or
(batch_size is not None and n >= batch_size)):
n += 1
yield id
def authenticateCredentials(self, credentials):
# group container don't authenticate
pass
def queryPrincipal(self, id, default=None):
return self.get(id, default)
class GroupCycle(Exception):
"""There is a cyclic relationship among groups."""
def nocycles(pids, seen, getPrincipal):
for pid in pids:
if pid in seen:
raise GroupCycle(pid, seen)
seen.append(pid)
principal = getPrincipal(pid)
# not every principal has groups and there is no consistent marker
# interface for mark group aware. See IUnauthenticatedPrincipal
groups = getattr(principal, 'groups', ())
nocycles(groups, seen, getPrincipal)
seen.pop()
# specialGroups
@zope.component.adapter(interfaces.IPrincipalCreated)
def specialGroups(event):
"""Set groups for IGroupAwarePrincipal."""
principal = event.principal
# only apply to non groups because it will end in cycle dependencies
# since the principal will have tis role anyway
if (IGroup.providedBy(principal) or
not (IGroupAwarePrincipal.providedBy(principal) or
IUnauthenticatedPrincipal.providedBy(principal))):
return
# global utility registered by everybodyGroup directive
everyone = zope.component.queryUtility(IEveryoneGroup)
if everyone is not None and everyone.id != principal.id and \
everyone.id not in principal.groups:
principal.groups.append(everyone.id)
if IUnauthenticatedPrincipal.providedBy(principal):
# global utility registered by unauthenticatedGroup directive
unAuthGroup = zope.component.queryUtility(IUnauthenticatedGroup)
if unAuthGroup is not None and unAuthGroup.id != principal.id and \
unAuthGroup.id not in principal.groups:
principal.groups.append(unAuthGroup.id)
else:
# global utility registered by authenticatedGroup directive
authGroup = zope.component.queryUtility(IAuthenticatedGroup)
if authGroup is not None and authGroup.id != principal.id and \
authGroup.id not in principal.groups:
principal.groups.append(authGroup.id)
@zope.component.adapter(interfaces.IPrincipalCreated)
def setGroupsForPrincipal(event):
"""Set local group information when a principal is created.
Note: IUnauthenticatedPrincipal does not provide IGroupAwarePrincipal which
is just wrong and makes the conditions a little bit complicated.
"""
principal = event.principal
# set only groups for group aware principals or unauthenticated which are
# group aware too. This allows us to apply local roles to unautenticated
# principals which allows to apply permissions/roles via local groups which
# the application does not provide at global level.
if not (IGroupAwarePrincipal.providedBy(principal) or
IUnauthenticatedPrincipal.providedBy(principal)):
return
authentication = event.authentication
for name, plugin in authentication.getAuthenticatorPlugins():
if not interfaces.IGroupContainer.providedBy(plugin):
continue
# set groups for principals but not a group to itself. This could
# happen for global defined groups
principal.groups.extend(
[id for id in plugin.getGroupsForPrincipal(principal.id)
if id != principal.id]) | z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/group.py | group.py |
"""Users
"""
import random
import socket
import time
from hashlib import md5
import persistent
import zope.component
import zope.interface
from zope.container import btree
from zope.container import contained
from zope.container.interfaces import DuplicateIDError
from zope.password.interfaces import IPasswordManager
from z3c.authenticator import interfaces
# get the IP address only once
try:
ip = socket.getaddrinfo(socket.gethostname(), 0)[-1][-1][0]
except BaseException:
ip = '127.0.0.1'
def generateUserIDToken(id):
"""Generates a unique user id token."""
t = int(time.time() * 1000)
r = int(random.random() * 100000000000000000)
data = "{} {} {} {}".format(ip, t, r, id)
return md5(data.encode('utf-8')).hexdigest()
@zope.interface.implementer(interfaces.IUser)
class User(persistent.Persistent, contained.Contained):
"""User stored in IUserContainer."""
def __init__(self, login, password, title, description='',
passwordManagerName="Plain Text"):
self._login = login
self._passwordManagerName = passwordManagerName
self.password = password
self.title = title
self.description = description
def getPasswordManagerName(self):
return self._passwordManagerName
passwordManagerName = property(getPasswordManagerName)
def _getPasswordManager(self):
return zope.component.getUtility(IPasswordManager,
self.passwordManagerName)
def getPassword(self):
return self._password
def setPassword(self, password, passwordManagerName=None):
if passwordManagerName is not None:
self._passwordManagerName = passwordManagerName
passwordManager = self._getPasswordManager()
self._password = passwordManager.encodePassword(password)
password = property(getPassword, setPassword)
def checkPassword(self, password):
passwordManager = self._getPasswordManager()
return passwordManager.checkPassword(self.password, password)
def getLogin(self):
return self._login
def setLogin(self, login):
oldLogin = self._login
self._login = login
if self.__parent__ is not None:
try:
self.__parent__.notifyLoginChanged(oldLogin, self)
except ValueError:
self._login = oldLogin
raise
login = property(getLogin, setLogin)
@zope.interface.implementer(interfaces.IUserContainer)
class UserContainer(btree.BTreeContainer):
"""A Persistent User Container and authenticator plugin.
See principalfolder.txt for details.
"""
def __init__(self):
super().__init__()
self.__id_by_login = self._newContainerData()
def notifyLoginChanged(self, oldLogin, principal):
"""Notify the Container about changed login of a principal.
We need this, so that our second tree can be kept up-to-date.
"""
# A user with the new login already exists
if principal.login in self.__id_by_login:
raise ValueError('Principal Login already taken!')
del self.__id_by_login[oldLogin]
self.__id_by_login[principal.login] = principal.__name__
def __setitem__(self, id, user):
"""Add a IPrincipal object within a correct id.
Create a UserContainer
>>> mc = UserContainer()
Try to add something not providing IUser
>>> try:
... mc.__setitem__(u'max', object())
... except Exception as e:
... print(e)
Item does not support IUser!
Create a user with no __name__, this should be added via the add
method
>>> user = User(u'max', u'passwd', u'sir')
>>> try:
... mc.__setitem__(u'max', user)
... except Exception as e:
... print(e)
There is no user id token given!
Probably we do have a __name__ during copy/paste, so we have to check
if we get a __parent__ as well
>>> user = User(u'usertoken', u'passwd', u'sir')
>>> user.__name__ = u'usertoken'
>>> user.__parent__ = u'parent'
>>> try:
... mc.__setitem__(u'usertoken', user)
... except Exception as e:
... print(e)
Paste a object is not supported!
Try to use a user with no login:
>>> user = User(u'', u'passwd', u'sir')
>>> user.__name__ = u''
>>> try:
... mc.__setitem__(u'', user)
... except Exception as e:
... print(e)
User does not provide a login value!
Add a login attr since __setitem__ is in need of one
>>> user = User(u'max', u'passwd', u'sir')
>>> user.__name__ = u'max'
>>> mc.__setitem__(u'max', user)
Now try to use the same login:
>>> user2 = User(u'max', u'passwd', u'sir')
>>> user2.__name__ = u'max'
>>> try:
... mc.__setitem__(u'max', user2)
... except Exception as e:
... print(e)
'Login already taken!'
"""
# check if we store correct implementations
if not interfaces.IUser.providedBy(user):
raise TypeError('Item does not support IUser!')
# check if there is a user id given
if user.__name__ != id:
raise ValueError('There is no user id token given!')
# check if there is a user id given in we store correct implementations
if user.__parent__ is not None:
raise ValueError('Paste a object is not supported!')
# The user doesn't provide a login
if not user.login:
raise ValueError('User does not provide a login value!')
# A user with the new login already exists
if user.login in self.__id_by_login:
raise DuplicateIDError('Login already taken!')
super().__setitem__(id, user)
self.__id_by_login[user.login] = id
def add(self, user):
token = generateUserIDToken(user.login)
# Pre set the user id like a ticket, so we can check it in __setitem__
user.__name__ = token
self[token] = user
return token, self[token]
def __delitem__(self, id):
"""Remove principal information."""
user = self[id]
super().__delitem__(id)
del self.__id_by_login[user.login]
def authenticateCredentials(self, credentials):
"""Return principal if credentials can be authenticated
"""
if not isinstance(credentials, dict):
return None
if not ('login' in credentials and 'password' in credentials):
return None
id = self.__id_by_login.get(credentials['login'])
if id is None:
return None
user = self[id]
if not user.checkPassword(credentials["password"]):
return None
return user
def getUserByLogin(self, login):
# don't bother catching KeyError, it's the task of the caller
return self[self.__id_by_login[login]]
def queryPrincipal(self, id, default=None):
user = self.get(id)
if user is not None:
return user
return default
def search(self, query, start=None, batch_size=None):
"""Search through this principal provider."""
search = query.get('search')
if search is None:
return
search = search.lower()
n = 1
for i, value in enumerate(self.values()):
if (search in value.title.lower() or
search in value.description.lower() or
search in value.login.lower()):
if not ((start is not None and i < start)
or (batch_size is not None and n > batch_size)):
n += 1
yield value.__name__ | z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/user.py | user.py |
"""Authentication
"""
import zope.component
import zope.event
import zope.interface
from zope.authentication.interfaces import IAuthentication
from zope.authentication.interfaces import IUnauthenticatedPrincipal
from zope.authentication.interfaces import PrincipalLookupError
from zope.component import queryNextUtility
from zope.container import btree
from zope.location.interfaces import ILocation
from zope.schema.fieldproperty import FieldProperty
from zope.schema.interfaces import ISourceQueriables
from z3c.authenticator import event
from z3c.authenticator import interfaces
@zope.interface.implementer(IAuthentication,
interfaces.IAuthenticator, ISourceQueriables)
class Authenticator(btree.BTreeContainer):
"""See z3c.authentication.interfaces.IAuthenticator."""
authenticatorPlugins = ()
credentialsPlugins = ()
includeNextUtilityForAuthenticate = FieldProperty(
interfaces.IAuthenticator['includeNextUtilityForAuthenticate'])
def _plugins(self, names, interface):
for name in names:
plugin = self.get(name)
if not interface.providedBy(plugin):
plugin = zope.component.queryUtility(interface, name,
context=self)
if plugin is not None:
yield name, plugin
def getAuthenticatorPlugins(self):
return self._plugins(self.authenticatorPlugins,
interfaces.IAuthenticatorPlugin)
def getCredentialsPlugins(self):
return self._plugins(self.credentialsPlugins,
interfaces.ICredentialsPlugin)
def authenticate(self, request):
authenticatorPlugins = [p for n, p in self.getAuthenticatorPlugins()]
for name, credplugin in self.getCredentialsPlugins():
credentials = credplugin.extractCredentials(request)
if credentials is None:
# do not invoke the auth plugin without credentials
continue
for authplugin in authenticatorPlugins:
if authplugin is None:
continue
principal = authplugin.authenticateCredentials(credentials)
if principal is None:
continue
# create authenticated principal
authenticated = interfaces.IAuthenticatedPrincipal(principal)
# send the IAuthenticatedPrincipalCreated event
zope.event.notify(event.AuthenticatedPrincipalCreated(
self, authenticated, request))
return authenticated
if self.includeNextUtilityForAuthenticate:
next = queryNextUtility(self, IAuthentication)
if next is not None:
principal = next.authenticate(request)
if principal is not None:
return principal
return None
def getPrincipal(self, id):
for name, authplugin in self.getAuthenticatorPlugins():
principal = authplugin.queryPrincipal(id)
if principal is None:
continue
# create found principal
found = interfaces.IFoundPrincipal(principal)
# send the IFoundPrincipalCreated event
zope.event.notify(event.FoundPrincipalCreated(self, found))
return found
next = queryNextUtility(self, IAuthentication)
if next is not None:
return next.getPrincipal(id)
raise PrincipalLookupError(id)
def getQueriables(self):
for name, authplugin in self.getAuthenticatorPlugins():
queriable = zope.component.queryMultiAdapter(
(authplugin, self), interfaces.IQueriableAuthenticator)
if queriable is not None:
yield name, queriable
def unauthenticatedPrincipal(self):
"""Return unauthenticated principal or None.
This allows you to return an unauthenticated principal. This could be
usefull if you don't like to fallback to the global unauthenticated
principal usage. Why is this usefull. The reason is, if a global
principal get returned, there is no event notification involved like
we have in IPrincipalCreated which whould allow to apply groups. And
there is no way to apply local groups to global unauthenticated
principals it they get returned by the global IAuthentication or the
fallback implementation. See zope.principalregistry
Usage:
Return an unauthenticated principal within this method if you need to
apply local groups. This allows to apply local groups for the returned
unauthenticated principal if you use a custom subscriber for
IPrincipalCreated. Note, the local group must define the global
unauthenticated principals id in the principals list. Use the zcml
directive called unauthenticatedPrincipal for define the global
unauthenticated principal.
"""
principal = zope.component.queryUtility(IUnauthenticatedPrincipal)
if principal is not None:
zope.event.notify(event.UnauthenticatedPrincipalCreated(self,
principal))
return principal
def unauthorized(self, id, request):
challengeProtocol = None
for name, credplugin in self.getCredentialsPlugins():
protocol = getattr(credplugin, 'challengeProtocol', None)
if challengeProtocol is None or protocol == challengeProtocol:
if credplugin.challenge(request):
if protocol is None:
return
elif challengeProtocol is None:
challengeProtocol = protocol
if challengeProtocol is None:
next = queryNextUtility(self, IAuthentication)
if next is not None:
next.unauthorized(id, request)
def logout(self, request):
challengeProtocol = None
for name, credplugin in self.getCredentialsPlugins():
protocol = getattr(credplugin, 'challengeProtocol', None)
if challengeProtocol is None or protocol == challengeProtocol:
if credplugin.logout(request):
if protocol is None:
return
elif challengeProtocol is None:
challengeProtocol = protocol
if challengeProtocol is None:
next = queryNextUtility(self, IAuthentication)
if next is not None:
next.logout(request)
@zope.component.adapter(interfaces.ISearchable, interfaces.IAuthenticator)
@zope.interface.implementer(interfaces.IQueriableAuthenticator, ILocation)
class QueriableAuthenticator:
"""Performs schema-based principal searches adapting ISearchable and
IAuthenticator.
Delegates the search to the adapted authenticator which also provides
ISearchable. See IAuthenticator.getQueriables for more infos.
"""
def __init__(self, authplugin, pau):
# locate them
if ILocation.providedBy(authplugin):
self.__parent__ = authplugin.__parent__
self.__name__ = authplugin.__name__
else:
self.__parent__ = pau
self.__name__ = ""
self.authplugin = authplugin
self.pau = pau
def search(self, query, start=None, batch_size=None):
yield from self.authplugin.search(query, start, batch_size) | z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/authentication.py | authentication.py |
"""Login Form
"""
import zope.component
from z3c.form import button
from z3c.form import field
from z3c.form.interfaces import IWidgets
from z3c.formui import form
from z3c.template.template import getLayoutTemplate
from z3c.template.template import getPageTemplate
from zope.authentication.interfaces import IAuthentication
from zope.authentication.interfaces import ILogout
from zope.authentication.interfaces import IUnauthenticatedPrincipal
from zope.component import hooks
from zope.publisher.browser import BrowserPage
from zope.session.interfaces import ISession
from zope.traversing.browser import absoluteURL
from z3c.authenticator import interfaces
from z3c.authenticator.interfaces import _
class LoginForm(form.Form):
"""Login form without prefix in form and widget which works with session
credentail plugin out of the box.
"""
template = getPageTemplate()
layout = getLayoutTemplate()
fields = field.Fields(interfaces.ILoginSchema)
nextURL = None
prefix = ''
@property
def message(self):
if IUnauthenticatedPrincipal.providedBy(self.request.principal):
return _('Please provide Login Information')
return ''
def updateWidgets(self):
self.widgets = zope.component.getMultiAdapter(
(self, self.request, self.getContent()), IWidgets)
# the session credential use input fields without prefixes
self.widgets.prefix = ''
self.widgets.ignoreContext = True
self.widgets.ignoreReadonly = True
self.widgets.update()
@button.buttonAndHandler(_('Log-in'))
def handleLogin(self, action):
"""Handle the subscribe action will register and login a user."""
if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
session = ISession(self.request, None)
sessionData = session.get('z3c.authenticator.credential.session')
if sessionData is not None and sessionData.get('camefrom'):
self.nextURL = sessionData['camefrom']
sessionData['camefrom'] = None
def __call__(self):
self.update()
if self.nextURL is not None:
# the redirect method will prevent us to redirect to a 3rd party
# domains since zope.publisher version 3.9.3
self.request.response.redirect(self.nextURL)
return ""
else:
return self.layout()
class SiteLogout(BrowserPage):
def __call__(self):
"""Force logout and avoid to hang around the login form."""
auth = zope.component.getUtility(IAuthentication)
ILogout(auth).logout(self.request)
siteURL = absoluteURL(hooks.getSite(), self.request)
self.request.response.redirect(siteURL + '/loginForm.html') | z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/browser/login.py | login.py |
"""Group Forms
"""
import zope.event
import zope.interface
import zope.lifecycleevent
import zope.schema
from z3c.form import button
from z3c.form import field
from z3c.formui import form
from zope.traversing.browser import absoluteURL
from z3c.authenticator import group
from z3c.authenticator import interfaces
from z3c.authenticator.widget import getSourceInputWidget
# Make z3c.configurator optional.
try:
from z3c.configurator import configurator
except ImportError:
configurator = None
from z3c.authenticator.interfaces import _
class IAddName(zope.interface.Interface):
"""Object name."""
__name__ = zope.schema.TextLine(
title='Object Name',
description='Object Name',
required=True)
# IGroupContainer
class GroupContainerAddForm(form.AddForm):
"""GroupContainer add form."""
label = _('Add Group Container.')
fields = field.Fields(IAddName)
fields += field.Fields(interfaces.IGroupContainer).select(
'prefix')
def createAndAdd(self, data):
obj = group.GroupContainer()
obj.prefix = data.get('prefix', '')
self.contentName = data.get('__name__', '')
zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj))
self.context[self.contentName] = obj
# configure
if configurator is not None:
configurator.configure(obj, data)
return obj
def nextURL(self):
obj = self.context[self.contentName]
return '%s/index.html' % absoluteURL(obj, self.request)
# IGroup
class GroupAddForm(form.AddForm):
"""Group add form."""
label = _('Add Group.')
fields = field.Fields(IAddName)
fields += field.Fields(interfaces.IGroup).select('title', 'description')
def createAndAdd(self, data):
title = data.get('title', '')
description = data.get('description', '')
obj = group.Group(title, description)
name = data.get('__name__', '')
prefix = self.context.prefix
if not name.startswith(prefix):
name = prefix + name
self.contentName = name
zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj))
self.context[self.contentName] = obj
# configure
if configurator is not None:
configurator.configure(obj, data)
return obj
def nextURL(self):
obj = self.context[self.contentName]
return '%s/index.html' % absoluteURL(obj, self.request)
class GroupEditForm(form.EditForm):
"""Group edit form."""
label = _('Edit Group.')
groupCycleErrorMessage = _('There is a cyclic relationship among groups.')
fields = field.Fields(interfaces.IGroup).select('title', 'description',
'principals')
fields['principals'].widgetFactory = getSourceInputWidget
@button.buttonAndHandler(_('Apply'), name='apply')
def handleApply(self, action):
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
try:
changes = self.applyChanges(data)
except group.GroupCycle:
self.status = self.groupCycleErrorMessage
return
if changes:
self.status = self.successMessage
else:
self.status = self.noChangesMessage | z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/browser/group.py | group.py |
"""User Forms
"""
import zope.event
import zope.interface
import zope.lifecycleevent
import zope.schema
from z3c.form import field
from z3c.formui import form
from zope.traversing.browser import absoluteURL
from z3c.authenticator import interfaces
from z3c.authenticator import user
# Make z3c.configurator optional.
try:
from z3c.configurator import configurator
except ImportError:
configurator = None
from z3c.authenticator.interfaces import _
class IAddName(zope.interface.Interface):
"""Object name."""
__name__ = zope.schema.TextLine(
title='Object Name',
description='Object Name',
required=True)
# IUserContainer
class UserContainerAddForm(form.AddForm):
"""UserContainer add form."""
label = _('Add User Container.')
contentName = None
fields = field.Fields(IAddName)
def createAndAdd(self, data):
obj = user.UserContainer()
self.contentName = data.get('__name__', '')
zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj))
self.context[self.contentName] = obj
# configure
if configurator is not None:
configurator.configure(obj, data)
return obj
def nextURL(self):
obj = self.context[self.contentName]
return '%s/index.html' % absoluteURL(obj, self.request)
# IUser
class UserAddForm(form.AddForm):
"""User add form."""
label = _('Add User.')
fields = field.Fields(interfaces.IUser).select(
'login',
'password',
'title',
'description',
'passwordManagerName')
def createAndAdd(self, data):
login = data.get('login', '')
password = data.get('password', '')
title = data.get('title', '')
description = data.get('description', '')
passwordManagerName = data.get('passwordManagerName', '')
obj = user.User(login, password, title, description,
passwordManagerName)
zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj))
self.contentName, usr = self.context.add(obj)
# configure
if configurator is not None:
configurator.configure(obj, data)
return obj
def nextURL(self):
obj = self.context[self.contentName]
return '%s/index.html' % absoluteURL(obj, self.request)
class UserEditForm(form.EditForm):
"""Group edit form."""
label = _('Edit User.')
fields = field.Fields(
interfaces.IUser).select(
'login',
'password',
'title',
'description',
'passwordManagerName') | z3c.authenticator | /z3c.authenticator-2.0-py3-none-any.whl/z3c/authenticator/browser/user.py | user.py |
Login and logout
----------------
Login and logout work both for basic auth and cookie auth.
Setup
~~~~~
The layout page template has to include two content providers (viewlet
mangers):
- ``login-logout-head`` inside the head tag to get automatic
redirects and JavaScript code which does the logout for basic
auth and
- ``login-logout`` inside the body tag to get login and logout links.
The sample template looks like this:
>>> import os.path
>>> template_path = os.path.join(os.path.dirname(__file__), "tests",
... "login-logout-template.pt")
>>> with open(template_path, "r") as t:
... print(t.read())
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
<tal:block replace="structure provider:login-logout-head" />
</head>
<body>
<tal:block replace="structure provider:login-logout" />
<tal:block replace="structure provider:pagelet" />
</body>
</html>
This template is registered for the ``IContainer`` interface in
``ftesting.zcml``. After creating a container the template is
used when browsing the container:
>>> from zope.container.btree import BTreeContainer
>>> layer.getRootFolder()['container'] = BTreeContainer()
Basic auth
~~~~~~~~~~
When the user is not logged in the login link is displayed:
>>> from zope.testbrowser.wsgi import Browser
>>> skinURL = 'http://localhost/++skin++PageletTestSkin/'
>>> wsgi_app = layer.make_wsgi_app()
>>> browser = Browser(wsgi_app=wsgi_app)
>>> browser.handleErrors = False
>>> browser.open(skinURL + 'container/@@default.html')
>>> browser.url
'http://localhost/++skin++PageletTestSkin/container/@@default.html'
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/@@login.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html">Login</a>
</body>
</html>
Selecting the link leads to the login page, as we use basic auth here,
we get an HTTP error 401 (unauthorized):
>>> login_url = browser.getLink('Login').url
>>> browser.raiseHttpErrors = False
>>> browser.getLink('Login').click()
>>> print(browser.headers['status'])
401 Unauthorized
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/@@login.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html
When adding correct credentials we get authorized:
>>> browser.addHeader('Authorization', 'Basic mgr:mgrpw')
>>> browser.open(browser.url)
We are redirected to the page where we selected the login link. After
logging in the login link is no longer displayed. As we did not
specify that logout is supported, no logout link is displayed:
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/@@default.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
</head>
<body>
</body>
</html>
Calling the login URL again leads directly to the page referred in nextURL:
>>> browser.open(login_url)
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/@@default.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
</head>
<body>
</body>
</html>
Calling the login URL again without the query parameter leeds to a
confirmation page telling that login was successfull:
>>> browser.open(login_url.split('?')[0])
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/@@login.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<h1>Login successful!</h1>
<p style="font-size: 200%"> You are now logged in as <em>Manager</em>. </p>
<a href=".">Back to the main page.</a>
</div>
</body>
</html>
Selecting the ``Back to the main page.`` link send the user back to
the default view of the container. (``ftesting.zcml`` defines
``@@default.html`` as the default view.):
>>> browser.getLink('Back to the main page.').click()
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
</head>
<body>
</body>
</html>
Providing an ``ILogoutSupported`` adapter leads to a logout link being
displayed:
>>> import zope.component
>>> import zope.interface
>>> import zope.authentication.logout
>>> import zope.authentication.interfaces
>>> zope.component.provideAdapter(
... zope.authentication.logout.LogoutSupported,
... adapts=[zope.interface.Interface],
... provides=zope.authentication.interfaces.ILogoutSupported)
>>> browser.reload()
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/@@logout.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html">Logout</a>
</body>
</html>
Logout is done using JavaScript and a redirect. zope.testbrowser >= 5.0
does not follow redirects if they use the meta tag.
As testbrowser is not able to execute JavaScript the user remains
authenticated:
>>> logout_url = browser.getLink('Logout').url
>>> browser.getLink('Logout').click()
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/@@logout.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
<script type="text/javascript"><!--
// clear HTTP Authentication
...
//-->
</script>
<meta http-equiv="refresh"
content="0;url=http://localhost/++skin++PageletTestSkin/container/@@default.html" />
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/@@logout.html/@@logout.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40logout.html">Logout</a>
<div>
<h1>You are being redirected!</h1>
<p style="font-size: 150%">
<a href="http://localhost/++skin++PageletTestSkin/container/@@default.html">
If you see this screen for more than 5 seconds, click here.
</a>
</p>
</div>
</body>
</html>
Calling the logout URL again after logout (simulated using a new
browser instance) leads directly to the page referred in nextURL:
>>> browser2 = Browser(logout_url, wsgi_app=wsgi_app)
>>> print(browser2.url)
http://localhost/++skin++PageletTestSkin/container/@@default.html
>>> print(browser2.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/@@login.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html">Login</a>
</body>
</html>
Calling the logout URL again without the query parameter leeds to a
confirmation page telling that logout was successfull:
>>> browser2.open(logout_url.split('?')[0])
>>> print(browser2.url)
http://localhost/++skin++PageletTestSkin/container/@@logout.html
>>> print(browser2.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
<script type="text/javascript"><!--
// clear HTTP Authentication
...
//-->
</script>
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/logout.html/@@login.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40logout.html">Login</a>
<div>
<h1>Logout successful!</h1>
<p style="font-size: 200%">
You are now logged out.
</p>
<a href=".">Back to the main page.</a>
</div>
</body>
</html>
Cookie auth
~~~~~~~~~~~
To do cookie auth we have to set up a pluggable auth utility (PAU)
with a authenticator plug-in (principal folder) first:
>>> from zope.authentication.interfaces import IAuthentication
>>> from zope.pluggableauth.interfaces import IAuthenticatorPlugin
>>> from zope.pluggableauth.authentication import PluggableAuthentication
>>> from zope.pluggableauth.plugins.principalfolder import PrincipalFolder
>>> from zope.site import site
>>> root = layer.getRootFolder()
>>> root['principal_folder'] = PrincipalFolder()
>>> sm = root.getSiteManager()
>>> sm.registerUtility(
... root['principal_folder'], IAuthenticatorPlugin, 'principal_folder')
>>> root['auth'] = PluggableAuthentication()
>>> sm.registerUtility(root['auth'], IAuthentication, '')
>>> root['auth'].credentialsPlugins = (u'Session Credentials',)
>>> root['auth'].authenticatorPlugins = (u'principal_folder',)
We need a principal inside the principal folder:
>>> from zope.pluggableauth.plugins.principalfolder import InternalPrincipal
>>> root['principal_folder']['1'] = InternalPrincipal(
... 'tester', 'tpass', 'Tester')
We use a new browser, so the principal is not logged in and the login
link is displayed:
>>> browser = Browser(wsgi_app=wsgi_app)
>>> browser.open(skinURL + 'container/@@default.html')
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/@@default.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/@@login.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html">Login</a>
</body>
</html>
Selecting the link leads to the login page:
>>> login_url = browser.getLink('Login').url
>>> browser.getLink('Login').click()
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F%2B%2Bskin%2B%2BPageletTestSkin%2Fcontainer%2F%40%40login.html%3FnextURL%3Dhttp%253A%2F%2Flocalhost%2F%252B%252Bskin%252B%252BPageletTestSkin%2Fcontainer%2F%2540%2540default.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<p>
Please provide Login Information
</p>
<form action="" method="post">
<div class="row">
<div class="label"><label for="login">User Name</label></div>
<div class="field">
<input type="text" name="login" id="login" />
</div>
</div>
<div class="row">
<div class="label"><label for="password">Password</label></div>
<div class="field">
<input type="password" name="password" id="password" />
</div>
</div>
<div class="row">
<input class="form-element" type="submit"
name="SUBMIT" value="Log in" />
</div>
<input type="hidden" name="camefrom" value="http://localhost/++skin++PageletTestSkin/container/@@login.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html">
</form>
</div>
</body>
</html>
Entering wrong username does not authorize but display an error
message:
>>> browser.getControl('User Name').value = 'me'
>>> browser.getControl('Password').value = 'tpass'
>>> browser.getControl('Log in').click()
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F%2B%2Bskin%2B%2BPageletTestSkin%2Fcontainer%2F%40%40login.html%3FnextURL%3Dhttp%253A%2F%2Flocalhost%2F%252B%252Bskin%252B%252BPageletTestSkin%2Fcontainer%2F%2540%2540default.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<p>
Please provide Login Information
</p>
<form action="" method="post">
<div class="row">
<div class="label"><label for="login">User Name</label></div>
<div class="field">
<input type="text" name="login" id="login" />
</div>
</div>
<div class="row">
<div class="label"><label for="password">Password</label></div>
<div class="field">
<input type="password" name="password" id="password" />
</div>
</div>
<div class="row">
<input class="form-element" type="submit"
name="SUBMIT" value="Log in" />
</div>
<input type="hidden" name="camefrom" value="http://localhost/++skin++PageletTestSkin/container/@@login.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html">
</form>
</div>
</body>
</html>
Entering wrong password does not authorize either:
>>> browser.getControl('User Name').value = 'tester'
>>> browser.getControl('Password').value = 'let me in'
>>> browser.getControl('Log in').click()
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F%2B%2Bskin%2B%2BPageletTestSkin%2Fcontainer%2F%40%40login.html%3FnextURL%3Dhttp%253A%2F%2Flocalhost%2F%252B%252Bskin%252B%252BPageletTestSkin%2Fcontainer%2F%2540%2540default.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<p>
Please provide Login Information
</p>
<form action="" method="post">
<div class="row">
<div class="label"><label for="login">User Name</label></div>
<div class="field">
<input type="text" name="login" id="login" />
</div>
</div>
<div class="row">
<div class="label"><label for="password">Password</label></div>
<div class="field">
<input type="password" name="password" id="password" />
</div>
</div>
<div class="row">
<input class="form-element" type="submit"
name="SUBMIT" value="Log in" />
</div>
<input type="hidden" name="camefrom" value="http://localhost/++skin++PageletTestSkin/container/@@login.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html">
</form>
</div>
</body>
</html>
After entering a correct username and password the user gets
authorized:
>>> browser.getControl('User Name').value = 'tester'
>>> browser.getControl('Password').value = 'tpass'
>>> browser.getControl('Log in').click()
The user gets redirected to the page where he selected the login
link. After logging in the login link is no longer displayed. As we
already specified that logout is supported, a logout link is
displayed:
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/@@default.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/@@logout.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html">Logout</a>
</body>
</html>
Calling the login URL again leads directly to the page referred in nextURL:
>>> browser.open(login_url)
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/@@default.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/@@logout.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html">Logout</a>
</body>
</html>
Calling the login URL again without the query parameter leeds to a
confirmation page telling that login was successfull:
>>> browser.open(login_url.split('?')[0])
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/@@login.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<h1>Login successful!</h1>
<p style="font-size: 200%"> You are now logged in as <em>Tester</em>. </p>
<a href=".">Back to the main page.</a>
</div>
</body>
</html>
Selecting the ``Back to the main page.`` link send the user back to
the default view of the container. (``ftesting.zcml`` defines
``@@default.html`` as the default view.):
>>> browser.getLink('Back to the main page.').click()
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/@@logout.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html">Logout</a>
</body>
</html>
Selecting the displayed logout link drops authentication information
and displays a confirmation page, which redirects to the default page
where the login link is displayed again:
>>> logout_url = browser.getLink('Logout').url
>>> browser.getLink('Logout').click()
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
<script type="text/javascript"><!--
// clear HTTP Authentication
...
//-->
</script>
<meta http-equiv="refresh"
content="0;url=http://localhost/++skin++PageletTestSkin/container/@@default.html" />
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/@@logout.html/@@logout.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40logout.html">Logout</a>
<div>
<h1>You are being redirected!</h1>
<BLANKLINE>
<p style="font-size: 150%">
<a href="http://localhost/++skin++PageletTestSkin/container/@@default.html">
If you see this screen for more than 5 seconds, click here.
</a>
</p>
</div>
</body>
</html>
>>> browser.getLink('If you see this screen for more than 5 seconds').click()
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/@@login.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html">Login</a>
</body>
</html>
Calling the logout URL again after logout leads directly to the page
referred in nextURL:
>>> browser.open(logout_url)
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/@@default.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/@@login.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40default.html">Login</a>
</body>
</html>
Calling the logout URL again without the query parameter leeds to a
confirmation page telling that logout was successfull:
>>> browser.open(logout_url.split('?')[0])
>>> print(browser.url)
http://localhost/++skin++PageletTestSkin/container/@@logout.html
>>> print(browser.contents)
<!DOCTYPE ...>
<html ...>
<head>
<title>PageletTest</title>
<script type="text/javascript"><!--
// clear HTTP Authentication
...
//-->
</script>
</head>
<body>
<a href="http://localhost/++skin++PageletTestSkin/container/logout.html/@@login.html?nextURL=http%3A//localhost/%2B%2Bskin%2B%2BPageletTestSkin/container/%40%40logout.html">Login</a>
<div>
<h1>Logout successful!</h1>
<p style="font-size: 200%">
You are now logged out.
</p>
<a href=".">Back to the main page.</a>
</div>
</body>
</html>
If the parameter ``camefrom`` is used twice, only the first one is actually
used:
>>> browser.open('http://localhost/++skin++PageletTestSkin/@@loginForm.html?camefrom=first-url&camefrom=second-url')
>>> print(browser.contents)
<!DOCTYPE ...>
...
<div class="row">
<input class="form-element" type="submit" name="SUBMIT" value="Log in" />
</div>
<input type="hidden" name="camefrom" value="first-url">
</form>
</div>
</body>
</html>
>>> 'second-url' in browser.contents
False
| z3c.authviewlet | /z3c.authviewlet-2.0.tar.gz/z3c.authviewlet-2.0/src/z3c/authviewlet/README.txt | README.txt |
"""Login and logout viewlets."""
import urllib.parse
import z3c.pagelet.interfaces
import zope.authentication.interfaces
import zope.component
import zope.i18n
import zope.i18nmessageid
import zope.interface
import zope.viewlet.interfaces
import zope.viewlet.manager
import zope.viewlet.viewlet
import z3c.authviewlet.interfaces
_ = zope.i18nmessageid.MessageFactory("z3c")
class ILoginLogoutHeadViewletManager(zope.viewlet.interfaces.IViewletManager):
"""ViewletManager for supporting header contents (e. g. JavaScript)."""
LoginLogoutHeadViewletManager = zope.viewlet.manager.ViewletManager(
'login-logout-head', ILoginLogoutHeadViewletManager)
class ILoginLogoutViewletManager(zope.viewlet.interfaces.IViewletManager):
"""ViewletManager for login and logout viewlets."""
LoginLogoutViewletManager = zope.viewlet.manager.ViewletManager(
'login-logout', ILoginLogoutViewletManager,
bases=(zope.viewlet.manager.ConditionalViewletManager,))
def authenticated(principal):
"Tell whether the principal is authenticated."
unauthenticated = zope.authentication.interfaces.IUnauthenticatedPrincipal
return not unauthenticated.providedBy(principal)
def logout_supported(request):
"Tell whether logout is supported."
logout = zope.authentication.interfaces.ILogoutSupported(request, None)
return logout is not None
def get_view_url(context, request, view_name):
"Compute the url of a view."
if view_name.startswith('@@'):
view_name = view_name[2:]
view_name_truncated = True
else:
view_name_truncated = False
view = zope.component.getMultiAdapter((context, request), name=view_name)
view_url = zope.component.getMultiAdapter(
(view, request), name='absolute_url')()
if view_name_truncated:
view_url = view_url.replace(view_name, '@@' + view_name)
return view_url
def render_pagelet(context, request, view_name):
"Render a pagelet."
pagelet = zope.component.getMultiAdapter(
(context, request), z3c.pagelet.interfaces.IPagelet, name=view_name)
return pagelet()
class LoginViewlet(zope.viewlet.viewlet.ViewletBase):
"""Display login link when user is not logged in."""
@property
def available(self):
return not authenticated(self.request.principal)
def render(self):
return '<a href="{}?nextURL={}">{}</a>'.format(
get_view_url(self.context, self.request, self.viewName),
urllib.parse.quote(self.request.getURL()),
zope.i18n.translate(_('[Login]', default='Login'),
domain='z3c', context=self.request))
class LogoutViewlet(zope.viewlet.viewlet.ViewletBase):
"""Display logout link when user is logged in and logout is supported."""
@property
def available(self):
return (
authenticated(self.request.principal)
and
logout_supported(self.request))
def render(self):
return '<a href="{}?nextURL={}">{}</a>'.format(
get_view_url(self. context, self.request, self.viewName),
urllib.parse.quote(self.request.getURL()),
zope.i18n.translate(_('[Logout]', default='Logout'),
domain='z3c',
context=self.request))
@zope.interface.implementer(z3c.authviewlet.interfaces.ILogin)
class HTTPAuthenticationLogin:
def login(self, nextURL=None):
# we don't want to keep challenging if we're authenticated
if not authenticated(self.request.principal):
auth = zope.component.getUtility(
zope.authentication.interfaces.IAuthentication)
auth.unauthorized(
self.request.principal.id, self.request)
return render_pagelet(self, self.request, 'login_failed.html')
else:
if nextURL is None:
return render_pagelet(self, self.request, 'login_success.html')
else:
self.request.response.redirect(nextURL)
class LoginFailedPagelet:
"Pagelet to display login failed notice."
class LoginSuccessfulPagelet:
"Pagelet to display login succecc notice."
@zope.interface.implementer(zope.authentication.interfaces.ILogout)
class HTTPAuthenticationLogout:
"""Since HTTP Authentication really does not know about logout, we are
simply challenging the client again."""
def logout(self, nextURL=None):
if authenticated(self.request.principal):
auth = zope.component.getUtility(
zope.authentication.interfaces.IAuthentication)
zope.authentication.interfaces.ILogout(auth).logout(self.request)
if nextURL:
return render_pagelet(self, self.request, 'redirect.html')
if nextURL is None:
return render_pagelet(self, self.request, 'logout_success.html')
else:
return self.request.response.redirect(nextURL)
class LogoutRedirectPagelet:
"Pagelet to display logout redirect."
class LogoutSuccessPagelet:
"Pagelet to display logout success." | z3c.authviewlet | /z3c.authviewlet-2.0.tar.gz/z3c.authviewlet-2.0/src/z3c/authviewlet/auth.py | auth.py |
Changes
=======
1.0 (2023-03-01)
----------------
Breaking changes:
- Drop support for Python 2.7, 3.5, 3.6.
New features:
- Add support for Python 3.9, 3.10, 3.11.
0.4.1 (2020-11-12)
------------------
Bug fixes:
- zc.buildout is not an install dependency, only used in testing.
0.4.0 (2020-04-21)
------------------
Breaking changes:
- Drop support for Python 3.4.
New features:
- When environment variable ``Z3C_AUTOINCLUDE_DEBUG`` is set,
log which packages are being automatically included.
Do this in a form that you can copy to a ``configure.zcml`` file.
- Add support for Python 3.8.
0.3.9 (2019-03-02)
------------------
Bug fixes:
- Catch and ignore AttributeError for ``module.__file__``.
Fixes `issue 6 <https://github.com/zopefoundation/z3c.autoinclude/issues/6>`_.
[maurits]
0.3.8 (2018-11-04)
------------------
New features:
- Add support for Python 3.6 and 3.7.
Bug fixes:
- Fix the ``includePlugins`` directive to read filenames
as native strings in Python 3.
0.3.7 (2016-08-24)
------------------
- Add support for Python 3.4, Python 3.5 and PyPy.
- When choosing between multiple (equivalent) packages that offer the
same namespace and there are no namespace-only packages, choose
either the one whose project name matches the namespace (if there
are no dots in the namespace), or the first when sorted by project
name. Previously, the first in the list generated from the
combination of iterating ``sys.path`` and asking ``pkg_resources``
for distributions was picked. This should increase test
repeatability but is not expected to be otherwise noticeable. See
`PR 3 <https://github.com/zopefoundation/z3c.autoinclude/pull/3>`_
for discussion.
0.3.6 (2016-01-29)
------------------
- Standardize namespace __init__.
- Fix broken tests.
0.3.5 (2013-09-12)
------------------
* If a module cannot be resolved, but raises ``ImportError``, log a
warn and continue. This fixes an issue where the determining the
includable packages would fail due to a problem with the importation
of one or potentially more modules. An example is the ``gobject``
module which provides a Python binding to ``GObject``. In a recent
API deprecation, one is no longer allowed to both import ``gi`` and
``gobject``.
0.3.4 (2011-03-11)
------------------
* Remove unnecessary distribution lookup in the PluginFinder.
0.3.3 (2010-05-06)
------------------
* Ignore case in tests in order to pass tests on Windows.
* Clearly specify license as ZPL (not public domain, as it was
claiming before).
0.3.2 (2009-12-19)
------------------
* Let ``subpackageDottedNames`` always return a sorted list of package names as
``os.listdir`` doesn't on some platforms.
0.3.1 (2009-05-04)
------------------
* z3c.autoinclude no longer (spuriously) depends on PasteScript.
0.3 (2009-03-03)
----------------
* Allow virtual namespace packages like 'plone' to be specified for the
package. I think this may need more thought for the dependency case.
* Allow ZCML ``includePlugins`` directive to specify a particular ZCML file to
try to load from plugins, so that loading of meta, configure and overrides
can be split across three ZCML files if desired. You can specify a file like:
<includePlugins package="." file="silly.zcml" />.
* Provide a separate ``includePluginsOverrides`` directive to be used when
loading overrides, and no longer look for 'overrides.zcml' files by default
with ``includePlugins``.
* Removed the deprecated ``autoinclude`` and ``autoincludeOverrides``
directives.
* `Allow autoinclusion to be disabled <http://lists.plone.org/pipermail/plone-framework-team/2009-February/005938.html>`_ by setting
``os.environ['Z3C_AUTOINCLUDE_PLUGINS_DISABLED']`` and
``os.environ['Z3C_AUTOINCLUDE_DEPENDENCIES_DISABLED']``, potentially useful for
test runners or debugging sessions.
For context on many of these changes, see `the PLIP #247 discussion <http://lists.plone.org/pipermail/plone-framework-team/2009-January/005823.html>`_.
0.2.2 (2008-04-22)
------------------
* Gracefully catch KeyErrors in ``namespaceForDottedName``; get_metadata_lines
will sometimes throw this for certain distribution types, apparently. In
particular, some systems' version of Python itself will be wrapped in a
distribution which throws this error, resulting in system-dependent
unresumable breakage of z3c.autoinclude prior to this fix.
0.2.1 (2008-04-21)
------------------
* Fixed bug which prevented proper inclusion of packages when the base
package's namespace has been extended by other installed packages.
* Rewrote ``distributionForPackage`` function.
* Added additional tests for ``includePlugins`` and utility functions.
* Fixed bug which made z3c.autoinclude look for ZCML in namespaces of nested
namespace packages (eg, if there happened to -- improperly -- be an
x/y/configure.zcml in a x.y.z package with an x.y namespace, it would have
been included; this is incorrect.)
0.2 (2008-04-18)
----------------
* Added new directive ``includePlugins``.
* Renamed ``autoinclude`` directive to ``includeDependencies``.
* Deprecated ``autoinclude`` directive.
0.1 (2008-02-25)
----------------
* Initial public release.
| z3c.autoinclude | /z3c.autoinclude-1.0.tar.gz/z3c.autoinclude-1.0/CHANGES.rst | CHANGES.rst |
Overview
========
This package adds two new ZCML directives to automatically detect
ZCML files to include: "includeDependencies" and "includePlugins".
When you want to include a Zope-based package in your application, you
have to repeat yourself in two places: you have to add the package
itself (in a setup.py, buildout, etc) and you also have to include its
ZCML with an <include> directive or a package-includes slug. Because
you have to repeat yourself, you can easily make an error where you
add a new package but forget to include its ZCML.
z3c.autoinclude lets you circumvent this error-prone process with
automatic detection and inclusion of ZCML files.
includeDependencies
-------------------
The "includeDependencies" directive searches through the dependencies
in your setup.py file (install_requires), and includes the ZCML files
in those packages that it finds. Inclusion order matches the order in
the setup.py file. You can pass a path for the package you want to
include dependencies for, but typically you pass in the current
package, as follows::
<includeDependencies package="." />
With this directive, you no longer have to add an explicit ``<include
package=new.dependency>`` for every new dependency of your project.
Grok_ and grokproject_ use this functionality out of the box. The
grokproject command will automatically add the ``includeDependencies``
directive in the ZCML of the project it generates. You can then stop
worrying about manual ZCML inclusion in the vast majority of cases.
includePlugins
--------------
The "includePlugins" directive uses entry points to find installed
packages that broadcast themselves as plugins to a particular base
package. You can pass a path for the package you want to include
plugins for, but typically you pass in the current package, as
follows::
<includePlugins package="." />
To broadcast a package as a plugin to a base package called "my_base",
add the following lines to the plugin package's ``setup.py``::
entry_points="""
[z3c.autoinclude.plugin]
target = my_base
"""
The Details
===========
Setup
-----
To make the z3c.autoinclude directives available for use in your
application or framework, you need to include it (in your
``meta.zcml`` for instance), like this::
<include package="z3c.autoinclude" file="meta.zcml" />
Grok already does this for you automatically.
Disabling z3c.autoinclude
-------------------------
It is often useful to disable z3c.autoinclude's functionality for
debugging purposes or test runs. To disable autoinclusion, set
the environment variables "Z3C_AUTOINCLUDE_DEPENDENCIES_DISABLED" and
"Z3C_AUTOINCLUDE_PLUGINS_DISABLED".
When autoinclusion is disabled, the autoinclusion directives will
issue a warning to the log and do nothing.
When environment variable "Z3C_AUTOINCLUDE_DEBUG" is set,
we log which packages are being automatically included.
We do this in a form that you can copy to a configure.zcml file.
ZCML Filenames
--------------
The includeDependencies directive automatically includes
``configure.zcml`` and ``meta.zcml`` files that live in the main
package directories. For automatic inclusion of dependencies'
overrides, there is an <includeDependenciesOverrides> directive.
In some cases, a package may use unusual names or
locations for its ZCML files. In that case you will need to modify
your package's ``configure.zcml`` and ``meta.zcml`` yourself to
include the ZCML using the manual ``include`` directive.
The includePlugins directive automatically includes ``configure.zcml``
and ``meta.zcml`` files by default, and the includePluginsOverrides
directive automatically includes ``overrides.zcml`` files by default.
But, like "<include>", these directives also have an optional "file"
parameter, so you can automatically include all ``foo.zcml`` files in
your package's plugins like this::
<includePlugins package="." file="foo.zcml" />
The includeDependencies directives will soon offer this option as well.
.. _Grok: http://grok.zope.org
.. _grokproject: http://pypi.python.org/pypi/grokproject
| z3c.autoinclude | /z3c.autoinclude-1.0.tar.gz/z3c.autoinclude-1.0/README.rst | README.rst |
in no particular order, some notes on things that I think ought to happen to this code:
* Profiling. As far as I know, none has been done, and I expect that the code is *very* slow. Then, obviously, optimizations should be considered.
* Documentation. It's still fairly poor; I think the whole damn thing is just so abstract that I can't figure out how to talk about it.
* May as well figure out how to make a PasteScript template to auto-generate the entry point.
* Better debugging tools/APIs: to see what will be autoincluded, turn on and off autoinclusion for individual packages, and freeze a ZCML file capturing autoinclusion information a la pip.
One day I also want to add another directive to autoinclude subpackages' ZCML; this is a frequent annoyance for me (see https://svn.openplans.org/svn/opencore/trunk/opencore/configuration/configure.zcml for an illustrative example)
| z3c.autoinclude | /z3c.autoinclude-1.0.tar.gz/z3c.autoinclude-1.0/TODO.rst | TODO.rst |
Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| z3c.autoinclude | /z3c.autoinclude-1.0.tar.gz/z3c.autoinclude-1.0/LICENSE.rst | LICENSE.rst |
import logging
from zope.configuration.fields import GlobalObject
from zope.configuration.xmlconfig import include
from zope.configuration.xmlconfig import includeOverrides
from zope.dottedname.resolve import resolve
from zope.interface import Interface
from zope.schema import NativeStringLine
from z3c.autoinclude import api
from z3c.autoinclude.dependency import DependencyFinder
from z3c.autoinclude.plugin import PluginFinder
from z3c.autoinclude.utils import distributionForPackage
log = logging.getLogger("z3c.autoinclude")
def includeZCMLGroup(_context, info, filename, override=False):
includable_zcml = info[filename]
# ^^ a key error would mean that we are trying to include a group of ZCML
# with a filename that wasn't ever searched for. that *should* be an error
zcml_context = repr(_context.info)
for dotted_name in includable_zcml:
log.debug(
'including file %s from package %s at %s',
filename,
dotted_name,
zcml_context,
)
for dotted_name in includable_zcml:
includable_package = resolve(dotted_name)
if override:
includeOverrides(_context, filename, includable_package)
else:
include(_context, filename, includable_package)
class IIncludeDependenciesDirective(Interface):
"""Auto-include any ZCML in the dependencies of this package."""
package = GlobalObject(
title="Package to auto-include for",
description="""
Auto-include all dependencies of this package.
""",
required=True,
)
def includeDependenciesDirective(_context, package):
if api.dependencies_disabled():
log.warn(
'z3c.autoinclude.dependency is disabled but is being invoked by %s'
% _context.info
)
return
dist = distributionForPackage(package)
info = DependencyFinder(dist).includableInfo(
['configure.zcml', 'meta.zcml'])
includeZCMLGroup(_context, info, 'meta.zcml')
includeZCMLGroup(_context, info, 'configure.zcml')
def includeDependenciesOverridesDirective(_context, package):
if api.dependencies_disabled():
log.warn(
'z3c.autoinclude.dependency is disabled but is being invoked by %s'
% _context.info
)
return
dist = distributionForPackage(package)
info = DependencyFinder(dist).includableInfo(['overrides.zcml'])
includeZCMLGroup(_context, info, 'overrides.zcml', override=True)
class IIncludePluginsDirective(Interface):
"""Auto-include any ZCML in the dependencies of this package."""
package = GlobalObject(
title="Package to auto-include for",
description="""
Auto-include all plugins to this package.
""",
required=True,
)
file = NativeStringLine(
title="ZCML filename to look for",
description="""
Name of a particular ZCML file to look for.
If omitted, autoinclude will scan for standard filenames
(e.g. meta.zcml, configure.zcml, overrides.zcml)
""",
required=False,
)
def includePluginsDirective(_context, package, file=None):
if api.plugins_disabled():
log.warn(
'z3c.autoinclude.plugin is disabled but is being invoked by %s'
% _context.info
)
return
dotted_name = package.__name__
if file is None:
zcml_to_look_for = ['meta.zcml', 'configure.zcml']
else:
zcml_to_look_for = [file]
info = PluginFinder(dotted_name).includableInfo(zcml_to_look_for)
for filename in zcml_to_look_for:
includeZCMLGroup(_context, info, filename)
def includePluginsOverridesDirective(_context, package, file=None):
if api.plugins_disabled():
log.warn(
'z3c.autoinclude.plugin is disabled but is being invoked by %s'
% _context.info
)
return
dotted_name = package.__name__
if file is None:
zcml_to_look_for = ['overrides.zcml']
else:
zcml_to_look_for = [file]
info = PluginFinder(dotted_name).includableInfo(zcml_to_look_for)
for filename in zcml_to_look_for:
includeZCMLGroup(_context, info, filename, override=True) | z3c.autoinclude | /z3c.autoinclude-1.0.tar.gz/z3c.autoinclude-1.0/src/z3c/autoinclude/zcml.py | zcml.py |
import logging
import os
from pkg_resources import iter_entry_points
from pkg_resources import resource_filename
from z3c.autoinclude.api import debug_enabled
from z3c.autoinclude.utils import DistributionManager
from z3c.autoinclude.utils import ZCMLInfo
from z3c.autoinclude.utils import create_report
logger = logging.getLogger("z3c.autoinclude")
class PluginFinder:
def __init__(self, platform_dottedname):
self.dottedname = platform_dottedname
def includableInfo(self, zcml_to_look_for):
includable_info = ZCMLInfo(zcml_to_look_for)
for plugin_distribution in find_plugins(self.dottedname):
include_finder = DistributionManager(plugin_distribution)
for plugin_dottedname in include_finder.dottedNames():
groups = zcml_to_include(plugin_dottedname, zcml_to_look_for)
for zcml_group in groups:
includable_info[zcml_group].append(plugin_dottedname)
if debug_enabled():
report = create_report(includable_info)
if "overrides.zcml" in zcml_to_look_for:
report.insert(
0, "includePluginsOverrides found in zcml of %s." %
self.dottedname)
else:
report.insert(
0, "includePlugins found in zcml of %s." %
self.dottedname)
logger.info("\n".join(report))
return includable_info
def find_plugins(dotted_name):
for ep in iter_entry_points('z3c.autoinclude.plugin'):
if ep.module_name == dotted_name:
yield ep.dist
def zcml_to_include(dotted_name, zcmlgroups=None):
if zcmlgroups is None:
zcmlgroups = ('meta.zcml', 'configure.zcml', 'overrides.zcml')
includable_info = []
for zcmlgroup in zcmlgroups:
filename = resource_filename(dotted_name, zcmlgroup)
if os.path.isfile(filename):
includable_info.append(zcmlgroup)
return includable_info | z3c.autoinclude | /z3c.autoinclude-1.0.tar.gz/z3c.autoinclude-1.0/src/z3c/autoinclude/plugin.py | plugin.py |
import os
import sys
from distutils.util import convert_path
from pprint import pformat
from pkg_resources import find_distributions
class DistributionManager:
def __init__(self, dist):
self.context = dist
def namespaceDottedNames(self):
"""Return dotted names of all namespace packages in distribution.
"""
return namespaceDottedNames(self.context)
def dottedNames(self):
"""Return dotted names of all relevant packages in a distribution.
Relevant packages are those packages that are directly under the
namespace packages in the distribution, but not the namespace packages
themselves. If no namespace packages exist, return those packages that
are directly in the distribution.
"""
dist_path = self.context.location
ns_dottednames = self.namespaceDottedNames()
if not ns_dottednames:
return subpackageDottedNames(dist_path)
result = []
for ns_dottedname in ns_dottednames:
path = os.path.join(dist_path, *ns_dottedname.split('.'))
subpackages = subpackageDottedNames(path, ns_dottedname)
for subpackage in subpackages:
if subpackage not in ns_dottednames:
result.append(subpackage)
return result
class ZCMLInfo(dict):
def __init__(self, zcml_to_look_for):
dict.__init__(self)
for zcml_group in zcml_to_look_for:
self[zcml_group] = []
def __bool__(self):
return any(self.values())
def subpackageDottedNames(package_path, ns_dottedname=None):
# we do not look for subpackages in zipped eggs
if not isUnzippedEgg(package_path):
return []
result = []
for subpackage_name in os.listdir(package_path):
full_path = os.path.join(package_path, subpackage_name)
if isPythonPackage(full_path):
if ns_dottedname:
result.append('{}.{}'.format(ns_dottedname, subpackage_name))
else:
result.append(subpackage_name)
return sorted(result)
def isPythonPackage(path):
if not os.path.isdir(path):
return False
for init_variant in ['__init__.py', '__init__.pyc', '__init__.pyo']:
if os.path.isfile(os.path.join(path, init_variant)):
return True
return False
def distributionForPackage(package):
package_dottedname = package.__name__
return distributionForDottedName(package_dottedname)
def distributionForDottedName(package_dottedname):
"""
This function is ugly and probably slow. It needs to be heavily
commented, it needs narrative doctests, it needs some broad
explanation, and it is arbitrary in some namespace cases.
Then it needs to be profiled.
"""
valid_dists_for_package = []
for path in sys.path:
dists = find_distributions(path, True)
for dist in dists:
if not isUnzippedEgg(dist.location):
continue
packages = find_packages(dist.location)
ns_packages = namespaceDottedNames(dist)
# if package_dottedname in ns_packages:
# continue
if package_dottedname not in packages:
continue
valid_dists_for_package.append((dist, ns_packages))
if len(valid_dists_for_package) == 0:
raise LookupError(
"No distributions found for package `%s`;"
" are you sure it is importable?" % package_dottedname)
if len(valid_dists_for_package) > 1:
non_namespaced_dists = [
(dist, ns_packages)
for dist, ns_packages in valid_dists_for_package
if len(ns_packages) == 0
]
if len(non_namespaced_dists) == 0:
# if we only have namespace packages at this point, 'foo.bar' and
# 'foo.baz', while looking for 'foo', we can just select the first
# because the choice has no effect. However, if possible, we prefer
# to select the one that matches the package name if it's the
# "root" namespace
if '.' not in package_dottedname:
for dist, _ in valid_dists_for_package:
if dist.project_name == package_dottedname:
return dist
# Otherwise, to be deterministic (because the order depends on both
# sys.path and `find_distributions`) we will sort them by
# project_name and return the first value.
valid_dists_for_package.sort(
key=lambda dist_ns: dist_ns[0].project_name)
return valid_dists_for_package[0][0]
# if we have packages 'foo', 'foo.bar', and 'foo.baz', the correct one
# is 'foo'.
valid_dists_for_package = (non_namespaced_dists)
# we really are in trouble if we get into a situation with more than
# one non-namespaced package at this point.
error_msg = '''
Multiple distributions were found that claim to provide the `%s` package. This
is most likely because one or more of them uses `%s` as a namespace package,
but forgot to declare it in the `namespace_packages` section of its `setup.py`.
Please make any necessary adjustments and reinstall the modified
distribution(s).
Distributions found: %s
'''
assert len(non_namespaced_dists) == 1, error_msg % (
package_dottedname,
package_dottedname,
pformat(non_namespaced_dists),
)
return valid_dists_for_package[0][0]
def namespaceDottedNames(dist):
"""
Return a list of dotted names of all namespace packages in a distribution.
"""
try:
ns_dottednames = list(
dist.get_metadata_lines('namespace_packages.txt'))
except OSError:
ns_dottednames = []
except KeyError:
ns_dottednames = []
return ns_dottednames
def isUnzippedEgg(path):
"""
Check whether a filesystem path points to an unzipped egg; z3c.autoinclude
does not support zipped eggs or python libraries that are not packaged as
eggs. This function can be called on e.g. entries in sys.path or the
location of a distribution object.
"""
return os.path.isdir(path)
# cargo-culted from setuptools 0.6c9's __init__.py;
# importing setuptools is unsafe, but i can't find any
# way to get the information that find_packages provides
# using pkg_resources and i can't figure out a way to
# avoid needing it.
def find_packages(where='.', exclude=()):
"""Return a list all Python packages found within directory 'where'
'where' should be supplied as a "cross-platform" (i.e. URL-style) path; it
will be converted to the appropriate local path syntax. 'exclude' is a
sequence of package names to exclude; '*' can be used as a wildcard in the
names, such that 'foo.*' will exclude all subpackages of 'foo' (but not
'foo' itself).
"""
out = []
stack = [(convert_path(where), '')]
while stack:
where, prefix = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where, name)
if (
'.' not in name
and os.path.isdir(fn)
and os.path.isfile(os.path.join(fn, '__init__.py'))
):
out.append(prefix + name)
stack.append((fn, prefix + name + '.'))
for pat in list(exclude) + ['ez_setup']:
from fnmatch import fnmatchcase
out = [item for item in out if not fnmatchcase(item, pat)]
return out
def create_report(info):
"""Create a report with a list of auto included zcml."""
if not info:
# Return a comment. Maybe someone wants to automatically include this
# in a zcml file, so make it a proper xml comment.
return ["<!-- No zcml files found to include. -->"]
report = []
# Try to report meta.zcml first.
filenames = list(info)
meta = "meta.zcml"
if meta in filenames:
filenames.remove(meta)
filenames.insert(0, meta)
for filename in filenames:
dotted_names = info[filename]
for dotted_name in dotted_names:
if filename == "overrides.zcml":
line = ' <includeOverrides package="{}" file="{}" />'.format(
dotted_name, filename)
elif filename == "configure.zcml":
line = ' <include package="%s" />' % dotted_name
else:
line = ' <include package="{}" file="{}" />'.format(
dotted_name, filename)
report.append(line)
return report | z3c.autoinclude | /z3c.autoinclude-1.0.tar.gz/z3c.autoinclude-1.0/src/z3c/autoinclude/utils.py | utils.py |
import logging
import os
from pkg_resources import get_distribution
from pkg_resources import get_provider
from zope.dottedname.resolve import resolve
from z3c.autoinclude.api import debug_enabled
from z3c.autoinclude.utils import DistributionManager
from z3c.autoinclude.utils import ZCMLInfo
from z3c.autoinclude.utils import create_report
logger = logging.getLogger("z3c.autoinclude")
class DependencyFinder(DistributionManager):
def includableInfo(self, zcml_to_look_for):
"""Return the packages in the dependencies which are includable.
zcml_to_look_for - a list of zcml filenames we are looking for
Returns a dictionary with the include candidates as keys, and lists
of dotted names of packages that contain the include candidates as
values.
"""
result = ZCMLInfo(zcml_to_look_for)
for req in self.context.requires():
dist_manager = DistributionManager(get_provider(req))
for dotted_name in dist_manager.dottedNames():
try:
module = resolve(dotted_name)
except ImportError as exc:
logger.warning(
"resolve(%r) raised import error: %s" %
(dotted_name, exc))
continue
module_file = getattr(module, '__file__', None)
if module_file is None:
logger.warning(
"%r has no __file__ attribute" %
dotted_name)
continue
for candidate in zcml_to_look_for:
candidate_path = os.path.join(
os.path.dirname(module_file), candidate
)
if os.path.isfile(candidate_path):
result[candidate].append(dotted_name)
if debug_enabled():
report = create_report(result)
if "overrides.zcml" in zcml_to_look_for:
report.insert(
0, "includeDependenciesOverrides found in zcml of %s." %
self.context.project_name)
else:
report.insert(
0, "includeDependencies found in zcml of %s." %
self.context.project_name)
logger.info("\n".join(report))
return result
def package_includes(project_name, zcml_filenames=None):
"""
Convenience function for finding zcml to load from requirements for
a given project. Takes a project name. DistributionNotFound errors
will be raised for uninstalled projects.
"""
if zcml_filenames is None:
zcml_filenames = ['meta.zcml', 'configure.zcml', 'overrides.zcml']
dist = get_distribution(project_name)
include_finder = DependencyFinder(dist)
return include_finder.includableInfo(zcml_filenames) | z3c.autoinclude | /z3c.autoinclude-1.0.tar.gz/z3c.autoinclude-1.0/src/z3c/autoinclude/dependency.py | dependency.py |
=========
CHANGES
=========
3.0 (2023-02-09)
================
- Drop support for Python 2.7, 3.4, 3.5, 3.6.
- Add support for Python 3.8, 3.9, 3.10, 3.11.
- Make tests compatible with ``zope.component >= 5``.
2.2.0 (2018-10-19)
==================
- Add support for Python 3.7.
- Drop support for Python 3.3.
2.1.0 (2017-05-03)
==================
- Add support for Python 3.4, 3.5, 3.6 and PyPy.
- Remove test dependency on ``zope.app.testing`` and
``zope.app.zcmlfiles``, among others.
2.0.0 (2012-11-17)
==================
- zope.configuration changed action tuples to action dicts. This version works
with the new action dict given from zope.configuration since version 3.8.0.
This version is not compatible with zope.configuration version less then
3.8.0
1.3.0 (2010-10-28)
==================
- Fundamental change in the way how baseregistry hooks into ZCA.
Now it uses hooks.setSite, which requires that zope.component hooks
are in place. Usually they are installed by zope.app.appsetup.
Unless you use zope.app.appsetup, install the hooks with
zope.component.hooks.setHooks().
This applies to zope.component versions >= 3.9.4.
1.2.0 (2009-12-27)
==================
- Moved browser dependencies to zmi extras
1.1.0 (2009-03-19)
==================
- Fix base registry management form failure in case, when a site has its
parent's local site manager (that isn't registered as utility) in its
__bases__.
- Use zope.site instead of zope.app.component.
- Drop unused dependencies on zope.app.i18n and zope.app.pagetemplate.
1.0.0 (2008-01-24)
==================
- Initial Release
| z3c.baseregistry | /z3c.baseregistry-3.0.tar.gz/z3c.baseregistry-3.0/CHANGES.rst | CHANGES.rst |
===============
Base Components
===============
The purpose of this package is to define, populate and use multiple
``IComponents`` instances using filesystem-based development -- in other
words, Python code and ZCML.
Motivation
----------
The current state of the component architecture allows us to
1. create a global components registry, populate it using ZCML, and use it
via the ``zope.component`` API functions.
2. define local sites (local components registries), populate them with local
(persistent) components, and use them selectively based on location --
commonly defined by the path of the URL.
Unfortunately, it is impossible to populate local sites with ZCML. The main
reason is the lack of addressability of local sites during the initial startup
process.
However, on the other hand we have a very advanced UI configuration system
that involves views, resources, layers and skins. So let's compare the two.
1. Views/Resources in the UI are like registered components in the component
architecture.
2. Skin Layers in the UI behave very much like registries. The default skin
is like the global base registry. Skins, like local sites, are activated
during traversal, but can be populated using ZCML.
3. Layers are really base layers to the skin layer. The equivalent in the
component architecture is to specify bases for a components registry,
which is possible since the Great Component Architecture refactoring for
Zope 3.3 in 2006.
But layers can be defined and configured via ZCML. The purpose of this package
is to be able to create base components registries and then populate them
using ZCML. (As a side note: As skin layers and layers are practically the
same components, there is no difference between the concept of global, local
and base components registries.)
The second feature is specific to the Zope application server. It provides an
UI to set the bases on a local site manager. The user can select among all
registries that have been registered as ``IComponents`` utilities.
There are also a few options that could be considered in the future. For
example, it would be simple to integrate the ``zope:registerIn`` directive
(see below for documentation) into the ``zope:configure`` directive.
If the above text is too dry and theoretical for you, here is the
summary. This package
1. implements Steve Alexander's long dream (at least 3 years) of defining
local sites via ZCML.
2. solves all of my (Stephan Richter) problems I am having with a complex
Application Service Provider (ASP) setup.
3. implements a missing feature that you and everyone else really wanted,
even if you did not know it yet.
Thanks goes to Jim Fulton, whose outstanding design of the
``zope.configuration`` and ``zope.component`` packages made the implementation
of the feature such a breeze. I also want to thank Fred Drake for helping with
the initial design ideas.
"Base Components" Registries
----------------------------
Base registries are global component registries implementing the
``IComponents`` interface. In comparison to the base global registry (also
known as ``globalSiteManager``), these registries are not necessarily
available via module globals and *must* be registered with a parent registry,
most commonly the base global registry:
>>> from z3c.baseregistry import baseregistry
>>> import zope.component
>>> myRegistry = baseregistry.BaseComponents(
... zope.component.globalSiteManager, 'myRegistry')
>>> myRegistry
<BaseComponents myRegistry>
Another *VERY IMPORTANT* requirement is that ``zope.component`` hooks are in
place. Install the hooks now:
>>> import zope.component.hooks
>>> zope.component.hooks.setHooks()
Since this registry does not implement any of the ``IComponents`` API itself,
it is not necessary to demonstrate those features here. Please see the
corresponding documentation in the ``zope.component`` package.
One feature of global registries must be that they pickle efficiently, since
they can be referenced in persisted objects. As you can see, the base registry
pickles quite well:
>>> import pickle
>>> jar = pickle.dumps(myRegistry, 2)
>>> len(jar) <= 100
True
However, when reading the jar, we get an error:
>>> pickle.loads(jar)
Traceback (most recent call last):
...
zope.interface.interfaces.ComponentLookupError: (<InterfaceClass zope.interface.interfaces.IComponents>, 'myRegistry')
This is because we have not registered the registry in its parent as an
``IComponents`` utility, yet:
>>> from zope.interface.interfaces import IComponents
>>> zope.component.provideUtility(myRegistry, IComponents, 'myRegistry')
>>> pickle.loads(jar)
<BaseComponents myRegistry>
Thus it is very important that you *always* register your base registry with
its parent!
Like any other components registry, a base registry can also have bases:
>>> myOtherRegistry = baseregistry.BaseComponents(
... zope.component.globalSiteManager, 'myRegistry', (myRegistry,))
>>> myOtherRegistry.__bases__
(<BaseComponents myRegistry>,)
Let's now have a look at how base registries can be defined and used
via ZCML, which is the usual mode of operation.
Defining Base Registries
------------------------
The above tasks are more commonly done in ZCML. Base components registries --
or any ``IComponents`` implementation for that matter -- can be seen as
utilities providing the aforementioned interface and are distinguishable by
name. So let's define a "custom" registry:
>>> custom = baseregistry.BaseComponents(
... zope.component.globalSiteManager, 'custom')
Let's make sure that the parent of the custom registry is the base registry:
>>> custom.__parent__
<BaseGlobalComponents base>
The registry is then registered using the standard utility directive. After
loading the meta directives for this package,
>>> from zope.configuration import xmlconfig
>>> from zope.configuration.config import ConfigurationConflictError
>>> context = xmlconfig.string('''
... <configure i18n_domain="zope">
... <include package="z3c.baseregistry" file="meta.zcml" />
... <include package="zope.component" file="meta.zcml" />
... </configure>
... ''')
we can register the registry:
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope">
...
... <utility
... component="README.custom"
... provides="zope.interface.interfaces.IComponents"
... name="custom" />
...
... </configure>
... ''', context=context)
The new registry can now be accessed as follows:
>>> custom = zope.component.getUtility(IComponents, name='custom')
>>> custom
<BaseComponents custom>
Populating Different Registries
-------------------------------
Now to the interesting part. Let's register components for both the global
base and the "custom" registry. Let's first create some utilities we can
register:
>>> import zope.interface
>>> class IExample(zope.interface.Interface):
... name = zope.interface.Attribute('Name of Example')
>>> @zope.interface.implementer(IExample)
... class Example(object):
... def __init__(self, name):
... self.name = name
... def __repr__(self):
... return '<%s %r>' %(self.__class__.__name__, self.name)
>>> example1 = Example('example1')
>>> example2 = Example('example2')
Create some adapters we can register:
>>> class IToAdapt1(zope.interface.Interface):
... pass
>>> class IToAdapt2(zope.interface.Interface):
... pass
>>> class IAdapted(zope.interface.Interface):
... pass
>>> @zope.component.adapter(IToAdapt1)
... @zope.interface.implementer(IAdapted)
... def adapter1(context):
... return "adapted1"
>>> @zope.component.adapter(IToAdapt2)
... @zope.interface.implementer(IAdapted)
... def adapter2(context):
... return "adapted2"
>>> @zope.interface.implementer(IToAdapt1)
... class ToAdapt1(object):
... def __init__(self, name):
... self.name = name
... def __repr__(self):
... return '<%s %r>' %(self.__class__.__name__, self.name)
>>> toAdapt1 = ToAdapt1('toAdapt1')
>>> @zope.interface.implementer(IToAdapt2)
... class ToAdapt2(object):
... def __init__(self, name):
... self.name = name
... def __repr__(self):
... return '<%s %r>' %(self.__class__.__name__, self.name)
>>> toAdapt2 = ToAdapt2('toAdapt2')
Let' now register "example1", adapter1 in the global registry
and "example2", "adapter2" in our custom registry:
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope">
...
... <utility component="README.example1"
... name="example1" />
... <adapter
... factory="README.adapter1"
... name="adapter1"/>
...
... <registerIn registry="README.custom">
... <utility component="README.example2"
... name="example2" />
... <adapter
... factory="README.adapter2"
... name="adapter2"/>
... </registerIn>
...
... </configure>
... ''', context=context)
Let's now make sure that the utilities have been registered in the right
registry:
>>> zope.component.getUtility(IExample, name="example1")
<Example 'example1'>
>>> zope.component.getUtility(IExample, name="example2")
Traceback (most recent call last):
...
zope.interface.interfaces.ComponentLookupError: (<InterfaceClass README.IExample>, 'example2')
Let's now make sure that the adapters have been registered in the right
registry:
>>> zope.component.getAdapter(toAdapt1, IAdapted, name="adapter1")
'adapted1'
>>> zope.component.getAdapter(toAdapt2, IAdapted, name="adapter2")
Traceback (most recent call last):
...
zope.interface.interfaces.ComponentLookupError: (<ToAdapt2 'toAdapt2'>, <InterfaceClass README.IAdapted>, 'adapter2')
>>> custom = zope.component.getUtility(IComponents, name='custom')
>>> custom.getUtility(IExample, name="example1")
Traceback (most recent call last):
...
zope.interface.interfaces.ComponentLookupError: (<InterfaceClass README.IExample>, 'example1')
>>> custom.getUtility(IExample, name="example2")
<Example 'example2'>
>>> custom.getAdapter(toAdapt1, IAdapted, name="adapter1")
Traceback (most recent call last):
...
zope.interface.interfaces.ComponentLookupError: (<ToAdapt1 'toAdapt1'>, <InterfaceClass README.IAdapted>, 'adapter1')
>>> custom.getAdapter(toAdapt2, IAdapted, name="adapter2")
'adapted2'
Let's now register other instances of the ``Example`` class without a
name. This should *not* cause a conflict error:
>>> example3 = Example('example3')
>>> example4 = Example('example4')
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope">
...
... <utility component="README.example3" />
...
... <registerIn registry="README.custom">
... <utility component="README.example4" />
... </registerIn>
...
... </configure>
... ''', context=context)
>>> zope.component.getUtility(IExample)
<Example 'example3'>
>>> custom.getUtility(IExample)
<Example 'example4'>
Using Base Registries
---------------------
Most commonly base registries will be used in local site managers. So let's
create a local site:
>>> from zope.site.folder import Folder
>>> site = Folder()
>>> from zope.site.site import LocalSiteManager
>>> site.setSiteManager(LocalSiteManager(site))
>>> sm = site.getSiteManager()
Initially only the base global registry is a base of the local site manager:
>>> sm.__bases__
(<BaseGlobalComponents base>,)
Now only registrations from the base site are available:
>>> sm.getUtility(IExample)
<Example 'example3'>
>>> sm.getUtility(IExample, name="example1")
<Example 'example1'>
>>> sm.getUtility(IExample, name="example2")
Traceback (most recent call last):
...
zope.interface.interfaces.ComponentLookupError: (<InterfaceClass README.IExample>, 'example2')
>>> sm.getAdapter(toAdapt1, IAdapted, name="adapter1")
'adapted1'
>>> sm.getAdapter(toAdapt2, IAdapted, name="adapter2")
Traceback (most recent call last):
...
zope.interface.interfaces.ComponentLookupError: (<ToAdapt2 'toAdapt2'>, <InterfaceClass README.IAdapted>, 'adapter2')
But if we add the "custom" registry, then things look more interesting:
>>> sm.__bases__ += (custom,)
>>> sm.__bases__
(<BaseGlobalComponents base>, <BaseComponents custom>)
>>> sm.getUtility(IExample)
<Example 'example3'>
>>> sm.getUtility(IExample, name="example1")
<Example 'example1'>
>>> sm.getUtility(IExample, name="example2")
<Example 'example2'>
>>> sm.getAdapter(toAdapt1, IAdapted, name="adapter1")
'adapted1'
>>> sm.getAdapter(toAdapt2, IAdapted, name="adapter2")
'adapted2'
But where is the registration for example 4? Well, the order of the bases
matters, like the order of base classes in Python matters. The bases run from
must specific to most generic. Thus, if we reverse the order,
>>> bases = list(sm.__bases__)
>>> bases.reverse()
>>> sm.__bases__ = bases
>>> sm.__bases__
(<BaseComponents custom>, <BaseGlobalComponents base>)
then our "custom" registry effectively overrides the global one:
>>> sm.getUtility(IExample)
<Example 'example4'>
>>> sm.getUtility(IExample, name="example1")
<Example 'example1'>
>>> sm.getUtility(IExample, name="example2")
<Example 'example2'>
Edge Cases and Food for Thought
-------------------------------
Duplicate Registrations
~~~~~~~~~~~~~~~~~~~~~~~
Like before, duplicate registrations are detected and reported:
>>> try:
... xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope">
...
... <registerIn registry="README.custom">
... <utility component="README.example3" name="default" />
... <utility component="README.example4" name="default" />
... </registerIn>
...
... </configure>
... ''', context=context)
... except ConfigurationConflictError as e:
... print(e)
Conflicting configuration actions
For: (<BaseComponents custom>, ('utility', <InterfaceClass README.IExample>, ...'default'))
...
But as we have seen before, no duplication error is raised, if the same
registration is made for different sites:
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope">
...
... <utility component="README.example3" name="default" />
...
... <registerIn registry="README.custom">
... <utility component="README.example4" name="default" />
... </registerIn>
...
... </configure>
... ''', context=context)
Overriding ZCML
~~~~~~~~~~~~~~~
Overriding should behave as usual. If I define something within a particular
site, then it should be only overridable in that site.
In the following example, ``base-overrides.zcml`` overrides only the global
registration of the following snippet to "example3":
>>> context.includepath = ('base.zcml', 'original.zcml')
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope">
...
... <utility component="README.example1" />
...
... <registerIn registry="README.custom">
... <utility component="README.example2" />
... </registerIn>
...
... </configure>
... ''', context=context, execute=False)
>>> context.includepath = ('base.zcml',)
>>> context = xmlconfig.string('''
... <includeOverrides package="z3c.baseregistry.tests"
... file="base-overrides.zcml" />
... ''', context=context)
>>> zope.component.getUtility(IExample)
<Example 'example3'>
>>> custom.getUtility(IExample)
<Example 'example2'>
In the next example, ``custom-overrides.zcml`` overrides only the custom
registration of the following snippet to "example3":
>>> context.includepath = ('base.zcml', 'original.zcml')
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope">
...
... <utility component="README.example1" />
...
... <registerIn registry="README.custom">
... <utility component="README.example4" />
... </registerIn>
...
... </configure>
... ''', context=context, execute=False)
>>> context.includepath = ('base.zcml',)
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope">
...
... <includeOverrides package="z3c.baseregistry.tests"
... file="custom-overrides.zcml" />
...
... </configure>
... ''', context=context)
>>> zope.component.getUtility(IExample)
<Example 'example1'>
>>> custom.getUtility(IExample)
<Example 'example3'>
Note: Sorry for the convoluted test sequence; this is just how it works. :-(
Nested Registry Usage
~~~~~~~~~~~~~~~~~~~~~
I thought about this one for a long time, but I think it is better not
allowing to nest ``zope:registerIn`` directives, because the logic of
manipulating the discriminator would be very complex for very little added
benefit.
>>> try:
... xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope">
...
... <registerIn registry="README.custom">
... <registerIn registry="zope.component.globalregistry.base">
... <utility component="README.example4" />
... </registerIn>
... </registerIn>
...
... </configure>
... ''', context=context)
... except Exception as e:
... print(e)
Nested ``registerIn`` directives are not permitted.
File...
Cleanup
~~~~~~~
Just unregister the ``zope.component`` hooks:
>>> zope.component.hooks.resetHooks()
Global Non-Component-Registration Actions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ZCML is not only responsible for populating the components registries, but also
to do other global configuration, such as defining security and assigning
interfaces to classes. On the other hand, the ``registerIn`` directive works
by manipulating the discriminator by prefixing it with the current
registry. While I assert that this is the right approach for component
registrations, it does not work for those other global configurations.
In order to address the issue, I need somehow more information. A balance must
be struck between the need to change existing directives and making the
solution non-monolithic. Here are some design ideas:
1. A Special Discriminator Prefix
All directives that globally manipulate the state of the system and do not
register a component have as their first discriminator entry a special
string, like "StateChange". The directive can then look for those entries and
not change the discriminator at this point.
Advantages include the ability to use those directives inside the
``registerIn`` directive and allow gradual upgrading. In the other hand, util
directives are adjusted, conflict resolution will not be available for those
scenarios.
2. A Registry of Global Action Callables
Here this package provides a registry of callables that change the state of
the system. Directive authors can then subscribe their callables to this
registry.
The big advantage of this approach is that you can make it work now for all
built-in directives without changing any implementation. The disadvantage is
that the solution hides the problem to directive authors, so that detailed
documentation must be provided to ensure integrity and avoid
surprises. Another disadvantage is the complexity of yet another registry.
3. Autodetection with False-Positives
As far as I can tell, all actions that manipulate the components registries
use the ``zope.component.zcml.handler`` function. Okay, so that allows me to
detect those. Unfortunately, there might be directives that do *not*
manipulate the state, for example ensuring the existence of something. There
are a bunch of those directives in the core.
The advantage here is that for the core it should just work. However, 3rd
party directive developers might be tripped by this feature. Also, we could
only issue warnings with this solution and probably need to be able to turn
them off.
I have not implemented any of those suggestions, waiting for input from the
community.
| z3c.baseregistry | /z3c.baseregistry-3.0.tar.gz/z3c.baseregistry-3.0/src/z3c/baseregistry/README.rst | README.rst |
__docformat__ = "reStructuredText"
import zope.component.globalregistry
import zope.component.hooks
import zope.configuration.config
import zope.configuration.fields
import zope.interface
from zope.configuration.exceptions import ConfigurationError
class IRegisterInDirective(zope.interface.Interface):
"""Use the specified registry for registering the contained components."""
registry = zope.configuration.fields.GlobalObject(
title="Registry",
description="Python path to the registry to use.",
required=True)
class ActionsProxy:
"""A proxy object for the actions list to decorate the incoming actions."""
original = None
registry = None
def __init__(self, original, registry):
self.original = original
self.registry = registry
def __decorate(self, action):
# handle action dict
# (was a tuple before 2.0, see zope.configuration 3.8 for changes)
# discriminator is a tuple like:
# ('utility',
# <InterfaceClass zope.component.interfaces.IFactory>,
# 'my.package.interfaces.IMyInterface')
# in the sample above this means we need to prepend our registry
# to the existing discriminator.
discriminator = action.get('discriminator', None)
if discriminator is not None:
# replace the first part from the existing descriminator tuple
# with our registry
action['discriminator'] = (self.registry, discriminator)
return action
def __setitem__(self, i, item):
if isinstance(i, slice):
item = [self.__decorate(x) for x in item]
else:
item = self.__decorate(item)
self.original.__setitem__(i, item)
def __iadd__(self, other):
other = [self.__decorate(item) for item in other]
self.original.__iadd__(other)
def append(self, item):
self.original.append(self.__decorate(item))
def insert(self, i, item):
self.original.insert(i, self.__decorate(item))
def extend(self, other):
other = [self.__decorate(item) for item in other]
self.original.extend(other)
def __len__(self):
return len(self.original)
def __getattr__(self, name):
return getattr(self.original, name)
class FakeBaseRegistrySite:
"""This a minimal fake Site, the only responsibility it has
is to store our registry as a SiteManager and return it later.
This is needed to fool siteinfo via setSite, zope.component.zcml.handler
will grab the registry via zope.component.getSiteManager() then."""
def __init__(self, sm):
self.sm = sm
def getSiteManager(self):
return self.sm
def setActiveRegistry(context, registry):
context.original = zope.component.hooks.getSite()
fakeSite = FakeBaseRegistrySite(registry)
zope.component.hooks.setSite(fakeSite)
def resetOriginalRegistry(context):
zope.component.hooks.setSite(context.original)
class RegisterIn(zope.configuration.config.GroupingContextDecorator):
# Marker that this directive has been used in the path
registryChanged = True
# Storage for the original site
original = None
def __init__(self, context, registry, **kw):
if hasattr(context, 'registryChanged') and context.registryChanged:
raise ConfigurationError(
'Nested ``registerIn`` directives are not permitted.')
super().__init__(context, **kw)
self.registry = registry
self.actions = ActionsProxy(context.actions, registry)
def before(self):
self.context.action(
discriminator=None,
callable=setActiveRegistry,
args=(self, self.registry)
)
def after(self):
self.context.action(
discriminator=None,
callable=resetOriginalRegistry,
args=(self,)
) | z3c.baseregistry | /z3c.baseregistry-3.0.tar.gz/z3c.baseregistry-3.0/src/z3c/baseregistry/zcml.py | zcml.py |
=================================
Setting Named Registries as Bases
=================================
While setting up named registries and filling them in ZCML is interesting in
itself, those features alone will not bring much, unless you can hook up those
named registries to local sites.
This is accomplished by setting the bases. Let's take our root folder, for
example. By default, only the global base registry is registered as a site. If
you have a quick look at ``ftesting.zcml``, you will notice that only
"example2" is available as named utility and "example1" as the unnamed one.
By setting the root folder site as the current site, we can simulate the
behavior of calling from within the root folder:
>>> import zope.component
>>> from zope.component import hooks
>>> hooks.setHooks()
>>> site = getRootFolder()
>>> hooks.setSite(site)
>>> site.getSiteManager().__bases__
(<BaseGlobalComponents base>,)
>>> zope.component.getUtility(IExample)
<Example 'example1'>
>>> zope.component.getUtility(IExample, name="example2")
<Example 'example2'>
>>> zope.component.getUtility(IExample, name="example4")
Traceback (most recent call last):
...
zope.interface.interfaces.ComponentLookupError: (<InterfaceClass z3c.baseregistry.browser.tests.IExample>, 'example4')
Let's now add the "custom" registry to the site as a base. After logging in ..
>>> from zope.testbrowser.wsgi import Browser
>>> manager = Browser()
>>> manager.handleErrors = False
>>> manager.addHeader('Authorization', 'Basic mgr:mgrpw')
>>> manager.open('http://localhost/manage')
you enter the site management area and then click on the "Bases" tab:
>>> manager.getLink('Manage Site').click()
>>> manager.getLink('Bases').click()
Let' now add the "custom" registry:
>>> addBasesSelection(manager, ['-- Global Base Registry --', 'custom'])
>>> manager.getControl('Apply').click()
Now, "example4" should be available, but "example3" is overridden by
"example1".
>>> site = getRootFolder()
>>> hooks.setSite(site)
>>> site.getSiteManager().__bases__
(<BaseGlobalComponents base>, <BaseComponents custom>)
>>> zope.component.getUtility(IExample)
<Example 'example1'>
>>> zope.component.getUtility(IExample, name="example2")
<Example 'example2'>
>>> zope.component.getUtility(IExample, name="example4")
<Example 'example4'>
However, if we change the order of the bases (starting from a fresh state),
>>> manager.open('http://localhost/manage')
>>> manager.getLink('Manage Site').click()
>>> manager.getLink('Bases').click()
>>> addBasesSelection(manager, ['custom', '-- Global Base Registry --'])
>>> manager.getControl('Apply').click()
then "custom" registry overrides entries from the global base registry:
>>> site = getRootFolder()
>>> hooks.setSite(site)
>>> site.getSiteManager().__bases__
(<BaseComponents custom>, <BaseGlobalComponents base>)
>>> zope.component.getUtility(IExample)
<Example 'example3'>
>>> zope.component.getUtility(IExample, name="example2")
<Example 'example2'>
>>> zope.component.getUtility(IExample, name="example4")
<Example 'example4'>
We can return to our original state:
>>> manager.open('http://localhost/manage')
>>> manager.getLink('Manage Site').click()
>>> manager.getLink('Bases').click()
>>> addBasesSelection(manager, ['-- Global Base Registry --'])
>>> manager.getControl('Apply').click()
>>> site.getSiteManager().__bases__
(<BaseGlobalComponents base>,)
>>> hooks.setSite(None)
| z3c.baseregistry | /z3c.baseregistry-3.0.tar.gz/z3c.baseregistry-3.0/src/z3c/baseregistry/browser/README.rst | README.rst |
from z3c.batching.batch import Batch
from z3c.batching.batch import Batches
class EmptyBatch(Batch):
def __init__(self, length, start, size, batches):
self.update(length, start, size)
self.batches = batches
def __eq__(self, other):
return ((self.size, self.start, self._length) ==
(other.size, other.start, other._length))
@property
def firstElement(self):
raise ValueError("EmptyBatch holds no item")
@property
def lastElement(self):
raise ValueError("EmptyBatch holds no item")
def __getitem__(self, key):
raise ValueError("EmptyBatch holds no item")
def __iter__(self):
raise ValueError("EmptyBatch holds no item")
class SubsetBatches(Batches):
def __init__(self, batch):
super().__init__(batch)
self.length = batch._length
def __getitem__(self, key):
if isinstance(key, slice):
return self.__getslice__(*key.indices(self.total))
if key not in self._batches:
if key < 0:
key = self.total + key
batch = EmptyBatch(
self.length, key * self.size, self.size, self)
self._batches[batch.index] = batch
try:
return self._batches[key]
except KeyError:
raise IndexError(key)
class SubsetBatch(Batch):
def __init__(self, sequence, length, start=0, size=20, batches=None):
self.sequence = sequence
self.update(length, start, size)
self.updateBatches(batches)
def updateBatches(self, batches):
if batches is None:
batches = SubsetBatches(self)
self.batches = batches
@property
def firstElement(self):
"""See interfaces.IBatch"""
return self.sequence[0]
@property
def lastElement(self):
"""See interfaces.IBatch"""
return self.sequence[-1]
def __getitem__(self, key):
"""See zope.interface.common.sequence.IMinimalSequence"""
if isinstance(key, slice):
return self.__getslice__(*key.indices(self._trueSize))
if key >= self._trueSize:
raise IndexError('batch index out of range')
return self.sequence[key]
def __iter__(self):
"""See zope.interface.common.sequence.IMinimalSequence"""
return iter(self.sequence)
def __eq__(self, other):
return ((self.size, self.start, self._length) ==
(other.size, other.start, other._length)) | z3c.batching | /z3c.batching-3.0.tar.gz/z3c.batching-3.0/src/z3c/batching/subset.py | subset.py |
"""Batching Support """
import zope.schema
from zope.interface.common import sequence
__docformat__ = 'restructuredtext'
class IBatch(sequence.IFiniteSequence):
"""A Batch represents a sub-list of the full sequence.
The Batch constructor takes a list (or any list-like object) of elements,
a starting index and the size of the batch. From this information all
other values are calculated.
"""
sequence = zope.interface.Attribute('Sequence')
batches = zope.interface.Attribute('Batches')
start = zope.schema.Int(
title='Start Index',
description=('The index of the sequence at which the batch starts. '
'If the full sequence is empty, the value is -1.'),
min=-1,
default=0,
required=True)
size = zope.schema.Int(
title='Batch Size',
description='The maximum size of the batch.',
min=1,
default=20,
required=True)
end = zope.schema.Int(
title='End Index',
description='The index of the sequence at which the batch ends.',
min=-1,
default=0,
readonly=True,
required=True)
index = zope.schema.Int(
title='Current Batch Index',
description='The index of the batch in relation to all batches.',
min=0,
readonly=True,
required=True)
number = zope.schema.Int(
title='Current Batch Number',
description='The number of the batch in relation to all batches.',
min=1,
readonly=True,
required=True)
total = zope.schema.Int(
title='Total Number of Batches',
description='The total number of batches available.',
min=1,
readonly=True,
required=True)
next = zope.schema.Field(
title='Next Batch',
description='The next batch of the sequence; ``None`` if last.',
readonly=True,
required=True)
previous = zope.schema.Field(
title='Previous Batch',
description='The previous batch of the sequence; ``None`` if first.',
readonly=True,
required=True)
firstElement = zope.schema.Field(
title='First Element',
description='The first element of the batch.',
readonly=True,
required=True)
totalElements = zope.schema.Int(
title='Total Number of Elements',
description='Return the length of the full sequence.',
min=1,
readonly=True,
required=True)
def __iter__():
"""Creates an iterator for the contents of the batch."""
def __contains__(item):
""" `x.__contains__(item)` <==> `item in x` """
def __eq__(other):
"""`x.__eq__(other)` <==> `x == other`"""
def __ne__(other):
"""`x.__ne__(other)` <==> `x != other`""" | z3c.batching | /z3c.batching-3.0.tar.gz/z3c.batching-3.0/src/z3c/batching/interfaces.py | interfaces.py |
"""Batching Implementation"""
import zope.interface
from zope.interface.common.sequence import IFiniteSequence
from zope.schema.fieldproperty import FieldProperty
from z3c.batching import interfaces
__docformat__ = 'restructuredtext'
@zope.interface.implementer(interfaces.IBatch)
class Batch:
"""Batch implementation. See IBatch"""
start = FieldProperty(interfaces.IBatch['start'])
size = FieldProperty(interfaces.IBatch['size'])
end = FieldProperty(interfaces.IBatch['end'])
def __init__(self, sequence, start=0, size=20, batches=None):
self.sequence = sequence
length = len(sequence)
self.update(length, start, size)
self.updateBatches(batches)
def update(self, length, start, size):
# See interfaces.IBatch
self._length = length
self.start = start
if length == 0:
self.start = -1
elif start >= length:
raise IndexError('start index key out of range')
# See interfaces.IBatch
self.size = size
self._trueSize = size
if start + size >= length:
self._trueSize = length - start
# See interfaces.IBatch
if length == 0:
self.end = -1
else:
self.end = start + self._trueSize - 1
def updateBatches(self, batches):
if batches is None:
batches = Batches(self)
self.batches = batches
@property
def index(self):
return self.start // self.size
@property
def number(self):
"""See interfaces.IBatch"""
return self.index + 1
@property
def total(self):
"""See interfaces.IBatch"""
total = self._length // self.size
if self._length % self.size:
total += 1
return total
@property
def next(self):
try:
return self.batches[self.index + 1]
except IndexError:
return None
@property
def previous(self):
idx = self.index - 1
if idx >= 0:
return self.batches[idx]
return None
@property
def firstElement(self):
"""See interfaces.IBatch"""
return self.sequence[self.start]
@property
def lastElement(self):
"""See interfaces.IBatch"""
return self.sequence[self.end]
def __getitem__(self, key):
"""See zope.interface.common.sequence.IMinimalSequence"""
if isinstance(key, slice):
return self.__getslice__(*key.indices(self._trueSize))
if key >= self._trueSize:
raise IndexError('batch index out of range')
return self.sequence[self.start + key]
def __iter__(self):
"""See zope.interface.common.sequence.IMinimalSequence"""
return iter(self.sequence[self.start: self.end + 1])
def __len__(self):
"""See zope.interface.common.sequence.IFiniteSequence"""
return self._trueSize
def __contains__(self, item):
for i in self:
if item == i:
return True
else:
return False
def __getslice__(self, i, j, k=1):
if k != 1:
raise ValueError('extended slicing not supported', k)
if j > self.end:
j = self._trueSize
return [self[idx] for idx in range(i, j)]
def __eq__(self, other):
return ((self.size, self.start, self.sequence) ==
(other.size, other.start, other.sequence))
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return '<%s start=%i, size=%i>' % (
self.__class__.__name__, self.start, self.size)
@zope.interface.implementer(IFiniteSequence)
class Batches:
"""A sequence object representing all the batches.
Used by a Batch.
"""
def __init__(self, batch):
self.size = batch.size
self.total = batch.total
self.sequence = batch.sequence
self._batches = {batch.index: batch}
def __len__(self):
return self.total
def __getitem__(self, key):
if isinstance(key, slice):
return self.__getslice__(*key.indices(self.total))
if key not in self._batches:
if key < 0:
key = self.total + key
batch = Batch(
self.sequence, key * self.size, self.size, self)
self._batches[batch.index] = batch
try:
return self._batches[key]
except KeyError:
raise IndexError(key)
def __getslice__(self, i, j, k=1):
if k != 1:
raise ValueError('extended slicing not supported')
j = min(j, self.total)
return [self[idx] for idx in range(i, j)]
def first_neighbours_last(batches, currentBatchIdx, nb_left, nb_right):
"""Build a sublist from a large batch list.
This is used to display batch links for a large table.
arguments:
* batches: a large sequence (may be a batches as well)
* currentBatchIdx: index of the current batch or item
* nb_left: number of neighbours before the current batch
* nb_right: number of neighbours after the current batch
The returned list gives:
* the first batch
* a None separator if necessary
* left neighbours of the current batch
* the current batch
* right neighbours of the current batch
* a None separator if necessary
* the last batch
Example:
>>> from z3c.batching.batch import first_neighbours_last as f_n_l
>>> batches = range(100) # it works with real batches as well
We try to get subsets at different levels:
>>> for i in range(0,6):
... f_n_l(batches, i, 2, 2)
[0, 1, 2, None, 99]
[0, 1, 2, 3, None, 99]
[0, 1, 2, 3, 4, None, 99]
[0, 1, 2, 3, 4, 5, None, 99]
[0, None, 2, 3, 4, 5, 6, None, 99]
[0, None, 3, 4, 5, 6, 7, None, 99]
>>> for i in range(93, 99):
... f_n_l(batches, i, 2, 2)
[0, None, 91, 92, 93, 94, 95, None, 99]
[0, None, 92, 93, 94, 95, 96, None, 99]
[0, None, 93, 94, 95, 96, 97, None, 99]
[0, None, 94, 95, 96, 97, 98, 99]
[0, None, 95, 96, 97, 98, 99]
[0, None, 96, 97, 98, 99]
Try with no previous and no next batch:
>>> f_n_l(batches, 0, 0, 0)
[0, None, 99]
>>> f_n_l(batches, 1, 0, 0)
[0, 1, None, 99]
>>> f_n_l(batches, 2, 0, 0)
[0, None, 2, None, 99]
Try with only 1 previous and 1 next batch:
>>> f_n_l(batches, 0, 1, 1)
[0, 1, None, 99]
>>> f_n_l(batches, 1, 1, 1)
[0, 1, 2, None, 99]
>>> f_n_l(batches, 2, 1, 1)
[0, 1, 2, 3, None, 99]
>>> f_n_l(batches, 3, 1, 1)
[0, None, 2, 3, 4, None, 99]
Try with incoherent values:
>>> f_n_l(batches, 0, -4, -10)
Traceback (most recent call last):
...
AssertionError
>>> f_n_l(batches, 2000, 3, 3)
Traceback (most recent call last):
...
AssertionError
"""
sublist = []
# setup some batches and indexes
firstIdx = 0
lastIdx = len(batches) - 1
assert currentBatchIdx >= 0 and currentBatchIdx <= lastIdx
assert nb_left >= 0 and nb_right >= 0
prevIdx = currentBatchIdx - nb_left
nextIdx = currentBatchIdx + 1
firstBatch = batches[0]
lastBatch = batches[lastIdx]
# add first batch
if firstIdx < currentBatchIdx:
sublist.append(firstBatch)
# there must probably be space
if firstIdx + 1 < prevIdx:
# we skip batches between first batch and first previous batch
sublist.append(None)
# add previous batches
for i in range(prevIdx, prevIdx + nb_left):
if firstIdx < i:
# append previous batches
sublist.append(batches[i])
# add current batch
sublist.append(batches[currentBatchIdx])
# add next batches
for i in range(nextIdx, nextIdx + nb_right):
if i < lastIdx:
# append previous batch
sublist.append(batches[i])
# there must probably be space
if nextIdx + nb_right < lastIdx:
# we skip batches between last batch and last next batch
sublist.append(None)
# add last batch
if currentBatchIdx < lastIdx:
sublist.append(lastBatch)
return sublist | z3c.batching | /z3c.batching-3.0.tar.gz/z3c.batching-3.0/src/z3c/batching/batch.py | batch.py |
.. contents::
Simple Batching
---------------
This module implements a simple batching mechanism that allows you to split a
large sequence into smaller batches. Let's start by creating a simple list,
which will be our full sequence:
Batch on empty root:
>>> from z3c.batching.batch import Batch
>>> batch = Batch([], size=3)
>>> len(batch)
0
>>> bool(batch)
False
>>> batch.firstElement
Traceback (most recent call last):
...
IndexError: ...
>>> batch.lastElement
Traceback (most recent call last):
...
IndexError: ...
>>> batch[0]
Traceback (most recent call last):
...
IndexError: ...
>>> batch.next is None
True
>>> batch.previous is None
True
>>> sequence = ['one', 'two', 'three', 'four', 'five', 'six', 'seven',
... 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen']
We can now create a batch for this sequence. Let's make our batch size 3:
>>> batch = Batch(sequence, size=3)
The first argument to the batch is always the full sequence. If no start
element is specified, the batch starts at the first element:
>>> list(batch)
['one', 'two', 'three']
The start index is commonly specified in the constructor though:
>>> batch = Batch(sequence, start=6, size=3)
>>> list(batch)
['seven', 'eight', 'nine']
Note that the start is an index and starts at zero. If the start index is
greater than the largest index of the sequence, an index error is raised:
>>> Batch(sequence, start=15, size=3)
Traceback (most recent call last):
...
IndexError: start index key out of range
A batch implements the finite sequence interface and thus supports some
standard methods. For example, you can ask the batch for its length:
>>> len(batch)
3
Note that the length returns the true size of the batch, not the size we asked
for:
>>> len(Batch(sequence, start=12, size=3))
1
Like any sequence, a non-empty batch is true-ish in a boolean context:
>>> bool(batch)
True
You can also get an element by index, which is relative to the batch:
>>> batch[0]
'seven'
>>> batch[1]
'eight'
>>> batch[2]
'nine'
Slicing:
>>> batch[:1]
['seven']
>>> batch[1:2]
['eight']
>>> batch[1:]
['eight', 'nine']
>>> batch[:]
['seven', 'eight', 'nine']
>>> batch[10:]
[]
If you ask for index that is out of range, an index error is raised:
>>> batch[3]
Traceback (most recent call last):
...
IndexError: batch index out of range
You can also iterate through the batch:
>>> iterator = iter(batch)
>>> next(iterator)
'seven'
>>> next(iterator)
'eight'
>>> next(iterator)
'nine'
Batch also implement some of IReadSequence interface:
>>> 'eight' in batch
True
>>> 'ten' in batch
False
>>> batch == Batch(sequence, start=6, size=3)
True
>>> batch != Batch(sequence, start=6, size=3)
False
>>> batch != Batch(sequence, start=3, size=3)
True
Besides all of those common API methods, there are several properties that were
designed to make your life simpler. The start and size are specified:
>>> batch.start
6
>>> batch.size
3
The end index of the batch is immediately computed:
>>> batch.end
8
The UI often requires that the number of the batch and the total number of
batches is computed:
>>> batch.number
3
>>> batch.total
5
You can also ask for the next batch:
>>> batch.next
<Batch start=9, size=3>
If the current batch is the last one, the next batch is None:
>>> Batch(sequence, start=12, size=3).next is None
True
The previous batch shows the previous batch:
>>> batch.previous
<Batch start=3, size=3>
If the current batch is the first one, the previous batch is None:
>>> Batch(sequence, start=0, size=3).previous is None
True
The final two properties deal with the elements within the batch. They ask for
the first and last element of the batch:
>>> batch.firstElement
'seven'
>>> batch.lastElement
'nine'
Total batches:
>>> batch = Batch(sequence[:-1], size=3)
>>> batch.total
4
We can have access to all batches:
>>> len(batch.batches)
4
>>> batch.batches[0]
<Batch start=0, size=3>
>>> batch.batches[3]
<Batch start=9, size=3>
>>> batch.batches[4]
Traceback (most recent call last):
...
IndexError: ...
>>> batch.batches[-1]
<Batch start=9, size=3>
>>> batch.batches[-2]
<Batch start=6, size=3>
Slicing:
>>> batch.batches[:1]
[<Batch start=0, size=3>]
>>> batch.batches[:]
[<Batch start=0, size=3>, <Batch start=3, size=3>, <Batch start=6, size=3>, <Batch start=9, size=3>]
>>> batch.batches[1:2]
[<Batch start=3, size=3>]
>>> batch.batches[1:]
[<Batch start=3, size=3>, <Batch start=6, size=3>, <Batch start=9, size=3>]
>>> batch.batches[10:]
[]
>>> batch.batches[2:50]
[<Batch start=6, size=3>, <Batch start=9, size=3>]
Batch neighbourhood of a large batch list
-----------------------------------------
When the full list of batches is too large to be displayed in a user interface,
we want to display only a subset of all the batches.
A helper function is provided for that purpose:
First build a large sequence of batches (or anything else):
>>> batches = range(100)
Then extract only the first and last items, as well as the neighbourhood of the
46th item (index = 45). We want 3 neighbours at the left, 5 at the right:
>>> from z3c.batching.batch import first_neighbours_last
>>> first_neighbours_last(batches, 45, 3, 5)
[0, None, 42, 43, 44, 45, 46, 47, 48, 49, 50, None, 99]
'None' can be used to display a separator in a user interface (see z3c.table)
| z3c.batching | /z3c.batching-3.0.tar.gz/z3c.batching-3.0/src/z3c/batching/README.txt | README.txt |
=========================
Changelog of z3c.bcrypt
=========================
2.0.1 (2018-08-01)
==================
- Package is deprecated in favor of `zope.password`_.
2.0.0 (2017-05-10)
==================
- Standardize namespace __init__.
- Add support for Python 3.4, 3.5, 3.6 and PyPy.
1.2 (2013-10-10)
================
- Only verify the first 4096 characters of a password to prevent
denial-of-service attacks through repeated submission of large
passwords, tying up server resources in the expensive computation
of the corresponding hashes.
See: https://www.djangoproject.com/weblog/2013/sep/15/security/
1.1 (2010-02-22)
================
- Fixes in the configure.zcml.
1.0 (2010-02-18)
================
- Initial public release.
.. _`zope.password`: https://pypi.org/project/zope.password/
| z3c.bcrypt | /z3c.bcrypt-2.0.1.tar.gz/z3c.bcrypt-2.0.1/CHANGES.rst | CHANGES.rst |
============
z3c.bcrypt
============
.. warning:: z3c.bcrypt has been superseeded with the new version of
`zope.password`_ as it now includes `bcrypt` support based on
the well-maintained `bcrypt`_ library. Please don't use
this package in new projects.
z3c.bcrypt provides `zope.password`_ compatible "password manager" utilities
that use bcrypt (or alternatively pbkdf2) encoding for storing passwords.
Both encoding schemes are implemented in the cryptacular_ library that is
a dependency for this package.
.. _`zope.password`: https://pypi.org/project/zope.password/
.. _cryptacular: https://pypi.org/project/cryptacular/
.. _`bcrypt`: https://pypi.org/project/bcrypt/
| z3c.bcrypt | /z3c.bcrypt-2.0.1.tar.gz/z3c.bcrypt-2.0.1/README.rst | README.rst |
Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| z3c.bcrypt | /z3c.bcrypt-2.0.1.tar.gz/z3c.bcrypt-2.0.1/LICENSE.rst | LICENSE.rst |
==================
Using z3c.bcrypt
==================
>>> from zope.interface.verify import verifyObject
>>> from zope.password.interfaces import IPasswordManager
>>> from z3c.bcrypt import BcryptPasswordManager
>>> manager = BcryptPasswordManager()
>>> verifyObject(IPasswordManager, manager)
True
>>> password = u"right \N{CYRILLIC CAPITAL LETTER A}"
>>> encoded = manager.encodePassword(password)
>>> encoded
'$2a$...'
>>> manager.checkPassword(encoded, password)
True
>>> manager.checkPassword(encoded, password + u"wrong")
False
>>> from z3c.bcrypt import PBKDF2PasswordManager
>>> manager = PBKDF2PasswordManager()
>>> verifyObject(IPasswordManager, manager)
True
>>> encoded = manager.encodePassword(password)
>>> encoded
u'$p5k2$...'
>>> manager.checkPassword(encoded, password)
True
>>> manager.checkPassword(encoded, password + u"wrong")
False
>>> # A previously encoded password, should be decodable even if the
>>> # current encoding of the same password is different::
>>> previouslyencoded = (
... '$p5k2$1000$LgAFPIlc9CgrlSaxHyTUMA='
... '=$IuUYplhMkR4qCl8-ONRVjEgJNwE=')
>>> encoded == previouslyencoded
False
>>> manager.checkPassword(previouslyencoded , password)
True
Excessively long "passwords" will take up a lot of computation time that
can be used as a DOS attack vector. The password managers in z3c.bcrypt will
only use the first 4096 characters of the incoming password for checking.
This is inspired by:
https://www.djangoproject.com/weblog/2013/sep/15/security/
This test would take significantly longer if the 4096 length limit would
not be in place. XXX how to test that reliably?
>>> incomming = '$p5k2$1000$' + 'a' * 1024 * 1024 * 100 # lot of data.
>>> manager.checkPassword(encoded, incomming)
False
Configuration
=============
This package provides a ``configure.zcml`` which installs
implementations of the ``IPasswordManager`` as utilities:
>>> from zope.configuration import xmlconfig
>>> _ = xmlconfig.string("""
... <configure
... xmlns="http://namespaces.zope.org/zope">
...
... <include package="z3c.bcrypt" />
... </configure>
... """)
>>> from zope import component
>>> from zope.password.interfaces import IPasswordManager
>>> component.getUtility(IPasswordManager, name='bcrypt')
<z3c.bcrypt.passwordmanager.BcryptPasswordManager object at ...>
>>> component.getUtility(IPasswordManager, name='pbkdf2')
<z3c.bcrypt.passwordmanager.PBKDF2PasswordManager object at ...>
| z3c.bcrypt | /z3c.bcrypt-2.0.1.tar.gz/z3c.bcrypt-2.0.1/src/z3c/bcrypt/USAGE.rst | USAGE.rst |
Blob File
=========
This package provides an implementation of zope.app.file.interfaces.IFile
which uses the Blob support introduced in ZODB 3.8. It's main purpose
is to provide an easy migration path for existing instances. For more
advanced file implementations see zope.file and z3c.extfile.
The standard implementation in zope.app.file uses chunk objects to
break big files into manageable parts. These chunks flow the server caches
whereas blobs are directly consumed by the publisher. The main difference
between this blob implementation and the old zope.app.file implementation
can be seen in a replacement of the chunk objects by Blobs.
| z3c.blobfile | /z3c.blobfile-0.1.5.zip/z3c.blobfile-0.1.5/README.txt | README.txt |
__docformat__ = 'restructuredtext'
from persistent import Persistent
import transaction
from zope.interface import implements
import zope.component
import zope.component.interfaces
import zope.app.publication.interfaces
from ZODB.blob import Blob
import interfaces
class File(Persistent):
"""A persistent content component storing binary file data."""
implements(zope.app.publication.interfaces.IFileContent,
interfaces.IBlobFile)
def __init__(self, data='', contentType=''):
self.contentType = contentType
self._blob = Blob()
f = self._blob.open('w')
f.write('')
f.close()
self._setData(data)
def open(self, mode='r'):
if mode != 'r' and 'size' in self.__dict__:
del self.__dict__['size']
return self._blob.open(mode)
def openDetached(self):
return open(self._blob.committed(), 'rb')
def _setData(self, data):
if 'size' in self.__dict__:
del self.__dict__['size']
# Search for a storable that is able to store the data
dottedName = ".".join((data.__class__.__module__,
data.__class__.__name__))
storable = zope.component.getUtility(interfaces.IStorage,
name=dottedName)
storable.store(data, self._blob)
def _getData(self):
fp = self._blob.open('r')
data = fp.read()
fp.close()
return data
_data = property(_getData, _setData)
data = property(_getData, _setData)
@property
def size(self):
if 'size' in self.__dict__:
return self.__dict__['size']
reader = self._blob.open()
reader.seek(0,2)
size = int(reader.tell())
reader.close()
self.__dict__['size'] = size
return size
def getSize(self):
return self.size
class FileReadFile(object):
"""Adapter for file-system style read access."""
def __init__(self, context):
self.context = context
def read(self, bytes=-1):
return self.context.data
def size(self):
return self.context.size
class FileWriteFile(object):
"""Adapter for file-system style write access."""
def __init__(self, context):
self.context = context
def write(self, data):
self.context._setData(data)
class FileReplacedEvent(zope.component.interfaces.ObjectEvent):
"""Notifies about the replacement of a zope.app.file with a z3c.blobfile."""
def __init__(self, object, blobfile):
super(FileReplacedEvent, self).__init__(object)
self.blobfile = blobfile | z3c.blobfile | /z3c.blobfile-0.1.5.zip/z3c.blobfile-0.1.5/src/z3c/blobfile/file.py | file.py |
__docformat__ = 'restructuredtext'
import struct
from cStringIO import StringIO
from zope.interface import implements
from zope.size.interfaces import ISized
from zope.size import byteDisplay
from zope.contenttype import guess_content_type
from z3c.blobfile.i18n import ZopeMessageFactory as _
from z3c.blobfile.file import File
import interfaces
IMAGE_INFO_BYTES = 1024
MAX_INFO_BYTES = 1 << 16
class Image(File):
implements(interfaces.IBlobImage)
def _setData(self, data):
super(Image, self)._setData(data)
firstbytes = self.getFirstBytes()
res = getImageInfo(firstbytes)
if res == ('image/jpeg', -1, -1):
# header was longer than firstbytes
start = len(firstbytes)
length = max(0, MAX_INFO_BYTES - start)
firstbytes += self.getFirstBytes(start, length)
res = getImageInfo(firstbytes)
contentType, self._width, self._height = res
if contentType:
self.contentType = contentType
data = property(File._getData, _setData)
def getFirstBytes(self, start=0, length=IMAGE_INFO_BYTES):
"""Returns the first bytes of the file.
Returns an amount which is sufficient to determine the image type.
"""
fp = self.open('r')
fp.seek(start)
firstbytes = fp.read(length)
fp.close()
return firstbytes
def getImageSize(self):
"""See interface `IImage`"""
return (self._width, self._height)
class ImageSized(object):
implements(ISized)
def __init__(self, image):
self._image = image
def sizeForSorting(self):
'''See `ISized`'''
return ('byte', self._image.getSize())
def sizeForDisplay(self):
'''See `ISized`'''
w, h = self._image.getImageSize()
if w < 0:
w = '?'
if h < 0:
h = '?'
bytes = self._image.getSize()
byte_size = byteDisplay(bytes)
mapping = byte_size.mapping
if mapping is None:
mapping = {}
mapping.update({'width': str(w), 'height': str(h)})
#TODO the way this message id is defined, it won't be picked up by
# i18nextract and never show up in message catalogs
return _(byte_size + ' ${width}x${height}', mapping=mapping)
class FileFactory(object):
def __init__(self, context):
self.context = context
def __call__(self, name, content_type, data):
if not content_type and data:
content_type, width, height = getImageInfo(data)
if not content_type:
content_type, encoding = guess_content_type(name, data, '')
if content_type.startswith('image/'):
return Image(data)
return File(data, content_type)
def getImageInfo(data):
data = str(data)
size = len(data)
height = -1
width = -1
content_type = ''
# handle GIFs
if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'):
# Check to see if content_type is correct
content_type = 'image/gif'
w, h = struct.unpack("<HH", data[6:10])
width = int(w)
height = int(h)
# See PNG 2. Edition spec (http://www.w3.org/TR/PNG/)
# Bytes 0-7 are below, 4-byte chunk length, then 'IHDR'
# and finally the 4-byte width, height
elif ((size >= 24) and data.startswith('\211PNG\r\n\032\n')
and (data[12:16] == 'IHDR')):
content_type = 'image/png'
w, h = struct.unpack(">LL", data[16:24])
width = int(w)
height = int(h)
# Maybe this is for an older PNG version.
elif (size >= 16) and data.startswith('\211PNG\r\n\032\n'):
# Check to see if we have the right content type
content_type = 'image/png'
w, h = struct.unpack(">LL", data[8:16])
width = int(w)
height = int(h)
# handle JPEGs
elif (size >= 2) and data.startswith('\377\330'):
content_type = 'image/jpeg'
jpeg = StringIO(data)
jpeg.read(2)
b = jpeg.read(1)
try:
w = -1
h = -1
while (b and ord(b) != 0xDA):
while (ord(b) != 0xFF): b = jpeg.read(1)
while (ord(b) == 0xFF): b = jpeg.read(1)
if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
jpeg.read(3)
h, w = struct.unpack(">HH", jpeg.read(4))
break
else:
jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
b = jpeg.read(1)
width = int(w)
height = int(h)
except struct.error:
pass
except ValueError:
pass
# handle BMPs
elif (size >= 30) and data.startswith('BM'):
kind = struct.unpack("<H", data[14:16])[0]
if kind == 40: # Windows 3.x bitmap
content_type = 'image/x-ms-bmp'
width, height = struct.unpack("<LL", data[18:26])
return content_type, width, height | z3c.blobfile | /z3c.blobfile-0.1.5.zip/z3c.blobfile-0.1.5/src/z3c/blobfile/image.py | image.py |
__docformat__ = 'restructuredtext'
import zope.interface
import interfaces
from zope.app.file.file import FileChunk
from zope.publisher.browser import FileUpload
MAXCHUNKSIZE = 1 << 16
class StringStorable(object):
zope.interface.implements(interfaces.IStorage)
def store(self, data, blob):
if not isinstance(data, str):
raise NotStorable("Could not store data (not of 'str' type).")
fp = blob.open('w')
fp.write(data)
fp.close()
class UnicodeStorable(StringStorable):
zope.interface.implements(interfaces.IStorage)
def store(self, data, blob):
if not isinstance(data, unicode):
raise NotStorable("Could not store data (not of 'unicode' "
"type).")
data = data.encode('UTF-8')
StringStorable.store(self, data, blob)
class FileChunkStorable(object):
zope.interface.implements(interfaces.IStorage)
def store(self, data, blob):
if not isinstance(data, FileChunk):
raise NotStorable("Could not store data (not a of 'FileChunk' "
"type).")
fp = blob.open('w')
chunk = data
while chunk:
fp.write(chunk._data)
chunk = chunk.next
fp.close()
class FileDescriptorStorable(object):
zope.interface.implements(interfaces.IStorage)
def store(self, data, blob):
if not isinstance(data, file):
raise NotStorable("Could not store data (not of 'file').")
filename = getattr(data, "name", None)
if filename is not None:
blob.consumeFile(filename)
return
class FileUploadStorable(object):
zope.interface.implements(interfaces.IStorage)
def store(self, data, blob):
if not isinstance(data, FileUpload):
raise NotStorable("Could not store data (not of 'FileUpload').")
data.seek(0)
fp = blob.open('w')
block = data.read(MAXCHUNKSIZE)
while block:
fp.write(block)
block = data.read(MAXCHUNKSIZE)
fp.close() | z3c.blobfile | /z3c.blobfile-0.1.5.zip/z3c.blobfile-0.1.5/src/z3c/blobfile/storages.py | storages.py |
__docformat__ = 'restructuredtext'
import zope.event
from zope import lifecycleevent
from zope.contenttype import guess_content_type
from zope.publisher import contenttype
from zope.schema import Text
from zope.exceptions.interfaces import UserError
from zope.app.file.interfaces import IFile
from z3c.blobfile.i18n import ZopeMessageFactory as _
from zope.dublincore.interfaces import IZopeDublinCore
from zope.app.file.browser.file import FileUpdateView
import zope.datetime
import time
from datetime import datetime
import z3c.blobfile.file
class FileView(object):
def show(self):
"""Returns file handle for efficient streaming."""
if self.request is not None:
self.request.response.setHeader('Content-Type',
self.context.contentType)
self.request.response.setHeader('Content-Length',
self.context.getSize())
try:
modified = IZopeDublinCore(self.context).modified
except TypeError:
modified = None
if modified is None or not isinstance(modified, datetime):
return self.context.openDetached()
header= self.request.getHeader('If-Modified-Since', None)
lmt = zope.datetime.time(modified.isoformat())
if header is not None:
header = header.split(';')[0]
try:
mod_since = long(zope.datetime.time(header))
except:
mod_since = None
if mod_since is not None:
if lmt <= mod_since:
self.request.response.setStatus(304)
return ''
self.request.response.setHeader('Last-Modified', zope.datetime.rfc1123_date(lmt))
return self.context.openDetached()
class FileAdd(FileUpdateView):
"""View that adds a new File object based on a file upload."""
def update_object(self, data, contenttype):
f = z3c.blobfile.file.File(data, contenttype)
zope.event.notify(lifecycleevent.ObjectCreatedEvent(f))
self.context.add(f)
self.request.response.redirect(self.context.nextURL())
return '' | z3c.blobfile | /z3c.blobfile-0.1.5.zip/z3c.blobfile-0.1.5/src/z3c/blobfile/browser/file.py | file.py |
import logging
from z3c.feature.core import xml, template
from z3c.feature.core.xml import etree
from z3c.builder.core import project, base
from z3c.feature.core.base import getFeatureSchema
from zope.schema import List
def prompt(field):
promptText = field.title
if field.default:
promptText += " [%s]" % field.default
if field.description:
promptText += " (? for help)"
promptText += ": "
nonSubmitValues = {}
if field.description:
nonSubmitValues['?'] = field.description
def getResponse(value):
while value in nonSubmitValues.keys():
print nonSubmitValues[value]
value = raw_input(promptText)
return unicode(value)
if hasattr(field, 'fromUnicode'):
if field.required and not field.default:
nonSubmitValues[""] = "Sorry, but this field is required."
value = getResponse(raw_input(promptText))
if value == "" and field.default:
print "using default value: %s" % field.default
value = field.default
if value != "":
value = field.fromUnicode(value)
elif isinstance(field, List):
valueList = []
value = None
while value != "":
value = getResponse(raw_input(promptText))
if value:
valueList.append(value)
value = valueList
else:
base.logger.warn("Not sure how to convert field: %s" % field)
value = unicode(value)
return value
def xmlToProject(node):
originalNode = node
node = xml.getNode(node)
name = raw_input("Enter the name for this project: ").strip()
while name == "":
print "You must provide a name for your project."
name = raw_input("Enter the name for this project: ").strip()
node.set('name',name)
# fill in missing xml by prompting
for featureNode in node.xpath('//feature'):
factory = xml.getFeatureFactory(featureNode)
schema = getFeatureSchema(factory)
data = xml.extractData(featureNode, schema, convert=False)
fieldNames = [n for n in schema if data.get(n) == '?']
if fieldNames:
print ""
header = "Options for: "+featureNode.get("type")
print header
print "-"*len(header)
for fieldName in fieldNames:
fieldValue = prompt(schema[fieldName])
fieldNode = featureNode.xpath('./%s' % fieldName.replace('_','-'))[0]
if isinstance(fieldValue, unicode):
fieldNode.text = fieldValue
elif isinstance(fieldValue, list):
fieldNode.text = None
for item in fieldValue:
itemNode = etree.SubElement(fieldNode, "item")
itemNode.text = item
print
print "Finished creating xml definition."
print
if raw_input("Do you want to see the generated xml definition? (y/[n]): ") == 'y':
print etree.tostring(node, pretty_print=True)
if raw_input("Does this look right? ([y]/n): ") == 'n':
print
raw_input("Ok, we'll start over.")
print
print '-'*78
print
return xmlToProject(originalNode)
return xml.xmlToProject(node) | z3c.boiler | /z3c.boiler-0.1.1.tar.gz/z3c.boiler-0.1.1/src/z3c/boiler/interactive.py | interactive.py |
======================================
ZBoiler - A Quick Way to Boil Projects
======================================
The ZBoiler package provides a small script to generate the boilerplate of a
project from a simple, high-level feature XML file. An example of such a
configuration file is `sample-project.xml`.
>>> from z3c.boiler import script
>>> def boil(args, showLog=False):
... try:
... script.main(args)
... except SystemExit, err:
... print 'Exit Code: %i' % err.code
... else:
... print 'Error: No proper exit.'
Let's generate the project using the script. We need to specify the
configuration file and a target directory.
>>> import os
>>> featureFile = os.path.join(
... os.path.dirname(script.__file__), 'sample-project.xml')
>>> boil(['-i', featureFile, '-o', buildPath])
INFO - Creating directory .../z3c.sampleproject
INFO - Creating file .../z3c.sampleproject/bootstrap.py
INFO - Creating file .../z3c.sampleproject/setup.py
INFO - Creating file .../z3c.sampleproject/buildout.cfg
INFO - Creating directory .../z3c.sampleproject/src
INFO - Creating directory .../z3c.sampleproject/src/z3c
INFO - Creating directory .../z3c.sampleproject/src/z3c/sampleproject
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/application.zcml
INFO - Creating directory .../z3c.sampleproject/src/z3c/sampleproject/browser
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/browser/configure.zcml
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/browser/message.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/browser/__init__.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/configure.zcml
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/interfaces.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/index.txt
INFO - Creating directory .../z3c.sampleproject/src/z3c/sampleproject/tests
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/tests/test_doc.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/tests/__init__.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/README.txt
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/message.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/__init__.py
INFO - Creating file .../z3c.sampleproject/src/z3c/__init__.py
INFO - Creating file .../z3c.sampleproject/ZBOILER.txt
INFO - Build finished
Exit Code: 0
Let's now have a look at the generated directory:
>>> ls(buildPath)
z3c.sampleproject/
ZBOILER.txt
bootstrap.py
buildout.cfg
setup.py
src/
z3c/
__init__.py
sampleproject/
README.txt
__init__.py
application.zcml
configure.zcml
index.txt
interfaces.py
message.py
browser/
__init__.py
configure.zcml
message.pytests/
__init__.py
test_doc.py
When we try to regenerate the project again, we get a failure, since the
directory already exists:
>>> boil(['-i', featureFile, '-o', buildPath])
CRITICAL - Failed building package because file .../z3c.sampleproject
already exists. Use --force to overwrite it.
Exit Code: 1
We can, however, force the directory to be overwritten as the message
mentions:
>>> boil(['-f', '-i', featureFile, '-o', buildPath])
INFO - Creating directory .../z3c.sampleproject
INFO - Creating file .../z3c.sampleproject/bootstrap.py
INFO - Creating file .../z3c.sampleproject/setup.py
INFO - Creating file .../z3c.sampleproject/buildout.cfg
INFO - Creating directory .../z3c.sampleproject/src
INFO - Creating directory .../z3c.sampleproject/src/z3c
INFO - Creating directory .../z3c.sampleproject/src/z3c/sampleproject
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/application.zcml
INFO - Creating directory .../z3c.sampleproject/src/z3c/sampleproject/browser
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/browser/configure.zcml
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/browser/message.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/browser/__init__.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/configure.zcml
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/interfaces.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/index.txt
INFO - Creating directory .../z3c.sampleproject/src/z3c/sampleproject/tests
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/tests/test_doc.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/tests/__init__.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/README.txt
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/message.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/__init__.py
INFO - Creating file .../z3c.sampleproject/src/z3c/__init__.py
INFO - Creating file .../z3c.sampleproject/ZBOILER.txt
INFO - Build finished
Exit Code: 0
If we want less information, we can simply tell the script to be quiet:
>>> boil(['-q', '-f', '-i', featureFile, '-o', buildPath])
Exit Code: 0
Fatal messages are still displayed:
>>> boil(['-q', '-i', featureFile, '-o', buildPath])
CRITICAL - Failed building package because file .../z3c.sampleproject
already exists. Use --force to overwrite it.
Exit Code: 1
We can also ask for more information:
>>> boil(['-v', '-f', '-i', featureFile, '-o', buildPath])
DEBUG - Updating <SimpleFileBuilder u'bootstrap.py'>
DEBUG - Updating <PartBuilder u'versions'>
DEBUG - Updating <PartBuilder u'zope3'>
DEBUG - Updating <PartBuilder u'z3c.sampleproject-app'>
DEBUG - Updating <PartBuilder u'z3c.sampleproject'>
DEBUG - Updating <PartBuilder u'database'>
DEBUG - Updating <PartBuilder u'docs'>
DEBUG - Updating <PartBuilder u'python'>
DEBUG - Updating <PartBuilder u'test'>
DEBUG - Updating <PartBuilder u'coverage-test'>
DEBUG - Updating <PartBuilder u'coverage-report'>
DEBUG - Updating <PackageBuilder u'z3c'>
DEBUG - Updating <PackageBuilder u'sampleproject'>
DEBUG - Updating <PackageBuilder u'browser'>
DEBUG - Updating <ModuleBuilder u'message.py'>
DEBUG - Updating <ModuleBuilder u'interfaces.py'>
DEBUG - Updating <PackageBuilder u'tests'>
DEBUG - Updating <SimpleFileBuilder u'test_doc.py'>
DEBUG - Updating <SimpleFileBuilder u'README.txt'>
DEBUG - Updating <ModuleBuilder u'message.py'>
DEBUG - Updating <FeatureDocBuilder u'ZBOILER.txt'>
INFO - Creating directory .../z3c.sampleproject
INFO - Creating file .../z3c.sampleproject/bootstrap.py
INFO - Creating file .../z3c.sampleproject/setup.py
INFO - Creating file .../z3c.sampleproject/buildout.cfg
INFO - Creating directory .../z3c.sampleproject/src
INFO - Creating directory .../z3c.sampleproject/src/z3c
INFO - Creating directory .../z3c.sampleproject/src/z3c/sampleproject
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/application.zcml
INFO - Creating directory .../z3c.sampleproject/src/z3c/sampleproject/browser
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/browser/configure.zcml
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/browser/message.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/browser/__init__.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/configure.zcml
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/interfaces.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/index.txt
INFO - Creating directory .../z3c.sampleproject/src/z3c/sampleproject/tests
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/tests/test_doc.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/tests/__init__.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/README.txt
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/message.py
INFO - Creating file .../z3c.sampleproject/src/z3c/sampleproject/__init__.py
INFO - Creating file .../z3c.sampleproject/src/z3c/__init__.py
INFO - Creating file .../z3c.sampleproject/ZBOILER.txt
INFO - Build finished
Exit Code: 0
It is also possible to use a built in project template as a basis for
a new project. To see an available list of built in templates, we use
the --list option.
>>> boil(['--list'])
Available Templates:
<BLANKLINE>
zope-project "Zope 3 Web Application"
Includes all the features you would want for a Zope 3 Web Application.
command-line "Command Line Program"
Includes all the features you would want for a command line program.
python-package "Python Package"
Just a simple python package with few bells and whistles.
Exit Code: 0
If we try to use a template that does not exist, then we are told to
use --list:
>>> boil(['-t','foobar'])
Could not find the template "foobar".
Use --list to see available templates.
Exit Code: 1
Last but not least, we also have some help for the `boil` script:
>>> boil(['-h'])
Usage: test [options]
<BLANKLINE>
Options:
-h, --help show this help message and exit
-i FILE, --input-file=FILE
The file containing the XML definition of the project.
-t TEMPLATE, --template=TEMPLATE
A project template. Use --list to see available
templates
-l, --list Show a list of available templates for use with
--template
-k, --interactive When specified, runs in interactive mode prompting you
to enter missing values.
-o DIR, --output-dir=DIR
The directory where project files should be generated.
-q, --quiet When specified, no messages are displayed.
-v, --verbose When specified, debug information is created.
-f, --force Force the package to be generated even overwriting any
existing files.
Exit Code: 0
When no arguments are specified, help is also shown:
>>> boil([])
Usage: test [options]
...
Exit Code: 0
| z3c.boiler | /z3c.boiler-0.1.1.tar.gz/z3c.boiler-0.1.1/src/z3c/boiler/README.txt | README.txt |
import logging
import optparse
import os
import sys
from z3c.feature.core import xml, template
from z3c.feature.core.interfaces import IFileBasedTemplateProvider
from z3c.feature.core.interfaces import MissingFeatureDependencyError
from z3c.builder.core import base, interfaces
from z3c.boiler import interactive
parser = optparse.OptionParser()
parser.add_option(
"-i", "--input-file", action="store",
dest="inputFile", metavar="FILE",
help="The file containing the XML definition of the project.")
parser.add_option(
"-t", "--template", action="store",
dest="template",
help="A project template. Use --list to see available templates")
parser.add_option(
"-l", "--list", action="store_true",
dest="listTemplates",
help="Show a list of available templates for use with --template")
parser.add_option(
"-k", "--interactive", action="store_true",
dest="interactive", default=False,
help=("When specified, runs in interactive mode "
"prompting you to enter missing values."))
parser.add_option(
"-o","--output-dir", action="store",
dest="outputDirectory", metavar="DIR",
default=u".",
help="The directory where project files should be generated.")
parser.add_option(
"-q","--quiet", action="store_true",
dest="quiet", default=False,
help="When specified, no messages are displayed.")
parser.add_option(
"-v","--verbose", action="store_true",
dest="verbose", default=False,
help="When specified, debug information is created.")
parser.add_option(
"-f","--force", action="store_true",
dest="force",
help=("Force the package to be generated "
"even overwriting any existing files."))
def main(args=None):
# Make sure we get the arguments.
if args is None:
args = sys.argv[1:]
if not args:
args = ['-h']
# Set up logger handler
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(base.formatter)
base.logger.addHandler(handler)
# Parse arguments
options, args = parser.parse_args(args)
if options.listTemplates:
print "Available Templates:"
print
temps = [(name, temp) for name, temp in template.getTemplateList().items()
if IFileBasedTemplateProvider.providedBy(temp)]
nameSize = max([len(name) for name, temp in temps])
for name, temp in temps:
nameLine = ' %s' % name
nameLine += ' '*(nameSize-len(name))
nameLine += ' "%s"' % temp.title
print nameLine
print nameSize*' '+' '+temp.description.strip().replace('\n','\n ')
sys.exit(0)
if not options.inputFile and not options.template:
print "You must specify an input file or template"
args = ['-h']
parser.parse_args(args)
elif not options.inputFile:
try:
inputFile = template.getTemplate(options.template).filename
except KeyError:
print "Could not find the template \"%s\"." % options.template
print "Use --list to see available templates."
sys.exit(1)
else:
inputFile = options.inputFile
base.logger.setLevel(logging.INFO)
if options.verbose:
base.logger.setLevel(logging.DEBUG)
if options.quiet:
base.logger.setLevel(logging.FATAL)
status = 0
# Parse the project XML file into builder components.
if options.interactive:
try:
builder = interactive.xmlToProject(open(inputFile, 'r'))
except KeyboardInterrupt:
print "\nquitting"
sys.exit(status)
else:
try:
builder = xml.xmlToProject(open(inputFile, 'r'))
except MissingFeatureDependencyError, e:
base.logger.fatal("An error occured:\n %r" % e)
sys.exit(1)
# Write the project using the builders.
try:
builder.update()
builder.write(options.outputDirectory, options.force)
except interfaces.FileExistsException, e:
base.logger.fatal("Failed building package because file %s "
"already exists. Use --force to overwrite "
"it." % e.filename)
status = 1
else:
base.logger.info("Build finished")
# Remove the handler again.
base.logger.removeHandler(handler)
# Exit cleanly.
sys.exit(status) | z3c.boiler | /z3c.boiler-0.1.1.tar.gz/z3c.boiler-0.1.1/src/z3c/boiler/script.py | script.py |
Introduction
============
This skin is a derivative of the zope.app.boston.Boston skin, which
supports pagelets, forms and javascript forms.
Usage:
It includes the information needed to configure itself. To add it
to your configuration;
1. Add it to your buildout...
eggs=...
z3c.boston
2. To use the skin, you can use a traversal adapter:
http://localhost:8080/++skin++z3c_boston/index.html
3. To configure this as your default skin, add this line to your
site.zcml file:
<includeOverrides package="z3c.boston" file="default_skin.zcml" />
| z3c.boston | /z3c.boston-1.0.2.tar.gz/z3c.boston-1.0.2/README.txt | README.txt |
z3c.boston.Boston
=================
This skin is a derivative of the zope.app.boston.Boston skin, which
supports pagelets, forms and javascript forms.
It includes the information needed to configure itself. To add it
to your configuration;
1. Add it to your buildout...
eggs=...
z3c.boston
2. To use the skin, you can use a traversal adapter:
http://localhost:8080/++skin++z3c_boston/index.html
3. To configure this as your default skin, add this line to your
site.zcml file:
<includeOverrides package="z3c.boston" file="default_skin.zcml" />
----------------------------------------------------------------------------
>>> from zope.testbrowser.testing import Browser
>>> browser = Browser()
>>> browser.addHeader('Authorization', 'Basic mgr:mgrpw')
>>> browser.handleErrors = False
Check if the css viewlet is available in the z3c_boston skin.
>>> browser.open('http://localhost/++skin++z3c_boston/@@contents.html')
>>> browser.url
'http://localhost/++skin++z3c_boston/@@contents.html'
>>> browser.contents
'...href="http://localhost/++skin++z3c_boston/@@/skin.css"...'
>>> browser.contents
'...href="http://localhost/++skin++z3c_boston/@@/widget.css"...'
>>> browser.contents
'...href="http://localhost/++skin++z3c_boston/@@/toolbar.css"...'
>>> browser.contents
'...href="http://localhost/++skin++z3c_boston/@@/xmltree.css"...'
Check if the javascript viewlet is available in the Boston skin.
>>> browser.open('http://localhost/++skin++z3c_boston/@@contents.html')
>>> browser.url
'http://localhost/++skin++z3c_boston/@@contents.html'
>>> browser.contents
'...src="http://localhost/++skin++z3c_boston/@@/boston.js"...'
>>> browser.contents
'...src="http://localhost/++skin++z3c_boston/@@/xmltree.js"...'
Check if the left viewlet is available in the Boston skin.
>>> browser.open('http://localhost/++skin++z3c_boston/@@contents.html')
>>> browser.url
'http://localhost/++skin++z3c_boston/@@contents.html'
>>> browser.contents
'...id="ToolBar"...'
>>> browser.contents
'...id="xmltree"...'
>>> browser.contents
'...id="addinginfo"...'
Make sure the edit form "works":
>>> browser.open(
... 'http://localhost/++skin++z3c_boston/+/zope.app.dtmlpage.DTMLPage=')
A demo pagelet is defined in demo.py. Load the pagelet.
>>> browser.open('http://localhost/++skin++z3c_boston/@@demo.html')
>>> browser.contents
'...PAGELET CONTENT...'
Verify standard viewlets
>>> browser.open('http://localhost/++skin++z3c_boston/@@demo.html')
>>> browser.contents
'...demo.css...'
>>> browser.contents
'...demo.js...'
Verify that the CSS for forms is included
>>> browser.open('http://localhost/++skin++z3c_boston/@@demo_form.html')
>>> browser.contents
'...div-form.css...'
Verify that formjs works
>>> browser.open('http://localhost/++skin++z3c_boston/@@demo_formjs.html')
>>> browser.contents
'...div-form.css...'
>>> browser.contents
'...jquery.js...'
>>> browser.contents
'...alert...'
| z3c.boston | /z3c.boston-1.0.2.tar.gz/z3c.boston-1.0.2/z3c/boston/README.txt | README.txt |
"""Browser UI code.
"""
import zope.component
import zope.interface
import zope.location
import zope.traversing.api
import zope.traversing.browser
from zope.proxy import sameProxiedObjects
from zope.publisher.interfaces.http import IHTTPRequest
from zope.traversing.interfaces import IContainmentRoot
from z3c.breadcrumb import interfaces
@zope.interface.implementer(interfaces.IBreadcrumbs)
class Breadcrumbs(zope.location.Location):
"""Breadcrumbs implementation using IBreadcrumb adapters."""
zope.component.adapts(zope.interface.Interface, IHTTPRequest)
def __init__(self, context, request):
self.context = context
self.request = request
self.__parent__ = context
def __getParent(self):
return getattr(self, '_parent', self.context)
def __setParent(self, parent):
self._parent = parent
__parent__ = property(__getParent, __setParent)
@property
def crumbs(self):
request = self.request
objects = []
for obj in ([self.context] +
list(zope.traversing.api.getParents(self.context))):
objects.append(obj)
if sameProxiedObjects(obj, request.getVirtualHostRoot()) or \
isinstance(obj, Exception):
break
objects.reverse()
for object in objects:
info = zope.component.queryMultiAdapter(
(object, self.request), interfaces.IBreadcrumb)
if info is None:
continue
yield {'name': info.name,
'url': info.url,
'activeURL': info.activeURL}
@zope.interface.implementer(interfaces.IBreadcrumb)
class GenericBreadcrumb:
"""A generic breadcrumb adapter."""
zope.component.adapts(zope.interface.Interface, IHTTPRequest)
# See interfaces.IBreadcrumb
activeURL = True
def __init__(self, context, request):
self.context = context
self.request = request
@property
def name(self):
"""See interfaces.IBreadcrumb"""
name = getattr(self.context, 'title', '')
if not name:
name = getattr(self.context, '__name__', '')
if not name and IContainmentRoot.providedBy(self.context):
name = 'top'
return name
@property
def url(self):
"""See interfaces.IBreadcrumb"""
return zope.traversing.browser.absoluteURL(self.context, self.request)
def CustomNameBreadcrumb(name):
return type('CustomNameBreadcrumb(%r)' % name,
(GenericBreadcrumb,), {'name': name}) | z3c.breadcrumb | /z3c.breadcrumb-3.0-py3-none-any.whl/z3c/breadcrumb/browser.py | browser.py |
======
README
======
The z3c.breadcrumb package provides base classes for breadcrumb
implementations. It allows you to write adapters for each content object which
provides it's own rule for providing the breadcrumb name, url and selection.
Let's do some imports we will use later.
>>> import zope.interface
>>> import zope.component
>>> from zope.publisher.interfaces.http import IHTTPRequest
>>> from zope.publisher.browser import TestRequest
>>> from zope.traversing.browser import absoluteURL
>>> from zope.container import contained
>>> from z3c.breadcrumb import interfaces
>>> from z3c.breadcrumb import browser
IBreadcrumb
-----------
Let's define a interface and a content object.
>>> class IOffice(zope.interface.Interface):
... """Office interface."""
>>> @zope.interface.implementer(IOffice)
... class Office(contained.Contained):
... def __init__(self, label):
... self.label = label
... self.activeURL = True
>>> office = Office('Zope Foundation')
>>> office.__name__ = 'ZF'
There is a generic breadcrumb implementation which is registered by
default. If we do not implement a custom IBreadcrumb the generic adapter will
return the ``title`` or ``__name__`` of the item. Let's register the default
adapter, this is normally done in ``configure.zcml``:
>>> zope.component.provideAdapter(browser.GenericBreadcrumb)
And see what we get:
>>> request = TestRequest()
>>> breadcrumb = zope.component.getMultiAdapter((office, request),
... interfaces.IBreadcrumb)
>>> breadcrumb.name
'ZF'
We can also implement a custom ``IBreadcrumb`` adapter and provide another
name for the breadcrumb name:
>>> @zope.interface.implementer(interfaces.IBreadcrumb)
... @zope.component.adapter(IOffice, IHTTPRequest)
... class BreadcrumbForOffice(object):
...
... def __init__(self, context, request):
... self.context = context
... self.request = request
...
... @property
... def name(self):
... return self.context.label
...
... @property
... def url(self):
... return absoluteURL(self.context, self.request)
...
... @property
... def activeURL(self):
... return self.context.activeURL
Let's register the custom ``IBreadcrumb`` adapter for IOffice:
>>> zope.component.provideAdapter(BreadcrumbForOffice)
And check the new breadcrumb name:
>>> breadcrumb = zope.component.getMultiAdapter((office, request),
... interfaces.IBreadcrumb)
>>> breadcrumb.name
'Zope Foundation'
CustomNameBreadcrumb
--------------------
Let's define another interface and a content object.
>>> class IOfficeContainer(zope.interface.Interface):
... """Container of offices."""
>>> @zope.interface.implementer(IOfficeContainer)
... class OfficeContainer(contained.Contained):
... pass
>>> offices = OfficeContainer()
>>> offices.__name__ = 'offices'
If the custom name for this kind of object is always the same it would quickly
get tedious to write a full IBreadcrumb implementation. As a shortcut you
can use CustomNameBreadcrumb to get an adapter that acts like
GenericBreadcrumb, but returns the name you want.
>>> adapter = browser.CustomNameBreadcrumb('Offices')
>>> adapter
<class 'z3c.breadcrumb.browser.CustomNameBreadcrumb('Offices')'>
>>> zope.component.provideAdapter(adapter,
... adapts=(IOfficeContainer, IHTTPRequest))
>>> breadcrumb = zope.component.getMultiAdapter((offices, request),
... interfaces.IBreadcrumb)
>>> breadcrumb.name
'Offices'
IBreadcrumbs
------------
There is also a IBreadcrumbs adapter which knows how to collect breadcrumb
informations for each item he traverses. We need to setup a little bit of
infrastructure:
>>> root = rootFolder
>>> root['office'] = office
Register the IBreadcrumbs adapter:
>>> zope.component.provideAdapter(browser.Breadcrumbs,
... (zope.interface.Interface, zope.interface.Interface),
... interfaces.IBreadcrumbs)
Now we can collect breadcrumbs for our items. You can see the url is correct
and the label ``Zope Foundation`` is collected by the custom IBreadcrumb
adapter:
>>> breadcrumbs = zope.component.getMultiAdapter((office, request),
... interfaces.IBreadcrumbs)
>>> from pprint import pprint
>>> pprint(list(breadcrumbs.crumbs))
[{'activeURL': True,
'name': 'top',
'url': 'http://127.0.0.1'},
{'activeURL': True,
'name': 'Zope Foundation',
'url': 'http://127.0.0.1/office'}]
>>> breadcrumbs.__parent__ is office
True
Default breadcrumbs stops on virtual host root
>>> request._vh_root = office
>>> pprint(list(breadcrumbs.crumbs))
[{'activeURL': True,
'name': 'Zope Foundation',
'url': 'http://127.0.0.1'}]
If the breadcrumb of an item is a Null-adapter, then the item is ignored.
>>> from zope.traversing.interfaces import IContainmentRoot
>>> zope.component.provideAdapter(
... lambda c, r: None,
... (IContainmentRoot, IHTTPRequest),
... interfaces.IBreadcrumb)
>>> request = TestRequest()
>>> breadcrumbs = zope.component.getMultiAdapter(
... (office, request), interfaces.IBreadcrumbs)
>>> pprint(list(breadcrumbs.crumbs))
[{'activeURL': True,
'name': 'Zope Foundation',
'url': 'http://127.0.0.1/office'}]
| z3c.breadcrumb | /z3c.breadcrumb-3.0-py3-none-any.whl/z3c/breadcrumb/README.txt | README.txt |
======================================
The Zope 3 Community's Project Builder
======================================
z3c.builder is a tool that helps you jump start development of a Zope
3 application by generating all the boiler plate code and
configuration for you.
Goals
-----
* Easy to use
* Easy to extend
* More or less complete
Brainstorming
-------------
The easiest thing to tackle is just generating all the files that are
needed without necessarily any customizable contents. A minimal eggs
and buildout based project would have a directory structure like this::
package-name/
bootstrap.py
buildout.cfg
setup.py
README.txt
CHANGES.txt
src/
namespace-package/
__init__.py
package/
__init__.py
Each section of this directory structure can be further configured ad
infinitum. The tricky part is deciding when enough is enough. Let's
consider each of these sections and what they offer.
bootstrap.py
~~~~~~~~~~~~
This is brain dead simple. There is a standard file that everyone
uses and we just need to copy it in. I don't think there is any
potential customization points.
buildout.cfg
~~~~~~~~~~~~
There are pretty much an infinite number of generic customizations you
can make to a buildout.cfg file. Here are some of the ones we might
want to support out of the box:
- Creation of multiple buildout.cfg files, for different uses
(developers, production, minimal?)
- kgs hookup, with support for using a remote extends buildout
option, or downloading a versions.cfg file upon project creation.
- Some typically used and useful parts:
- tests
- coverage
- python interpreter
- ctags
- documentation generators
(note that some of these parts require additional files to be
added to the src tree in order to make sense)
- Zope Server setup.
This bleeds into all the zope 3 configuration that we might
want to do and also paster setup. This would include basically
anything you can configure in zope.conf files.
setup.py
~~~~~~~~
This is relatively straight forward. There are the obvious keyword
arguments that are passed to the setup() command that we'll want to
configure. There are however some slightly more interesting peices:
- long_description: Since this is what becomes the python page,
we'll want to hook up the boiler plate code for using a
combination of README.txt, CHANGES.txt and others to generate the
full long description. This shouldn't be that hard.
- classifiers: It's always a pain in the ass to remember what all
the different classifiers can be and how they should be
formatted.
- extras_requires: we may want to configure what extras_requires
sections there are. Typically we would have a test and an app
section. There might also be a docs section and others.
- entry_points: this is where it gets a bit trickier. Paster has
it's own entry point boiler plate code that you need. We may also
want to configure any number of additonal command line script
entry points.
README.txt
~~~~~~~~~~
Just a simple file dump with maybe some configurable initial content.
CHANGES.txt
~~~~~~~~~~~
Another simple file dump with an example of the change log format that
we've standardized on.
Other Python Files
~~~~~~~~~~~~~~~~~~
The rest of the files are just for mkaing proper python modules and
should be brain dead simple.
Conclusion
~~~~~~~~~~
I think starting by making a project builder for simple egg/buildout
based projects is a good starting point. It's an atainable and useful
goal which will give us the experience we need to tackle the more
complex task of zope boiler plate.
| z3c.builder.core | /z3c.builder.core-0.1.0.tar.gz/z3c.builder.core-0.1.0/README.txt | README.txt |
import os
import zope.interface
from zope.schema.fieldproperty import FieldProperty
from z3c.builder.core import base, interfaces, python
class AddFormBuilder(python.ModuleBuilderGetter, base.ContentBuilder):
zope.interface.implements(interfaces.IAddFormBuilder)
interface = FieldProperty(interfaces.IAddFormBuilder['interface'])
factory = FieldProperty(interfaces.IAddFormBuilder['factory'])
fields = FieldProperty(interfaces.IAddFormBuilder['fields'])
next = FieldProperty(interfaces.IAddFormBuilder['next'])
label = FieldProperty(interfaces.IAddFormBuilder['label'])
def __init__(self, name, interface, factory,
fields=(), next='index.html', label=u'Add Form'):
super(AddFormBuilder, self).__init__(name)
self.interface = interface
self.factory = factory
self.fields = tuple([str(f) for f in fields])
self.next = next
self.label = label
def update(self):
"""See interfaces.IBaseBuilder"""
self.getModuleBuilder().imports += [
'z3c.form.form.AddForm',
'z3c.form.field.Fields',
'zope.traversing.browser.absoluteURL',
self.interface,
self.factory]
def render(self):
"""See interfaces.IContentBuilder"""
template = open(base.getTemplatePath('add-form.py'), 'r').read()
output = (template %{
'interface': self.interface.rsplit('.', 1)[-1],
'label': self.label,
'fields': ', '.join([repr(field) for field in self.fields]),
'factory': self.factory.rsplit('.', 1)[-1],
'next': self.next,
'className':self.name,
})
output += '\n'
return output
class EditFormBuilder(python.ModuleBuilderGetter, base.ContentBuilder):
zope.interface.implements(interfaces.IEditFormBuilder)
interface = FieldProperty(interfaces.IEditFormBuilder['interface'])
fields = FieldProperty(interfaces.IEditFormBuilder['fields'])
label = FieldProperty(interfaces.IEditFormBuilder['label'])
def __init__(self, name, interface, fields=(), label=u'Edit Form'):
super(EditFormBuilder, self).__init__(name)
self.interface = interface
self.fields = tuple([str(f) for f in fields])
self.label = label
def update(self):
self.getModuleBuilder().imports += [
'z3c.form.form.EditForm',
'z3c.form.field.Fields',
self.interface]
def render(self):
template = open(base.getTemplatePath('edit-form.py'), 'r').read()
output = (template %{
'interface': self.interface.rsplit('.', 1)[-1],
'label': self.label,
'fields': ', '.join([repr(field) for field in self.fields]),
'className':self.name,
})
output += '\n'
return output
class SimpleDisplayFormBuilder(python.ModuleBuilderGetter, base.ContentBuilder):
zope.interface.implements(interfaces.IDisplayFormBuilder)
interface = FieldProperty(interfaces.IDisplayFormBuilder['interface'])
fields = FieldProperty(interfaces.IDisplayFormBuilder['fields'])
template = FieldProperty(interfaces.IDisplayFormBuilder['template'])
def __init__(self, name, interface, template=None, fields=()):
super(SimpleDisplayFormBuilder, self).__init__(name)
self.interface = interface
self.template = template
self.fields = tuple([str(f) for f in fields])
def update(self):
self.getModuleBuilder().imports += [
'z3c.form.form.Form',
'z3c.form.form.DisplayForm',
'z3c.form.field.Fields',
self.interface]
# Add the template for the form.
if self.template:
browserPackage = self.getModuleBuilder().__parent__
if 'display.pt' not in browserPackage:
zpt = base.SimpleFileBuilder(
u'display.pt', base.getTemplatePath('simple-display-form.pt'))
browserPackage.add(zpt)
zpt.update()
def render(self):
template = open(
base.getTemplatePath('simple-display-form.py'), 'r').read()
output = (template %{
'interface': self.interface.rsplit('.', 1)[-1],
'fields': ', '.join([repr(field) for field in self.fields]),
'template': self.template,
'className': self.name,
})
output += '\n'
return output | z3c.builder.core | /z3c.builder.core-0.1.0.tar.gz/z3c.builder.core-0.1.0/src/z3c/builder/core/form.py | form.py |
import zope.interface
from zope.schema.fieldproperty import FieldProperty
from z3c.builder.core import base, interfaces
ZOPE_NS = 'http://namespaces.zope.org/zope'
BROWSER_NS = 'http://namespaces.zope.org/browser'
ZCML_NS = 'http://namespaces.zope.org/zcml'
Z3C_NS = 'http://namespaces.zope.org/z3c'
class ZCMLDirectiveBuilder(base.BuilderContainer, base.ContentBuilder):
zope.interface.implements(interfaces.IZCMLDirectiveBuilder)
namespace = FieldProperty(interfaces.IZCMLDirectiveBuilder['namespace'])
#name = FieldProperty(interfaces.IZCMLDirectiveBuilder['name'])
attributes = FieldProperty(interfaces.IZCMLDirectiveBuilder['attributes'])
indent = FieldProperty(interfaces.IZCMLDirectiveBuilder['indent'])
_indentSpaces = 2
_indentAttributeSpaces = 4
def __init__(self, namespace, name, attributes=None, indent=0):
super(ZCMLDirectiveBuilder, self).__init__(unicode(name))
self.namespace = namespace
if not attributes:
attributes = {}
self.attributes = attributes
self.indent = indent
def getZCMLBuilder(self):
"""See interfaces.IZCMLDirectiveBuilder"""
builder = self
while not interfaces.IZCMLFileBuilder.providedBy(builder):
builder = builder.__parent__
return builder
def add(self, builder):
"""See interfaces.IBuilderContainer"""
name = base.getUUID()
self[name] = builder
return name
def update(self):
"""See interfaces.IBaseBuilder"""
zcml = self.getZCMLBuilder()
if self.namespace is not None and self.namespace not in zcml.namespaces:
zcml.namespaces.append(self.namespace)
for builder in self.values():
builder.indent = self.indent + 1
builder.update()
def render(self):
"""See interfaces.IContentBuilder"""
output = ''
prefix = ''
if self.namespace:
prefix = self.namespace.rsplit('/')[-1] + ':'
# Write XML node
indent = ' ' * self._indentSpaces * self.indent
attrIndent = indent + ' '*self._indentAttributeSpaces
output += indent + '<%s%s' %(prefix, self.name)
if self.attributes:
for name, attr in reversed(self.attributes.items()):
output += '\n' + attrIndent + '%s="%s"' %(name, attr)
output += '\n' + attrIndent
if not len(self):
output += '/>\n'
return output
output += '>\n'
# Write all sub-builders.
for builder in self.values():
output += builder.render()
output += '\n'
# Close XML node.
output += indent + '</%s%s>\n' %(prefix, self.name)
# Return result.
return output
class ZCMLFileBuilder(ZCMLDirectiveBuilder, base.FileBuilder):
zope.interface.implements(interfaces.IZCMLFileBuilder)
i18n_domain = FieldProperty(interfaces.IZCMLFileBuilder['i18n_domain'])
namespaces = FieldProperty(interfaces.IZCMLFileBuilder['namespaces'])
def __init__(self, name):
ZCMLDirectiveBuilder.__init__(self, None, 'configure')
base.FileBuilder.__init__(self, self.name, str(name))
def update(self):
"""See interfaces.IBaseBuilder"""
self.namespaces = []
if not self.i18n_domain:
project = self.getProject()
self.i18n_domain = project.name
super(ZCMLFileBuilder, self).update()
# Create list of attributes
self.attributes = {}
if self.i18n_domain:
self.attributes['i18n_domain'] = self.i18n_domain
for namespace in self.namespaces:
name = namespace.rsplit('/', 1)[-1]
self.attributes['xmlns:'+name] = namespace
def __repr__(self):
return '<%s %r>' %(self.__class__.__name__, self.filename) | z3c.builder.core | /z3c.builder.core-0.1.0.tar.gz/z3c.builder.core-0.1.0/src/z3c/builder/core/zcml.py | zcml.py |
import os
import zope.interface
import zope.schema
from zope.container.constraints import contains, containers
from zope.container.interfaces import IOrderedContainer, IContained
from zope.schema.vocabulary import SimpleTerm
from zope.schema.vocabulary import SimpleVocabulary
troveClassifiers = open(os.path.join(os.path.dirname(__file__),
'trove-classifiers.txt')).read().split('\n')
troveClassiferVocabulary = SimpleVocabulary(map(SimpleTerm,
troveClassifiers))
class FileExistsException(Exception):
"""Exception to throw if a file that will be written already exists."""
filename = None
def __init__(self, filename, message=u''):
super(FileExistsException, self).__init__(message)
self.filename = filename
# --- Basic Builder Components ------------------------------------------------
class IBaseBuilder(IContained):
"""A builder constructs code from a programmatic desciption."""
name = zope.schema.TextLine(
title=u'Name',
description=u'The name of the builder instance.')
def update():
"""Update the builder before rendering.
The purpose of this method is to prepare the builder and dependents
for rendering.
"""
class IBuilderContainer(IBaseBuilder, IOrderedContainer):
"""A container for other builders."""
contains(IBaseBuilder)
def add(builder):
"""Add a builder to the container.
The name is usually computed from the name of the builder.
The name of the builder in the component is returned.
"""
def remove(builder):
"""Remove the builder from the container."""
class IProjectGetter(zope.interface.Interface):
"""Gets the project the builser belongs to."""
def getProject():
"""Return the project instance."""
class IContentBuilder(IBaseBuilder):
"""Build a piece of content/code within a file."""
def render():
"""Render the code and return the result as a string."""
class IFilesystemBuilder(IBaseBuilder):
"""Builds and writes a filesystem-level component."""
def write(target):
"""Write the new file(s) into the target directory."""
class IFileBuilder(IFilesystemBuilder):
"""Bulder to construct a single file with all its content."""
filename = zope.schema.ASCIILine(
title=u'File Name',
description=u'The name of the file to be created.')
class IDirectoryBuilder(IFilesystemBuilder, IBuilderContainer):
"""Builder to construct a directory and all its content."""
contains(IFileBuilder, '.IDirectoryBuilder')
dirname = zope.schema.ASCIILine(
title=u'Directory Name',
description=u'The name of the directory to be created.')
# --- Python Code Builders ----------------------------------------------------
class IPythonPathRoot(zope.interface.Interface):
"""Marker interface flagging the root directory."""
class IPythonPathGetter(zope.interface.Interface):
"""Gets a full Python path of the current builder."""
def getPythonPath():
"""Return full Python path as a string."""
class IModuleBuilderGetter(zope.interface.Interface):
"""Gets the next module builder."""
def getModuleBuilder():
"""Return the next module builder."""
class IPackageBuilder(IDirectoryBuilder, IPythonPathGetter):
"""Builds a full Python package or sub-package."""
packageName = zope.schema.ASCIILine(
title=u'Package Name',
description=u'The name of the package to be created.',
required=True)
initTemplate = zope.schema.Bytes(
title=u'Init Template',
description=u'The content template for the `__init__.py` file.',
required=True)
class IModuleBuilder(IFileBuilder, IBuilderContainer, IPythonPathGetter):
"""Builds a Python module."""
moduleName = zope.schema.ASCIILine(
title=u'Module Name',
description=u'The name of the module to be created.')
imports = zope.schema.List(
title=u'Import List',
description=u'The list of objects to import.')
# --- Content Builders --------------------------------------------------------
class IFunctionBuilder(IContentBuilder):
"""A builder to construct a function."""
args = zope.schema.Tuple(
title=u'Args',
description=u'List of function arguments.',
required=False)
kwargs = zope.schema.Dict(
title=u'Kwargs',
description=u'<apping of function keyword arguments.',
required=False)
docstring = zope.schema.ASCII(
title=u'Interface Docstring',
description=u'The docstring of the function.')
indent = zope.schema.Int(
title=u'Indentation Level',
description=u'The number of columns to indent the function.',
default=0)
code = zope.schema.ASCII(
title=u'Code',
description=u'The source code of the function.')
class IFieldBuilder(IContentBuilder):
"""A builder to create a field for an interface builder."""
fieldName = zope.schema.ASCIILine(
title=u'Field Name',
description=u'The name of the field.',
required=True)
type = zope.schema.ASCIILine(
title=u'Type',
description=u'The full Python path of the type of the field.',
required=True)
attributes = zope.schema.Dict(
title=u'Attributes',
key_type = zope.schema.ASCIILine(),
value_type = zope.schema.Field(),
description=u'The attributes of the field.')
indent = zope.schema.Int(
title=u'Indentation Level',
description=u'The number of columns to indent the field.',
default=0)
class IInterfaceBuilder(IPythonPathGetter, IContentBuilder):
"""A builder to construct interfaces and schemas."""
docstring = zope.schema.ASCII(
title=u'Interface Docstring',
description=u'The docstring of the itnerface.')
bases = zope.schema.List(
title=u'Bases',
description=u'A list of base interfaces.')
class IClassFromInterfaceBuilder(IContentBuilder):
#className = zope.schema.TextLine(
# title=u'Class Name',
# description=u'The name of the generated class.')
interface = zope.schema.Field(
title=u'Interface',
description=u'The interface to generate the class from.')
docstring = zope.schema.ASCII(
title=u'Interface Docstring',
description=u'The docstring of the interface.')
bases = zope.schema.List(
title=u'Bases',
description=u'A list of base interfaces (full Python path).',
value_type=zope.schema.DottedName(title=u'Full Python Path'))
implementations = zope.schema.Dict(
title=u'Implementations',
description=u'A collection of method implementations.',
key_type=zope.schema.ASCIILine(),
value_type=zope.schema.ASCII())
# --- Setup Builders ---------------------------------------------------------
class ISetupBuilder(IFileBuilder):
version = zope.schema.TextLine(
title=u"Version",
default=u"0.1.0",
required=False)
license = zope.schema.TextLine(
title=u"License",
default=u"GPLv3",
required=False)
author = zope.schema.TextLine(
title=u"Author",
default=u"",
required=False)
author_email = zope.schema.TextLine(
title=u"Author Email",
default=u"",
required=False)
description = zope.schema.TextLine(
title=u"Description",
default=u"",
required=False)
keywords = zope.schema.List(
title=u"Keywords",
value_type=zope.schema.TextLine(),
required=False)
namespace_packages = zope.schema.List(
title=u'Namespace Packages',
value_type=zope.schema.TextLine(),
required=False)
url = zope.schema.TextLine(
title=u'URL',
required=False)
classifiers = zope.schema.List(
title=u"Trove Classifiers",
value_type=zope.schema.Choice(
vocabulary=troveClassiferVocabulary),
required=False)
install_requires = zope.schema.List(
title=u"Install Requires",
value_type=zope.schema.ASCIILine(),
required=False)
extras_require = zope.schema.Dict(
title=u"Extras Require",
key_type=zope.schema.TextLine(),
value_type=zope.schema.List(value_type=zope.schema.TextLine()))
entry_points = zope.schema.Dict(
title=u"Extras Require",
key_type=zope.schema.TextLine(),
value_type=zope.schema.List(value_type=zope.schema.TextLine()))
def addExtrasRequires(name, requirements):
"""Add the requirements to the named extra.
Multiple calls should not override each other.
"""
def removeExtrasRequires(name):
"""Remove the requirements from the named extra."""
def addEntryPoints(name, entries):
"""Add entry points for the given name.
Multiple calls should not override each other.
"""
def removeEntryPoints(name):
"""Remove the entry points from the named section."""
# --- Buildout Config Builders ------------------------------------------------
class IPartBuilder(IFileBuilder):
values = zope.schema.List(
title=u"Values",
description=(u"A list of values set for this part."),
required=True)
autoBuild = zope.schema.Bool(
title=u"Auto-Build",
description=(u"A flag, when set, causes the part to be built "
u"automatically"),
default=True,
required=True)
def addValue(key, value):
"""Add a value to the part."""
def removeValue(key):
"""Remove a value by key."""
class IBuildoutConfigBuilder(IBuilderContainer, IFileBuilder):
"""An object generating the `buildout.cfg` file."""
extends = zope.schema.List(
title=u"Extends",
description=(u"A list of buildout configurations used to extend the "
u"configuration file."),
value_type=zope.schema.TextLine(),
required=True)
names = zope.schema.List(
title=u"Names",
description=u"A list of part names that are automatically built.",
value_type=zope.schema.TextLine(),
required=True)
# --- ZCML Builders -----------------------------------------------------------
class IZCMLDirectiveBuilder(IBuilderContainer, IContentBuilder):
"""A ZCML Directive Builder."""
namespace = zope.schema.URI(
title=u'Namespace',
description=u'Namespace URI of the directive.',
required=False)
#name = zope.schema.TextLine(
# title=u'Name',
# description=u'The directive name.',
# required=True)
attributes = zope.schema.Dict(
title=u'Attributes',
description=u'A collection of attributes of the ZCML directive.',
required=False)
indent = zope.schema.Int(
title=u'Indentation Level',
description=u'The number of columns to indent the directive.',
default=0)
def getZCMLBuilder():
"""Get the ZCML File Builder."""
class IZCMLFileBuilder(IZCMLDirectiveBuilder, IFileBuilder):
"""A ZCML File Builder."""
i18n_domain = zope.schema.TextLine(
title=u'I18n Domain',
description=u'The I18n domain to use for localization.',
required=False)
namespaces = zope.schema.List(
title=u'Namespaces',
description=u'A list of namespaces used in the file.',
required=True)
# --- Form Builders -----------------------------------------------------------
class IFormBuilder(IContentBuilder):
"""Generic form builder."""
interface = zope.schema.ASCIILine(
title=u'Interface',
description=u'Full path to the interface.')
fields = zope.schema.Tuple(
title=u'Fields',
description=u'A list of fields to display.',
value_type=zope.schema.ASCIILine())
class IAddFormBuilder(IFormBuilder):
"""Add form builder."""
label = zope.schema.TextLine(
title=u'Label',
description=u'A label of the form.')
factory = zope.schema.ASCIILine(
title=u'Factory',
description=u'Full path to the factory.')
next = zope.schema.ASCII(
title=u'Next URL',
description=u'The relative URL to go to after adding the object.')
class IEditFormBuilder(IFormBuilder):
"""Edit form builder."""
label = zope.schema.TextLine(
title=u'Label',
description=u'A label of the form.')
class IDisplayFormBuilder(IFormBuilder):
"""Display form builder."""
template = zope.schema.Text(
title=u'Template',
description=u'A template for displaying the data.',
required=False)
# --- Project Builders --------------------------------------------------------
class IProjectBuilder(IDirectoryBuilder):
"""A Python Project Builder."""
projectName = zope.schema.ASCIILine(
title=u"Project Name")
commentHeader = zope.schema.Text(
title=u"Comment Header",
required=False)
def write(target, force=False):
"""Write the new project in the target directory.
If `force` is set, then any existing project in the target path is
ignored, and the new one is wrtten over it.
"""
class IBuildoutProjectBuilder(IProjectBuilder):
"""A Buildout-based Python Project Builder."""
package = zope.schema.Object(
title=u"Project Code Package",
schema=IPackageBuilder,
readonly=True)
setup = zope.schema.Object(
title=u"Project Setup",
schema=ISetupBuilder,
readonly=True)
buildout = zope.schema.Object(
title=u"Project Buildout",
schema=IFileBuilder,
readonly=True) | z3c.builder.core | /z3c.builder.core-0.1.0.tar.gz/z3c.builder.core-0.1.0/src/z3c/builder/core/interfaces.py | interfaces.py |
import types
import zope.interface
from zope.schema.fieldproperty import FieldProperty
from z3c.builder.core import base, interfaces
class ModuleBuilderGetter(object):
zope.interface.implements(interfaces.IModuleBuilderGetter)
def getModuleBuilder(self):
module = self
while not interfaces.IModuleBuilder.providedBy(module):
module = module.__parent__
if module is None:
raise ValueError(
'No module builder was found and the root node of '
'the project tree was reached.')
return module
class PackageBuilder(base.DirectoryBuilder):
zope.interface.implements(interfaces.IPackageBuilder)
initTemplate = base.getTemplatePath('__init__.py')
initNamespaceTemplate = base.getTemplatePath('__init__namespace.py')
packageName = FieldProperty(interfaces.IPackageBuilder['packageName'])
def __init__(self, name, packageName=None):
if packageName is None:
packageName = str(name)
super(PackageBuilder, self).__init__(name, packageName)
self.packageName = packageName
def getPythonPath(self):
if interfaces.IPythonPathRoot.providedBy(self.__parent__):
return self.packageName
if self.__parent__ is None:
return self.packageName
return self.__parent__.getPythonPath() + '.' + str(self.packageName)
def update(self):
"""See interfaces.IBaseBuilder"""
super(PackageBuilder, self).update()
matches = [subBuilder for subBuilder in self.values()
if (interfaces.IFileBuilder.providedBy(subBuilder) and
subBuilder.filename == '__init__.py')]
if matches:
return
template = self.initTemplate
try:
project = self.getProject()
except ValueError:
project = None
if project and self.getPythonPath() in project.setup.namespace_packages:
template = self.initNamespaceTemplate
self['__init__.py'] = base.SimpleFileBuilder(
u'__init__.py', template)
class ModuleBuilder(base.BuilderContainer, base.FileBuilder):
zope.interface.implements(interfaces.IModuleBuilder)
moduleName = FieldProperty(interfaces.IModuleBuilder['moduleName'])
imports = FieldProperty(interfaces.IModuleBuilder['imports'])
def __init__(self, name, moduleName=None):
super(ModuleBuilder, self).__init__(name)
if moduleName is None:
moduleName = str(name)[:-3]
self.moduleName = moduleName
self.filename = str(name)
def getPythonPath(self):
return self.__parent__.getPythonPath() + '.' + str(self.moduleName)
def update(self):
self.imports = []
super(ModuleBuilder, self).update()
def render(self):
"""See interfaces.IContentBuilder"""
output = []
# Render comment header.
project = self.getProject()
output.append(project.commentHeader)
# Render module doc string.
output.append('"""Module Documentation"""\n')
# Render imports making sure none is duplicated.
for path in sorted(set(self.imports)):
module, name = tuple(path.rsplit('.', 1))
if module != self.getPythonPath():
output.append('from %s import %s\n' % (module, name))
output.append('\n\n')
# Render all sub-builders.
for subBuilder in self.values():
output.append(subBuilder.render())
output.append('\n\n')
# Return a concatenated version of all pieces.
return ''.join(output)
class FieldBuilder(ModuleBuilderGetter, base.ContentBuilder):
zope.interface.implements(interfaces.IFieldBuilder)
fieldName = FieldProperty(interfaces.IFieldBuilder['fieldName'])
type = FieldProperty(interfaces.IFieldBuilder['type'])
attributes = FieldProperty(interfaces.IFieldBuilder['attributes'])
indent = FieldProperty(interfaces.IFieldBuilder['indent'])
_numberOfSpaces = 4
def __init__(self, name, type, indent=0, **attributes):
self.name = name
self.type = type
self.indent = indent
self.attributes = attributes
def update(self):
self.getModuleBuilder().imports.append(self.type)
def render(self):
indent = ' ' * (self.indent * self._numberOfSpaces)
output = ''
output += indent + '%s = %s(' %(self.name, self.type.rsplit('.')[-1])
if self.attributes:
output += '\n'
indent += ' ' * (self._numberOfSpaces)
for item in reversed(self.attributes.items()):
output += indent + '%s=%r,\n' %item
if self.attributes:
output += indent
output += ')\n'
return output
class FunctionBuilder(ModuleBuilderGetter, base.ContentBuilder):
zope.interface.implements(interfaces.IFunctionBuilder)
fieldName = FieldProperty(interfaces.IFieldBuilder['fieldName'])
type = FieldProperty(interfaces.IFieldBuilder['type'])
attributes = FieldProperty(interfaces.IFieldBuilder['attributes'])
indent = FieldProperty(interfaces.IFieldBuilder['indent'])
_numberOfSpaces = 4
def __init__(self, name, args=(), kwargs=None,
docstring='', indent=0, code=''):
self.name = name
self.args = args
self.kwargs = (kwargs and dict(kwargs)) or {}
self.docstring = docstring
self.indent = indent
self.code = code
def render(self):
# Generate the proper indentation level.
indent = ' ' * (self.indent * self._numberOfSpaces)
output = ''
# Render the first part of the function header.
output += indent+'def %s(' %str(self.name)
# Render the position arguments.
output += ', '.join([str(arg) for arg in self.args])
if self.args and self.kwargs:
output += ', '
# Render keyword arguments.
output += ', '.join(['%s=%r' %item for item in self.kwargs.items()])
output += '):\n'
# Render body of function
indent += self._numberOfSpaces * ' '
if self.docstring:
output += indent + '"""%s"""' %self.docstring
if self.code:
output += '\n'
for line in self.code.split('\n'):
output += indent + line + '\n'
if not self.code and not self.docstring:
output += indent + 'pass'
output += '\n'
return output
class InterfaceBuilder(ModuleBuilderGetter,
base.BuilderContainer, base.ContentBuilder):
zope.interface.implements(interfaces.IInterfaceBuilder)
docstring = FieldProperty(interfaces.IInterfaceBuilder['docstring'])
bases = FieldProperty(interfaces.IInterfaceBuilder['bases'])
def __init__(self, name):
super(InterfaceBuilder, self).__init__(name)
self.docstring = ''
self.bases = []
def add(self, builder):
if isinstance(builder, (FunctionBuilder, FieldBuilder)):
builder.indent = 1
return super(InterfaceBuilder, self).add(builder)
def getPythonPath(self):
return self.__parent__.getPythonPath() + '.' + str(self.name)
def update(self):
if len(self.bases) == 0:
self.bases = ['zope.interface.Interface']
self.getModuleBuilder().imports += self.bases
for builder in self.values():
builder.update()
def render(self):
bases = [path.rsplit('.', 1)[-1] for path in self.bases]
output = ''
output += 'class %s(%s):\n' %(str(self.name), ', '.join(bases))
output += ' """%s"""\n' %self.docstring
for builder in self.values():
output += builder.render()
output += '\n'
return output
class ClassFromInterfaceBuilder(ModuleBuilderGetter, base.ContentBuilder):
zope.interface.implements(interfaces.IClassFromInterfaceBuilder)
interface = FieldProperty(
interfaces.IClassFromInterfaceBuilder['interface'])
bases = FieldProperty(
interfaces.IClassFromInterfaceBuilder['bases'])
docstring = FieldProperty(
interfaces.IClassFromInterfaceBuilder['docstring'])
implementations = FieldProperty(
interfaces.IClassFromInterfaceBuilder['implementations'])
def __init__(self, name, interface, bases=None):
super(ClassFromInterfaceBuilder, self).__init__(name)
self.interface = interface
self.bases = list(bases) if bases is not None else []
self.docstring = ''
self.implementations = {}
def _resolve(self, path):
pieces = path.split('.')
# Find package root.
root = self
while not interfaces.IPythonPathRoot.providedBy(root.__parent__):
root = root.__parent__
# Find builder
path = ''
builder = root
for piece in pieces:
if path:
path += '.'
path += piece
for sub in builder.values():
if (hasattr(sub, 'getPythonPath') and
path == sub.getPythonPath()):
builder = sub
break
return builder
def addImplementation(self, name, code):
self.implementations[name] = code
def getPythonPath(self):
return self.__parent__.getPythonPath() + '.' + str(self.name)
def update(self):
# Determine the bases
if len(self.bases) == 0:
self.bases = ['object']
self.getModuleBuilder().imports += self.bases
# Compute the interface, if necessary
if isinstance(self.interface, types.StringTypes):
self.interface = self._resolve(self.interface)
# Add import for interface
self.__parent__.imports.append('zope.interface.implements')
self.__parent__.imports.append(self.interface.getPythonPath())
# Generate docstring if necessary
if not self.docstring:
self.docstring = "Implementation of ``%s``" % self.interface.getPythonPath()
# Generate fields and methods
self.fields = [entry for entry in self.interface.values()
if isinstance(entry, FieldBuilder)]
self.methods = [entry for entry in self.interface.values()
if isinstance(entry, FunctionBuilder)]
# Add imports if needed
if len(self.fields):
self.__parent__.imports.append(
'zope.schema.fieldproperty.FieldProperty')
def render(self):
bases = [path.rsplit('.', 1)[-1] for path in self.bases]
output = ''
output += 'class %s(%s):\n' %(self.name, ', '.join(bases))
output += ' """%s"""\n' %self.docstring
output += ' implements(%s)\n\n' %self.interface.name
for field in self.fields:
output += " %s = FieldProperty(%s['%s'])\n" %(
field.name, self.interface.name, field.name)
output += '\n'
for method in self.methods:
output += ' def %s(' %method.name
allargs = ['self']
allargs += [str(arg) for arg in method.args]
allargs += ['%s=%r' %item for item in method.kwargs.items()]
output += ', '.join(allargs)
output += '):\n'
output += ' """See ``%s``."""\n' %self.interface.getPythonPath()
if method.name in self.implementations:
impl = self.implementations[method.name]
output += ' '*8
output += impl.replace('\n', '\n'+' '*8)
output += '\n'
return output | z3c.builder.core | /z3c.builder.core-0.1.0.tar.gz/z3c.builder.core-0.1.0/src/z3c/builder/core/python.py | python.py |
import os
import zope.interface
from zope.schema.fieldproperty import FieldProperty
from z3c.builder.core import base, interfaces
class PartBuilder(base.ContentBuilder):
zope.interface.implements(interfaces.IPartBuilder)
values = FieldProperty(interfaces.IPartBuilder['values'])
autoBuild = FieldProperty(interfaces.IPartBuilder['autoBuild'])
def __init__(self, name, values=None, autoBuild=True):
super(PartBuilder, self).__init__(name)
if values is None:
values = []
self.values = list(values)
self.autoBuild = autoBuild
def addValue(self, key, value):
self.values.append((key, value))
def removeValue(self, key):
for item in self.values:
if item[0] == key:
self.values.remove(item)
return
def render(self):
output = ''
output += '[%s]\n' %self.name
for key, value in self.values:
output += '%s = %s\n' %(key, value)
return output
class BuildoutConfigBuilder(base.BuilderContainer, base.FileBuilder):
zope.interface.implements(interfaces.IBuildoutConfigBuilder)
extends = FieldProperty(interfaces.IBuildoutConfigBuilder['extends'])
names = FieldProperty(interfaces.IBuildoutConfigBuilder['names'])
def __init__(self):
super(BuildoutConfigBuilder, self).__init__(u'buildout.cfg')
self.extends = [u'http://download.zope.org/zope3.4/3.4.0/versions.cfg']
self.names = []
def update(self):
self.names = [part.name for part in self.values()
if part.autoBuild]
for part in self.values():
part.update()
def render(self):
output = ''
output += '[buildout]\n'
output += 'extends = %s\n' %(' \n'.join(self.extends))
output += 'develop = .\n'
output += 'parts = %s\n' %' '.join(self.names)
output += 'versions = versions\n'
if len(self):
output += '\n'
for part in self.values():
output += part.render()
output += '\n'
return output
def __repr__(self):
return '<%s for %r>' %(self.__class__.__name__, self.getProject().name) | z3c.builder.core | /z3c.builder.core-0.1.0.tar.gz/z3c.builder.core-0.1.0/src/z3c/builder/core/buildout.py | buildout.py |
import logging
import os
import uuid
import zope.interface
from zope.schema.fieldproperty import FieldProperty
from zope.container import contained, ordered
from z3c.builder.core import interfaces
formatter = logging.Formatter('%(levelname)s - %(message)s')
logger = logging.getLogger('info')
def getTemplatePath(fn):
return os.path.join(os.path.dirname(__file__), 'file-templates', fn)
def getUUID():
return str(uuid.uuid4())
class ProjectGetter(object):
zope.interface.implements(interfaces.IProjectGetter)
def getProject(self):
project = self
while not interfaces.IProjectBuilder.providedBy(project):
project = project.__parent__
if project is None:
raise ValueError(
'No project builder was found and the root node of '
'the project tree was reached.')
return project
class BaseBuilder(contained.Contained):
zope.interface.implements(interfaces.IBaseBuilder)
name = FieldProperty(interfaces.IBaseBuilder['name'])
def __init__(self, name):
self.name = name
def update(self):
"""See interfaces.IBaseBuilder"""
logger.debug("Updating %s" %self)
def __repr__(self):
return '<%s %r>' %(self.__class__.__name__, self.name)
class BuilderContainer(BaseBuilder, ordered.OrderedContainer):
zope.interface.implements(interfaces.IBuilderContainer)
def __init__(self, name):
super(BuilderContainer, self).__init__(name)
ordered.OrderedContainer.__init__(self)
def update(self):
"""See interfaces.IBaseBuilder"""
super(BuilderContainer, self).update()
for subBuilder in self.values():
subBuilder.update()
def add(self, builder):
"""See interfaces.IBuilderContainer"""
self[builder.name] = builder
return builder.name
def remove(self, builder):
"""See interfaces.IBuilderContainer"""
del self[builder.__name__]
class ContentBuilder(BaseBuilder, ProjectGetter):
zope.interface.implements(interfaces.IContentBuilder)
def render(self):
"""See interfaces.IContentBuilder"""
raise NotImplementedError(
"The `render()` method is not implemented by %s." %self)
class FilesystemBuilder(BaseBuilder, ProjectGetter):
zope.interface.implements(interfaces.IFilesystemBuilder)
def write(self, target):
"""See interfaces.IFilesystemBuilder"""
raise NotImplementedError(
"The `write(target)` method is not implemented.")
class DirectoryBuilder(FilesystemBuilder, BuilderContainer):
zope.interface.implements(interfaces.IDirectoryBuilder)
dirname = FieldProperty(interfaces.IDirectoryBuilder['dirname'])
def __init__(self, name, dirname=None):
super(DirectoryBuilder, self).__init__(name)
# Use the builder name as the default directory name.
if dirname is None:
dirname = str(name)
self.dirname = dirname
def write(self, target):
"""See interfaces.IFilesystemBuilder"""
dirpath = os.path.join(target, self.dirname)
logger.info("Creating directory %s" % dirpath)
os.mkdir(dirpath)
for subBuilder in self.values():
subBuilder.write(dirpath)
class FileBuilder(FilesystemBuilder):
zope.interface.implements(interfaces.IFileBuilder)
filename = FieldProperty(interfaces.IFileBuilder['filename'])
def __init__(self, name, filename=None):
super(FileBuilder, self).__init__(name)
if filename is None:
filename = str(name)
self.filename = filename
def render(self):
"""See interfaces.IContentBuilder"""
raise NotImplementedError("The `render()` method is not implemented.")
def write(self, target):
"""See interfaces.IFilesystemBuilder"""
filepath = os.path.join(target, self.filename)
logger.info("Creating file %s" % filepath)
file = open(filepath, 'w')
file.write(self.render())
file.close()
class SimpleFileBuilder(FileBuilder):
def __init__(self, name, template, filename=None):
super(SimpleFileBuilder, self).__init__(name, filename)
self.template = template
def render(self):
"""See interfaces.IContentBuilder"""
return open(self.template, 'r').read() | z3c.builder.core | /z3c.builder.core-0.1.0.tar.gz/z3c.builder.core-0.1.0/src/z3c/builder/core/base.py | base.py |
==========================
The Zope 3 Project Builder
==========================
The Zope 3 Project Builder was designed to interpret a high-level feature list
into a functional Python project. This package implements the code generation
pieces without worrying about the high-level features.
This package uses the concept of builders to construct a new project. The
process of building consists of two phases: (1) updating, and (2)
rendering/writing. Only (1) is well-defined at the fundamental level. In
addition, every builder *must* have a name.
>>> from z3c.builder.core import base
>>> builder = base.BaseBuilder(u'myBuilder')
>>> builder
<BaseBuilder u'myBuilder'>
>>> builder.name
u'myBuilder'
>>> builder.update()
Updating <BaseBuilder u'myBuilder'>
Builders often use sub-builders to complete the rendering. So another
important base class is the builder container:
>>> container = base.BuilderContainer(u'myContainer')
>>> container.add(builder)
u'myBuilder'
>>> container.update()
Updating <BuilderContainer u'myContainer'>
Updating <BaseBuilder u'myBuilder'>
>>> container.remove(builder)
>>> container.keys()
[]
It is also an ordered container:
>>> container.add(base.BaseBuilder(u'n1'))
u'n1'
>>> container.add(base.BaseBuilder(u'n2'))
u'n2'
>>> container.keys()
[u'n1', u'n2']
>>> container.updateOrder([u'n2', u'n1'])
>>> container.keys()
[u'n2', u'n1']
Rendering versus Writing
------------------------
Beyond the base builder, there are two types of builders, the ones that render
content and the ones the write files/directories.
The basic content rendering builder is named `ContentBuilder`.
>>> content = base.ContentBuilder(u'content')
>>> content
<ContentBuilder u'content'>
Every content builder must implement the `render()` method:
>>> content.render()
Traceback (most recent call last):
...
NotImplementedError: The `render()` method is not implemented by
<ContentBuilder u'content'>.
As you can see the `ContentBuilder` class is meant to be used as a base class.
Let's now look at builders that write files. They are known as filesystem
builders.
>>> fs = base.FilesystemBuilder(u'fs')
>>> fs
<FilesystemBuilder u'fs'>
Every filesystem builder must implement the `write(target)` method, where the
target is a path to the directory the builder is writing to.
>>> fs.write(buildPath)
Traceback (most recent call last):
...
NotImplementedError: The `write(target)` method is not implemented.
There are two implementations of the filesystem builder, the
`DirectoryBuilder` and the `FileBuilder` class.
The name of the directory builder is used as the initial directory name that
it creates.
>>> dir = base.DirectoryBuilder(u'myDir')
>>> dir
<DirectoryBuilder u'myDir'>
>>> dir.dirname
'myDir'
When the builder is written, it creates the directory.
>>> dir.update()
Updating <DirectoryBuilder u'myDir'>
>>> dir.write(buildPath)
Creating directory .../myDir
The name of the file builder is used to create the filename as well.
>>> file = base.FileBuilder(u'myFile.txt')
>>> file
<FileBuilder u'myFile.txt'>
>>> file.filename
'myFile.txt'
When the builder is written, it creates the file. It turns out that the file
builder is both, a filesystem and content builder.
>>> file.update()
Updating <FileBuilder u'myFile.txt'>
>>> file.write(buildPath)
Traceback (most recent call last):
...
NotImplementedError: The `render()` method is not implemented.
So, the `render()` method is not implemented. However, there is a simple file
builder that creates files based on a template file.
>>> import os
>>> template = os.path.join(buildPath, 'template.txt')
>>> open(template, 'w').write('File Contents')
>>> file = base.SimpleFileBuilder(u'rendered.txt', template)
>>> file.update()
Updating <SimpleFileBuilder u'rendered.txt'>
>>> file.write(buildPath)
Creating file .../rendered.txt
Let's now look at the generated file.
>>> more(buildPath, 'rendered.txt')
File Contents
Those are all the basic builders. In the "Specific Builders" section below you
can find a list of documents that document the fully implemented
builders. Those builders can be used to build full projects.
Builder Classes Layout
----------------------
A layout (UML class diagram) of all builder classes can be found at::
./class-diagram.png
All green classes can be used directly for building a project. Yellow and red
classes are meant to be used as abstract builder classes.
Specific Builders
-----------------
- ``project.txt``
Documents the project builder, the most upper-level builder.
- ``python.txt``
Documents and demonstrates builders that produce Python code.
- ``setup.txt``
Documents the setup builder which generates the `setup.py` file.
- ``buildout.txt``
Documents the buidlout builder that generates the ``buildout.cfg`` file.
- ``zcml.txt``
Documents the generation of ZCML directives.
- ``form.txt``
Documents the builders for `z3c.form`-based forms.
| z3c.builder.core | /z3c.builder.core-0.1.0.tar.gz/z3c.builder.core-0.1.0/src/z3c/builder/core/README.txt | README.txt |
import os
import shutil
import zope.interface
from rwproperty import getproperty
from zope.schema.fieldproperty import FieldProperty
from z3c.builder.core import base, buildout, interfaces, python, setup
class ProjectBuilder(base.DirectoryBuilder):
zope.interface.implements(interfaces.IProjectBuilder)
projectName = FieldProperty(interfaces.IProjectBuilder['projectName'])
commentHeader = FieldProperty(interfaces.IProjectBuilder['commentHeader'])
def __init__(self, name, projectName=None):
super(ProjectBuilder, self).__init__(name)
if projectName is None:
projectName = str(name)
self.projectName = self.dirname = projectName
self.commentHeader = unicode(open(
base.getTemplatePath('gpl3-header.py'), 'r').read())
def update(self):
self.directoryPath = unicode(self.name)
self.commentHeader = self.commentHeader %self.__dict__
for builder in self.values():
builder.update()
def write(self, target, force=False):
"""See interfaces.IProjectBuilder"""
dirPath = os.path.join(target, self.dirname)
if os.path.exists(dirPath):
if not force:
raise interfaces.FileExistsException(dirPath)
shutil.rmtree(dirPath)
super(ProjectBuilder, self).write(target)
class BuildoutProjectBuilder(ProjectBuilder):
zope.interface.implements(interfaces.IBuildoutProjectBuilder)
@getproperty
def setup(self):
return self['setup.py']
@getproperty
def buildout(self):
return self['buildout.cfg']
@getproperty
def package(self):
return self['src'].package
def __init__(self, name, projectName=None):
super(BuildoutProjectBuilder, self).__init__(name, projectName)
# Create the minimum amount files necessary to build a valid project
self['bootstrap.py'] = base.SimpleFileBuilder(
u'bootstrap.py', base.getTemplatePath('bootstrap.py'))
self['setup.py'] = setup.SetupBuilder()
self['buildout.cfg'] = buildout.BuildoutConfigBuilder()
self['src'] = SrcDirectoryBuilder()
self['src'].updateModules(self.name)
class SrcDirectoryBuilder(base.DirectoryBuilder):
zope.interface.implements(interfaces.IPythonPathRoot)
def __init__(self):
super(SrcDirectoryBuilder, self).__init__(u'src')
self.package = python.PackageBuilder(u'')
def updateModules(self, projectName):
modules = list(reversed(unicode(projectName).split('.')))
builder = self
while len(modules) > 0:
name = modules.pop()
nextBuilder = python.PackageBuilder(name)
if len(modules) == 0:
nextBuilder = self.package
nextBuilder.dirname = nextBuilder.packageName = str(name)
nextBuilder.name = name
builder.add(nextBuilder)
builder = nextBuilder
def update(self):
for builder in self.values():
builder.update()
def __repr__(self):
return '<%s for %r>' %(self.__class__.__name__, self.getProject().name) | z3c.builder.core | /z3c.builder.core-0.1.0.tar.gz/z3c.builder.core-0.1.0/src/z3c/builder/core/project.py | project.py |
Changelog
=========
3.0 (2023-02-08)
----------------
- Drop support for Python 2.7, 3.5, 3.6.
[icemac]
- Add support for Python 3.9, 3.10, 3.11.
[icemac]
2.2 (2019-10-16)
----------------
- Fix DeprecationWarnings: import moves from ``zope.component`` to ``zope.interface``.
Depend on zope.interface >= 3.8.0.
[jensens]
- Add support for Python 3.8a3.
[icemac]
2.1 (2018-11-06)
----------------
- Changed ruleset of IRuleset to TextLine to work with
`zope.configuration >= 4.2`. See
`Products.CMFPlone#2591 <https://github.com/plone/Products.CMFPlone/issues/2591>`_.
[pbauer]
2.0 (2018-03-22)
----------------
* Add support for Python 3.5, 3.6, 3.7, PyPy2 and PyPy3.
[icemac]
2.0a1 - April 22, 2010
----------------------
* Added `Purge`` event and ``IPurgeable` and ``IPurgePaths`` interfaces.
Although this package doesn't provide any purging support, it is convenient
to keep the interfaces necessary for other packages to describe their cache
purging behaviour here. This allows a relatively harmless dependency on
z3c.caching, even in generic code, as distinct from a higher-level,
application server specific framework.
[optilude]
* Added concept of an explicitly declare ruleset type. Optional by default,
but can be made required by setting `explicit` to `True`.
[optilude]
* Added ``ILastModified`` implementation for a view which delegates to the
view's context.
[optilude]
* Added ``enumerateTypes()`` method to the registry, used to list all currently
used cache rule ids.
[optilude]
* Made the registry use the ZCA more directly.
[matthewwilkes]
1.0b1 - October 15, 2008
------------------------
* Initial release
[wichert]
| z3c.caching | /z3c.caching-3.0.tar.gz/z3c.caching-3.0/CHANGES.rst | CHANGES.rst |
Introduction
============
Caching of web pages is a complicated process: there are many possible
policies to choose from, and the right policy can depend on factors such as
who is making the request, the URL is being retrieved and resource
negotiation settings such as accepted languages and encodings,
Hardcoding caching logic in an application is not desirable, especially for
reusable code. It is also not possible to allow an administrator to manually
configure the caching headers for every resource in an application. This
packages tries to address this problem by providing a cache ruleset
framework: it allows implementors to specify a ruleset for every component.
Administrators can then define a policy which dictates the correct caching
behaviour for each ruleset.
Depending on your environment there are different options for turning
the ruleset into HTTP caching headers.
* If you are using Plone_ 3 and CacheFu_ you can use `five.caching`_ to
integrate with CacheSetup.
* If you are using Zope 2.12 or later, you can use `plone.caching`_ to
integrate with the publisher events and `plone.cachepurging`_ if you require
support for ``PURGE`` requests.
* If you are using Plone 4, you can also use `plone.app.caching`_, which
provides UI and default behaviour for `plone.caching`_ and
`plone.cachepurging`_.
* In a WSGI environment you could set the ruleset in `environ` or a response
header and add a piece of middleware which acts on those hints.
Usage
=====
You can register rulesets using either ZCML or directly in python. If you
use ZCML you can use the ``<cache:ruleset />`` directive::
<configure
xmlns="http://namespaces.zope.org/zope"
xmlns:browser="http://namespaces.zope.org/browser"
xmlns:cache="http://namespaces.zope.org/cache"/>
<include package="z3c.caching" file="meta.zcml" />
<cache:rulesetType
name="plone.contentTypes"
title="Plone content types"
description="Non-folderish content types"
/>
<cache:ruleset
for=".frontpage.FrontpageView"
ruleset="plone.contentTypes"
/>
<browser:page
for="..interfaces.IFrontpage"
class=".frontpage.FrontpageView"
name="frontpage_view"
template="templates/frontpage_view.pt"
permission="zope2.View" />
</configure>
This example sets up a browser view called ``frontpage_view`` and
associates it with the ``plone.contentTypes`` ruleset.
**NOTE:** Ruleset names should be *dotted names*. That is, they should consist
only of upper or lowercase letters, digits, underscores and/or periods (dots).
The idea is that this forms a namespace similar to namespaces created by
packages and modules in Python.
You can specify either a class or an interface in the ``for`` attribute. As
with an adapter registration, a more specific registration can be used to
override a more generic one.
Above, we also add some metadata about the type of ruleset using the
``<cache:rulesetType />`` directive. This is principally useful for UI support
and can be often be skipped.
If you prefer to use python directly you can do so::
from z3c.caching.registry import register
from frontpage import FrontpageView
register(FrontpageView, "plone.contentTypes")
To find the ruleset for an object use the ``lookup()`` method::
from z3c.caching.registry import lookup
cacheRule = lookup(FrontpageView)
To declare the ruleset type metadata, use the ``declareType`` method::
from z3c.caching.registry import declareType
declareType = declareType(name="plone.contentTypes", \
title=u"Plone content types", \
description=u"Non-folderish content types")
If you want to get a list of all declared types, use the ``enumerateTypes()``
method::
from z3c.caching.registry import enumerate
for type_ in enumerateTypes():
...
The ``type_`` object provides ``IRulesetType`` and has attributes for
``name``, ``title`` and ``description``.
Strict mode
-----------
By default, you are not required to declare the type of a ruleset before using
it. This is convenient, but increases the risk of typos or a proliferation of
rulesets that are semantically equivalent. If you want to guard against this
case, you can put the ruleset into explicit mode, like this::
from z3c.caching.registry import setExplicitMode
setExplicitMode(True)
Information about cacheable resources
=====================================
This package is intentionally simple, and depends only on a small set of core
Zope Toolkit packages. However, real-world caching often requires specific
information about published (and potentially cacheable) resources, such as
when the underlying resource was last modified, and which URLs to purge if
the caching proxy needs to be purged.
``z3c.caching`` aims to be a "safe" and minimalist dependency for packages
which want to declare how they can be cached. Hence, whilst the implementation
of such things as setting cache control response headers and supporting
purging of a caching reverse proxy are left up to other packages,
``z3c.caching`` provides a few interfaces which "caching-aware" packages can
implement, for higher level frameworks (such as `plone.caching`_ and
`plone.cachepurging`_) to rely on. This avoids a direct dependency between
such packages and those higher level frameworks.
These interfaces are described below. A few helper components are also
provided. To configure them, you can include ``z3c.caching``'s ZCML
configuration::
<include package="z3c.caching" />
Last modified date/time
-----------------------
The ``ILastModified`` adapter interface can be used to describe the last
modified date of a given published object::
class ILastModified(Interface):
"""An abstraction to help obtain a last-modified date for a published
resource.
Should be registered as an unnamed adapter from a published object
(e.g. a view).
"""
def __call__():
"""Return the last-modified date, as a Python datetime object.
The datetime returned must be timezone aware and should normally
be in the local timezone.
May return None if the last modified date cannot be determined.
"""
One implementation for this interface is provided by default: When looked up
for a Zope browser view, it will delegate to an ``ILastModified`` adapter on
the view's context. Higher level packages may choose to implement this adapter
for other types of publishable resources, and/or different types of view
context.
Cache purging
-------------
High-traffic sites often put a caching proxy such as `Squid`_ or `Varnish`_
in front of the web application server to offload the caching of resources.
Such proxies can be controlled via response headers (perhaps set via caching
operations looked up based on ``z3c.caching`` rulesets). Most caching proxies
also support so-called ``PURGE`` requests, where the web application sends a
request directly to the caching proxy asking it to purge (presumably old)
copies it may hold of a resource (e.g. because that resource has changed).
This package does not implement any communication with caching proxies. If
you need that in a Zope 2 context, consider `plone.cachepurging`_. However,
a few components are included to help packages declare their behaviour in
relation to a caching proxy that supports purging.
Firstly, ``z3.caching`` defines a ``Purge`` event, described the interface
``z3c.caching.interfaces.IPurgeEvent``::
class IPurgeEvent(IObjectEvent):
"""Event which can be fired to purge a particular object.
This event is not fired anywhere in this package. Instead, higher level
frameworks are expected to fire this event when an object may need to be
purged.
It is safe to fire the event multiple times for the same object. A given
object will only be purged once.
"""
If an object has been changed so that it may need to be purged, you can fire
the event, like so::
from z3c.caching.purge import Purge
from zope.event import notify
notify(Purge(context))
A higher level framework such as `plone.cachepurging`_ can listen to this
event to queue purge requests for the object.
Of course, the most common reason to purge an object's cached representations
is that it has been modified or removed. ``z3c.caching`` provides event
handlers for the standard ``IObjectModifiedEvent``, ``IObjectMovedEvent`` and
``IObjectRemovedEvent`` events, which re-broadcasts a ``Purge`` event for
the modified/moved/removed object.
To opt into these event handlers, simply mark your content object with the
``IPurgeable`` interface, e.g.::
from z3c.caching.interfaces import IPurgeable
class MyContent(Persistent):
implements(IPurgeable)
...
You can also do this declaratively in ZCML, even for classes not under your
control::
<class class=".content.MyContent">
<implements interface="z3c.caching.interfaces.IPurgeable" />
</class>
These helpers can signal to a framework like `plone.cachepurging`_ that the
object needs to be purged, but this is not enough to know how to construct
the ``PURGE`` request. The caching proxy also needs to be told which path or
paths to purge. This is the job of the ``IPurgePaths`` adapter interface::
class IPurgePaths(Interface):
"""Return paths to send as PURGE requests for a given object.
The purging hook will look up named adapters from the objects sent to
the purge queue (usually by an IPurgeEvent being fired) to this interface.
The name is not significant, but is used to allow multiple implementations
whilst still permitting per-type overrides. The names should therefore
normally be unique, prefixed with the dotted name of the package to which
they belong.
"""
def getRelativePaths():
"""Return a list of paths that should be purged. The paths should be
relative to the virtual hosting root, i.e. they should start with a
'/'.
These paths will be rewritten to incorporate virtual hosting if
necessary.
"""
def getAbsolutePaths():
"""Return a list of paths that should be purged. The paths should be
relative to the domain root, i.e. they should start with a '/'.
These paths will *not* be rewritten to incorporate virtual hosting.
"""
The difference between the "relative" and "absolute" paths only comes into
effect if virtual hosting is used. In most cases, you want to implement
``getRelativePaths()`` to return a path that is relative to the current
virtual hosting root. In Zope 2, you can get this via the
``absolute_url_path()`` function on any traversable item. Alternatively,
you can look up an ``IAbsoluteURL`` adapter and discard the domain portion.
``getAbsolutePaths()`` is mainly useful for paths that are "special" to the
caching proxy. For example, you could configure Varnish to purge the entire
cache when sending a request to ``/_purge_all``, and then implement
``getAbsolutePaths()`` to return an iterable with that string in it.
Here is the default implementation from `plone.cachepurging`_, which purges
the default path of an object derived from Zope 2's ``OFS.Traversable``::
class TraversablePurgePaths(object):
"""Default purge for OFS.Traversable-style objects
"""
implements(IPurgePaths)
adapts(ITraversable)
def __init__(self, context):
self.context = context
def getRelativePaths(self):
return [self.context.absolute_url_path()]
def getAbsolutePaths(self):
return []
In ZCML, this is registered as::
<adapter factory=".paths.TraversablePurgePaths" name="default" />
The Plone-specific `plone.app.caching` implements further adapters (with
other, unique names) for things like the default view method alias (``/view``)
and downloadable paths for Archetypes image and file fields.
.. _Plone: http://plone.org/
.. _CacheFu: http://plone.org/products/cachefu
.. _five.caching: http://pypi.python.org/pypi/five.caching
.. _plone.caching: http://pypi.python.org/pypi/plone.caching
.. _plone.cachepurging: http://pypi.python.org/pypi/plone.cachepurging
.. _plone.app.caching: http://pypi.python.org/pypi/plone.app.caching
.. _Squid: http://squid-cache.org
.. _Varnish: http://varnish-cache.org
| z3c.caching | /z3c.caching-3.0.tar.gz/z3c.caching-3.0/README.rst | README.rst |
from zope import schema
from zope.interface import Interface
from zope.interface.interfaces import IObjectEvent
class IRulesetRegistry(Interface):
def register(obj, rule):
"""Mark objects that are implementers of `obj` to use the caching
rule `rule`. The name should be a dotted name, consisting only of
upper or lowercase letters, digits, and/or periods.
"""
def unregister(obj):
"""Remove any prior rule registration attached to obj in this
registry. N.B. registries are hierarchical, a parent may still
provide rules.
"""
def clear():
"""Remove all rule registrations in this registry.
"""
def lookup(obj):
"""Return the id of the rule associated with `obj`. If no rule has
been registered `None` is returned.
"""
def __getitem__(obj):
"""Convenience spelling for `lookup(obj)`.
"""
def declareType(name, type, description):
"""Declare a new ruleset type. This will put a new `IRulesetType`
into the list of objects returned by `enumerate`. The name should be
a dotted name, consisting only of upper or lowercase letters, digits,
and/or periods.
"""
def enumerateTypes():
"""Return a sequence of all unique registered rule set types, as
``IRuleSetType`` objects.
"""
explicit = schema.Bool(
title="Explicit mode",
description=("If true, ruleset types must be declared before being"
" used."),
required=True,
default=False)
class IRulesetType(Interface):
"""A ruleset type. The name can be used in a <cache:ruleset /> directive.
The title and description are used for UI support.
"""
name = schema.DottedName(title="Ruleset name")
title = schema.TextLine(title="Title")
description = schema.TextLine(title="Description", required=False)
class ILastModified(Interface):
"""An abstraction to help obtain a last-modified date for a published
resource.
Should be registered as an unnamed adapter from a published object
(e.g. a view).
"""
def __call__():
"""Return the last-modified date, as a Python datetime object.
The datetime returned must be timezone aware and should normally be
in the local timezone.
May return None if the last modified date cannot be determined.
"""
class IPurgeEvent(IObjectEvent):
"""Event which can be fired to purge a particular object.
This event is not fired anywhere in this package. Instead, higher level
frameworks are expected to fire this event when an object may need to be
purged.
It is safe to fire the event multiple times for the same object. A given
object will only be purged once.
"""
class IPurgeable(Interface):
"""Marker interface for content which should be purged when modified or
removed.
Event handlers are registered for ``IObjectModifiedEvent`` and
``IObjectRemovedEvent`` for contexts providing this interface. These are
automatically purged.
"""
class IPurgePaths(Interface):
"""Return paths to send as PURGE requests for a given object.
The purging hook will look up named adapters from the objects sent to
the purge queue (usually by an IPurgeEvent being fired) to this interface.
The name is not significant, but is used to allow multiple implementations
whilst still permitting per-type overrides. The names should therefore
normally be unique, prefixed with the dotted name of the package to which
they belong.
"""
def getRelativePaths():
"""Return a list of paths that should be purged. The paths should be
relative to the virtual hosting root, i.e. they should start with a
'/'.
These paths will be rewritten to incorporate virtual hosting if
necessary.
"""
def getAbsolutePaths():
"""Return a list of paths that should be purged. The paths should be
relative to the domain root, i.e. they should start with a '/'.
These paths will *not* be rewritten to incorporate virtual hosting.
""" | z3c.caching | /z3c.caching-3.0.tar.gz/z3c.caching-3.0/src/z3c/caching/interfaces.py | interfaces.py |
import warnings
from zope.component import adapts
from zope.component import getGlobalSiteManager
from zope.component import getUtilitiesFor
from zope.component import queryUtility
from zope.interface import Attribute
from zope.interface import Interface
from zope.interface import implementer
from zope.interface.interfaces import IComponents
from z3c.caching.interfaces import IRulesetRegistry
from z3c.caching.interfaces import IRulesetType
class ICacheRule(Interface):
"""Represents the cache rule applied to an object.
This is strictly an implementation detail of IRulesetRegistry.
"""
id = Attribute("The identifier of this cache rule")
@implementer(ICacheRule)
class CacheRule:
__slots__ = ("id")
def __init__(self, identifier):
self.id = identifier
@implementer(IRulesetType)
class RulesetType:
__slots__ = ('name', 'title', 'description',)
def __init__(self, name, title, description):
self.name = name
self.title = title
self.description = description
def get_context_to_cacherule_adapter_factory(rule):
"""Given a cache rule return an adapter factory which expects an object
but only returns the pre-specified cache rule."""
def CacheRuleFactory(context):
return CacheRule(rule)
CacheRuleFactory.id = rule
return CacheRuleFactory
@implementer(IRulesetRegistry)
class RulesetRegistry:
adapts(IComponents)
def __init__(self, registry):
self.registry = registry
def register(self, obj, rule):
rule = str(rule) # We only want ascii, tyvm
if self.explicit and queryUtility(IRulesetType, rule) is None:
raise LookupError(
"Explicit mode set and ruleset %s not found" %
rule)
factory = get_context_to_cacherule_adapter_factory(rule)
existing = self.directLookup(obj)
if existing is None:
# Only register if we haven't got this one already
self.registry.registerAdapter(
factory, provided=ICacheRule, required=(obj,))
else:
warnings.warn(
"Ignoring attempted to register caching rule %s for %s."
" %s is already registered." %
(rule, repr(obj), existing))
return None
def unregister(self, obj):
self.registry.unregisterAdapter(provided=ICacheRule, required=(obj,))
return None
def clear(self):
# We force the iterator to be evaluated to start with as the backing
# storage will be changing size
for rule in list(self.registry.registeredAdapters()):
if rule.provided != ICacheRule:
continue # Not our responsibility
else:
self.registry.unregisterAdapter(factory=rule.factory,
provided=rule.provided,
required=rule.required)
for type_ in list(self.registry.registeredUtilities()):
if type_.provided != IRulesetType:
continue # Not our responsibility
else:
self.registry.unregisterUtility(component=type_.component,
provided=IRulesetType,
name=type_.name)
self.explicit = False
return None
def lookup(self, obj):
rule = ICacheRule(obj, None)
if rule is not None:
return rule.id
return None
__getitem__ = lookup
def declareType(self, name, title, description):
type_ = RulesetType(name, title, description)
self.registry.registerUtility(type_, IRulesetType, name=name)
def enumerateTypes(self):
for name, type_ in getUtilitiesFor(IRulesetType):
yield type_
def _get_explicit(self):
return getattr(self.registry, '_z3c_caching_explicit', False)
def _set_explicit(self, value):
setattr(self.registry, '_z3c_caching_explicit', value)
explicit = property(_get_explicit, _set_explicit)
# Helper methods
def directLookup(self, obj):
"""Find a rule _directly_ assigned to `obj`"""
for rule in self.registry.registeredAdapters():
if rule.provided != ICacheRule:
continue
if rule.required == (obj, ):
return rule.factory(None).id
return None
def getGlobalRulesetRegistry():
return IRulesetRegistry(getGlobalSiteManager(), None)
# Convenience API
def register(obj, rule):
registry = getGlobalRulesetRegistry()
if registry is None:
raise LookupError("Global registry initialised")
return registry.register(obj, rule)
def unregister(obj):
registry = getGlobalRulesetRegistry()
if registry is None:
raise LookupError("Global registry initialised")
return registry.unregister(obj)
def lookup(obj):
registry = getGlobalRulesetRegistry()
if registry is None:
return None
return registry.lookup(obj)
def enumerateTypes():
registry = getGlobalRulesetRegistry()
if registry is None:
raise LookupError("Global registry initialised")
return registry.enumerateTypes()
def declareType(name, title, description):
registry = getGlobalRulesetRegistry()
if registry is None:
raise LookupError("Global registry initialised")
registry.declareType(name, title, description)
def setExplicitMode(mode=True):
registry = getGlobalRulesetRegistry()
if registry is None:
raise LookupError("Global registry initialised")
registry.explicit = mode
__all__ = ['getGlobalRulesetRegistry', 'register', 'unregister', 'lookup',
'enumerateTypes', 'declareType', 'setExplicitMode'] | z3c.caching | /z3c.caching-3.0.tar.gz/z3c.caching-3.0/src/z3c/caching/registry.py | registry.py |
=========================
Change log for z3c.celery
=========================
1.6.0 (2022-06-23)
==================
- Update to celery 5.x, drop Python-2 support
1.5.0 (2021-11-15)
==================
- Provide JsonFormatter if python-json-logger is installed
1.4.3 (2021-02-26)
==================
- Fix logging setup
1.4.2 (2019-12-12)
==================
- Make HandleAfterAbort compatible with celery-4.1.1 serialization changes
1.4.1 (2019-11-15)
==================
- Annotate transaction with principal and task name, like zope.app.publication
1.4.0 (2019-10-30)
==================
- Set the URL of the (fake) zope request (which is used to set the principal) to
the task name
1.3.0 (2019-05-22)
==================
- Added support for Python 3.6 and 3.7.
1.2.3 (2018-06-28)
==================
- Add logging for task retry.
1.2.2 (2018-03-23)
==================
- Ensure ZODB connection can be closed, even if execution is aborted in the
middle of a transaction
1.2.1 (2018-02-02)
==================
- Add bw-compat for persisted tasks that still have a `_task_id_` parameter
1.2.0 (2018-01-23)
==================
- Support task retry
1.1.0 (2017-10-11)
==================
- Make worker process boot timeout configurable
1.0.2 (2017-10-05)
==================
- Also apply "always endInteration" to HandleAfterAbort
- Also apply "retry on ConflictError" to HandleAfterAbort
1.0.1 (2017-10-04)
==================
- Always call endInteraction, even on error during commit or abort,
so we don't pollute the interaction state for the next task run
1.0 (2017-09-29)
================
- Introduce ``Abort`` control flow exception
- Allow overriding the principal id the job runs as
- Support reading configuration from a filesystem-based (non-importable) python file
- Don't use celery's deprecated default app mechanism
- Support running an actual "celery worker" with the single-process "solo" worker_pool
0.1 (2017-02-21)
================
- Initial release. Extract from zeit.cms.
| z3c.celery | /z3c.celery-1.6.0.tar.gz/z3c.celery-1.6.0/CHANGES.rst | CHANGES.rst |
Usage
=====
Integration with Zope
---------------------
To successfully configure Celery in Zope place the ``celeryconfig.py`` in the
``PYTHONPATH``. The configuration will be taken from there.
Define your tasks as ``shared_task()`` so they can be used in the tests and
when running the server.
`z3c.celery` provides its own celery app: ``z3c.celery.CELERY``. It does the
actual the integration work.
Jobs by default run as the same principal that was active when the job was
enqueued. You can override this by passing a different principal id to ``delay``::
my_task.delay(my, args, etc, _principal_id_='zope.otheruser')
Worker setup
------------
Place the ``celeryconfig.py`` in your working directory. Now you can start the
celery worker using the following command:
.. code-block:: console
$ celery worker --app=z3c.celery.CELERY --config=celeryconfig
The `celeryconfig`_ can include all default celery config options. In addition
the variable ``ZOPE_CONF`` pointing to your ``zope.conf`` has to be present.
This ``celeryconfig.py`` and the referenced ``zope.conf`` should be identical to
the ones, your Zope is started with.
Additionally you can specify a variable ``LOGGING_INI`` pointing to a logging
config (an ini file in `configuration file format`_, which might be your
paste.ini). See `Logging`_ for details.
Example::
ZOPE_CONF = '/path/to/zope.conf'
LOGGING_INI = '/path/to/paste.ini'
broker_url = 'redis://localhost:6379/0'
result_backend = 'redis://localhost:6379/0'
imports = ['my.tasks']
.. _`celeryconfig` : http://docs.celeryproject.org/en/latest/userguide/configuration.html
.. _`configuration file format` : https://docs.python.org/2/library/logging.config.html#configuration-file-format
Execute code after ``transaction.abort()``
------------------------------------------
If running a task fails the transaction is aborted. In case you need to write
something to the ZODB raise :class:`z3c.celery.celery.HandleAfterAbort` in your
task. This exception takes a callable and its arguments. It is run in a
separate transaction after ``transaction.abort()`` for the task was called.
It is possible to pass a keyword argument ``message`` into
:class:`~z3c.celery.celery.HandleAfterAbort`. This message will be serialized
and returned to celery in the task result. It is not passed to the callback.
Accessing the ``task_id`` in the task
-------------------------------------
There seems currently no way to get the task_id from inside the task when it is
a shared task. The task implementation in ``z3c.celery`` provides a solution.
You have to bind the shared task. This allows you to access the task instance
as first parameter of the task function. The ``task_id`` is stored there on the
``task_id`` attribute. Example::
@shared_task(bind=True)
def get_task_id(self):
"""Get the task id of the job."""
return self.task_id
Logging
-------
``z3c.celery`` provides a special formatter for the python logging module,
which can also be used as a generic formatter as it will omit task specific
output if there is none. It allows to include task id and task name of the
current task in the log message if they are available. Include it in your
logging configuration:
.. code-block:: ini
[formatter_generic]
class = z3c.celery.logging.TaskFormatter
format = %(asctime)s %(task_name)s %(task_id)s %(message)s
If ``python-json-logger`` is installed, we also provide ``z3c.celery.logging.JsonFormatter``.
Running end to end tests using layers
-------------------------------------
Motivation: Celery 4.x provides py.test fixtures. There is some infrastructure
in this package to use these fixtures together with `plone.testing.Layer`.
The following steps are required to set the layers up correctly:
In your package depend on ``z3c.celery[layer]``.
Create a layer which provides the following resources:
* ``celery_config``: dict of config options for the celery app. It has to
include a key ``ZOPE_CONF`` which has to point to a `zope.conf` file.
See the template in :mod:`z3c.celery.testing`.
* ``celery_parameters``: dict of parameters used to instantiate Celery
* ``celery_worker_parameters``: dict of parameters used to instantiate celery
workers
* ``celery_includes``: list of dotted names to load the tasks in the worker
Example::
class CelerySettingsLayer(plone.testing.Layer):
"""Settings for the Celery end to end tests."""
def setUp(self):
self['celery_config'] = {
'ZOPE_CONF': '/path/to/my/test-zope.conf'}
self['celery_parameters'] = (
z3c.celery.conftest.celery_parameters())
self['celery_worker_parameters'] = {'queues': ('celery',)}
self['celery_includes'] = ['my.module.tasks']
def tearDown(self):
del self['celery_config']
del self['celery_includes']
del self['celery_parameters']
del self['celery_worker_parameters']
Create a layer which brings the settings layer and the :class:`EndToEndLayer`
together, example::
CELERY_SETTINGS_LAYER = CelerySettingsLayer()
CONFIGURED_END_TO_END_LAYER = z3c.celery.layer.EndToEndLayer(
bases=[CELERY_SETTINGS_LAYER], name="ConfiguredEndToEndLayer")
Create a layer which combines the configured EndToEndLayer with the ZCMLLayer
of your application. (This should be the one created by
:class:`plone.testing.zca.ZCMLSandbox`.)
Example::
MY_PROJ_CELERY_END_TO_END_LAYER = plone.testing.Layer(
bases=(CONFIGURED_END_TO_END_LAYER, ZCML_LAYER),
name="MyProjectCeleryEndToEndLayer")
.. note::
The ZCMLLayer has to be the last one in the list of the bases because the
EndToEndLayer forks the workers when it is set up. If the ZCML is already
there running a task in the worker will break because as first step it has
to load the `zope.conf`.
.. caution::
All tasks to be run in end to end tests have to shared tasks. This is
necessary because the end to end tests have to use a different Celery
instance than ``z3c.celery.CELERY``. Example::
@celery.shared_task
def my_task():
do_stuff()
Implementation notes
--------------------
In case of a ``ZODB.POSException.ConflictError`` the worker process will wait
and restart the operation again. This is done with active wait
(``time.sleep()``) and not via the ``self.retry()`` mechanism of celery, as we
were not able to figure out to get it flying.
| z3c.celery | /z3c.celery-1.6.0.tar.gz/z3c.celery-1.6.0/doc/usage.rst | usage.rst |
z3c.celery
==========
Integration of Celery 4 with Zope 3.
This package is compatible with Python version 2.7, 3.6 and 3.7.
Features
--------
* integration into the Zope transaction (schedule tasks at
``transaction.commit()``)
* runs jobs
* in a Zope environment with loaded ZCML and ZODB connection
* in a transaction with retry on `ConflictError`
* as the user who scheduled the job
* test infrastructure to run tests in-line or in a worker
* support for py.test fixtures and zope.testrunner layers
.. toctree::
:maxdepth: 2
usage
testing
api
about
changes
- :ref:`genindex`
| z3c.celery | /z3c.celery-1.6.0.tar.gz/z3c.celery-1.6.0/doc/index.rst | index.rst |
from .loader import ZopeLoader
from .session import celery_session
from celery._state import _task_stack
from celery.utils.serialization import raise_with_context
import ZODB.POSException
import celery
import celery.exceptions
import celery.utils
import contextlib
import json
import logging
import random
import socket
import time
import transaction
import zope.app.publication.zopepublication
import zope.authentication.interfaces
import zope.component
import zope.component.hooks
import zope.publisher.browser
import zope.security.management
log = logging.getLogger(__name__)
class HandleAfterAbort(RuntimeError):
"""Exception whose callback is executed after ``transaction.abort()``."""
def __init__(self, callback, *args, **kwargs):
self.message = kwargs.pop('message', u'')
# Conform to BaseException API so it works with celery's serialization
# (before 4.1.1 it just worked, but that was rather accidental)
if isinstance(callback, str):
self.message = callback
if isinstance(self.message, bytes):
self.message = self.message.decode('utf-8')
super().__init__(self.message)
self.callback = callback
self.c_args = args
self.c_kwargs = kwargs
def __call__(self):
self.callback(*self.c_args, **self.c_kwargs)
def __str__(self):
return self.message
class Abort(HandleAfterAbort):
"""Exception to signal successful task completion, but transaction should
be aborted instead of commited.
"""
class Retry(celery.exceptions.Retry, HandleAfterAbort):
"""With cooperation from TransactionAwareTask.retry(), this moves the
actual re-queueing of the task into the proper "error handling"
transaction phase.
"""
def __init__(self, *args, **kw):
self.signature = kw.pop('signature', None)
celery.exceptions.Retry.__init__(self, *args, **kw)
def __call__(self):
try:
self.signature.apply_async()
log.warning('Task submitted for retry in %s seconds.', self.when)
except Exception as exc:
log.error('Task retry failed', exc_info=True)
raise celery.exceptions.Reject(exc, requeue=False)
def get_principal(principal_id):
"""Return the principal to the principal_id."""
auth = zope.component.getUtility(
zope.authentication.interfaces.IAuthentication)
return auth.getPrincipal(principal_id)
def login_principal(principal, task_name=None):
"""Start an interaction with `principal`."""
request = zope.publisher.browser.TestRequest(
environ={'SERVER_URL': 'http://%s' % socket.getfqdn()})
if task_name:
# I'd rather set PATH_INFO, but that doesn't influence getURL().
request._traversed_names = ['celery', task_name]
request.setPrincipal(principal)
zope.security.management.newInteraction(request)
class TransactionAwareTask(celery.Task):
"""Wrap every Task execution in a transaction begin/commit/abort.
(Code inspired by gocept.runner.runner.MainLoop)
"""
abstract = True # Base class. Don't register as an executable task.
def __call__(self, *args, **kw):
"""Run the task.
Parameters:
_run_asynchronously_ ... if `True` run the task its own transaction
context, otherwise run it in inline
(optional, default: `False` to be able to
run tasks easily inline)
_principal_id_ ... run asynchronous task as this user, ignored if
running synchronously (optional)
Returns whatever the task returns itself.
"""
run_asynchronously = kw.pop('_run_asynchronously_', False)
principal_id = kw.pop('_principal_id_', None)
# BBB This was removed in 1.2.0 but there still might be (scheduled)
# tasks that transmit this argument, so we need to remove it.
kw.pop('_task_id_', None)
is_eager = self.app.conf['task_always_eager']
if is_eager:
# This is the only part of celery.Task.__call__ that actually is
# relevant -- since in non-eager mode, it's not called at all:
# celery.app.trace.build_tracer() says, "if the task doesn't define
# a custom __call__ method we optimize it away by simply calling
# the run method directly".
# (Note that the push_request() call in __call__ would be actively
# harmful in non-eager mode, since it hides the actual request that
# was set by app.trace; but as it's not called, it's not an issue.)
_task_stack.push(self)
try:
if run_asynchronously:
result = self.run_in_worker(principal_id, args, kw)
else:
result = self.run_in_same_process(args, kw)
finally:
if is_eager:
_task_stack.pop()
return result
def run_in_same_process(self, args, kw):
try:
return self.run(*args, **kw)
except Abort as handle:
transaction.abort()
handle()
return handle.message
except HandleAfterAbort as handle:
handle()
raise
def run_in_worker(self, principal_id, args, kw, retries=0):
with self.configure_zope():
try:
with self.transaction(principal_id):
return self.run(*args, **kw)
except HandleAfterAbort as handle:
for handle_retries in range(self.max_retries):
try:
with self.transaction(principal_id):
handle()
except celery.exceptions.Retry:
# We have to handle ConflictErrors manually, since we
# don't want to retry the whole task (which was
# erroneous anyway), but only the after-abort portion.
countdown = random.uniform(0, 2 ** handle_retries)
log.warning('Waiting %s seconds for retry.', countdown)
time.sleep(countdown)
continue
else:
break
else:
log.warning('Giving up on %r after %s retries',
handle, self.max_retries)
if isinstance(handle, Abort):
return handle.message
else:
raise handle
@contextlib.contextmanager
def transaction(self, principal_id):
if principal_id:
transaction.begin()
login_principal(get_principal(principal_id), self.name)
txn = transaction.get()
txn.setUser(str(principal_id))
txn.setExtendedInfo('task_name', self.name)
try:
yield
except Exception:
transaction.abort()
raise
else:
try:
transaction.commit()
except ZODB.POSException.ConflictError:
log.warning('Conflict while publishing', exc_info=True)
transaction.abort()
self.retry(
countdown=random.uniform(0, 2 ** self.request.retries))
finally:
transaction.abort()
zope.security.management.endInteraction()
@contextlib.contextmanager
def configure_zope(self):
old_site = zope.component.hooks.getSite()
db = self.app.conf.get('ZODB')
connection = db.open()
root_folder = connection.root()[
zope.app.publication.zopepublication.ZopePublication.root_name]
zope.component.hooks.setSite(root_folder)
try:
yield
finally:
connection.close()
zope.component.hooks.setSite(old_site)
_eager_use_session_ = False # Hook for tests
def apply_async(self, args=None, kw=None, task_id=None, **options):
self._assert_json_serializable(args, kw)
if kw is None:
kw = {}
if task_id is None:
task_id = celery.utils.gen_unique_id()
kw.setdefault('_principal_id_', self._get_current_principal_id())
# Accomodations for tests:
# 1. Normally we defer (asynchronous) task execution to the transaction
# commit via celery_session (see else-branch below). But in
# always_eager mode the execution is synchronous, so the whole task
# would run _during_ the commit phase, which totally breaks if inside
# the task the transaction is touched in any way, e.g. by calling for a
# savepoint. Since we need to support this kind of completely normal
# behaviour, we bypass the session in always_eager mode.
# 2. To simplify tests concerning our celery-integration mechanics we
# provide a hook so tests can force using the session even in
# always_eager mode (because otherwise those tests would have to use an
# end-to-end setup, which would make the introspection they need
# complicated if not impossible).
# XXX These actually rather belongs into CelerySession, but that would
# get mechanically complicated.
if self.app.conf['task_always_eager'] and not self._eager_use_session_:
self.__call__(*args, **kw)
elif self.name == 'celery.ping':
# Part of celery.contrib.testing setup, we need to perform this
# immediately, because it has no transaction integration.
return super().apply_async(args, kw, task_id=task_id, **options)
else:
# Hook so tests can force __call__ to use run_in_worker even when
# always_eager is True, by passing in this kw explicitly.
kw.setdefault('_run_asynchronously_', True)
celery_session.add_call(
super().apply_async, args, kw, task_id, **options)
return self.AsyncResult(task_id)
def _assert_json_serializable(self, *args, **kw):
json.dumps(args)
json.dumps(kw)
def _get_current_principal_id(self):
interaction = zope.security.management.queryInteraction()
if interaction is None:
principal_id = None
else:
principal_id = interaction.participations[0].principal.id
return principal_id
def retry(self, args=None, kwargs=None, exc=None, throw=True,
eta=None, countdown=None, max_retries=None, **options):
# copy&paste from superclass, we need to use a Retry exception that
# uses the HandleAfterAbort mechanics to integrate with transactions.
request = self.request
retries = request.retries + 1
max_retries = self.max_retries if max_retries is None else max_retries
if request.called_directly:
raise_with_context(
exc or celery.exceptions.Retry('Task can be retried', None))
if not eta and countdown is None:
countdown = self.default_retry_delay
# Add interaction information now, while it's still present. Our
# apply_async() would normally do this, but it's called via
# HandleAfterAbort when the original interaction has already ended.
options.setdefault('_principal_id_', self._get_current_principal_id())
S = self.signature_from_request(
request, args, kwargs,
countdown=countdown, eta=eta, retries=retries,
**options
)
if max_retries is not None and retries > max_retries:
if exc:
raise_with_context(exc)
raise self.MaxRetriesExceededError(
"Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
self.name, request.id, S.args, S.kwargs))
ret = Retry(exc=exc, when=eta or countdown, signature=S)
if request.is_eager:
S.apply().get()
if throw:
raise ret
return ret
if throw:
raise ret
else:
ret()
return ret
CELERY = celery.Celery(
__name__, task_cls=TransactionAwareTask, loader=ZopeLoader,
strict_typing=False) | z3c.celery | /z3c.celery-1.6.0.tar.gz/z3c.celery-1.6.0/src/z3c/celery/celery.py | celery.py |
import celery.concurrency.asynpool
import celery.loaders.app
import celery.signals
import celery.utils.collections
import imp
import logging.config
import os.path
import zope.app.wsgi
class ZopeLoader(celery.loaders.app.AppLoader):
"""Sets up the Zope environment in the Worker processes."""
def on_worker_init(self):
logging_ini = self.app.conf.get('LOGGING_INI')
if not logging_ini:
return
@celery.signals.setup_logging.connect(weak=False)
def setup_logging(*args, **kw):
"""Make the loglevel finely configurable via a config file."""
config_file = os.path.abspath(logging_ini)
logging.config.fileConfig(
config_file, dict(
__file__=config_file, here=os.path.dirname(config_file)),
disable_existing_loggers=False)
if self.app.conf.get('DEBUG_WORKER'):
assert self.app.conf.get('worker_pool') == 'solo'
self.on_worker_process_init()
# Work around <https://github.com/celery/celery/issues/4323>.
if self.app.conf.get('worker_boot_timeout'):
celery.concurrency.asynpool.PROC_ALIVE_TIMEOUT = float(
self.app.conf['worker_boot_timeout'])
def on_worker_process_init(self):
conf = self.app.conf
configfile = conf.get('ZOPE_CONF')
if not configfile:
raise ValueError(
'Celery setting ZOPE_CONF not set, '
'check celery worker config.')
db = zope.app.wsgi.config(configfile)
conf['ZODB'] = db
def on_worker_shutdown(self):
if 'ZODB' in self.app.conf:
self.app.conf['ZODB'].close()
def read_configuration(self):
"""Read configuration from either
* an importable python module, given by its dotted name in
CELERY_CONFIG_MODULE. Note that this can also be set via
`$ bin/celery worker --config=<modulename>`. (Also note that "celery
worker" includes the cwd on the pythonpath.)
* or a plain python file (given by an absolute path in
CELERY_CONFIG_FILE)
If neither env variable is present, no configuration is read, and some
defaults are used instead that most probably don't work (they assume
amqp on localhost as broker, for example).
"""
module = os.environ.get('CELERY_CONFIG_MODULE')
if module:
return super().read_configuration()
pyfile = os.environ.get('CELERY_CONFIG_FILE')
if pyfile:
module = self._import_pyfile(pyfile)
return celery.utils.collections.DictAttribute(module)
def _import_pyfile(self, filename):
"""Applies Celery configuration by reading the given python file
(absolute filename), which unfortunately Celery does not support.
(Code inspired by flask.config.Config.from_pyfile)
"""
module = imp.new_module('config')
module.__file__ = filename
try:
with open(filename) as config_file:
exec(compile(
config_file.read(), filename, 'exec'), module.__dict__)
except IOError as e:
e.strerror = 'Unable to load configuration file (%s)' % e.strerror
raise e
else:
return module | z3c.celery | /z3c.celery-1.6.0.tar.gz/z3c.celery-1.6.0/src/z3c/celery/loader.py | loader.py |
Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| z3c.checkversions | /z3c.checkversions-2.1-py3-none-any.whl/z3c.checkversions-2.1.dist-info/LICENSE.rst | LICENSE.rst |
from pkg_resources import Requirement
from pkg_resources import parse_version
from setuptools import package_index
def _final_version(parsed_version):
"""Function copied from zc.buildout.easy_install._final_version."""
return not parsed_version.is_prerelease
class Checker:
"""Base class for version checkers
attributes:
index_url: url of an alternative package index
verbose: display every version, not only new ones,
and display the previous version as a comment
blacklist: filename of the blacklist
incremental: suggest only one package upgrade
"""
__custom_url = False
def __init__(self,
index_url=None,
verbose=False,
blacklist=None,
incremental=False):
self.verbose = verbose
self.incremental = incremental
if blacklist:
# create a set of tuples with bad versions
with open(blacklist) as b:
self.blacklist = {
tuple(map(lambda x: x.strip(), line.split('=')))
for line in b.readlines()
if '=' in line
}
else:
self.blacklist = set()
self.pi = package_index.PackageIndex(search_path=())
self._set_index_url(index_url)
if index_url is not None:
self.__custom_url = True
def _set_index_url(self, url):
"""Set the index URL."""
if url is not None:
self.pi.index_url = url
if not self.pi.index_url.endswith('/'):
self.pi.index_url += '/'
def check(self, level=0):
"""Search new versions in a version list
versions must be a dict {'name': 'version'}
The new version is limited to the given level:
Example with version x.y.z
level = 0: checks new version x
level = 1: checks new version y
level = 2: checks new version z
By default, the highest version is found.
"""
versions = self.get_versions()
for name, version in sorted(versions.items()):
if self.incremental == 'stop':
# skip subsequent scans
print("{}={}".format(name, version))
continue
try:
parsed_version = parse_version(version)
except ValueError:
# This could be a requirements specification instead
# of a straight version number
req = Requirement(f'{name}{version}')
for spec in req.specifier:
parsed_version = parse_version(spec.version)
break # Just use the first one
req = Requirement.parse(name)
self.pi.find_packages(req)
new_dist = None
# loop all index versions until we find the 1st newer version
# that keeps the major versions (below level)
# and is a final version
# and is not in the blacklist
for dist in self.pi[req.key]:
if self.incremental == 'stop':
continue
if (dist.project_name, dist.version) in self.blacklist:
continue
if (_final_version(parsed_version)
and not _final_version(dist.parsed_version)):
# only skip non-final releases if the current release is
# a final one
continue
# trunk the version tuple to the first `level` elements
trunked_current = (
parsed_version.base_version.split('.')[:level])
trunked_candidate = (
dist.parsed_version.base_version.split('.')[:level])
while len(trunked_candidate) < level:
trunked_candidate.append('00000000')
while len(trunked_current) < level:
trunked_current.append('00000000')
# ok now we can compare: -> skip if we're still higher.
if trunked_candidate > trunked_current:
continue
new_dist = dist
break
if new_dist and new_dist.parsed_version > parsed_version:
if self.incremental is True:
self.incremental = 'stop'
if self.verbose:
print("{}={} # was: {}".format(
name, new_dist.version, version))
else:
print("{}={}".format(name, new_dist.version))
elif self.verbose:
print("{}={}".format(name, version))
def get_versions(self):
"""Get a dict {'name': 'version', ...} with package versions to check.
This should be implemented by derived classes
"""
raise NotImplementedError | z3c.checkversions | /z3c.checkversions-2.1-py3-none-any.whl/z3c/checkversions/base.py | base.py |
import os
from optparse import OptionParser
def main():
usage = (
"Usage: %prog [-v] [-l LEVEL] [-i INDEX] [-b BLACKLIST] [-1]"
" [buildout_file]")
parser = OptionParser(description=__doc__, usage=usage)
parser.add_option('-l', '--level',
type='int',
dest='level',
default=0,
help="Version level to check")
parser.add_option('-i', '--index',
dest='index',
help="Provide and alternative package index URL")
parser.add_option('-b', '--blacklist',
dest='blacklist',
default="",
help="Provide a blacklist file with bad versions")
parser.add_option('-1', '--incremental',
dest='incremental',
action='store_true',
default=False,
help="Suggest only one upgrade. Skip others.")
parser.add_option('-v', '--verbose',
dest='verbose',
action='store_true',
default=False,
help="Verbose mode (prints old versions too)")
options, args = parser.parse_args()
if len(args) > 1:
parser.error("You must specify only one argument")
if options.blacklist != "" and not os.path.exists(options.blacklist):
parser.error(
'The blacklist file "%s" does not exist!' % options.blacklist)
kw = {}
if options.index is not None:
kw['index_url'] = options.index
if len(args) == 1:
from z3c.checkversions import buildout
kw['filename'] = args[0]
factory = buildout.Checker
else:
from z3c.checkversions import installed
factory = installed.Checker
checker = factory(blacklist=options.blacklist,
incremental=options.incremental,
verbose=options.verbose,
**kw)
checker.check(level=options.level)
if __name__ == '__main__':
main() | z3c.checkversions | /z3c.checkversions-2.1-py3-none-any.whl/z3c/checkversions/main.py | main.py |
import calendar
import zope.component
import zope.datetime
import zope.interface
import interfaces
class ModifiedSinceValidator(object):
"""
>>> import datetime
>>> from zope.interface.verify import verifyObject
>>> from zope.publisher.interfaces.browser import IBrowserRequest
>>> from zope.publisher.browser import TestRequest
>>> from zope.publisher.browser import BrowserView
>>> def format(dt):
... return zope.datetime.rfc1123_date(
... calendar.timegm(dt.utctimetuple()))
>>> lmt = datetime.datetime(2007, 1, 6, 13, 42, 12,
... tzinfo = zope.datetime.tzinfo(60))
ModifiedSinceValidator is a HTTP validator utility that will evaluate
a HTTP request to see if it passes or fails the If-Modifed* protocol.
>>> validator = ModifiedSinceValidator()
>>> verifyObject(interfaces.IHTTPValidator, validator)
True
If-Modified-Since
=================
The If-Modified-Since request-header field is used with a method to
make it conditional: if the requested variant has not been modified
since the time specified in this field, an entity will not be
returned from the server; instead, a 304 (not modified) response will
be returned without any message-body.
>>> class SimpleView(BrowserView):
... def __call__(self):
... self.request.response.setStatus(200)
... self.request.response.setHeader('Last-Modified', format(lmt))
... return 'Rendered view representation.'
Create a context adapter to find the last modified date of the context
object. We store the lastmodifed datatime object as a class attribute so
that we can easily change its value during these tests.
>>> class LastModification(object):
... zope.interface.implements(interfaces.ILastModificationDate)
... lastmodified = None
... def __init__(self, context, request, view):
... pass
A ILastModificationDate adapter must be registered for this validator
to know when a view was last modified.
>>> request = TestRequest(
... environ = {'IF_MODIFIED_SINCE': format(lmt)})
>>> request['IF_MODIFIED_SINCE']
'Sat, 06 Jan 2007 12:42:12 GMT'
>>> view = SimpleView(None, request)
>>> validator.valid(None, request, view) #doctest:+ELLIPSIS
True
Now register the last modified data adapter, and set up
>>> gsm = zope.component.getGlobalSiteManager()
>>> gsm.registerAdapter(LastModification, (None, IBrowserRequest, None))
Since there is no last modification date by default the request is valid.
>>> validator.valid(None, request, view)
True
Set the last modification date to be equal.
>>> LastModification.lastmodified = lmt
>>> validator.valid(None, request, view)
False
Increase the current last modification time of the view by 1 second.
>>> LastModification.lastmodified = lmt + datetime.timedelta(seconds = 1)
>>> validator.valid(None, request, view)
True
Decrease the current last modification time of the view by 1 second.
>>> LastModification.lastmodified = lmt - datetime.timedelta(seconds = 1)
>>> validator.valid(None, request, view)
False
Test invalid request data.
>>> invalidrequest = TestRequest(environ = {'IF_MODIFIED_SINCE': 'XXX'})
>>> validator.valid(None, invalidrequest, view)
True
>>> LastModification.lastmodified = lmt
If-UnModified-Since
===================
>>> request = TestRequest(
... environ = {'IF_UNMODIFIED_SINCE': format(lmt)})
>>> request['IF_UNMODIFIED_SINCE']
'Sat, 06 Jan 2007 12:42:12 GMT'
>>> view = SimpleView(None, request)
The If-Unmodified-Since request-header field is used with a method to
make it conditional. If the requested resource has not been modified
since the time specified in this field, the server SHOULD perform the
requested operation as if the If-Unmodified-Since header were not
present.
>>> validator.valid(None, request, view)
True
Increase the current last modified time of the view by 1 second.
>>> LastModification.lastmodified = lmt + datetime.timedelta(seconds = 1)
>>> validator.valid(None, request, view)
False
Decrease the current last modified time of the view by 1 second.
>>> LastModification.lastmodified = lmt - datetime.timedelta(seconds = 1)
>>> validator.valid(None, request, view)
True
Invalid date header.
>>> request = TestRequest(
... environ = {'IF_UNMODIFIED_SINCE': 'xxx'})
>>> view = SimpleView(None, request)
>>> validator.valid(None, request, view)
False
If no `If-Modified-Since` or `If-UnModified-Since` conditional HTTP
headers are set then the request is valid.
>>> request = TestRequest()
>>> view = SimpleView(None, request)
>>> validator.valid(None, request, view)
Traceback (most recent call last):
...
ValueError: Protocol implementation is broken - evaluate should be False
But then the validator should not evaluate the request.
>>> validator.evaluate(None, request, view)
False
Valid responses
===============
>>> LastModification.lastmodified = lmt
>>> request = TestRequest(
... environ = {'IF_UNMODIFIED_SINCE': format(lmt)})
>>> view = SimpleView(None, request)
Since we have a conditional header present the validator can evaluate
the data.
>>> validator.evaluate(None, request, view)
True
>>> validator.valid(None, request, view)
True
>>> validator.updateResponse(None, request, view) is None
True
>>> request.response.getStatus()
599
>>> request.response.getHeader('Last-Modified')
'Sat, 06 Jan 2007 12:42:12 GMT'
Since the `Last-Modified` header is already set, it doesn't get overriden.
>>> LastModification.lastmodified = lmt + datetime.timedelta(seconds = 1)
>>> validator.updateResponse(None, request, view)
>>> request.response.getStatus()
599
>>> request.response.getHeader('Last-Modified')
'Sat, 06 Jan 2007 12:42:12 GMT'
Invalid responses
=================
>>> LastModification.lastmodified = lmt + datetime.timedelta(seconds = 1)
>>> request = TestRequest(environ = {'IF_UNMODIFIED_SINCE': format(lmt)})
>>> view = SimpleView(None, request)
Since we have a conditional header present the validator can evaluate
the data.
>>> validator.evaluate(None, request, view)
True
>>> validator.valid(None, request, view)
False
>>> validator.updateResponse(None, request, view) is None
True
>>> request.response.getStatus()
599
>>> request.response.getHeader('Last-Modified')
'Sat, 06 Jan 2007 12:42:13 GMT'
>>> validator.invalidStatus(None, request, view)
304
Since the `Last-Modified` header is already set, it doesn't get overriden.
>>> LastModification.lastmodified = lmt
>>> validator.updateResponse(None, request, view)
>>> request.response.getHeader('Last-Modified')
'Sat, 06 Jan 2007 12:42:13 GMT'
Query strings
=============
If a query string is present in the request, then the client requested
a content negotiated view, or else they tried to fill out a form. Either
way the request must evaluate to True, and be executed.
>>> LastModification.lastmodified = lmt + datetime.timedelta(seconds = 1)
>>> request = TestRequest(environ = {'IF_UNMODIFIED_SINCE': format(lmt),
... 'QUERY_STRING': 'argument=true'})
>>> view = SimpleView(None, request)
>>> validator.evaluate(None, request, view)
True
>>> validator.valid(None, request, view)
True
We should not update the response when there is a query string present.
>>> validator.updateResponse(None, request, view) is None
True
>>> request.response.getHeader('Last-Modified') is None
True
Cleanup
-------
>>> gsm.unregisterAdapter(LastModification,
... (None, IBrowserRequest, None))
True
"""
zope.interface.implements(interfaces.IHTTPValidator)
def ifModifiedSince(self, request, mtime, header):
headervalue = request.getHeader(header, None)
if headervalue is not None:
# current last modification time for this view
last_modification_time = long(calendar.timegm(mtime.utctimetuple()))
try:
headervalue = long(zope.datetime.time(
headervalue.split(";", 1)[0]))
except:
# error processing the HTTP-date value - return the
# default value.
return True
else:
return last_modification_time > headervalue
# By default all HTTP Cache validators should return True so that the
# request proceeds as normal.
return True
def evaluate(self, context, request, view):
return \
request.getHeader("If-Modified-Since", None) is not None or \
request.getHeader("If-UnModified-Since", None) is not None
def getDataStorage(self, context, request, view):
return zope.component.queryMultiAdapter(
(context, request, view), interfaces.ILastModificationDate)
def valid(self, context, request, view):
if request.get("QUERY_STRING", "") != "":
# a query string was supplied in the URL, so the data supplied
# by the ILastModificationDate does not apply to this view.
return True
lmd = self.getDataStorage(context, request, view)
if lmd is None:
return True
lmd = lmd.lastmodified
if lmd is None:
return True
if request.getHeader("If-Modified-Since", None) is not None:
return self.ifModifiedSince(request, lmd, "If-Modified-Since")
if request.getHeader("If-UnModified-Since", None) is not None:
return not self.ifModifiedSince(
request, lmd, "If-UnModified-Since")
raise ValueError(
"Protocol implementation is broken - evaluate should be False")
def invalidStatus(self, context, request, view):
return 304
def updateResponse(self, context, request, view):
if request.response.getHeader("Last-Modified", None) is None and \
request.get("QUERY_STRING", "") == "":
storage = self.getDataStorage(context, request, view)
if storage is not None and storage.lastmodified is not None:
lmd = zope.datetime.rfc1123_date(
calendar.timegm(storage.lastmodified.utctimetuple()))
request.response.setHeader("Last-Modified", lmd) | z3c.conditionalviews | /z3c.conditionalviews-1.0b1.tar.gz/z3c.conditionalviews-1.0b1/src/z3c/conditionalviews/lastmodification.py | lastmodification.py |
from zope import interface
from zope import schema
class IETag(interface.Interface):
"""
Entity tags are used for comparing two or more entities from the same
requested view.
Used by the .etag.ETagValidator to validate a request against `If-Match`
and `If-None-Match` conditional HTTP headers.
"""
weak = interface.Attribute("""
Boolean value indicated that the entity tag is weak.
""")
etag = interface.Attribute("""
The current entity tag of this view.
""")
class ILastModificationDate(interface.Interface):
"""
Used by the ModificationSinceValidator to adapt a view in order to
validate the `If-Modified-Since` and `If-UnModified-Since` conditional
HTTP headers.
"""
lastmodified = schema.Datetime(
title = u"Last modification date",
description = u"Indicates the last time this view last changed.",
required = False)
class IHTTPValidator(interface.Interface):
"""
This adapter is responsible for validating a HTTP request against one
or more conditional headers.
When a view is called then for each validator that is registered with
the system, all validators that could possible return False, that is
their `evaluate` method returns True are counted. And if the number
of validators whose evaluate method returns True equals the number
of validators who say that the request is invalid (i.e. the valid
method returns False) then the request is considered invalid by this
package.
When a request is invalid then the `invalidStatus` method is called to
set the status code of the response and the view we are adapter is not
called.
If a request is valid then the view we adapted is called.
In both situations, after the view is called or the `invalidStatus`
then the `updateResponse` method is called for each registered validators.
This method should (if not present) add a validator HTTP header to
the response, so clients know how to make a request conditional.
"""
def evaluate(context, request, view):
"""
Return `True` if this request is a conditional request and this
validator knows can validate the request.
"""
def valid(context, request, view):
"""
Return `True` request is valid and should be executed.
If the request is not valid then the `invalidStatus` method will
be called.
By default this method should always return `True`.
"""
def invalidStatus(context, request, view):
"""
Return the integer status of that the response should be considering
that this validator evaluated the request as invalid.
If more then more validator are involved in failing a request then
the first validator used will in the validation algorithm will be
used. This isn't ideal but in practice, this problem is unlikely to
show up.
"""
def updateResponse(context, request, view):
"""
This method is always called, and should set a HTTP header informing
the current data needed to invalid a request the next time they
request the adapted view.
""" | z3c.conditionalviews | /z3c.conditionalviews-1.0b1.tar.gz/z3c.conditionalviews-1.0b1/src/z3c/conditionalviews/interfaces.py | interfaces.py |
===================
z3c.condtionalviews
===================
z3c.conditionalviews is a mechanism to validate a HTTP request based on some
conditional protocol like entity tags, or last modification date. It is also
extensible so that protocols like WebDAV can define there own conditional
protocol like the IF header.
It works by implementing each conditional protocol as a `IHTTPValidator`
utility, see etag and lastmodification modules for the most common use cases.
Then when certain views are called by the publisher we lookup these utilities
and ask them to validate the request object according to whatever protocol
the utility implements.
At the time of the view is called, and when we validate the request, we
generally have access to the context, request and view itself. So the
`IHTTPValidator` utilities generally adapt these 3 objects to an object
implementing an interface specific to the protocol in question. For example
the entity tag validator looks up an adapter implementing `IEtag`.
Integration with Zope
=====================
>>> import zope.component
>>> import zope.interface
>>> import z3c.conditionalviews.interfaces
>>> import z3c.conditionalviews.tests
Decorator
---------
In order to integrate common browser views that can be cached, we can decorate
the views call method with the `z3c.conditionalviews.ConditionalView` object.
Note that all the views used in this test are defined in the ftesting.zcml
file.
>>> response = http(r"""
... GET /@@simpleview.html HTTP/1.1
... Host: localhost
... """, handle_errors = False)
>>> response.getStatus()
200
>>> response.getHeader('content-length')
'82'
>>> response.getHeader('content-type')
'text/plain'
>>> print response.getBody()
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Since we haven't yet defined an adapter implementing IETag, the response
contains no ETag header.
>>> response.getHeader('ETag') is None
True
Define our IETag implementation.
>>> class SimpleEtag(object):
... zope.interface.implements(z3c.conditionalviews.interfaces.IETag)
... def __init__(self, context, request, view):
... pass
... weak = False
... etag = "3d32b-211-bab57a40"
>>> zope.component.getGlobalSiteManager().registerAdapter(
... SimpleEtag,
... (zope.interface.Interface,
... zope.publisher.interfaces.browser.IBrowserRequest,
... zope.interface.Interface))
>>> response = http(r"""
... GET /@@simpleview.html HTTP/1.1
... Host: localhost
... """, handle_errors = False)
>>> response.getStatus()
200
>>> response.getHeader('content-length')
'82'
>>> response.getHeader('content-type')
'text/plain'
>>> response.getHeader('ETag')
'"3d32b-211-bab57a40"'
>>> print response.getBody()
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Now by setting the request header If-None-Match: "3d32b-211-bab57a40", our
view fails the validation and a 304 response is returned.
>>> response = http(r"""
... GET /@@simpleview.html HTTP/1.1
... Host: localhost
... If-None-Match: "3d32b-211-bab57a40"
... """, handle_errors = False)
>>> response.getStatus()
304
>>> response.getHeader('ETag')
'"3d32b-211-bab57a40"'
>>> response.getBody()
''
XXX - this seems wrong the content-length and content-type should not be set
for this response.
>>> response.getHeader('content-length')
'0'
>>> response.getHeader('content-type')
'text/plain'
Now make sure that we haven't broken the publisher, by making sure that we
can still pass arguments to the different views.
>>> response = http(r"""
... GET /@@simpleview.html?letter=y HTTP/1.1
... Host: localhost
... """, handle_errors = False)
>>> response.getStatus()
200
>>> response.getHeader('content-length')
'82'
>>> print response.getBody()
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
We are now getting a charset value for this request because the default
value for the SimpleView is not a unicode string, while the data received
from the request is automatically converted to unicode by default.
>>> response.getHeader('content-type')
'text/plain;charset=utf-8'
Since there is a query string present in the request, we don't set the ETag
header.
>>> response.getHeader('ETag') is None
True
The query string present in the following request causes the request to
be valid, otherwise it would be invalid.
>>> response = http(r"""
... GET /@@simpleview.html?letter=y HTTP/1.1
... If-None-Match: "3d32b-211-bab57a40"
... Host: localhost
... """, handle_errors = False)
>>> response.getStatus()
200
Generic HTTP conditional publication
====================================
We can integrate the validation method with the publication call method. This
as the effect of trying to validate every request that passes through the
publications `callObject` method. This is useful to validate requests that
modify objects so that the client can say modify this resource if it hasn't
changed since it last downloaded the resource, or if there is no existing
resource at a location.
This has the added benifit in that we don't have to specify how some one
implements the PUT method.
>>> resp = http(r"""
... PUT /testfile HTTP/1.1
... Authorization: Basic mgr:mgrpw
... Content-type: text/plain
... Content-length: 55
... aaaaaaaaaa
... aaaaaaaaaa
... aaaaaaaaaa
... aaaaaaaaaa
... aaaaaaaaaa""", handle_errors = False)
>>> resp.getStatus()
201
>>> resp.getHeader('Content-length')
'0'
>>> resp.getHeader('Location')
'http://localhost/testfile'
>>> resp.getHeader('ETag', None) is None
True
We can now get the resource and the entity tag.
>>> resp = http(r"""
... GET /testfile HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
>>> resp.getStatus()
200
>>> resp.getHeader('ETag')
'"testfile:1"'
>>> print resp.getBody()
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
We could have used the HEAD method to get the entity tag.
>>> resp = http(r"""
... HEAD /testfile HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
>>> resp.getStatus()
200
>>> resp.getHeader('ETag')
'"testfile:1"'
With no 'If-None-Match' header we override the data.
>>> resp = http(r"""
... PUT /testfile HTTP/1.1
... Authorization: Basic mgr:mgrpw
... Content-type: text/plain
... Content-length: 55
... bbbbbbbbbb
... bbbbbbbbbb
... bbbbbbbbbb
... bbbbbbbbbb
... bbbbbbbbbb""", handle_errors = False)
>>> resp.getStatus()
200
>>> resp.getHeader('Content-length')
'0'
>>> resp.getHeader('Location', None) is None
True
>>> resp.getHeader('ETag')
'"testfile:2"'
>>> resp = http(r"""
... GET /testfile HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
>>> resp.getStatus()
200
>>> print resp.getBody()
bbbbbbbbbb
bbbbbbbbbb
bbbbbbbbbb
bbbbbbbbbb
bbbbbbbbbb
Specifying a `If-None-Match: "*"` header, says to upload the data only if there
is no resource at the location specified in the request URI. If there is a
resource at the location then a `412 Precondition Failed` response is
returned and the resource is not modified'
>>> resp = http(r"""
... PUT /testfile HTTP/1.1
... Authorization: Basic mgr:mgrpw
... If-None-Match: "*"
... Content-type: text/plain
... Content-length: 55
... cccccccccc
... cccccccccc
... cccccccccc
... cccccccccc
... cccccccccc""")
>>> resp.getStatus()
412
>>> resp.getHeader('Content-length')
'0'
>>> resp.getHeader('Location', None) is None
True
>>> resp.getHeader('ETag')
'"testfile:2"'
The file does not change.
>>> resp = http(r"""
... GET /testfile HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
>>> resp.getStatus()
200
>>> print resp.getBody()
bbbbbbbbbb
bbbbbbbbbb
bbbbbbbbbb
bbbbbbbbbb
bbbbbbbbbb
And now since testfile2 does exist yet we content the content.
>>> resp = http(r"""
... PUT /testfile2 HTTP/1.1
... Authorization: Basic mgr:mgrpw
... If-None-Match: "*"
... Content-type: text/plain
... Content-length: 55
... yyyyyyyyyy
... yyyyyyyyyy
... yyyyyyyyyy
... yyyyyyyyyy
... yyyyyyyyyy""")
>>> resp.getStatus()
201
>>> resp.getHeader('Content-length')
'0'
>>> resp.getHeader('Location')
'http://localhost/testfile2'
>>> resp.getHeader('ETag', None) is None # No etag adapter is configured
True
>>> resp = http(r"""
... GET /testfile2 HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
>>> resp.getStatus()
200
>>> print resp.getBody()
yyyyyyyyyy
yyyyyyyyyy
yyyyyyyyyy
yyyyyyyyyy
yyyyyyyyyy
We can now delete the resource, only if it hasn't changed. So for the
'/testfile' resource we can use its first entity tag to confirm this.
>>> resp = http(r"""
... DELETE /testfile HTTP/1.1
... Authorization: Basic mgr:mgrpw
... If-Match: "testfile:1"
... """)
>>> resp.getStatus()
412
And the file still exists.
>>> resp = http(r"""
... GET /testfile HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
>>> resp.getStatus()
200
But using a valid entity tag we can delete the resource.
>>> resp = http(r"""
... DELETE /testfile HTTP/1.1
... Authorization: Basic mgr:mgrpw
... If-Match: "testfile:2"
... """)
>>> resp.getStatus()
200
>>> resp.getBody()
''
>>> resp = http(r"""
... GET /testfile HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
>>> resp.getStatus()
404
Method not allowed
==================
We should still get a `405 Method Not Allowed` status for methods that aren't
registered yet.
We need to be logged in order to traverse to the file.
>>> resp = http(r"""
... FROG /testfile2 HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
>>> resp.getStatus()
405
>>> resp.getHeader('ETag', None) is None
True
Cleanup
=======
>>> zope.component.getGlobalSiteManager().unregisterAdapter(
... SimpleEtag,
... (zope.interface.Interface,
... zope.publisher.interfaces.browser.IBrowserRequest,
... zope.interface.Interface))
True
| z3c.conditionalviews | /z3c.conditionalviews-1.0b1.tar.gz/z3c.conditionalviews-1.0b1/src/z3c/conditionalviews/README.txt | README.txt |
import zope.interface
import zope.component
from zope.app.http.interfaces import INullResource
import interfaces
class ETagValidator(object):
"""
>>> from zope.interface.verify import verifyObject
>>> from zope.publisher.interfaces.browser import IBrowserRequest
>>> from zope.publisher.browser import TestRequest
>>> from zope.publisher.browser import BrowserView
>>> class SimpleView(BrowserView):
... def __call__(self):
... self.request.response.setStatus(200)
... self.request.response.setHeader('ETag', '"xxxetag"')
... return 'Rendered view representation'
The ETagValidator is a HTTP utility validator that implements the entity
tag protocol.
>>> validator = ETagValidator()
>>> verifyObject(interfaces.IHTTPValidator, validator)
True
We need to make sure that we can corrctly parse any `If-Match`, or
`If-None-Match` HTTP header.
>>> request = TestRequest(environ = {
... 'NOQUOTE': 'aa',
... 'ONE': '"aa"',
... 'TWO': '"aa", "bb"',
... 'ALL': '"aa", *, "bb"',
... 'WEAK': 'W/"w1"',
... 'WEAK_TWO': 'W/"w1", W/"w2"',
... })
>>> view = SimpleView(None, request)
>>> validator.parseMatchList(request, 'missing')
[]
>>> validator.parseMatchList(request, 'noquote')
[]
>>> validator.parseMatchList(request, 'one')
['aa']
>>> validator.parseMatchList(request, 'two')
['aa', 'bb']
>>> validator.parseMatchList(request, 'all')
['aa', '*', 'bb']
>>> validator.parseMatchList(request, 'weak')
['w1']
>>> validator.parseMatchList(request, 'weak_two')
['w1', 'w2']
When neither a `If-None-Match` or a `If-Match` header is present in the
request then we cannot evaluate this request as a conditional request,
according to the `If-None-Match` or `If-Match` protocol.
>>> validator.evaluate(None, request, view)
False
But if someone does try and validate the request then it is just True.
>>> validator.valid(None, request, view)
True
If-None-Match
=============
Define a simple ETag adapter for getting the current entity tag of a
view. We can change the value of the current etag by setting the
etag class attribute.
>>> class CurrentETag(object):
... zope.interface.implements(interfaces.IETag)
... def __init__(self, context, request, view):
... pass
... weak = False
... etag = 'xyzzy'
>>> request = TestRequest(environ = {'IF_NONE_MATCH': '"xyzzy"'})
>>> view = SimpleView(None, request)
Since we have a conditional header present the validator can evaluate
this request.
>>> validator.evaluate(None, request, view)
True
No current IETag adapter available so the request is valid, and the
update response method works but doesn't set any headers.
>>> validator.valid(None, request, view)
True
>>> validator.updateResponse(None, request, view) is None
True
>>> request.response.getHeader('ETag', None) is None
True
But if the `If-None-Match` value is '*' then the request is invalid
even tough the resource has no entity tag.
>>> request._environ['IF_NONE_MATCH'] = '"*"'
>>> validator.valid(None, request, view)
False
>>> request._environ['IF_NONE_MATCH'] = '"xyzzy"'
The default value for the current entity tab is the same as in the request,
so the request is invalid, that is none of the entity tags match.
>>> zope.component.getGlobalSiteManager().registerAdapter(
... CurrentETag, (None, IBrowserRequest, None))
>>> validator.valid(None, request, view)
False
Etags don't match so the request is valid.
>>> CurrentETag.etag = 'xxx'
>>> validator.valid(None, request, view)
True
Test '*' which matches all values.
>>> request._environ['IF_NONE_MATCH'] = '"*"'
>>> validator.valid(None, request, view)
False
Test multiple `If-None-Match` values.
>>> request._environ['IF_NONE_MATCH'] = '"xxx", "yyy"'
>>> validator.valid(None, request, view)
False
>>> CurrentETag.etag = 'xxxzz'
>>> validator.valid(None, request, view)
True
Test multiple `If-None-Match` values with a '*'
>>> request._environ['IF_NONE_MATCH'] = '"*", "xxx", "yyy"'
>>> validator.valid(None, request, view)
False
>>> CurrentETag.etag = None
>>> validator.valid(None, request, view)
False
If-Match
========
>>> request = TestRequest(environ = {'IF_MATCH': '"xyzzy"'})
>>> view = SimpleView(None, request)
>>> CurrentETag.etag = None
Since we have a conditional header present the validator can
evaluate this request.
>>> validator.evaluate(None, request, view)
True
Since there is no entity tag for the view, we don't match 'xyzzy', or
equivalently it is set to None.
>>> validator.valid(None, request, view)
False
The entity tags differ.
>>> CurrentETag.etag = 'xxx'
>>> validator.valid(None, request, view)
False
The entity tags are the same.
>>> CurrentETag.etag = 'xyzzy'
>>> validator.valid(None, request, view)
True
A `If-Match` header value of '*' matches everything.
>>> request._environ['IF_MATCH'] = '"*"'
>>> validator.valid(None, request, view)
True
Try multiple values.
>>> request._environ['IF_MATCH'] = '"xxx", "yyy"'
>>> validator.valid(None, request, view)
False
>>> request._environ['IF_MATCH'] = '"xyzzy", "yyy"'
>>> validator.valid(None, request, view)
True
Try multiple values with an '*' value.
>>> request._environ['IF_MATCH'] = '"xxx", "*", "yyy"'
>>> validator.valid(None, request, view)
True
Common responses
================
Whether or not a request is valid or invalid the updateResponse method
is called after the status of the request is set by either the view / or
the `invalidStatus` method. Note that the updateResponse method does not
return any value. If it did then this value is not used for anything.
>>> CurrentETag.etag = 'xxx'
>>> request = TestRequest(environ = {'IF_NONE_MATCH': '"xyzzy"'})
>>> view = SimpleView(None, request)
>>> validator.valid(None, request, view)
True
>>> validator.updateResponse(None, request, view) is None
True
>>> request.response.getStatus() # status is unset
599
>>> request.response.getHeader('ETag')
'"xxx"'
Since the `ETag` response header is set, we don't override it. Changing
the current entity tag and recalling the updateResponse method confirms
this. Note that this feature is neccessary to avoid situations where
a developer manages the entity tag of a view independently of this package.
>>> CurrentETag.etag = 'yyy'
>>> validator.updateResponse(None, request, view) is None
True
>>> request.response.getStatus()
599
>>> request.response.getHeader('ETag')
'"xxx"'
Marking the current entity tag as weak.
>>> CurrentETag.weak = True
>>> validator.updateResponse(None, request, view)
>>> request.response.getHeader('ETag')
'"xxx"'
Since the 'ETag' header is already set we need to recreate the response
object to test the condition when the weak attribute is True.
>>> request = TestRequest(environ = {'IF_NONE_MATCH': '"xyzzy"'})
>>> view = SimpleView(None, request)
>>> validator.valid(None, request, view)
True
>>> validator.updateResponse(None, request, view)
>>> request.response.getHeader('ETag')
'W/"yyy"'
>>> CurrentETag.weak = False
Invalid header
==============
If the header doesn't parse then the requets is True.
>>> request._environ['IF_NONE_MATCH'] = '"yyy"'
>>> validator.valid(None, request, view)
False
Now if we are missing the double quotes around the entity tag.
>>> request._environ['IF_NONE_MATCH'] = 'yyy'
>>> validator.valid(None, request, view)
True
Invalid status
==============
In the case of entity tags and invalid responses we should return a 304
for the GET, and HEAD method requests and 412 otherwise.
>>> CurrentETag.etag = 'xyzzy'
>>> request = TestRequest(environ = {'IF_NONE_MATCH': '"xyzzy"'})
>>> request.method
'GET'
>>> view = SimpleView(None, request)
>>> validator.valid(None, request, view)
False
>>> validator.updateResponse(None, request, view) is None
True
>>> request.response.getStatus()
599
>>> request.response.getHeader('ETag')
'"xyzzy"'
>>> validator.invalidStatus(None, request, view)
304
And the same for `HEAD` methods.
>>> CurrentETag.etag = 'xyzzy'
>>> request = TestRequest(environ = {'IF_NONE_MATCH': '"xyzzy"',
... 'REQUEST_METHOD': 'HEAD'})
>>> request.method
'HEAD'
>>> view = SimpleView(None, request)
>>> validator.valid(None, request, view)
False
>>> validator.invalidStatus(None, request, view)
304
For anyother request method we get a `412 Precondition failed` response.
>>> request = TestRequest(environ = {'IF_NONE_MATCH': '"xyzzy"',
... 'REQUEST_METHOD': 'FROG'})
>>> request.method
'FROG'
>>> view = SimpleView(None, request)
>>> validator.valid(None, request, view)
False
>>> validator.invalidStatus(None, request, view)
412
Query strings
=============
If a query is present in the request then either the client is filling
in a form with a GET method (oh why..), or else they are trying to do
some content negotiation, and hence the data supplied by the IETag adapter
does not apply to the view. But there are still cases where a request with
a query string can still fail.
>>> request = TestRequest(environ = {'IF_NONE_MATCH': '"xyzzy"',
... 'REQUEST_METHOD': 'GET',
... 'QUERY_STRING': 'argument=value'})
>>> view = SimpleView(None, request)
>>> validator.evaluate(None, request, view)
True
>>> validator.valid(None, request, view)
True
>>> request._environ['IF_NONE_MATCH'] = '"*"'
>>> validator.valid(None, request, view)
False
>>> request = TestRequest(environ = {'IF_MATCH': '"xyzzy"',
... 'REQUEST_METHOD': 'GET',
... 'QUERY_STRING': 'argument=value'})
>>> view = SimpleView(None, request)
>>> validator.evaluate(None, request, view)
True
>>> validator.valid(None, request, view)
False
>>> request._environ['IF_MATCH'] = '"*"'
>>> validator.valid(None, request, view)
True
Finally if we have a query string then when we try and update the
response we should not set the entity tag.
>>> validator.updateResponse(None, request, view) is None
True
>>> request.response.getHeader('ETag', None) is None
True
Null resources
==============
Additional functionality is needed to deal with null resources.
>>> import zope.app.http.put
>>> nullresource = zope.app.http.put.NullResource(None, 'test')
The `If-None-Match: "*"' says that a request is valid if the resource
corresponding to the resource does not exsist.
>>> request = TestRequest(environ = {'IF_NONE_MATCH': '"*"'})
>>> view = SimpleView(nullresource, request)
>>> validator.valid(nullresource, request, view)
True
The `If-Match: "*"` header says that a request is valid if the resource
corresponding the the request exsists. A null resource does not exist - it
is a temporary non-presistent content object used as an location in the
database that might exist, if a user PUT's data to it.
>>> request = TestRequest(environ = {'IF_MATCH': '"*"'})
>>> view = SimpleView(nullresource, request)
>>> validator.valid(nullresource, request, view)
False
Cleanup
-------
>>> zope.component.getGlobalSiteManager().unregisterAdapter(
... CurrentETag, (None, IBrowserRequest, None))
True
"""
zope.interface.implements(interfaces.IHTTPValidator)
def parseMatchList(self, request, header):
ret = []
matches = request.getHeader(header, None)
if matches is not None:
for val in matches.split(","):
val = val.strip()
if val == "*":
ret.append(val)
else:
if val[:2] == "W/":
val = val[2:]
if val[0] + val[-1] == '""' and len(val) > 2:
ret.append(val[1:-1])
return ret
def evaluate(self, context, request, view):
return request.getHeader("If-None-Match", None) is not None or \
request.getHeader("If-Match") is not None
def getDataStorage(self, context, request, view):
return zope.component.queryMultiAdapter(
(context, request, view), interfaces.IETag)
def _matches(self, context, request, etag, matchset):
if "*" in matchset:
if INullResource.providedBy(context):
return False
return True
if request.get("QUERY_STRING", "") == "" and etag in matchset:
return True
return False
def valid(self, context, request, view):
etag = self.getDataStorage(context, request, view)
if etag is not None:
# A request can still be invalid without knowing entity tag.
# If-Match: "*" matches everything
etag = etag.etag
# Test the most common validator first.
matchset = self.parseMatchList(request, "If-None-Match")
if matchset:
return not self._matches(context, request, etag, matchset)
matchset = self.parseMatchList(request, "If-Match")
if matchset:
return self._matches(context, request, etag, matchset)
# Always default to True, this can happen if the requests contains
# invalid data.
return True
def invalidStatus(self, context, request, view):
if request.method in ("GET", "HEAD"):
return 304
else:
# RFC2616 Section 14.26:
# Instead, if the request method was GET or HEAD, the server
# SHOULD respond with a 304 (Not Modified) response, including
# the cache-related header fields (particularly ETag) of one of
# the entities that matched.
return 412
def updateResponse(self, context, request, view):
if request.response.getHeader("ETag", None) is None and \
request.get("QUERY_STRING", "") == "":
etag = self.getDataStorage(context, request, view)
weak = etag and etag.weak
etag = etag and etag.etag
if etag:
if weak:
request.response.setHeader("ETag", 'W/"%s"' % etag)
else:
request.response.setHeader("ETag", '"%s"' % etag) | z3c.conditionalviews | /z3c.conditionalviews-1.0b1.tar.gz/z3c.conditionalviews-1.0b1/src/z3c/conditionalviews/etag.py | etag.py |
import zope.component
import zope.publisher.http
import zope.publisher.publish
import zope.publisher.interfaces
import zope.app.http.interfaces
import zope.app.publication.http
import zope.app.publication.interfaces
import interfaces
def validate(context, request, func, viewobj, *args, **kw):
# count the number of invalid and evaulated validators, if evaluated is
# greater then zero and equal to hte invalid count then the request is
# invalid.
evaluated = invalid = 0
validators = [validator
for validator_name, validator in
zope.component.getUtilitiesFor(interfaces.IHTTPValidator)]
invalidStatus = 999
for validator in validators:
if validator.evaluate(context, request, viewobj):
evaluated += 1
if not validator.valid(context, request, viewobj):
invalid += 1
invalidStatus = validator.invalidStatus(
context, request, viewobj)
if evaluated > 0 and evaluated == invalid:
# The request is invalid so we do not process it.
request.response.setStatus(invalidStatus)
result = ""
else:
# The request is valid so we do process it.
result = func(viewobj, *args, **kw)
for validator in validators:
validator.updateResponse(context, request, viewobj)
return result
class BoundConditionalView(object):
def __init__(self, pt, ob):
object.__setattr__(self, "im_func", pt)
object.__setattr__(self, "im_self", ob)
def __call__(self, *args, **kw):
args = (self.im_self,) + args
return validate(self.im_self.context, self.im_self.request,
self.im_func, *args, **kw)
###############################################################################
#
# Decorators to turn a specific view into a conditonal view. For example
# file downloads / upload views.
#
###############################################################################
class ConditionalView(object):
def __init__(self, viewmethod):
self.viewmethod = viewmethod
def __get__(self, instance, class_):
return BoundConditionalView(self.viewmethod, instance)
###############################################################################
#
# Generic publication object to turn a whole set of request handlers into
# conditional views.
#
###############################################################################
class ConditionalHTTPRequest(zope.publisher.http.HTTPRequest):
zope.interface.classProvides(
zope.app.publication.interfaces.IHTTPRequestFactory)
def setPublication(self, publication):
super(ConditionalHTTPRequest, self).setPublication(
ConditionalPublication(publication))
class ConditionalPublication(object):
def __init__(self, publication):
self._publication = publication
for name in zope.publisher.interfaces.IPublication:
if name not in ("callObject",):
setattr(self, name, getattr(publication, name))
def callObject(self, request, ob):
# Exception handling, dont try to call request.method
if not zope.app.http.interfaces.IHTTPException.providedBy(ob):
view = zope.component.queryMultiAdapter(
(ob, request), name = request.method)
method = getattr(view, request.method, None)
if method is None:
raise zope.app.publication.http.MethodNotAllowed(ob, request)
ob = BoundConditionalView(method.im_func, method.im_self)
return zope.publisher.publish.mapply(
ob, request.getPositionalArguments(), request) | z3c.conditionalviews | /z3c.conditionalviews-1.0b1.tar.gz/z3c.conditionalviews-1.0b1/src/z3c/conditionalviews/__init__.py | __init__.py |
__docformat__ = "reStructuredText"
import zope.component
import zope.interface
import zope.schema
from z3c.configurator import interfaces
def getAdapterFactories(component, specific=True):
"""Get adapter registrations where @iface is provided and prefer
the specific registrations."""
iface = interfaces.IConfigurationPlugin
gsm = zope.component.getGlobalSiteManager()
res = {}
for reg in gsm.registeredAdapters():
# Only get adapters for which this interface is provided
if reg.provided is None or not reg.provided.isOrExtends(iface):
continue
if reg.required[0].providedBy(component):
res[reg.name] = reg.factory
if specific or reg.name in res:
continue
res[reg.name] = reg.factory
return res
def requiredPlugins(component, names=[]):
"""returns a list of tuples of (name, pluginfactory) in the right
order to be executed"""
if not names:
# get all names we have available
names = getAdapterFactories(component,
specific=True).keys()
# we need this in order to get dependencies from plugins which are
# not available in the unconfigured component because the provided
# interfaces may change during execution
plugins = getAdapterFactories(component,
specific=False)
def _add(name, res):
if name in seen:
return
seen.add(name)
deps = getattr(plugins[name], 'dependencies', ())
for dep in deps:
if dep not in res:
_add(dep, res)
if name not in res:
res.append(name)
seen = set()
res = []
for name in names:
_add(name, res)
return [(name, plugins[name]) for name in res]
def configure(component, data, names=[], useNameSpaces=False):
plugins = requiredPlugins(component, names)
for name, factory in plugins:
if useNameSpaces is True:
d = data.get(name, {})
else:
d = data
plugin = factory(component)
plugin(d)
@zope.interface.implementer(interfaces.IConfigurationPlugin)
class ConfigurationPluginBase:
def __init__(self, context):
self.context = context
def __call__(self, data):
raise NotImplementedError
@zope.interface.implementer(interfaces.ISchemaConfigurationPlugin)
class SchemaConfigurationPluginBase:
schema = zope.interface.Interface
def __init__(self, context):
self.context = context
def verify(self, data):
for name, field in zope.schema.getFields(self.schema).items():
field.validate(data.get(name))
def __call__(self, data):
raise NotImplementedError | z3c.configurator | /z3c.configurator-3.0-py3-none-any.whl/z3c/configurator/configurator.py | configurator.py |
================
The Configurator
================
The configurator is designed to extend a component after its
creation. Traditionally this is done by listening to ``ObjectCreatedEvent``
events. However, this low-level method does not suffice, since configuration
often depends on other configuration steps and additional data is often needed
to complete the configuration. And this is where the configurator comes
in. It uses a separate plugin mechanism to implement the mentioned high-level
functionality.
Before we can demonstrate the configuration mechanism, we'll have to create an
interface and a component on which the configuration can act upon:
>>> import zope.interface
>>> class ISomething(zope.interface.Interface):
... """Some interesting interface."""
>>> @zope.interface.implementer(ISomething)
... class Something(object):
... """Implementation of something."""
>>> something = Something()
Now we can have the configuration act on the component:
>>> from z3c import configurator
>>> configurator.configure(something, {})
The second argument is the data dictionary, which can be used to pass in
additional information that might be needed during the configuration. It is up
to each plugin to interpret the data.
Of course nothing happens, since no configuration plugins are
registered. Let's now create a new configuration plugin, which sets a new
attribute on the component:
>>> import zope.component
>>> from z3c.configurator import interfaces
>>> class AddFooAttribute(configurator.ConfigurationPluginBase):
... zope.component.adapts(ISomething)
...
... def __call__(self, data):
... setattr(self.context, 'foo', data.get('foo'))
>>> zope.component.provideAdapter(AddFooAttribute, name='add foo')
If we execute the configuration again, the attribute will be added:
>>> configurator.configure(something, {'foo': u'my value'})
>>> something.foo
u'my value'
Dependencies
------------
Now that we have simple configuration plugins, we can also develop plugins
that depend on another one. Let's create a configuration plugin that adds some
additional data to the foo attribute. Clearly, the foo attribute has to exist
before this step can be taken. The ``dependencies`` attribute can be used to
specify all plugin dependencies by name:
>>> class ExtendFooAttribute(configurator.ConfigurationPluginBase):
... zope.component.adapts(ISomething)
... dependencies = ('add foo',)
...
... def __call__(self, data):
... self.context.foo = u'Text: ' + self.context.foo
>>> zope.component.provideAdapter(ExtendFooAttribute, name='extend foo')
If we now execute the configuration again, the extended result should be seen:
>>> something = Something()
>>> configurator.configure(something, {'foo': u'my value'})
>>> something.foo
u'Text: my value'
Data Schemas
------------
For purely informational purposes, a ``schema`` attribute is used on the
plugin to describe the fields that the plugin expects from the data
dictionary. For adding another simple attribute, this could look as follows:
>>> import zope.schema
>>> class IAddBar(zope.interface.Interface):
... bar = zope.schema.Text(title=u'Bar')
>>> class AddBarAttribute(configurator.SchemaConfigurationPluginBase):
... zope.component.adapts(ISomething)
... schema = IAddBar
...
... def __call__(self, data):
... self.verify(data)
... setattr(self.context, 'bar', data.get('bar'))
>>> zope.component.provideAdapter(AddBarAttribute, name='add bar')
The advantage of using the base class for this case is that it provides a
``verify()`` method that allows you to verify the data against the shema. We
can now run the configuration again:
>>> something = Something()
>>> configurator.configure(something, {'foo': u'my value', 'bar': u'value'})
>>> something.bar
u'value'
The value must exist and be valid:
>>> something = Something()
>>> configurator.configure(something, {'foo': u'my value'})
Traceback (most recent call last):
...
RequiredMissing: bar
>>> something = Something()
>>> configurator.configure(something, {'foo': u'my value', 'bar': 1})
Traceback (most recent call last):
...
WrongType: (1, <type 'unicode'>, 'bar')
Data Namespaces
---------------
In order to not confuse attribute names if two plugins share a common
name it is possible to pass data as a dictionary of dictionaries. The
keys of the dictionary is the name under which the plugins are
registered.
>>> something = Something()
>>> data = {u'add foo': {'foo': u'foo value'},
... u'add bar': {'bar': u'bar value'}}
>>> configurator.configure(something, data, useNameSpaces=True)
>>> something.foo, something.bar
(u'Text: foo value', u'bar value')
Named Configuration
-------------------
Sometimes we do not want all registered configuration plugins to be
executed. This can be achieved by providing the names argument to the
configure function.
Let us create a new something:
>>> something = Something()
If we now configure it without names we get both attributes set.
>>> configurator.configure(something, {'foo': u'my value', 'bar': u'asdf'})
>>> sorted(something.__dict__.items())
[('bar', 'asdf'), ('foo', 'Text: my value')]
Now let us just configure the plugin 'add bar'.
>>> something = Something()
>>> configurator.configure(something, {'foo': u'my value', 'bar': u'asdf'},
... names=['add bar'])
>>> something.__dict__
{'bar': u'asdf'}
Dependencies of plugins are always executed - they don't have to be
added to the ```names``` argument.
>>> something = Something()
>>> configurator.configure(something, {'foo': u'my value'},
... names=['extend foo'])
>>> something.foo
u'Text: my value'
Named configurations are usefull when called manually through the web
(see browser/README.txt). The configurator package does not look if a
configuration is already applied if called twice. It is the
responsibility of the plugin to be aware that it doesn't do things
twice or delete things.
Wrong Implementations
---------------------
A configurator must provide a __call__ method.
>>> class CallNotImplemented(configurator.ConfigurationPluginBase):
... zope.component.adapts(ISomething)
>>> zope.component.provideAdapter(CallNotImplemented, name='no call')
>>> configurator.configure(something, None, names=['no call'])
Traceback (most recent call last):
...
NotImplementedError
The same must happen for a schema base configurator.
>>> class SchemaCallNotImplemented(configurator.SchemaConfigurationPluginBase):
... zope.component.adapts(ISomething)
>>> zope.component.provideAdapter(SchemaCallNotImplemented, name='schema no call')
>>> configurator.configure(something, None, names=['schema no call'])
Traceback (most recent call last):
...
NotImplementedError
No Recursion
------------
It's possible to define recursive dependencies without to run into recursion
errors. Let's define a new plugin free object:
>>> class IFoo(zope.interface.Interface):
... """Just a foo interface."""
>>> @zope.interface.implementer(IFoo)
... class Foo(object):
... """Implementation of foo."""
Let's define another plugin named `first` which depends on a plugin named
`second`.
>>> log = []
>>> class FirstPlugin(configurator.ConfigurationPluginBase):
... zope.component.adapts(IFoo)
... dependencies = ('second',)
...
... def __call__(self, data):
... log.append('FirstPlugin called')
>>> zope.component.provideAdapter(FirstPlugin, name='first')
And define a plugin named `second` which depends on `first`:
>>> class SecondPlugin(configurator.ConfigurationPluginBase):
... zope.component.adapts(IFoo)
... dependencies = ('first',)
...
... def __call__(self, data):
... log.append('SecondPlugin called')
>>> zope.component.provideAdapter(SecondPlugin, name='second')
>>> foo = Foo()
>>> configurator.configure(foo, {})
>>> for msg in sorted(log): print(msg)
FirstPlugin called
SecondPlugin called
| z3c.configurator | /z3c.configurator-3.0-py3-none-any.whl/z3c/configurator/README.txt | README.txt |
=========================
Calling Configurators TTW
=========================
A configuration view is registered to apply named configuration on any
object. We defined two example configurators which we now gonna apply
to the site object.
>>> from zope.testbrowser.wsgi import Browser
>>> browser = Browser(wsgi_app=layer.make_wsgi_app())
>>> browser.addHeader('Authorization','Basic mgr:mgrpw')
>>> browser.handleErrors = False
>>> browser.open('http://localhost/manage')
>>> browser.url
'http://localhost/@@contents.html'
The view is registered in the zmi_views menu
>>> browser.getLink(u'Configurators').click()
>>> viewURL = browser.url
>>> viewURL
'http://localhost/@@configurators.html'
>>> sel = browser.getControl(name="form.pluginNames.to")
First we can choose from the registered named plugins.
>>> plugs = browser.getControl(name="form.pluginNames.from").options
>>> sorted(plugs)
['z3c.configurator.testing.setdescription', 'z3c.configurator.testing.settitle']
>>> browser.open(viewURL + '?form.pluginNames=z3c.configurator.testing.settitle')
We have choosen a plugin, so now we have a form for the arguments needed.
>>> browser.getControl('Some Argument').value
''
>>> browser.getControl('Some Argument').value = "New Title"
>>> browser.getControl('Apply').click()
XXX form.pluginNames have to be set, but we can't because the widget
uses javascript.
| z3c.configurator | /z3c.configurator-3.0-py3-none-any.whl/z3c/configurator/browser/README.txt | README.txt |
from zope import formlib
from zope import interface
from zope import schema
from zope.browserpage import ViewPageTemplateFile
from zope.browserpage import namedtemplate
from zope.formlib import form
from z3c.configurator import configurator
from z3c.configurator import interfaces
from z3c.configurator.i18n import _
class SelectPlugins(form.PageForm):
"""a form to choose plugins, to be applied"""
form_fields = form.Fields(
schema.Choice(__name__='pluginName',
title=_('Plugin Name'),
vocabulary="Configurator Plugin Names")
)
@form.action(label=_('Apply Configuration'))
def selectPlugins(self, action, data):
pluginName = data.get('pluginName')
configurator.configure(self.context, names=[pluginName])
self.status = _('Configuration applied')
class IGenerateSchema(interface.Interface):
"""Schema for the minimal generator parameters"""
seed = schema.TextLine(
title=_('Seed'),
description=_('A seed for the random generator'),
default='sample',
required=False,
)
class ConfigureForm(form.PageForm):
"""Configurator Plugin form"""
base_template = form.EditForm.template
template = ViewPageTemplateFile('configure.pt')
subforms = []
form_fields = form.Fields(
schema.List(__name__='pluginNames',
title='Plugin Names',
value_type=schema.Choice(
__name__='pluginName',
title=_('Plugin Name'),
vocabulary="Configurator Plugin Names")
))
workDone = False
@property
def _pluginNames(self):
names = self.request.form.get(self.prefix + '.pluginNames')
if names and not isinstance(names, list):
return [names]
return names
def setUpWidgets(self, ignore_request=False):
if self._pluginNames:
plugins = configurator.requiredPlugins(self.context,
self._pluginNames)
self.subforms = []
for name, factory in plugins:
plugin = factory(self.context)
if not interfaces.ISchemaConfigurationPlugin.providedBy(
plugin):
continue
subform = PluginSchemaForm(context=self.context,
request=self.request,
plugin=plugin,
prefix=name)
subform.form_fields = form.Fields(plugin.schema)
self.subforms.append(subform)
super().setUpWidgets(ignore_request=ignore_request)
@form.action(_("Update"))
def handleUpdate(self, action, data):
if not self._pluginNames:
return
self.setUpWidgets(ignore_request=False)
result = self.template()
return result
def _pluginsSelected(self, action):
return not not self.request.form.get(self.prefix + '.pluginNames')
@form.action(_("Apply"), condition='_pluginsSelected')
def handleApply(self, action, data):
configuratorData = {}
for subform in self.subforms:
subform.update()
formData = {}
form.getWidgetsData(subform.widgets, subform.prefix, formData)
configuratorData[subform.prefix] = formData
configurator.configure(self.context,
configuratorData,
names=self._pluginNames,
useNameSpaces=True)
self.status = 'Applied: %s' % ' '.join(self._pluginNames)
@interface.implementer(formlib.interfaces.ISubPageForm)
class PluginSchemaForm(form.AddForm):
"""An editor for a single schema based plugin"""
template = namedtemplate.NamedTemplate('default')
actions = []
def __init__(self, context, request, plugin=None,
schema=None, prefix=''):
self.plugin = plugin
self.schema = schema
self.prefix = prefix
super().__init__(context, request) | z3c.configurator | /z3c.configurator-3.0-py3-none-any.whl/z3c/configurator/browser/views.py | views.py |
import os, shutil, sys, tempfile
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --setup-source and --download-base to point to
local resources, you can keep this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", help="use a specific zc.buildout version")
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
options, args = parser.parse_args()
######################################################################
# load/install distribute
to_reload = False
try:
import pkg_resources, setuptools
if not hasattr(pkg_resources, '_distribute'):
to_reload = True
raise ImportError
except ImportError:
ez = {}
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
exec(urlopen('http://python-distribute.org/distribute_setup.py').read(), ez)
setup_args = dict(to_dir=tmpeggs, download_delay=0, no_fake=True)
ez['use_setuptools'](**setup_args)
if to_reload:
reload(pkg_resources)
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
######################################################################
# Install buildout
ws = pkg_resources.working_set
cmd = [sys.executable, '-c',
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
distribute_path = ws.find(
pkg_resources.Requirement.parse('distribute')).location
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[distribute_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=distribute_path)) != 0:
raise Exception(
"Failed to execute command:\n%s",
repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | z3c.contents | /z3c.contents-1.0.0a1.tar.gz/z3c.contents-1.0.0a1/bootstrap.py | bootstrap.py |
__docformat__ = "reStructuredText"
import zope.interface
import zope.component
from zope.container.interfaces import IReadContainer
from zope.container.interfaces import IObjectFindFilter
from zope.container.find import SimpleIdFindFilter
from zope.index.text.interfaces import ISearchableText
from zope.publisher.interfaces.browser import IBrowserRequest
import z3c.table.value
from z3c.contents import interfaces
from z3c.contents import browser
def _search_helper(id, obj, container, id_filters, object_filters, result):
# check id filters if we get a match then return immediately
for id_filter in id_filters:
if id_filter.matches(id):
result.append(obj)
return
# now check all object filters
for object_filter in object_filters:
if object_filter.matches(obj):
result.append(obj)
return
# do we need to check sub containers?
if not IReadContainer.providedBy(obj):
return
for key, value in obj.items():
_search_helper(key, value, obj, id_filters, object_filters, result)
@zope.interface.implementer(IObjectFindFilter)
class SearchableTextFindFilter(object):
"""Filter objects on the ISearchableText adapters to the object."""
def __init__(self, terms):
self.terms = terms
def matches(self, object):
"""Check if one of the search terms is found in the searchable text
interface.
"""
adapter = ISearchableText(object, None)
if adapter is None:
return False
searchable = adapter.getSearchableText().lower()
for term in [t.lower() for t in self.terms]:
if term in searchable:
return True
return False
class SearchableValues(z3c.table.value.ValuesMixin):
"""Values based on given search."""
zope.component.adapts(IReadContainer, IBrowserRequest,
interfaces.IContentsPage)
@property
def values(self):
# search form is not enabled
if not self.table.allowSearch:
return self.context.values()
# first setup and update search form
searchForm = browser.ContentsSearchForm(self.context,
self.request)
searchForm.table = self.table
searchForm.update()
# expose the search form in the table for rendering
self.table.searchForm = searchForm
# not searching
if not searchForm.searchterm:
return self.context.values()
# setup search filters
criterias = searchForm.searchterm.strip().split(' ')
if not criterias:
# only empty strings given
return self.context.values()
result = []
id_filters = [SimpleIdFindFilter(criterias)]
object_filters = [SearchableTextFindFilter(criterias)]
# query items
for key, value in self.context.items():
_search_helper(key, value, self.context, id_filters, object_filters,
result)
return result | z3c.contents | /z3c.contents-1.0.0a1.tar.gz/z3c.contents-1.0.0a1/src/z3c/contents/value.py | value.py |
__docformat__ = "reStructuredText"
import transaction
import zope.interface
import zope.i18nmessageid
import zope.i18n
from zope.annotation.interfaces import IAnnotations
from zope.container.interfaces import IContainerNamesContainer
from zope.container.interfaces import DuplicateIDError
from zope.copypastemove import ItemNotFoundError
from zope.copypastemove.interfaces import IPrincipalClipboard
from zope.copypastemove.interfaces import IObjectCopier, IObjectMover
from zope.copypastemove.interfaces import IContainerItemRenamer
from zope.exceptions import DuplicationError
from zope.exceptions.interfaces import UserError
from zope.security.proxy import removeSecurityProxy
from zope.security.interfaces import Unauthorized
from zope.traversing.interfaces import TraversalError
from zope.traversing import api
from z3c.form import button, field
from z3c.formui import form
from z3c.table import table
from z3c.template.template import getPageTemplate
from z3c.contents import interfaces
_ = zope.i18nmessageid.MessageFactory('z3c')
class ContentsSearchForm(form.Form):
"""Search form for IContentsPage."""
template = getPageTemplate()
prefix = 'search'
ignoreContext = True
table = None
searchterm = u''
fields = field.Fields(field.Field(
zope.schema.TextLine(
title=_(u'Search'),
description=_('Search term'),
default=u''), 'searchterm'))
@button.buttonAndHandler(_('Search'), name='search')
def handleSearch(self, action):
data, errors = self.extractData()
if errors:
self.status = u'Some error message'
return
self.searchterm = data.get('searchterm', '')
def queryPrincipalClipboard(request):
"""Return the clipboard based on the request."""
user = request.principal
annotations = IAnnotations(user, None)
if annotations is None:
return None
return IPrincipalClipboard(annotations, None)
def safeGetAttr(obj, attr, default):
"""Attempts to read the attr, returning default if Unauthorized."""
try:
return getattr(obj, attr, default)
except Unauthorized:
return default
# conditions
def canCut(form):
return form.supportsCut
def canCopy(form):
return form.supportsCopy
def canDelete(form):
return form.supportsDelete
def canPaste(form):
return form.supportsPaste
def canRename(form):
return form.supportsRename
@zope.interface.implementer(interfaces.IContentsPage)
class ContentsPage(table.Table, form.Form):
"""Generic IContainer management page."""
template = getPageTemplate()
# internal search form provided by IValues adapter
searchForm = None
# internal defaults
selectedItems = []
ignoreContext = False
supportsCut = False
supportsCopy = False
supportsDelete = False
supportsPaste = False
supportsRename = False
# sort attributes
sortOn = 1 # initial sort on name column
# customize this part
allowCut = True
allowCopy = True
allowDelete = True
allowPaste = True
allowRename = True
allowSearch = True
prefix = 'contents'
# error messages
cutNoItemsMessage = _('No items selected for cut')
cutItemsSelected = _('Items selected for cut')
copyItemsSelected = _('Items choosen for copy')
copyNoItemsMessage = _('No items selected for copy')
copySucsessMessage = _('Data successfully copied')
deleteErrorMessage = _('Could not delete the selected items')
deleteNoItemsMessage = _('No items selected for delete')
deleteSucsessMessage = _('Data successfully deleted')
pasteSucsessMessage = _('Data successfully pasted')
renameErrorMessage = _('Could not rename all selected items')
renameDuplicationMessage = _('Duplicated item name')
renameItemNotFoundMessage = _('Item not found')
def update(self):
# first setup search values, generate rows, setup headers and columns
super(ContentsPage, self).update()
# second find out if we support paste
self.clipboard = queryPrincipalClipboard(self.request)
self.setupCopyPasteMove()
# third setup form part
self.updateWidgets()
self.updateActions()
self.actions.execute()
# fix for update-render bug; ie: when we copy, paste should show
# up for the same container).
self.setupCopyPasteMove()
self.updateActions()
def setupCopyPasteMove(self):
hasContent = self.hasContent
if self.allowCut:
self.supportsCut = hasContent
if self.allowCopy:
self.supportsCopy = hasContent
if self.allowDelete:
self.supportsDelete = hasContent
if self.allowPaste:
self.supportsPaste = self.hasClipboardContents
if self.allowRename:
self.supportsRename = (hasContent and self.supportsCut and
not IContainerNamesContainer.providedBy(self.context))
def updateAfterActionExecution(self):
"""Adjust new container length and copa paste move status."""
super(ContentsPage, self).update()
self.setupCopyPasteMove()
self.updateActions()
def render(self):
"""Render the template."""
return self.template()
@property
def hasContent(self):
return bool(self.values)
@property
def isPasteable(self):
"""Decide if there is anything to paste."""
target = self.context
if self.clipboard is None:
return False
items = self.clipboard.getContents()
for item in items:
try:
obj = api.traverse(self.context, item['target'])
except TraversalError:
pass
else:
if item['action'] == 'cut':
mover = IObjectMover(obj)
moveableTo = safeGetAttr(mover, 'moveableTo', None)
if moveableTo is None or not moveableTo(self.context):
return False
elif item['action'] == 'copy':
copier = IObjectCopier(obj)
copyableTo = safeGetAttr(copier, 'copyableTo', None)
if copyableTo is None or not copyableTo(self.context):
return False
else:
raise
return True
@property
def hasClipboardContents(self):
"""Interogate the ``PrinicipalAnnotation`` to see if clipboard
contents exist."""
if not self.isPasteable:
return False
# touch at least one item in clipboard to confirm contents
items = self.clipboard.getContents()
for item in items:
try:
api.traverse(self.context, item['target'])
except TraversalError:
pass
else:
return True
return False
@button.buttonAndHandler(_('Copy'), name='copy', condition=canCopy)
def handleCopy(self, action):
if not len(self.selectedItems):
self.status = self.copyNoItemsMessage
return
items = []
append = items.append
for obj in self.selectedItems:
__name__ = api.getName(obj)
copier = IObjectCopier(obj)
if not copier.copyable():
m = {"name": __name__}
if __name__:
m["name"] = __name__
self.status = _(
"Object '${name}' (${name}) cannot be copied",
mapping=m)
else:
self.status = _("Object '${name}' cannot be copied",
mapping=m)
transaction.doom()
return
append(api.joinPath(api.getPath(self.context), __name__))
self.status = self.copyItemsSelected
# store the requested operation in the principal annotations:
self.clipboard.clearContents()
self.clipboard.addItems('copy', items)
@button.buttonAndHandler(_('Cut'), name='cut', condition=canCut)
def handleCut(self, action):
if not len(self.selectedItems):
self.status = self.cutNoItemsMessage
return
items = []
append = items.append
for obj in self.selectedItems:
mover = IObjectMover(obj)
__name__ = api.getName(obj)
if not mover.moveable():
m = {"name": __name__}
if name:
m["name"] = __name__
self.status = _(
"Object '${name}' (${name}) cannot be moved",
mapping=m)
else:
self.status = _("Object '${name}' cannot be moved",
mapping=m)
transaction.doom()
return
append(api.joinPath(api.getPath(self.context), __name__))
self.status = self.cutItemsSelected
# store the requested operation in the principal annotations:
self.clipboard.clearContents()
self.clipboard.addItems('cut', items)
@button.buttonAndHandler(_('Paste'), name='paste', condition=canPaste)
def handlePaste(self, action):
items = self.clipboard.getContents()
moved = False
not_pasteable_ids = []
for item in items:
duplicated_id = False
try:
obj = api.traverse(self.context, item['target'])
except TraversalError:
pass
else:
if item['action'] == 'cut':
mover = IObjectMover(obj)
try:
mover.moveTo(self.context)
moved = True
except DuplicateIDError:
duplicated_id = True
elif item['action'] == 'copy':
copier = IObjectCopier(obj)
try:
copier.copyTo(self.context)
except DuplicateIDError:
duplicated_id = True
else:
raise
if duplicated_id:
not_pasteable_ids.append(api.getName(obj))
if moved:
# Clear the clipboard if we do a move, but not if we only do a copy
self.clipboard.clearContents()
if not_pasteable_ids != []:
# Show the ids of objects that can't be pasted because
# their ids are already taken.
# TODO Can't we add a 'copy_of' or something as a prefix
# instead of raising an exception ?
transaction.doom()
raise UserError(
_("The given name(s) %s is / are already being used" %(
str(not_pasteable_ids))))
else:
# we need to update the table rows again, otherwise we don't
# see the new item in the table
self.updateAfterActionExecution()
self.status = self.pasteSucsessMessage
@button.buttonAndHandler(_('Delete'), name='delete', condition=canDelete)
def handleDelete(self, action):
if not len(self.selectedItems):
self.status = self.deleteNoItemsMessage
return
try:
for item in self.selectedItems:
self.executeDelete(item)
except KeyError:
self.status = self.deleteErrorMessage
transaction.doom()
# update the table rows before we start with rendering
self.updateAfterActionExecution()
self.status = self.deleteSucsessMessage
def executeDelete(self, item):
"""Do the actual item deletion
"""
del self.context[api.getName(item)]
@button.buttonAndHandler(_('Rename'), name='rename', condition=canRename)
def handlerRename(self, action):
changed = False
errorMessages = {}
renameCol = self.columnByName.get('renameColumn')
if renameCol:
for item in list(self.values):
if item in self.selectedItems:
errorMsg = None
oldName = renameCol.getItemValue(item)
newName = renameCol.getRenameValue(item)
if newName is not None and oldName != newName:
try:
container = removeSecurityProxy(self.context)
renamer = IContainerItemRenamer(container)
renamer.renameItem(oldName, newName)
changed = True
except DuplicationError:
errorMsg = self.renameDuplicationMessage
changed = True
except ItemNotFoundError:
errorMsg = self.renameItemNotFoundMessage
changed = True
elif newName is None:
errorMsg = _('No name given')
elif newName is not None and oldName == newName:
errorMsg = _('No new name given')
if errorMsg is not None:
key = renameCol.getItemKey(item)
errorMessages[key] = zope.i18n.translate(
errorMsg, context=self.request)
if changed:
self.status = self.renameErrorMessage
# update the table rows before we start with rendering
self.updateAfterActionExecution()
# and set error message back to the new rename column
renameCol = self.columnByName.get('renameColumn')
if renameCol:
renameCol.errorMessages = errorMessages
class Contents(ContentsPage):
"""ContentsPage with useful defaults."""
# contents defaults
cssClasses = {'table': 'contents'}
cssClassEven = u'even'
cssClassOdd = u'odd'
cssClassSelected = u'selected'
batchSize = 25
startBatchingAt = 25 | z3c.contents | /z3c.contents-1.0.0a1.tar.gz/z3c.contents-1.0.0a1/src/z3c/contents/browser.py | browser.py |
========
Contents
========
The goal of this package is to offer a modular replacement for the default
contents.html page used in Zope3.
Sample data setup
-----------------
Let's create a sample container which we can use as our context:
>>> from z3c.contents import testing
>>> container = testing.SampleContainer()
add them to the root:
>>> root['container'] = container
Now setup some items based on our testing Content object. Note this object is
defined in the testing module because it must be pickle-able because the object
copier pickles objects during copy/paste:
>>> from z3c.contents.testing import Content
>>> container[u'zero'] = Content('Zero', 0)
>>> container[u'first'] = Content('First', 1)
>>> container[u'second'] = Content('Second', 2)
>>> container[u'third'] = Content('Third', 3)
>>> container[u'fourth'] = Content('Fourth', 4)
And we need to setup the form defaults first:
>>> from z3c.form.testing import setupFormDefaults
>>> setupFormDefaults()
And we need to configure our contents.pt template for the ContentsPage. We
also configure the template for the search sub form here too. And we
make sure the configuration is applied to the global site manager, to
avoid problems with unpicklable z3c:template adapters.
>>> import os
>>> import sys
>>> from zope.configuration import xmlconfig
>>> from zope.component.hooks import setSite, getSite
>>> site = getSite()
>>> setSite(None)
>>> import z3c.template
>>> context = xmlconfig.file('meta.zcml', z3c.template)
>>> contentsTemplate = os.path.join(os.path.dirname(z3c.contents.__file__),
... 'contents.pt')
>>> searchTemplate = os.path.join(os.path.dirname(z3c.contents.__file__),
... 'search.pt')
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:template
... for="z3c.contents.interfaces.IContentsPage"
... template="%s"
... />
... <z3c:template
... for="z3c.contents.browser.ContentsSearchForm"
... template="%s"
... />
... </configure>
... """ % (contentsTemplate, searchTemplate), context=context)
And load the formui configuration, which will make sure that all macros get
registered correctly.
>>> from zope.configuration import xmlconfig
>>> import zope.component
>>> import zope.viewlet
>>> import zope.publisher
>>> import zope.browserresource
>>> import z3c.macro
>>> import z3c.template
>>> import z3c.formui
>>> xmlconfig.XMLConfig('meta.zcml', zope.component)()
>>> xmlconfig.XMLConfig('meta.zcml', zope.viewlet)()
>>> xmlconfig.XMLConfig('meta.zcml', zope.component)()
>>> xmlconfig.XMLConfig('meta.zcml', zope.publisher)()
>>> xmlconfig.XMLConfig('meta.zcml', zope.browserresource)()
>>> xmlconfig.XMLConfig('meta.zcml', z3c.macro)()
>>> xmlconfig.XMLConfig('meta.zcml', z3c.template)()
>>> xmlconfig.XMLConfig('configure.zcml', z3c.formui)()
And support the div form layer for our request:
>>> from z3c.formui.interfaces import IDivFormLayer
>>> from zope.interface import alsoProvides
>>> from z3c.form.testing import TestRequest
>>> request = TestRequest()
>>> alsoProvides(request, IDivFormLayer)
Restore the site now that we're done with the configuration.
>>> setSite(site)
ContentsPage
------------
Now we can create a ContentsPage:
>>> from z3c.contents import browser
>>> firstPage = browser.ContentsPage(container, request)
>>> firstPage.update()
>>> print(firstPage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
<div class="viewspace">
<div>
<fieldset>
<legend>Search</legend>
<table>
<tr>
<td class="row">
<label for="search-widgets-searchterm">Search</label>
<input id="search-widgets-searchterm"
name="search.widgets.searchterm"
class="text-widget required textline-field"
value="" type="text" />
</td>
<td class="action">
<input id="search-buttons-search"
name="search.buttons.search"
class="submit-widget button-field" value="Search"
type="submit" />
</td>
</tr>
</table>
</fieldset>
</div>
</div>
<div>
<div class="buttons">
<input id="contents-buttons-copy"
name="contents.buttons.copy"
class="submit-widget button-field" value="Copy"
type="submit" />
<input id="contents-buttons-cut" name="contents.buttons.cut"
class="submit-widget button-field" value="Cut"
type="submit" />
<input id="contents-buttons-delete"
name="contents.buttons.delete"
class="submit-widget button-field" value="Delete"
type="submit" />
<input id="contents-buttons-rename"
name="contents.buttons.rename"
class="submit-widget button-field" value="Rename"
type="submit" />
</div>
</div>
</form>
Columns
-------
We register our predefined columns as adapters this allows us later to enhance
existing contents.html pages with additional columns. Use the adapter directive
for this:
>>> import zope.component
>>> from zope.container.interfaces import IContainer
>>> from z3c.table.interfaces import IColumn
>>> from z3c.contents import interfaces
>>> from z3c.table.column import CheckBoxColumn
>>> zope.component.provideAdapter(CheckBoxColumn,
... (IContainer, None, interfaces.IContentsPage),
... provides=IColumn, name='checkBoxColumn')
>>> from z3c.contents import column
>>> zope.component.provideAdapter(column.RenameColumn,
... (IContainer, None, interfaces.IContentsPage),
... provides=IColumn, name='renameColumn')
>>> from z3c.table.column import CreatedColumn
>>> zope.component.provideAdapter(CreatedColumn,
... (IContainer, None, interfaces.IContentsPage),
... provides=IColumn, name='createdColumn')
>>> from z3c.table.column import ModifiedColumn
>>> zope.component.provideAdapter(ModifiedColumn,
... (IContainer, None, interfaces.IContentsPage),
... provides=IColumn, name='modifiedColumn')
Now let's update and render the contents page again:
>>> firstPage.update()
>>> print(firstPage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
<div class="viewspace">
<div>
<fieldset>
<legend>Search</legend>
<table>
<tr>
<td class="row">
<label for="search-widgets-searchterm">Search</label>
<input id="search-widgets-searchterm"
name="search.widgets.searchterm"
class="text-widget required textline-field"
value="" type="text" />
</td>
<td class="action">
<input id="search-buttons-search"
name="search.buttons.search"
class="submit-widget button-field" value="Search"
type="submit" />
</td>
</tr>
</table>
</fieldset>
<table>
<thead>
<tr>
<th>X</th>
<th class="sorted-on ascending">Name</th>
<th>Created</th>
<th>Modified</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="first" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/first">first</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="fourth" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/fourth">fourth</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="second" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/second">second</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="third" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/third">third</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
</table>
</div>
</div>
<div>
<div class="buttons">
<input id="contents-buttons-copy"
name="contents.buttons.copy"
class="submit-widget button-field" value="Copy"
type="submit" />
<input id="contents-buttons-cut" name="contents.buttons.cut"
class="submit-widget button-field" value="Cut"
type="submit" />
<input id="contents-buttons-delete"
name="contents.buttons.delete"
class="submit-widget button-field" value="Delete"
type="submit" />
<input id="contents-buttons-rename"
name="contents.buttons.rename"
class="submit-widget button-field" value="Rename"
type="submit" />
</div>
</div>
</form>
Sorting
-------
The contents page supports sorting by columns. We can do this be set the
sortOn request variable as we see in the head link of each column. Let's
reverse the default sort order. Note, order depends on the alphabetic oder of
number names and not on the number itself.
>>> sorterRequest = TestRequest(form={'contents-sortOn': 'contents-checkBoxColumn-0',
... 'contents-sortOrder':'descending'})
>>> alsoProvides(sorterRequest, IDivFormLayer)
>>> sortingPage = browser.ContentsPage(container, sorterRequest)
>>> sortingPage.update()
>>> print(sortingPage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
<div class="viewspace">
<div>
<fieldset>
<legend>Search</legend>
<table>
<tr>
<td class="row">
<label for="search-widgets-searchterm">Search</label>
<input id="search-widgets-searchterm"
name="search.widgets.searchterm"
class="text-widget required textline-field"
value="" type="text" />
</td>
<td class="action">
<input id="search-buttons-search"
name="search.buttons.search"
class="submit-widget button-field" value="Search"
type="submit" />
</td>
</tr>
</table>
</fieldset>
<table>
<thead>
<tr>
<th class="sorted-on descending">X</th>
<th>Name</th>
<th>Created</th>
<th>Modified</th>
</tr>
</thead>
<tbody>
<tr>
<td class="sorted-on descending"><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td><a href="http://127.0.0.1/container/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td class="sorted-on descending"><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="third" /></td>
<td><a href="http://127.0.0.1/container/third">third</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td class="sorted-on descending"><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="second" /></td>
<td><a href="http://127.0.0.1/container/second">second</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td class="sorted-on descending"><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="fourth" /></td>
<td><a href="http://127.0.0.1/container/fourth">fourth</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td class="sorted-on descending"><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="first" /></td>
<td><a href="http://127.0.0.1/container/first">first</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
</table>
</div>
</div>
<div>
<div class="buttons">
<input id="contents-buttons-copy"
name="contents.buttons.copy"
class="submit-widget button-field" value="Copy"
type="submit" />
<input id="contents-buttons-cut" name="contents.buttons.cut"
class="submit-widget button-field" value="Cut"
type="submit" />
<input id="contents-buttons-delete"
name="contents.buttons.delete"
class="submit-widget button-field" value="Delete"
type="submit" />
<input id="contents-buttons-rename"
name="contents.buttons.rename"
class="submit-widget button-field" value="Rename"
type="submit" />
</div>
</div>
</form>
Let's make coverage happy and sort on the rename column:
>>> sorterRequest = TestRequest(form={'contents-sortOn': 'contents-renameColumn-1',
... 'contents-sortOrder':'ascending'})
>>> alsoProvides(sorterRequest, IDivFormLayer)
>>> sortingPage = browser.ContentsPage(container, sorterRequest)
>>> sortingPage.update()
>>> print(sortingPage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
...
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="first" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/first">first</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="fourth" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/fourth">fourth</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="second" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/second">second</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="third" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/third">third</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
...
Copy
----
First we need to setup another container which we can copy to:
>>> secondContainer = testing.SampleContainer()
>>> root['secondContainer'] = secondContainer
And we need another contents page instance:
>>> secondPage = browser.ContentsPage(secondContainer, request)
As you can see the second page for the second container has no items and
no buttons:
>>> secondPage.update()
>>> print(secondPage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
<div class="viewspace">
<div>
<fieldset>
<legend>Search</legend>
<table>
<tr>
<td class="row">
<label for="search-widgets-searchterm">Search</label>
<input id="search-widgets-searchterm"
name="search.widgets.searchterm"
class="text-widget required textline-field"
value="" type="text" />
</td>
<td class="action">
<input id="search-buttons-search"
name="search.buttons.search"
class="submit-widget button-field" value="Search"
type="submit" />
</td>
</tr>
</table>
</fieldset>
<table>
<thead>
<tr>
<th>X</th>
<th class="sorted-on ascending">Name</th>
<th>Created</th>
<th>Modified</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div>
<div class="buttons">
</div>
</div>
</form>
Now we start with copy the ``zero`` item from the first page. We can do this
by using some request variables. Let's setup a new request. See the feedback
we will get as form message:
Also note that an additional ``Paste`` button will show up, because we should
be able to paste objects within the same container they're copied from.
>>> copyRequest = TestRequest(
... form={'contents-checkBoxColumn-0-selectedItems': ['zero'],
... 'contents.buttons.copy': 'Copy'})
>>> alsoProvides(copyRequest, IDivFormLayer)
>>> copyPage = browser.ContentsPage(container, copyRequest)
>>> copyPage.update()
>>> print(copyPage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
<div class="viewspace">
<div class="status">
<div class="summary">Items choosen for copy</div>
</div>
<div>
<fieldset>
<legend>Search</legend>
<table>
<tr>
<td class="row">
<label for="search-widgets-searchterm">Search</label>
<input id="search-widgets-searchterm"
name="search.widgets.searchterm"
class="text-widget required textline-field"
value="" type="text" />
</td>
<td class="action">
<input id="search-buttons-search"
name="search.buttons.search"
class="submit-widget button-field" value="Search"
type="submit" />
</td>
</tr>
</table>
</fieldset>
<table>
<thead>
<tr>
<th>X</th>
<th class="sorted-on ascending">Name</th>
<th>Created</th>
<th>Modified</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="first" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/first">first</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="fourth" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/fourth">fourth</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="second" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/second">second</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="third" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/third">third</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" checked="checked" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
</table>
</div>
</div>
<div>
<div class="buttons">
<input id="contents-buttons-copy"
name="contents.buttons.copy"
class="submit-widget button-field" value="Copy"
type="submit" />
<input id="contents-buttons-cut" name="contents.buttons.cut"
class="submit-widget button-field" value="Cut"
type="submit" />
<input id="contents-buttons-paste"
name="contents.buttons.paste"
class="submit-widget button-field" value="Paste"
type="submit" />
<input id="contents-buttons-delete"
name="contents.buttons.delete"
class="submit-widget button-field" value="Delete"
type="submit" />
<input id="contents-buttons-rename"
name="contents.buttons.rename"
class="submit-widget button-field" value="Rename"
type="submit" />
</div>
</div>
</form>
Copy - Paste
------------
Now we can go to the second page and paste our selected object. Just prepare
a request which simulates that we clicked at the paste button and we can see
that we pasted the selected item to the second container. You can also see
that the ``Paste`` button, because the clipboard contains items copied
from another container.
>>> pasteRequest = TestRequest(form={'contents.buttons.paste': 'Paste'})
>>> alsoProvides(pasteRequest, IDivFormLayer)
>>> pastePage = browser.ContentsPage(secondContainer, pasteRequest)
>>> pastePage.update()
>>> print(pastePage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
<div class="viewspace">
<div class="status">
<div class="summary">Data successfully pasted</div>
</div>
<div>
<fieldset>
<legend>Search</legend>
<table>
<tr>
<td class="row">
<label for="search-widgets-searchterm">Search</label>
<input id="search-widgets-searchterm"
name="search.widgets.searchterm"
class="text-widget required textline-field"
value="" type="text" />
</td>
<td class="action">
<input id="search-buttons-search"
name="search.buttons.search"
class="submit-widget button-field" value="Search"
type="submit" />
</td>
</tr>
</table>
</fieldset>
<table>
<thead>
<tr>
<th>X</th>
<th class="sorted-on ascending">Name</th>
<th>Created</th>
<th>Modified</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
</table>
</div>
</div>
<div>
<div class="buttons">
<input id="contents-buttons-copy"
name="contents.buttons.copy"
class="submit-widget button-field" value="Copy"
type="submit" />
<input id="contents-buttons-cut" name="contents.buttons.cut"
class="submit-widget button-field" value="Cut"
type="submit" />
<input id="contents-buttons-paste"
name="contents.buttons.paste"
class="submit-widget button-field" value="Paste"
type="submit" />
<input id="contents-buttons-delete"
name="contents.buttons.delete"
class="submit-widget button-field" value="Delete"
type="submit" />
<input id="contents-buttons-rename"
name="contents.buttons.rename"
class="submit-widget button-field" value="Rename"
type="submit" />
</div>
</div>
</form>
Cut
---
This part shows how to cut an object from one container and paste it to another
container.
>>> cutRequest = TestRequest(
... form={'contents-checkBoxColumn-0-selectedItems': ['first', 'second'],
... 'contents.buttons.cut': 'Cut'})
>>> alsoProvides(cutRequest, IDivFormLayer)
>>> cutPage = browser.ContentsPage(container, cutRequest)
>>> cutPage.update()
>>> print(cutPage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
...
<div class="status">
<div class="summary">Items selected for cut</div>
</div>
...
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="first" checked="checked" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/first">first</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="fourth" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/fourth">fourth</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="second" checked="checked" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/second">second</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="third" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/third">third</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
...
Cut - Paste
-----------
And we can paste the selectded items to the second container:
>>> pasteRequest = TestRequest(form={'contents.buttons.paste': 'Paste'})
>>> alsoProvides(pasteRequest, IDivFormLayer)
>>> pastePage = browser.ContentsPage(secondContainer, pasteRequest)
>>> pastePage.update()
>>> print(pastePage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
<div class="viewspace">
<div class="status">
<div class="summary">Data successfully pasted</div>
</div>
<div>
<fieldset>
<legend>Search</legend>
<table>
<tr>
<td class="row">
<label for="search-widgets-searchterm">Search</label>
<input id="search-widgets-searchterm"
name="search.widgets.searchterm"
class="text-widget required textline-field"
value="" type="text" />
</td>
<td class="action">
<input id="search-buttons-search"
name="search.buttons.search"
class="submit-widget button-field" value="Search"
type="submit" />
</td>
</tr>
</table>
</fieldset>
<table>
<thead>
<tr>
<th>X</th>
<th class="sorted-on ascending">Name</th>
<th>Created</th>
<th>Modified</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="first" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/first">first</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="second" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/second">second</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
</table>
</div>
</div>
<div>
<div class="buttons">
<input id="contents-buttons-copy"
name="contents.buttons.copy"
class="submit-widget button-field" value="Copy"
type="submit" />
<input id="contents-buttons-cut" name="contents.buttons.cut"
class="submit-widget button-field" value="Cut"
type="submit" />
<input id="contents-buttons-delete"
name="contents.buttons.delete"
class="submit-widget button-field" value="Delete"
type="submit" />
<input id="contents-buttons-rename"
name="contents.buttons.rename"
class="submit-widget button-field" value="Rename"
type="submit" />
</div>
</div>
</form>
As you can see the first page does not contain the ``first`` and ``second``
item after paste them to the second container. Also the ``paste button`` is
gone:
>>> firstPage.update()
>>> print(firstPage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
<div class="viewspace">
<div>
<fieldset>
<legend>Search</legend>
<table>
<tr>
<td class="row">
<label for="search-widgets-searchterm">Search</label>
<input id="search-widgets-searchterm"
name="search.widgets.searchterm"
class="text-widget required textline-field"
value="" type="text" />
</td>
<td class="action">
<input id="search-buttons-search"
name="search.buttons.search"
class="submit-widget button-field" value="Search"
type="submit" />
</td>
</tr>
</table>
</fieldset>
<table>
<thead>
<tr>
<th>X</th>
<th class="sorted-on ascending">Name</th>
<th>Created</th>
<th>Modified</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="fourth" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/fourth">fourth</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="third" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/third">third</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
</table>
</div>
</div>
<div>
<div class="buttons">
<input id="contents-buttons-copy"
name="contents.buttons.copy"
class="submit-widget button-field" value="Copy"
type="submit" />
<input id="contents-buttons-cut" name="contents.buttons.cut"
class="submit-widget button-field" value="Cut"
type="submit" />
<input id="contents-buttons-delete"
name="contents.buttons.delete"
class="submit-widget button-field" value="Delete"
type="submit" />
<input id="contents-buttons-rename"
name="contents.buttons.rename"
class="submit-widget button-field" value="Rename"
type="submit" />
</div>
</div>
</form>
Delete
------
The contents page offers also an option for delete items. Let's select some
items and click the delete button:
>>> deleteRequest = TestRequest(
... form={'contents-checkBoxColumn-0-selectedItems': ['third', 'fourth'],
... 'contents.buttons.delete': 'Delete'})
>>> alsoProvides(deleteRequest, IDivFormLayer)
>>> deletePage = browser.ContentsPage(container, deleteRequest)
>>> deletePage.update()
>>> print(deletePage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
...
<div class="status">
<div class="summary">Data successfully deleted</div>
</div>
...
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/container/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
...
Rename
------
If we like to rename items, we can do this with the ``Rename`` button. This
means if we use them, we will get input widgets for the selected items rendered
in the table. After that, we can click the button another time which will
do the renaming. Let's setup a table which we select items and click the
``Rename`` button:
>>> renameRequest = TestRequest(
... form={'contents-checkBoxColumn-0-selectedItems': ['first', 'second'],
... 'contents.buttons.rename': 'Rename'})
>>> alsoProvides(renameRequest, IDivFormLayer)
>>> renamePage = browser.ContentsPage(secondContainer, renameRequest)
>>> renamePage.update()
>>> print(renamePage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
...
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="first" checked="checked" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/first">first</a> <input type="text" name="contents-renameColumn-1-Zmlyc3Q=-rename" value="first" /></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="second" checked="checked" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/second">second</a> <input type="text" name="contents-renameColumn-1-c2Vjb25k-rename" value="second" /></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
...
Now we rename the ``second`` item to ``fifth``:
>>> renameRequest = TestRequest(
... form={'contents-checkBoxColumn-0-selectedItems': ['first', 'second'],
... 'contents-renameColumn-1-Zmlyc3Q=-rename': 'first',
... 'contents-renameColumn-1-c2Vjb25k-rename': 'fifth',
... 'contents.buttons.rename': 'Rename'})
>>> alsoProvides(renameRequest, IDivFormLayer)
>>> renamePage = browser.ContentsPage(secondContainer, renameRequest)
>>> renamePage.update()
>>> print(renamePage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
...
<div class="status">
<div class="summary">Could not rename all selected items</div>
</div>
...
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="fifth" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/fifth">fifth</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="first" checked="checked" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/first">first</a> <input type="text" name="contents-renameColumn-1-Zmlyc3Q=-rename" value="first" />No new name given</td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
...
If we try to rename one item to another items name we will get a duplication
error. Let's test this:
>>> renameRequest = TestRequest(
... form={'contents-checkBoxColumn-0-selectedItems': ['fifth', 'first'],
... 'contents-renameColumn-1-Zmlyc3Q=-rename': 'fifth',
... 'contents-renameColumn-1-ZmlmdGg=-rename': 'first',
... 'contents.buttons.rename': 'Rename'})
>>> alsoProvides(renameRequest, IDivFormLayer)
>>> renamePage = browser.ContentsPage(secondContainer, renameRequest)
>>> renamePage.update()
>>> print(renamePage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
...
<div class="status">
<div class="summary">Could not rename all selected items</div>
</div>
...
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="fifth" checked="checked" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/fifth">fifth</a> <input type="text" name="contents-renameColumn-1-ZmlmdGg=-rename" value="first" />Duplicated item name</td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="first" checked="checked" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/first">first</a> <input type="text" name="contents-renameColumn-1-Zmlyc3Q=-rename" value="fifth" />Duplicated item name</td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
...
As you can see everything goes right. We can check the containers which should
reflect the same as we see in the tables. Note the ``third`` and ``fourth``
items get deleted and are gone now and the ``second`` item get renamed to
``fifth``:
>>> sorted(container.items())
[(u'zero', <Content Zero 0>)]
>>> sorted(secondContainer.items())
[(u'fifth', <Content Second 2>), (u'first', <Content First 1>),
(u'zero', <Content Zero 0>)]
Search
------
Register ISearchableText adapter for the contained objects, the default
filters for searching include searching the keys (content __name__) and using
an ISearchableText adapter for the contained objects.
>>> from z3c.contents.testing import SearchableTextForContent
>>> zope.component.provideAdapter(SearchableTextForContent)
The default search adapter matches search terms to the objects id in the
container or to any possible string attribute.
>>> searchRequest = TestRequest(form={'search.buttons.search': 'Search',
... 'search.widgets.searchterm': u'1 zero'})
>>> alsoProvides(searchRequest, IDivFormLayer)
>>> searchPage = browser.ContentsPage(secondContainer, searchRequest)
>>> searchPage.update()
>>> print(searchPage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
...
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="first" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/first">first</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
...
Headers
-------
We have adapters to the columns that support inclusion of links in the headers
to sort the columns.
>>> from z3c.contents.header import ContentsColumnHeader
>>> from z3c.table.interfaces import IColumnHeader
>>> zope.component.provideAdapter(ContentsColumnHeader,
... (IContainer, None, interfaces.IContentsPage, column.RenameColumn),
... provides=IColumnHeader)
Now we shall see that the name column header includes a link with arguments to
sort the table by that column.
>>> headerRequest = TestRequest()
>>> alsoProvides(headerRequest, IDivFormLayer)
>>> headerPage = browser.ContentsPage(secondContainer, headerRequest)
>>> headerPage.update()
>>> print(headerPage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
...
<thead>
<tr>
<th>X</th>
<th class="sorted-on ascending"><a href="?contents-sortOn=contents-renameColumn-1&contents-sortOrder=descending" title="Sort">Name</a></th>
<th>Created</th>
<th>Modified</th>
</tr>
</thead>
...
When we perform a search we also expect the the search terms will also be
included in the query so as to maintain the search across views.
>>> searchRequest = TestRequest(form={'search.buttons.search': 'Search',
... 'search.widgets.searchterm': u'First zero'})
>>> alsoProvides(searchRequest, IDivFormLayer)
>>> searchPage = browser.ContentsPage(secondContainer, searchRequest)
>>> searchPage.update()
>>> print(searchPage.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
...
<thead>
<tr>
<th>X</th>
<th class="sorted-on ascending"><a href="?contents-sortOn=contents-renameColumn-1&contents-sortOrder=descending&search.widgets.searchterm=First+zero" title="Sort">Name</a></th>
<th>Created</th>
<th>Modified</th>
</tr>
</thead>
...
Batching
--------
TODO: add tests for batching
Contents
--------
There is a ContentsPage with useful defaults. This contents page provides
a CSS class called ``contents`` for the table tag and uses ``even`` and ``odd``
row CSS class markers. The default batch size is set to ``25``:
>>> request = TestRequest()
>>> alsoProvides(request, IDivFormLayer)
>>> contents = browser.Contents(secondContainer, request)
>>> contents.update()
>>> print(contents.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="contents" name="contents">
<div class="viewspace">
<div>
<fieldset>
<legend>Search</legend>
<table>
<tr>
<td class="row">
<label for="search-widgets-searchterm">Search</label>
<input id="search-widgets-searchterm"
name="search.widgets.searchterm"
class="text-widget required textline-field"
value="" type="text" />
</td>
<td class="action">
<input id="search-buttons-search"
name="search.buttons.search"
class="submit-widget button-field" value="Search"
type="submit" />
</td>
</tr>
</table>
</fieldset>
<table class="contents">
<thead>
<tr>
<th>X</th>
<th class="sorted-on ascending"><a href="?contents-sortOn=contents-renameColumn-1&contents-sortOrder=descending" title="Sort">Name</a></th>
<th>Created</th>
<th>Modified</th>
</tr>
</thead>
<tbody>
<tr class="even">
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="fifth" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/fifth">fifth</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr class="odd">
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="first" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/first">first</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
<tr class="even">
<td><input type="checkbox" class="checkbox-widget" name="contents-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td class="sorted-on ascending"><a href="http://127.0.0.1/secondContainer/zero">zero</a></td>
<td>01/01/01 01:01</td>
<td>02/02/02 02:02</td>
</tr>
</tbody>
</table>
</div>
</div>
<div>
<div class="buttons">
<input id="contents-buttons-copy"
name="contents.buttons.copy"
class="submit-widget button-field" value="Copy"
type="submit" />
<input id="contents-buttons-cut" name="contents.buttons.cut"
class="submit-widget button-field" value="Cut"
type="submit" />
<input id="contents-buttons-delete"
name="contents.buttons.delete"
class="submit-widget button-field" value="Delete"
type="submit" />
<input id="contents-buttons-rename"
name="contents.buttons.rename"
class="submit-widget button-field" value="Rename"
type="submit" />
</div>
</div>
</form>
| z3c.contents | /z3c.contents-1.0.0a1.tar.gz/z3c.contents-1.0.0a1/src/z3c/contents/README.txt | README.txt |
Changes
=======
2.1.0 (2017-04-24)
------------------
- Support (and require) coverage.py >= 4.0.
- Fix incorrect highlighting of missed lines when processing coverage.py data
(broken since 2.0.2).
- Dropped Python 2.6 support.
- Added Python 3.4, 3.5 and 3.6 support.
2.0.3 (2015-11-09)
------------------
- Standardize namespace __init__.
2.0.2 (2013-10-01)
------------------
- Bug: coveragereport now also accepts non-ASCII chars in source files
(also fix the case when enscript is not available).
2.0.1 (2013-10-01)
------------------
- Bug: coveragereport now also accepts non-ASCII chars in source files.
2.0.0 (2013-02-20)
------------------
- Added Python 3.3 and PyPy 1.9 support.
- Dropped Python 2.4 and 2.5 support.
1.3.1 (2012-10-24)
------------------
- Nicer PyPI description. Doctests are tests, not docs.
- ``coveragereport`` now accepts ``--path-alias``.
- ``coveragereport``: new color step between yellow (90%) and green (100%), a
yellowish-green (95%).
1.3.0 (2012-09-06)
------------------
- ``coveragereport`` now accepts ``--help``, ``--verbose`` and ``--quiet``
options, with verbose being on by default.
- ``coveragereport`` now can handle .coverage files produced by
http://pypi.python.org/pypi/coverage
- Bugfix: sorting by numbered of uncovered lines was broken in the
``all.html`` report.
1.2.0 (2010-02-11)
------------------
- Rename the ``coverage`` script to ``coveragereport``, to avoid name clashes
with Ned Batchelder's excellent coverage.py.
1.1.3 (2009-07-24)
------------------
- Bug: Doctest did not normalize the whitespace in `coveragediff.txt`. For
some reason it passes while testing independently, but when running all
tests, it failed.
1.1.2 (2008-04-14)
------------------
- Bug: When a package path contained anywhere the word "test", it was ignored
from the coverage report. The intended behavior, however, was to ignore
files that relate to setting up tests.
- Bug: Sort the results of `os.listdir()` in `README.txt` to avoid
non-deterministic failures.
- Bug: The logic for ignoring unit and functional test modules also used to
ignore modules and packages called `testing`.
- Change "Unit test coverage" to "Test coverage" in the title -- it works
perfectly fine for functional tests too.
1.1.1 (2008-01-31)
------------------
- Bug: When the package was released, the test which tests the availability of
an SVN revision number failed. Made the test more reliable.
1.1.0 (2008-01-29)
------------------
- Feature: The ``main()`` coverage report function now accepts the arguments
of the script as a function argument, making it easier to configure the
script from buildout.
- Feature: When the report directory does not exist, the report generator
creates it for you.
- Feature: Eat your own dog food by creating a buildout that can create
coverage reports.
- Bug: Improved the test coverage to 100%.
1.0.1 (2007-09-26)
------------------
- Bug: Fixed meta-data.
1.0.0 (2007-09-26)
------------------
- First public release.
0.2.1
-----
- Feature: Added the ``--web`` option to ``coveragediff``.
- Feature: Added a test suite.
0.2.0
-----
- Feature: Added ``coveragediff.py``.
0.1.0
-----
- Initial release of ``coveragereport.py``.
| z3c.coverage | /z3c.coverage-2.1.0.tar.gz/z3c.coverage-2.1.0/CHANGES.rst | CHANGES.rst |
============
z3c.coverage
============
.. image:: https://travis-ci.org/zopefoundation/z3c.coverage.png
:target: https://travis-ci.org/zopefoundation/z3c.coverage
This package contains tools to work with Python coverage data.
``coveragereport`` produces HTML reports from coverage data, with
syntax-highlighted source code and per-package aggregate numbers.
``coveragediff`` compares two sets of coverage reports and reports
regressions, that is, increases in the number of untested lines of code.
.. contents::
Using coveragereport
====================
::
$ coveragereport --help
Usage: coveragereport [options] [inputpath [outputdir]]
Converts coverage reports to HTML. If the input path is omitted, it defaults
to coverage or .coverage, whichever exists. If the output directory is
omitted, it defaults to inputpath + /report or ./coverage-reports, depending
on whether the input path points to a directory or a file.
Options:
-h, --help show this help message and exit
-q, --quiet be quiet
-v, --verbose be verbose (default)
--strip-prefix=PREFIX
strip base directory from filenames loaded from
.coverage
--path-alias=PATH=LOCALPATH
define path mappings for filenames loaded from
.coverage
Example use with ``zope.testrunner``::
$ bin/test --coverage=coverage
$ coveragereport
$ ln -s mypackage.html coverage/report/index.html
$ xdg-open coverage/report/index.html
$ xdg-open coverage/report/all.html
Example use with ``nose`` and ``coverage.py``::
$ nosetests --with-coverage --cover-erase
$ coveragereport --strip-prefix=/full/path/to/source/
$ ln -s mypackage.html coverage-reports/index.html
$ xdg-open coverage-reports/index.html
$ xdg-open coverage-reports/all.html
Sample report:
.. image:: http://i.imgur.com/mkqA3.png
.. note:: You need `enscript <http://www.gnu.org/software/enscript/>`_
installed and available in your ``$PATH`` if you want syntax
highlighting.
Using coveragediff
==================
::
Usage: coveragediff [options] olddir newdir
Options:
-h, --help show this help message and exit
--include=REGEX only consider files matching REGEX
--exclude=REGEX ignore files matching REGEX
--email=ADDR send the report to a given email address (only if
regressions were found)
--from=ADDR set the email sender address
--subject=SUBJECT set the email subject
--web-url=BASEURL include hyperlinks to HTML-ized coverage reports at a
given URL
Usage example with ``zope.testrunner``::
$ bin/test --coverage=coverage
$ vi src/...
$ mv coverage coverage.old
$ bin/test --coverage=coverage
$ coveragediff coverage.old coverage
You cannot use ``coveragediff`` with ``coverage.py`` data. More on that below.
Output example::
$ coveragediff coverage.old coverage
my.package.module: 36 new lines of untested code
my.package.newmodule: new file with 15 lines of untested code (out of 23)
Output with clickable links::
$ coveragediff coverage.old coverage --web-url=http://example.com/coverage
my.package.module: 36 new lines of untested code
See http://example.com/coverage/my.package.module.html
my.package.newmodule: new file with 15 lines of untested code (out of 23)
See http://example.com/coverage/my.package.newmodule.html
Output via email, convenient for continuous integration::
$ coveragediff coverage.old coverage --web-url=http://example.com/coverage \
--email 'Developers <[email protected]>' \
--from 'Buildbot <[email protected]>'
That last example doesn't produce any output, but sends an email (via SMTP
to localhost:25).
Getting coverage data
=====================
zope.testrunner
---------------
`zope.testrunner <http://pypi.python.org/pypi/zope.testrunner>`_ can
produce a directory full of files named ``dotted.package.name.cover``
that contain source code annotated with coverage information. To get
them, use ::
bin/test --coverage=outdir/
Both ``coveragereport`` and ``coveragediff`` accept this as inputs.
coverage.py
-----------
`coverage.py <http://pypi.python.org/pypi/coverage>`_ can produce
a ``.coverage`` file containing (incomplete) coverage information. To get it,
use ::
coverage run bin/testrunner
``coveragereport`` can take the ``.coverage`` file as an input, but it
also needs access to the matching source files. And you have to manually
specify the absolute pathname prefix of your source tree so that the
report know how to translate filenames into dotted package names. Also,
it's not enough to have *absolute* pathnames, you need to supply the
*canonical* absolute pathname (with no symlink segments), such as returned
by ``os.path.realpath``. This is very inconvenient. Sorry.
``coveragediff`` is unable to compare two ``.coverage`` files and report
regressions. One reason for that is the incompleteness of the data format
(it line numbers of executed statements, but doesn't say which lines contain
code and which ones are blank/comments/continuation lines/excluded source
lines). The other reason is simpler: nobody wrote the code. `;)`
Unfortunately ``coverage annotate`` does not produce files compatible
with ``coveragereport``/``coveragediff``. This could also be remedied
if somebody wrote a patch.
.. note:: If you want to use a ``.coverage`` file produced on another machine
or simply in a different working directory, you will need to
tell ``coveragereport`` how to adjust the absolute filenames so that
the sources can be found. Use the ``--path-alias`` option for that.
Alternatively you could use ``coverage combine`` to manipulate the
``.coverage`` file itself, as described in the documentation.
trace.py
--------
The ``*.cover`` annotated-source format produced by ``zope.testrunner``
actually comes from the Python standard library module `trace.py
<http://docs.python.org/library/trace>`_. You can probably use trace.py
directly. I've never tried.
Frequently Asked Questions
==========================
Why use z3c.coverage instead of coverage html?
----------------------------------------------
Some people prefer the look of the reports produced by z3c.coverage.
Some people find per-package coverage summaries or the tree-like navigation
convenient.
Should I use zope.testrunner's built-in coverage, or coverage run bin/test?
-----------------------------------------------------------------------------
``coverage.py`` is *much* faster, but using it (and hooking it up to z3c.coverage)
is perhaps less convenient. E.g. if you use ``zc.buildout 1.5.x`` with
``zc.recipe.testrunner``, you will be unable to use ``coverage run bin/test``
because of mystic semi-broken site isolation magic of the former.
Did anyone actually ask any of these questions?
-----------------------------------------------
Does asking myself count?
| z3c.coverage | /z3c.coverage-2.1.0.tar.gz/z3c.coverage-2.1.0/README.rst | README.rst |
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
__version__ = '2015-07-01'
# See zc.buildout's changelog if this version is up to date.
tmpeggs = tempfile.mkdtemp(prefix='bootstrap-')
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --find-links to point to local resources, you can keep
this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("--version",
action="store_true", default=False,
help=("Return bootstrap.py version."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
parser.add_option("--allow-site-packages",
action="store_true", default=False,
help=("Let bootstrap.py use existing site packages"))
parser.add_option("--buildout-version",
help="Use a specific zc.buildout version")
parser.add_option("--setuptools-version",
help="Use a specific setuptools version")
parser.add_option("--setuptools-to-dir",
help=("Allow for re-use of existing directory of "
"setuptools versions"))
options, args = parser.parse_args()
if options.version:
print("bootstrap.py version %s" % __version__)
sys.exit(0)
######################################################################
# load/install setuptools
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
ez = {}
if os.path.exists('ez_setup.py'):
exec(open('ez_setup.py').read(), ez)
else:
exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez)
if not options.allow_site_packages:
# ez_setup imports site, which adds site packages
# this will remove them from the path to ensure that incompatible versions
# of setuptools are not in the path
import site
# inside a virtualenv, there is no 'getsitepackages'.
# We can't remove these reliably
if hasattr(site, 'getsitepackages'):
for sitepackage_path in site.getsitepackages():
# Strip all site-packages directories from sys.path that
# are not sys.prefix; this is because on Windows
# sys.prefix is a site-package directory.
if sitepackage_path != sys.prefix:
sys.path[:] = [x for x in sys.path
if sitepackage_path not in x]
setup_args = dict(to_dir=tmpeggs, download_delay=0)
if options.setuptools_version is not None:
setup_args['version'] = options.setuptools_version
if options.setuptools_to_dir is not None:
setup_args['to_dir'] = options.setuptools_to_dir
ez['use_setuptools'](**setup_args)
import setuptools
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
######################################################################
# Install buildout
ws = pkg_resources.working_set
setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
# Fix sys.path here as easy_install.pth added before PYTHONPATH
cmd = [sys.executable, '-c',
'import sys; sys.path[0:0] = [%r]; ' % setuptools_path +
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
requirement = 'zc.buildout'
version = options.buildout_version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
try:
return not parsed_version.is_prerelease
except AttributeError:
# Older setuptools
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setuptools_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if subprocess.call(cmd) != 0:
raise Exception(
"Failed to execute command:\n%s" % repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | z3c.coverage | /z3c.coverage-2.1.0.tar.gz/z3c.coverage-2.1.0/bootstrap.py | bootstrap.py |
Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| z3c.coverage | /z3c.coverage-2.1.0.tar.gz/z3c.coverage-2.1.0/LICENSE.rst | LICENSE.rst |
from __future__ import print_function
import sys
import os
import datetime
import cgi
import subprocess
import optparse
import tempfile
import coverage
from coverage.data import CoverageData
from coverage.files import PathAliases, relative_filename
HIGHLIGHT_COMMAND = ['enscript', '-q', '--footer', '--header', '-h',
'--language=html', '--highlight=python', '--color',
'-o', '-']
#: Expected encoding of highlight command (enscript).
HIGHLIGHT_CMD_ENCODING = 'latin1'
class Lazy(object):
"""Descriptor for lazy evaluation"""
def __init__(self, func):
self.func = func
self.name = func.__name__
def __get__(self, obj, cls):
if obj is None:
return self
value = self.func(obj)
obj.__dict__[self.name] = value
return value
class CoverageNode(dict):
"""Tree node.
Leaf nodes have no children (items() == []) and correspond to Python
modules. Branches correspond to Python packages. Child nodes are
accessible via the Python mapping protocol, as you would normally use
a dict. Item keys are non-qualified module names.
"""
@Lazy
def covered(self):
return sum(child.covered for child in self.values())
@Lazy
def total(self):
return sum(child.total for child in self.values())
@Lazy
def uncovered(self):
return self.total - self.covered
@Lazy
def percent(self):
if self.total != 0:
return 100 * self.covered // self.total
else:
return 100
@Lazy
def html_source(self):
return ''
def __str__(self):
return '%s%% covered (%s of %s lines uncovered)' % \
(self.percent, self.uncovered, self.total)
def get_at(self, path):
"""Return a tree node for a given path.
The path is a sequence of child node names.
"""
node = self
for name in path:
node = node[name]
return node
def set_at(self, path, node):
"""Create a tree node at a given path.
The path is a sequence of child node names.
Creates intermediate nodes if necessary.
"""
parent = self
for name in path[:-1]:
parent = parent.setdefault(name, CoverageNode())
parent[path[-1]] = node
class TraceCoverageNode(CoverageNode):
"""Coverage node loaded from an annotated source file."""
def __init__(self, cover_filename):
self.cover_filename = cover_filename
self.covered, self.total = self._parse(cover_filename)
def _parse(self, filename):
"""Parse a plain-text coverage report and return (covered, total)."""
covered = 0
total = 0
with open(filename) as file:
for line in file:
if line.startswith(' ' * 7) or len(line) < 7:
continue
total += 1
if not line.startswith('>>>>>>'):
covered += 1
return (covered, total)
@Lazy
def html_source(self):
text = syntax_highlight(self.cover_filename)
text = highlight_uncovered_lines(text)
return '<pre>%s</pre>' % text
class CoverageCoverageNode(CoverageNode):
"""Coverage node loaded from a coverage.py data file."""
def __init__(self, cov, source_filename):
self.cov = cov
self.source_filename = source_filename
(filename_again, statements, excluded, missing,
missing_str) = cov.analysis2(source_filename)
self.covered = len(statements) - len(excluded) - len(missing)
self.total = len(statements) - len(excluded)
self._missing = set(missing)
self._statements = set(statements)
self._excluded = set(excluded)
@Lazy
def annotated_source(self):
MISSING = '>>>>>> '
STATEMENT = ' 1: '
EXCLUDED = ' # '
OTHER = ' '
lines = []
f = open(self.source_filename)
for n, line in enumerate(f, start=1):
if n in self._missing: prefix = MISSING
elif n in self._excluded: prefix = EXCLUDED
elif n in self._statements: prefix = STATEMENT
else: prefix = OTHER
lines.append(prefix + line)
return ''.join(lines)
@Lazy
def html_source(self):
tmpdir = tempfile.mkdtemp(prefix='z3c.coverage')
tmpfilename = os.path.join(tmpdir,
os.path.basename(self.source_filename) + '.cover')
tmpf = open(tmpfilename, 'w')
tmpf.write(self.annotated_source)
tmpf.close()
text = syntax_highlight(tmpf.name)
os.unlink(tmpfilename)
os.rmdir(tmpdir)
text = highlight_uncovered_lines(text)
return '<pre>%s</pre>' % text
def get_file_list(path, filter_fn=None):
"""Return a list of files in a directory.
If you can specify a predicate (a callable), only file names matching it
will be returned.
"""
return filter(filter_fn, os.listdir(path))
def filename_to_list(filename):
"""Return a list of package/module names from a filename.
One example is worth a thousand descriptions:
>>> filename_to_list('z3c.coverage.__init__.cover')
['z3c', 'coverage', '__init__']
"""
return filename.split('.')[:-1]
def create_tree_from_files(filelist, path):
"""Create a tree with coverage statistics.
Takes the directory for coverage reports and a list of filenames relative
to that directory. Parses all the files and constructs a module tree with
coverage statistics.
Returns the root node of the tree.
"""
root = CoverageNode()
for filename in filelist:
tree_index = filename_to_list(filename)
filepath = os.path.join(path, filename)
root.set_at(tree_index, TraceCoverageNode(filepath))
return root
def create_tree_from_coverage(cov, strip_prefix=None, path_aliases=None):
"""Create a tree with coverage statistics.
Takes a coverage.coverage() instance.
Returns the root node of the tree.
"""
root = CoverageNode()
if path_aliases:
apply_path_aliases(cov, dict([alias.partition('=')[::2]
for alias in path_aliases]))
for filename in cov.data.measured_files():
if strip_prefix and filename.startswith(strip_prefix):
short_name = filename[len(strip_prefix):]
short_name = short_name.replace('/', os.path.sep)
short_name = short_name.lstrip(os.path.sep)
else:
short_name = relative_filename(filename)
tree_index = filename_to_list(short_name.replace(os.path.sep, '.'))
if 'tests' in tree_index or 'ftests' in tree_index:
continue
root.set_at(tree_index, CoverageCoverageNode(cov, filename))
return root
def apply_path_aliases(cov, alias_map):
"""Adjust filenames in coverage data."""
data = CoverageData()
aliases = PathAliases()
for k, v in alias_map.items():
aliases.add(k, v)
data.update(cov.data, aliases)
cov.data = data
def traverse_tree(tree, index, function):
"""Preorder traversal of a tree.
``index`` is the path of the root node (usually []).
``function`` gets one argument: the path of a node.
"""
function(tree, index)
for key, node in tree.items():
traverse_tree(node, index + [key], function)
def traverse_tree_in_order(tree, index, function, order_by):
"""Preorder traversal of a tree.
``index`` is the path of the root node (usually []).
``function`` gets one argument: the path of a node.
``order_by`` gets one argument a tuple of (key, node).
"""
function(tree, index)
for key, node in sorted(tree.items(), key=order_by):
traverse_tree_in_order(node, index + [key], function, order_by)
def index_to_url(index):
"""Construct a relative hyperlink to a tree node given its path."""
if index:
return '%s.html' % '.'.join(index)
return 'index.html'
def index_to_nice_name(index):
"""Construct an indented name for the node given its path."""
if index:
return ' ' * 4 * (len(index) - 1) + index[-1]
else:
return 'Everything'
def index_to_name(index):
"""Construct the full name for the node given its path."""
if index:
return '.'.join(index)
return 'everything'
def percent_to_colour(percent):
if percent == 100:
return 'green'
elif percent >= 95:
return '#74F300'
elif percent >= 90:
return 'yellow'
elif percent >= 80:
return 'orange'
else:
return 'red'
def print_table_row(html, node, file_index):
"""Generate a row for an HTML table."""
nice_name = index_to_nice_name(file_index)
if not node.keys():
nice_name += '.py'
else:
nice_name += '/'
print('<tr><td><a href="%s">%s</a></td>' %
(index_to_url(file_index), nice_name), file=html)
print('<td style="background: %s"> </td>' %
(percent_to_colour(node.percent)), file=html)
print('<td>covered %s%% (%s of %s uncovered)</td></tr>' %
(node.percent, node.uncovered, node.total), file=html)
HEADER = """
<html>
<head><title>Test coverage for %(name)s</title>
<style type="text/css">
a {text-decoration: none; display: block; padding-right: 1em;}
a:hover {background: #EFA;}
hr {height: 1px; border: none; border-top: 1px solid gray;}
.notcovered {background: #FCC;}
.footer {margin: 2em; font-size: small; color: gray;}
</style>
</head>
<body><h1>Test coverage for %(name)s</h1>
<table>
"""
FOOTER = """
<div class="footer">
%s
</div>
</body>
</html>"""
def generate_html(output_filename, tree, my_index, info, path, footer=""):
"""Generate HTML for a tree node.
``output_filename`` is the output file name.
``tree`` is the root node of the tree.
``my_index`` is the path of the node for which you are generating this HTML
file.
``info`` is a list of paths of child nodes.
``path`` is the directory name for the plain-text report files.
"""
html = open(output_filename, 'w')
print(HEADER % {'name': index_to_name(my_index)}, file=html)
info = [(tree.get_at(node_path), node_path) for node_path in info]
def key(node_info):
(node, node_path) = node_info
return (len(node_path), -node.uncovered, node_path and node_path[-1])
info.sort(key=key)
for node, file_index in info:
if not file_index:
continue # skip root node
print_table_row(html, node, file_index)
print('</table><hr/>', file=html)
source = tree.get_at(my_index).html_source
if not isinstance(source, str):
source = source.encode(HIGHLIGHT_CMD_ENCODING)
print(source, file=html)
print(FOOTER % footer, file=html)
html.close()
def syntax_highlight(filename):
"""Return HTML with syntax-highlighted Python code from a file."""
# TODO: use pygments instead
try:
pipe = subprocess.Popen(HIGHLIGHT_COMMAND + [filename],
stdout=subprocess.PIPE)
text, stderr = pipe.communicate()
if pipe.returncode != 0:
raise OSError
except OSError:
# Failed to run enscript; maybe it is not installed? Disable
# syntax highlighting then.
with open(filename, 'r') as file:
text = cgi.escape(file.read())
else:
text = text.decode(HIGHLIGHT_CMD_ENCODING)
text = text[text.find('<PRE>') + len('<PRE>'):]
text = text[:text.find('</PRE>')]
return text
def highlight_uncovered_lines(text):
"""Highlight lines beginning with '>>>>>>'."""
def color_uncov(line):
# The line must start with the missing line indicator or some HTML
# was put in front of it.
if line.startswith('>' * 6) or '>' + '>' * 6 in line:
return ('<div class="notcovered">%s</div>'
% line.rstrip('\n'))
return line
text = ''.join(map(color_uncov, text.splitlines(True)))
return text
def generate_htmls_from_tree(tree, path, report_path, footer=""):
"""Generate HTML files for all nodes in the tree.
``tree`` is the root node of the tree.
``path`` is the directory name for the plain-text report files.
``report_path`` is the directory name for the output files.
"""
def make_html(node, my_index):
info = []
def list_parents_and_children(node, index):
position = len(index)
my_position = len(my_index)
if position <= my_position and index == my_index[:position]:
info.append(index)
elif (position == my_position + 1 and
index[:my_position] == my_index):
info.append(index)
return
traverse_tree(tree, [], list_parents_and_children)
output_filename = os.path.join(report_path, index_to_url(my_index))
if not my_index:
return # skip root node
generate_html(output_filename, tree, my_index, info, path, footer)
traverse_tree(tree, [], make_html)
def generate_overall_html_from_tree(tree, output_filename, footer=""):
"""Generate an overall HTML file for all nodes in the tree."""
html = open(output_filename, 'w')
print(HEADER % {'name': ', '.join(sorted(tree.keys()))}, file=html)
def print_node(node, file_index):
if file_index: # skip root node
print_table_row(html, node, file_index)
def sort_by(node_info):
(key, node) = node_info
return (-node.uncovered, key)
traverse_tree_in_order(tree, [], print_node, sort_by)
print('</table><hr/>', file=html)
print(FOOTER % footer, file=html)
html.close()
def create_report_path(report_path):
if not os.path.exists(report_path):
os.makedirs(report_path)
def filter_fn(filename):
"""Filter interesting coverage files.
>>> filter_fn('z3c.coverage.__init__.cover')
True
>>> filter_fn('z3c.coverage.tests.cover')
False
>>> filter_fn('z3c.coverage.tests.test_foo.cover')
False
>>> filter_fn('z3c.coverage.ftests.test_bar.cover')
False
>>> filter_fn('z3c.coverage.testing.cover')
True
>>> filter_fn('z3c.coverage.testname.cover')
True
>>> filter_fn('something-unrelated.txt')
False
>>> filter_fn('<doctest something-useless.cover')
False
"""
parts = filename.split('.')
return (filename.endswith('.cover') and
not filename.startswith('<') and
'tests' not in parts and
'ftests' not in parts)
def load_coverage(path, opts):
"""Load coverage information from ``path``.
``path`` can point to a directory full of files named *.cover, or it can
point to a single pickle file containing coverage information.
"""
if os.path.isdir(path):
filelist = get_file_list(path, filter_fn)
tree = create_tree_from_files(filelist, path)
return tree
else:
cov = coverage.coverage(data_file=path, config_file=False)
cov.load()
tree = create_tree_from_coverage(cov, strip_prefix=opts.strip_prefix,
path_aliases=opts.path_alias)
return tree
def make_coverage_reports(path, report_path, opts):
"""Convert reports from ``path`` into HTML files in ``report_path``."""
if opts.verbose:
print("Loading coverage reports from %s" % path)
tree = load_coverage(path, opts=opts)
if opts.verbose:
print(tree)
rev = get_svn_revision(os.path.join(path, os.path.pardir))
timestamp = str(datetime.datetime.utcnow()) + "Z"
footer = "Generated for revision %s on %s" % (rev, timestamp)
create_report_path(report_path)
generate_htmls_from_tree(tree, path, report_path, footer)
generate_overall_html_from_tree(
tree, os.path.join(report_path, 'all.html'), footer)
if opts.verbose:
print("Generated HTML files in %s" % report_path)
def get_svn_revision(path):
"""Return the Subversion revision number for a working directory."""
try:
pipe = subprocess.Popen(['svnversion', path], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = pipe.communicate()
rev = stdout.strip()
except OSError:
rev = ""
if not rev:
rev = "UNKNOWN"
return rev
def main(args=None):
"""Process command line arguments and produce HTML coverage reports."""
parser = optparse.OptionParser(
"usage: %prog [options] [inputpath [outputdir]]",
description=(
'Converts coverage reports to HTML. If the input path is'
' omitted, it defaults to coverage or .coverage, whichever'
' exists. If the output directory is omitted, it defaults to'
' inputpath + /report or ./coverage-reports, depending on whether'
' the input path points to a directory or a file.'))
parser.add_option('-q', '--quiet', help='be quiet',
action='store_const', const=0, dest='verbose')
parser.add_option('-v', '--verbose', help='be verbose (default)',
action='store_const', const=1, dest='verbose', default=1)
parser.add_option('--strip-prefix', metavar='PREFIX',
help=('strip base directory from filenames loaded '
'from .coverage'),
)
parser.add_option('--path-alias', metavar='PATH=LOCALPATH',
help=('define path mappings for filenames loaded '
'from .coverage'),
action='append')
if args is None:
args = sys.argv[1:]
opts, args = parser.parse_args(list(args))
if len(args) > 0:
path = args[0]
else:
if os.path.exists('coverage'):
# backward compat: default input path used to be 'coverage'
path = 'coverage'
else:
path = '.coverage'
if len(args) > 1:
report_path = args[1]
else:
if os.path.isdir(path):
# backward compat: default input path is 'coverage', default output
# path is 'coverage/reports'
report_path = os.path.join(path, 'reports')
else:
report_path = 'coverage-reports'
if len(args) > 2:
parser.error("too many arguments")
make_coverage_reports(path, report_path, opts=opts)
if __name__ == '__main__':
main() | z3c.coverage | /z3c.coverage-2.1.0.tar.gz/z3c.coverage-2.1.0/src/z3c/coverage/coveragereport.py | coveragereport.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.