prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>whoispy.py<|end_file_name|><|fim▁begin|>import re import sys import whoisSrvDict import whoispy_sock import parser_branch OK = '\033[92m' FAIL = '\033[91m' ENDC = '\033[0m' def query(domainName): rawMsg = "" tldName = "" whoisSrvAddr = "" regex = re.compile('.+\..+') match = regex.search(domainName) if not match: # Invalid domain _display_fail("Invalid domain format") return None # Divice TLD regex = re.compile('\..+') match = regex.search(domainName) if match: tldName = match.group() else: _display_fail("Can not parse TLD") return None # Get TLD List if not (tldName in whoisSrvDict.get_whoisSrvDict()): _display_fail("Not Found TLD whois server") return None whoisSrvAddr = whoisSrvDict.get_whoisSrvDict().get(tldName) rawMsg = whoispy_sock.get_rawMsg(whoisSrvAddr , domainName, 43) return parser_branch.get_parser(rawMsg, whoisSrvAddr) # Display method def _display_fail(msg): <|fim_middle|> def _display_safe(msg): sys.stdout.write( OK ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) <|fim▁end|>
sys.stdout.write( FAIL ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC )
<|file_name|>whoispy.py<|end_file_name|><|fim▁begin|>import re import sys import whoisSrvDict import whoispy_sock import parser_branch OK = '\033[92m' FAIL = '\033[91m' ENDC = '\033[0m' def query(domainName): rawMsg = "" tldName = "" whoisSrvAddr = "" regex = re.compile('.+\..+') match = regex.search(domainName) if not match: # Invalid domain _display_fail("Invalid domain format") return None # Divice TLD regex = re.compile('\..+') match = regex.search(domainName) if match: tldName = match.group() else: _display_fail("Can not parse TLD") return None # Get TLD List if not (tldName in whoisSrvDict.get_whoisSrvDict()): _display_fail("Not Found TLD whois server") return None whoisSrvAddr = whoisSrvDict.get_whoisSrvDict().get(tldName) rawMsg = whoispy_sock.get_rawMsg(whoisSrvAddr , domainName, 43) return parser_branch.get_parser(rawMsg, whoisSrvAddr) # Display method def _display_fail(msg): sys.stdout.write( FAIL ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) def _display_safe(msg): <|fim_middle|> <|fim▁end|>
sys.stdout.write( OK ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC )
<|file_name|>whoispy.py<|end_file_name|><|fim▁begin|>import re import sys import whoisSrvDict import whoispy_sock import parser_branch OK = '\033[92m' FAIL = '\033[91m' ENDC = '\033[0m' def query(domainName): rawMsg = "" tldName = "" whoisSrvAddr = "" regex = re.compile('.+\..+') match = regex.search(domainName) if not match: # Invalid domain <|fim_middle|> # Divice TLD regex = re.compile('\..+') match = regex.search(domainName) if match: tldName = match.group() else: _display_fail("Can not parse TLD") return None # Get TLD List if not (tldName in whoisSrvDict.get_whoisSrvDict()): _display_fail("Not Found TLD whois server") return None whoisSrvAddr = whoisSrvDict.get_whoisSrvDict().get(tldName) rawMsg = whoispy_sock.get_rawMsg(whoisSrvAddr , domainName, 43) return parser_branch.get_parser(rawMsg, whoisSrvAddr) # Display method def _display_fail(msg): sys.stdout.write( FAIL ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) def _display_safe(msg): sys.stdout.write( OK ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) <|fim▁end|>
_display_fail("Invalid domain format") return None
<|file_name|>whoispy.py<|end_file_name|><|fim▁begin|>import re import sys import whoisSrvDict import whoispy_sock import parser_branch OK = '\033[92m' FAIL = '\033[91m' ENDC = '\033[0m' def query(domainName): rawMsg = "" tldName = "" whoisSrvAddr = "" regex = re.compile('.+\..+') match = regex.search(domainName) if not match: # Invalid domain _display_fail("Invalid domain format") return None # Divice TLD regex = re.compile('\..+') match = regex.search(domainName) if match: <|fim_middle|> else: _display_fail("Can not parse TLD") return None # Get TLD List if not (tldName in whoisSrvDict.get_whoisSrvDict()): _display_fail("Not Found TLD whois server") return None whoisSrvAddr = whoisSrvDict.get_whoisSrvDict().get(tldName) rawMsg = whoispy_sock.get_rawMsg(whoisSrvAddr , domainName, 43) return parser_branch.get_parser(rawMsg, whoisSrvAddr) # Display method def _display_fail(msg): sys.stdout.write( FAIL ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) def _display_safe(msg): sys.stdout.write( OK ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) <|fim▁end|>
tldName = match.group()
<|file_name|>whoispy.py<|end_file_name|><|fim▁begin|>import re import sys import whoisSrvDict import whoispy_sock import parser_branch OK = '\033[92m' FAIL = '\033[91m' ENDC = '\033[0m' def query(domainName): rawMsg = "" tldName = "" whoisSrvAddr = "" regex = re.compile('.+\..+') match = regex.search(domainName) if not match: # Invalid domain _display_fail("Invalid domain format") return None # Divice TLD regex = re.compile('\..+') match = regex.search(domainName) if match: tldName = match.group() else: <|fim_middle|> # Get TLD List if not (tldName in whoisSrvDict.get_whoisSrvDict()): _display_fail("Not Found TLD whois server") return None whoisSrvAddr = whoisSrvDict.get_whoisSrvDict().get(tldName) rawMsg = whoispy_sock.get_rawMsg(whoisSrvAddr , domainName, 43) return parser_branch.get_parser(rawMsg, whoisSrvAddr) # Display method def _display_fail(msg): sys.stdout.write( FAIL ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) def _display_safe(msg): sys.stdout.write( OK ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) <|fim▁end|>
_display_fail("Can not parse TLD") return None
<|file_name|>whoispy.py<|end_file_name|><|fim▁begin|>import re import sys import whoisSrvDict import whoispy_sock import parser_branch OK = '\033[92m' FAIL = '\033[91m' ENDC = '\033[0m' def query(domainName): rawMsg = "" tldName = "" whoisSrvAddr = "" regex = re.compile('.+\..+') match = regex.search(domainName) if not match: # Invalid domain _display_fail("Invalid domain format") return None # Divice TLD regex = re.compile('\..+') match = regex.search(domainName) if match: tldName = match.group() else: _display_fail("Can not parse TLD") return None # Get TLD List if not (tldName in whoisSrvDict.get_whoisSrvDict()): <|fim_middle|> whoisSrvAddr = whoisSrvDict.get_whoisSrvDict().get(tldName) rawMsg = whoispy_sock.get_rawMsg(whoisSrvAddr , domainName, 43) return parser_branch.get_parser(rawMsg, whoisSrvAddr) # Display method def _display_fail(msg): sys.stdout.write( FAIL ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) def _display_safe(msg): sys.stdout.write( OK ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) <|fim▁end|>
_display_fail("Not Found TLD whois server") return None
<|file_name|>whoispy.py<|end_file_name|><|fim▁begin|>import re import sys import whoisSrvDict import whoispy_sock import parser_branch OK = '\033[92m' FAIL = '\033[91m' ENDC = '\033[0m' def <|fim_middle|>(domainName): rawMsg = "" tldName = "" whoisSrvAddr = "" regex = re.compile('.+\..+') match = regex.search(domainName) if not match: # Invalid domain _display_fail("Invalid domain format") return None # Divice TLD regex = re.compile('\..+') match = regex.search(domainName) if match: tldName = match.group() else: _display_fail("Can not parse TLD") return None # Get TLD List if not (tldName in whoisSrvDict.get_whoisSrvDict()): _display_fail("Not Found TLD whois server") return None whoisSrvAddr = whoisSrvDict.get_whoisSrvDict().get(tldName) rawMsg = whoispy_sock.get_rawMsg(whoisSrvAddr , domainName, 43) return parser_branch.get_parser(rawMsg, whoisSrvAddr) # Display method def _display_fail(msg): sys.stdout.write( FAIL ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) def _display_safe(msg): sys.stdout.write( OK ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) <|fim▁end|>
query
<|file_name|>whoispy.py<|end_file_name|><|fim▁begin|>import re import sys import whoisSrvDict import whoispy_sock import parser_branch OK = '\033[92m' FAIL = '\033[91m' ENDC = '\033[0m' def query(domainName): rawMsg = "" tldName = "" whoisSrvAddr = "" regex = re.compile('.+\..+') match = regex.search(domainName) if not match: # Invalid domain _display_fail("Invalid domain format") return None # Divice TLD regex = re.compile('\..+') match = regex.search(domainName) if match: tldName = match.group() else: _display_fail("Can not parse TLD") return None # Get TLD List if not (tldName in whoisSrvDict.get_whoisSrvDict()): _display_fail("Not Found TLD whois server") return None whoisSrvAddr = whoisSrvDict.get_whoisSrvDict().get(tldName) rawMsg = whoispy_sock.get_rawMsg(whoisSrvAddr , domainName, 43) return parser_branch.get_parser(rawMsg, whoisSrvAddr) # Display method def <|fim_middle|>(msg): sys.stdout.write( FAIL ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) def _display_safe(msg): sys.stdout.write( OK ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) <|fim▁end|>
_display_fail
<|file_name|>whoispy.py<|end_file_name|><|fim▁begin|>import re import sys import whoisSrvDict import whoispy_sock import parser_branch OK = '\033[92m' FAIL = '\033[91m' ENDC = '\033[0m' def query(domainName): rawMsg = "" tldName = "" whoisSrvAddr = "" regex = re.compile('.+\..+') match = regex.search(domainName) if not match: # Invalid domain _display_fail("Invalid domain format") return None # Divice TLD regex = re.compile('\..+') match = regex.search(domainName) if match: tldName = match.group() else: _display_fail("Can not parse TLD") return None # Get TLD List if not (tldName in whoisSrvDict.get_whoisSrvDict()): _display_fail("Not Found TLD whois server") return None whoisSrvAddr = whoisSrvDict.get_whoisSrvDict().get(tldName) rawMsg = whoispy_sock.get_rawMsg(whoisSrvAddr , domainName, 43) return parser_branch.get_parser(rawMsg, whoisSrvAddr) # Display method def _display_fail(msg): sys.stdout.write( FAIL ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) def <|fim_middle|>(msg): sys.stdout.write( OK ) sys.stdout.write("%s\n" % msg) sys.stdout.write( ENDC ) <|fim▁end|>
_display_safe
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages def validate_match(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] <|fim▁hole|> warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages<|fim▁end|>
red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr)
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): <|fim_middle|> def validate_match(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages <|fim▁end|>
team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages def validate_match(match, official_match, official_srs): <|fim_middle|> <|fim▁end|>
error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: <|fim_middle|> for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages def validate_match(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages <|fim▁end|>
team1sr = sr break
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: <|fim_middle|> for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages def validate_match(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages <|fim▁end|>
team2sr = sr break
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: <|fim_middle|> team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages def validate_match(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages <|fim▁end|>
team3sr = sr break
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: <|fim_middle|> if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages def validate_match(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages <|fim▁end|>
error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber))
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: <|fim_middle|> tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages def validate_match(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages <|fim▁end|>
error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs)))
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: <|fim_middle|> return warning_messages, error_messages def validate_match(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages <|fim▁end|>
warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score))
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages def validate_match(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: <|fim_middle|> elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages <|fim▁end|>
error_level = 2
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages def validate_match(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: <|fim_middle|> return error_level, warning_messages, error_messages <|fim▁end|>
error_level = 1
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def <|fim_middle|>(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages def validate_match(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages <|fim▁end|>
__validate_alliance
<|file_name|>validate_match.py<|end_file_name|><|fim▁begin|>''' Created on Mar 4, 2017 @author: preiniger ''' def __validate_alliance(alliance_color, teams, official_sr): team1sr = None team2sr = None team3sr = None # TODO: there has to be a better way... but I'd rather not touch the DB for sr in teams[0].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team1sr = sr break for sr in teams[1].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team2sr = sr break for sr in teams[2].scoreresult_set.all(): if sr.match.matchNumber == official_sr.official_match.matchNumber: team3sr = sr break team_srs = [team1sr, team2sr, team3sr] team_srs = [sr for sr in team_srs if sr != None] warning_messages = [] error_messages = [] for team in teams: if team != official_sr.team1 and team != official_sr.team2 and team != official_sr.team3: error_messages.append((alliance_color + " team mismatch", teams, team.teamNumber)) if len(team_srs) != 3: error_messages.append((alliance_color + " wrong number of teams", 3, len(team_srs))) tele_high_tubes = 0 tele_mid_tubes = 0 tele_low_tubes = 0 for sr in team_srs: tele_high_tubes += sr.high_tubes_hung tele_mid_tubes += sr.mid_tubes_hung tele_low_tubes += sr.low_tubes_hung total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes if total_score != official_sr.total_score: warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score)) return warning_messages, error_messages def <|fim_middle|>(match, official_match, official_srs): error_level = 0 warning_messages = [] error_messages = [] red_teams = [match.red1, match.red2, match.red3] blue_teams = [match.blue1, match.blue2, match.blue3] red_sr = official_srs[0] blue_sr = official_srs[1] red_warning, red_error = __validate_alliance("Red", red_teams, red_sr) blue_warning, blue_error = __validate_alliance("Blue", blue_teams, blue_sr) warning_messages.extend(red_warning) warning_messages.extend(blue_warning) error_messages.extend(red_error) error_messages.extend(blue_error) if len(error_messages) != 0: error_level = 2 elif len(warning_messages) != 0: error_level = 1 return error_level, warning_messages, error_messages <|fim▁end|>
validate_match
<|file_name|>entities_to_cascades.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.core.management.base import BaseCommand from optparse import make_option from py3compat import PY2 from snisi_core.models.Entities import AdministrativeEntity as AEntity if PY2: import unicodecsv as csv else: import csv logger = logging.getLogger(__name__) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('-f', help='CSV file', action='store', dest='filename'), ) def handle(self, *args, **options): headers = ['name', 'region', 'cercle_commune', 'commune_quartier'] f = open(options.get('filename'), 'w') csv_writer = csv.DictWriter(f, fieldnames=headers) csv_writer.writeheader() csv_writer.writerow({ 'name': "label", 'region': "Région", 'cercle_commune': "Cercle", 'commune_quartier': "Commune", }) for region in AEntity.objects.filter(type__slug='region'): logger.info(region) is_bko = region.name == 'BAMAKO' for cercle in AEntity.objects.filter(parent=region): logger.info(cercle) for commune in AEntity.objects.filter(parent=cercle): logger.info(commune) if not is_bko: csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': cercle.name, 'commune_quartier': commune.name<|fim▁hole|> for vfq in AEntity.objects.filter(parent=commune): for v in (region, cercle, commune, vfq): if not len(v.name.strip()): continue csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': commune.name, 'commune_quartier': vfq.name }) f.close()<|fim▁end|>
}) continue
<|file_name|>entities_to_cascades.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.core.management.base import BaseCommand from optparse import make_option from py3compat import PY2 from snisi_core.models.Entities import AdministrativeEntity as AEntity if PY2: import unicodecsv as csv else: import csv logger = logging.getLogger(__name__) class Command(BaseCommand): <|fim_middle|> <|fim▁end|>
option_list = BaseCommand.option_list + ( make_option('-f', help='CSV file', action='store', dest='filename'), ) def handle(self, *args, **options): headers = ['name', 'region', 'cercle_commune', 'commune_quartier'] f = open(options.get('filename'), 'w') csv_writer = csv.DictWriter(f, fieldnames=headers) csv_writer.writeheader() csv_writer.writerow({ 'name': "label", 'region': "Région", 'cercle_commune': "Cercle", 'commune_quartier': "Commune", }) for region in AEntity.objects.filter(type__slug='region'): logger.info(region) is_bko = region.name == 'BAMAKO' for cercle in AEntity.objects.filter(parent=region): logger.info(cercle) for commune in AEntity.objects.filter(parent=cercle): logger.info(commune) if not is_bko: csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': cercle.name, 'commune_quartier': commune.name }) continue for vfq in AEntity.objects.filter(parent=commune): for v in (region, cercle, commune, vfq): if not len(v.name.strip()): continue csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': commune.name, 'commune_quartier': vfq.name }) f.close()
<|file_name|>entities_to_cascades.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.core.management.base import BaseCommand from optparse import make_option from py3compat import PY2 from snisi_core.models.Entities import AdministrativeEntity as AEntity if PY2: import unicodecsv as csv else: import csv logger = logging.getLogger(__name__) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('-f', help='CSV file', action='store', dest='filename'), ) def handle(self, *args, **options): <|fim_middle|> <|fim▁end|>
headers = ['name', 'region', 'cercle_commune', 'commune_quartier'] f = open(options.get('filename'), 'w') csv_writer = csv.DictWriter(f, fieldnames=headers) csv_writer.writeheader() csv_writer.writerow({ 'name': "label", 'region': "Région", 'cercle_commune': "Cercle", 'commune_quartier': "Commune", }) for region in AEntity.objects.filter(type__slug='region'): logger.info(region) is_bko = region.name == 'BAMAKO' for cercle in AEntity.objects.filter(parent=region): logger.info(cercle) for commune in AEntity.objects.filter(parent=cercle): logger.info(commune) if not is_bko: csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': cercle.name, 'commune_quartier': commune.name }) continue for vfq in AEntity.objects.filter(parent=commune): for v in (region, cercle, commune, vfq): if not len(v.name.strip()): continue csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': commune.name, 'commune_quartier': vfq.name }) f.close()
<|file_name|>entities_to_cascades.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.core.management.base import BaseCommand from optparse import make_option from py3compat import PY2 from snisi_core.models.Entities import AdministrativeEntity as AEntity if PY2: <|fim_middle|> else: import csv logger = logging.getLogger(__name__) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('-f', help='CSV file', action='store', dest='filename'), ) def handle(self, *args, **options): headers = ['name', 'region', 'cercle_commune', 'commune_quartier'] f = open(options.get('filename'), 'w') csv_writer = csv.DictWriter(f, fieldnames=headers) csv_writer.writeheader() csv_writer.writerow({ 'name': "label", 'region': "Région", 'cercle_commune': "Cercle", 'commune_quartier': "Commune", }) for region in AEntity.objects.filter(type__slug='region'): logger.info(region) is_bko = region.name == 'BAMAKO' for cercle in AEntity.objects.filter(parent=region): logger.info(cercle) for commune in AEntity.objects.filter(parent=cercle): logger.info(commune) if not is_bko: csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': cercle.name, 'commune_quartier': commune.name }) continue for vfq in AEntity.objects.filter(parent=commune): for v in (region, cercle, commune, vfq): if not len(v.name.strip()): continue csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': commune.name, 'commune_quartier': vfq.name }) f.close() <|fim▁end|>
import unicodecsv as csv
<|file_name|>entities_to_cascades.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.core.management.base import BaseCommand from optparse import make_option from py3compat import PY2 from snisi_core.models.Entities import AdministrativeEntity as AEntity if PY2: import unicodecsv as csv else: <|fim_middle|> logger = logging.getLogger(__name__) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('-f', help='CSV file', action='store', dest='filename'), ) def handle(self, *args, **options): headers = ['name', 'region', 'cercle_commune', 'commune_quartier'] f = open(options.get('filename'), 'w') csv_writer = csv.DictWriter(f, fieldnames=headers) csv_writer.writeheader() csv_writer.writerow({ 'name': "label", 'region': "Région", 'cercle_commune': "Cercle", 'commune_quartier': "Commune", }) for region in AEntity.objects.filter(type__slug='region'): logger.info(region) is_bko = region.name == 'BAMAKO' for cercle in AEntity.objects.filter(parent=region): logger.info(cercle) for commune in AEntity.objects.filter(parent=cercle): logger.info(commune) if not is_bko: csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': cercle.name, 'commune_quartier': commune.name }) continue for vfq in AEntity.objects.filter(parent=commune): for v in (region, cercle, commune, vfq): if not len(v.name.strip()): continue csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': commune.name, 'commune_quartier': vfq.name }) f.close() <|fim▁end|>
import csv
<|file_name|>entities_to_cascades.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.core.management.base import BaseCommand from optparse import make_option from py3compat import PY2 from snisi_core.models.Entities import AdministrativeEntity as AEntity if PY2: import unicodecsv as csv else: import csv logger = logging.getLogger(__name__) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('-f', help='CSV file', action='store', dest='filename'), ) def handle(self, *args, **options): headers = ['name', 'region', 'cercle_commune', 'commune_quartier'] f = open(options.get('filename'), 'w') csv_writer = csv.DictWriter(f, fieldnames=headers) csv_writer.writeheader() csv_writer.writerow({ 'name': "label", 'region': "Région", 'cercle_commune': "Cercle", 'commune_quartier': "Commune", }) for region in AEntity.objects.filter(type__slug='region'): logger.info(region) is_bko = region.name == 'BAMAKO' for cercle in AEntity.objects.filter(parent=region): logger.info(cercle) for commune in AEntity.objects.filter(parent=cercle): logger.info(commune) if not is_bko: c <|fim_middle|> for vfq in AEntity.objects.filter(parent=commune): for v in (region, cercle, commune, vfq): if not len(v.name.strip()): continue csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': commune.name, 'commune_quartier': vfq.name }) f.close() <|fim▁end|>
sv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': cercle.name, 'commune_quartier': commune.name }) continue
<|file_name|>entities_to_cascades.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.core.management.base import BaseCommand from optparse import make_option from py3compat import PY2 from snisi_core.models.Entities import AdministrativeEntity as AEntity if PY2: import unicodecsv as csv else: import csv logger = logging.getLogger(__name__) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('-f', help='CSV file', action='store', dest='filename'), ) def handle(self, *args, **options): headers = ['name', 'region', 'cercle_commune', 'commune_quartier'] f = open(options.get('filename'), 'w') csv_writer = csv.DictWriter(f, fieldnames=headers) csv_writer.writeheader() csv_writer.writerow({ 'name': "label", 'region': "Région", 'cercle_commune': "Cercle", 'commune_quartier': "Commune", }) for region in AEntity.objects.filter(type__slug='region'): logger.info(region) is_bko = region.name == 'BAMAKO' for cercle in AEntity.objects.filter(parent=region): logger.info(cercle) for commune in AEntity.objects.filter(parent=cercle): logger.info(commune) if not is_bko: csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': cercle.name, 'commune_quartier': commune.name }) continue for vfq in AEntity.objects.filter(parent=commune): for v in (region, cercle, commune, vfq): if not len(v.name.strip()): c <|fim_middle|> csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': commune.name, 'commune_quartier': vfq.name }) f.close() <|fim▁end|>
ontinue
<|file_name|>entities_to_cascades.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.core.management.base import BaseCommand from optparse import make_option from py3compat import PY2 from snisi_core.models.Entities import AdministrativeEntity as AEntity if PY2: import unicodecsv as csv else: import csv logger = logging.getLogger(__name__) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('-f', help='CSV file', action='store', dest='filename'), ) def <|fim_middle|>(self, *args, **options): headers = ['name', 'region', 'cercle_commune', 'commune_quartier'] f = open(options.get('filename'), 'w') csv_writer = csv.DictWriter(f, fieldnames=headers) csv_writer.writeheader() csv_writer.writerow({ 'name': "label", 'region': "Région", 'cercle_commune': "Cercle", 'commune_quartier': "Commune", }) for region in AEntity.objects.filter(type__slug='region'): logger.info(region) is_bko = region.name == 'BAMAKO' for cercle in AEntity.objects.filter(parent=region): logger.info(cercle) for commune in AEntity.objects.filter(parent=cercle): logger.info(commune) if not is_bko: csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': cercle.name, 'commune_quartier': commune.name }) continue for vfq in AEntity.objects.filter(parent=commune): for v in (region, cercle, commune, vfq): if not len(v.name.strip()): continue csv_writer.writerow({ 'name': "choice_label", 'region': region.name, 'cercle_commune': commune.name, 'commune_quartier': vfq.name }) f.close() <|fim▁end|>
handle
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyGarden.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2.<|fim▁hole|> "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)<|fim▁end|>
try: import django except ImportError: raise ImportError(
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import sys if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyGarden.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
<|file_name|>console.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <[email protected]> # Copyright (c) 2015-2016 Jose Antonio Chavarría <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext<|fim▁hole|> from gi.repository import Gtk class Console(Gtk.Window): def __init__(self): super(Console, self).__init__() sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box) def on_timeout(self, user_data): self.progress.pulse() return True def on_click_hide(self, widget, data=None): self.hide() return True<|fim▁end|>
_ = gettext.gettext
<|file_name|>console.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <[email protected]> # Copyright (c) 2015-2016 Jose Antonio Chavarría <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext _ = gettext.gettext from gi.repository import Gtk class Console(Gtk.Window): de<|fim_middle|> <|fim▁end|>
f __init__(self): super(Console, self).__init__() sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box) def on_timeout(self, user_data): self.progress.pulse() return True def on_click_hide(self, widget, data=None): self.hide() return True
<|file_name|>console.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <[email protected]> # Copyright (c) 2015-2016 Jose Antonio Chavarría <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext _ = gettext.gettext from gi.repository import Gtk class Console(Gtk.Window): def __init__(self): su<|fim_middle|> def on_timeout(self, user_data): self.progress.pulse() return True def on_click_hide(self, widget, data=None): self.hide() return True <|fim▁end|>
per(Console, self).__init__() sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box)
<|file_name|>console.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <[email protected]> # Copyright (c) 2015-2016 Jose Antonio Chavarría <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext _ = gettext.gettext from gi.repository import Gtk class Console(Gtk.Window): def __init__(self): super(Console, self).__init__() sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box) def on_timeout(self, user_data): se<|fim_middle|> def on_click_hide(self, widget, data=None): self.hide() return True <|fim▁end|>
lf.progress.pulse() return True
<|file_name|>console.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <[email protected]> # Copyright (c) 2015-2016 Jose Antonio Chavarría <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext _ = gettext.gettext from gi.repository import Gtk class Console(Gtk.Window): def __init__(self): super(Console, self).__init__() sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box) def on_timeout(self, user_data): self.progress.pulse() return True def on_click_hide(self, widget, data=None): se<|fim_middle|> <|fim▁end|>
lf.hide() return True
<|file_name|>console.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <[email protected]> # Copyright (c) 2015-2016 Jose Antonio Chavarría <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext _ = gettext.gettext from gi.repository import Gtk class Console(Gtk.Window): def __<|fim_middle|>elf): super(Console, self).__init__() sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box) def on_timeout(self, user_data): self.progress.pulse() return True def on_click_hide(self, widget, data=None): self.hide() return True <|fim▁end|>
init__(s
<|file_name|>console.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <[email protected]> # Copyright (c) 2015-2016 Jose Antonio Chavarría <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext _ = gettext.gettext from gi.repository import Gtk class Console(Gtk.Window): def __init__(self): super(Console, self).__init__() sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box) def on<|fim_middle|>elf, user_data): self.progress.pulse() return True def on_click_hide(self, widget, data=None): self.hide() return True <|fim▁end|>
_timeout(s
<|file_name|>console.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <[email protected]> # Copyright (c) 2015-2016 Jose Antonio Chavarría <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext _ = gettext.gettext from gi.repository import Gtk class Console(Gtk.Window): def __init__(self): super(Console, self).__init__() sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box) def on_timeout(self, user_data): self.progress.pulse() return True def on<|fim_middle|>elf, widget, data=None): self.hide() return True <|fim▁end|>
_click_hide(s
<|file_name|>camera_set_partition.py<|end_file_name|><|fim▁begin|># coding: utf-8 # Copyright (C) 2017 Open Path View, Maison Du Libre # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # Contributors: Benjamin BERNARD <[email protected]> # Email: [email protected] # Description: Camera Set Partition, represent a partition of ImagesSets. from typing import NamedTuple, List from opv_import.model import ImageSet CameraSetPartition = NamedTuple( 'CameraSetPartition',<|fim▁hole|> ('fetcher_next_indexes', List[int]), ('break_reason', str), ('number_of_incomplete_sets', int), ('number_of_complete_sets', int), ('max_consecutive_incomplete_sets', int) ] )<|fim▁end|>
[ ('ref_set', ImageSet), ('images_sets', List[ImageSet]), ('start_indexes', List[int]),
<|file_name|>TestMriServer.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import unittest<|fim▁hole|> from mri import MriServer from mri.dispatch import MriServerDispatch class TestMriServer(unittest.TestCase): def test_new_dispatch(self): server = MriServer("http://www.httpbin.com", "testuser", "testpass") task = {"title": "TEST", "id": "000112233"} dispatch = server.new_dispatch(task) test_against = MriServerDispatch(task, "http://www.httpbin.com", "testuser", "testpass") self.assertEqual(dispatch, test_against) if __name__ == '__main__': unittest.main()<|fim▁end|>
<|file_name|>TestMriServer.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import unittest from mri import MriServer from mri.dispatch import MriServerDispatch class TestMriServer(unittest.TestCase): <|fim_middle|> if __name__ == '__main__': unittest.main() <|fim▁end|>
def test_new_dispatch(self): server = MriServer("http://www.httpbin.com", "testuser", "testpass") task = {"title": "TEST", "id": "000112233"} dispatch = server.new_dispatch(task) test_against = MriServerDispatch(task, "http://www.httpbin.com", "testuser", "testpass") self.assertEqual(dispatch, test_against)
<|file_name|>TestMriServer.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import unittest from mri import MriServer from mri.dispatch import MriServerDispatch class TestMriServer(unittest.TestCase): def test_new_dispatch(self): <|fim_middle|> if __name__ == '__main__': unittest.main() <|fim▁end|>
server = MriServer("http://www.httpbin.com", "testuser", "testpass") task = {"title": "TEST", "id": "000112233"} dispatch = server.new_dispatch(task) test_against = MriServerDispatch(task, "http://www.httpbin.com", "testuser", "testpass") self.assertEqual(dispatch, test_against)
<|file_name|>TestMriServer.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import unittest from mri import MriServer from mri.dispatch import MriServerDispatch class TestMriServer(unittest.TestCase): def test_new_dispatch(self): server = MriServer("http://www.httpbin.com", "testuser", "testpass") task = {"title": "TEST", "id": "000112233"} dispatch = server.new_dispatch(task) test_against = MriServerDispatch(task, "http://www.httpbin.com", "testuser", "testpass") self.assertEqual(dispatch, test_against) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
unittest.main()
<|file_name|>TestMriServer.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import unittest from mri import MriServer from mri.dispatch import MriServerDispatch class TestMriServer(unittest.TestCase): def <|fim_middle|>(self): server = MriServer("http://www.httpbin.com", "testuser", "testpass") task = {"title": "TEST", "id": "000112233"} dispatch = server.new_dispatch(task) test_against = MriServerDispatch(task, "http://www.httpbin.com", "testuser", "testpass") self.assertEqual(dispatch, test_against) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_new_dispatch
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|>class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view <|fim▁hole|> raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator)<|fim▁end|>
def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm):
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): <|fim_middle|> def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
""" Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): <|fim_middle|> def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
self.perm = perm
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): <|fim_middle|> class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm)
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): <|fim_middle|> class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
""" Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): <|fim_middle|> def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view)
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): <|fim_middle|> class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): <|fim_middle|> return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs)
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): <|fim_middle|> <|fim▁end|>
""" Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator)
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): <|fim_middle|> def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
self.perm = perm self.error_view = error_view
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): <|fim_middle|> <|fim▁end|>
def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator)
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): <|fim_middle|> return checks_permissions(self.error_view)(decorator) <|fim▁end|>
if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs)
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): <|fim_middle|> class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
raise PermissionRequired(perm)
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: <|fim_middle|> else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
self.view = view_or_error
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: <|fim_middle|> if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
error_view = view_or_error
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: <|fim_middle|> from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
from django.conf import settings error_view = settings.PERMISSIONS_VIEW
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: <|fim_middle|> def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
self.view = view_or_request
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): <|fim_middle|> return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
raise PermissionRequired(self.perm)
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def <|fim_middle|>(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
__init__
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def <|fim_middle|>(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
require_permissions
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def <|fim_middle|>(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
__init__
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def <|fim_middle|>(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
__call__
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def <|fim_middle|>(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
dec
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def <|fim_middle|>(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
__init__
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def <|fim_middle|>(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
__call__
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|> class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def <|fim_middle|>(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator) <|fim▁end|>
decorator
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) <|fim▁hole|> description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision)<|fim▁end|>
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): <|fim_middle|> class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
"""File extension on upload is not allowed""" pass
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): <|fim_middle|> def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename)
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): <|fim_middle|> def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs)
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): <|fim_middle|> class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
return self.can_write(user=user)
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: <|fim_middle|> def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): <|fim_middle|> def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
return "%s: %s" % (self.article.current_revision.title, self.original_filename)
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): <|fim_middle|> def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): <|fim_middle|> class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename)
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): <|fim_middle|> def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number)
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: <|fim_middle|> def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): <|fim_middle|> def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
"""Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1])
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): <|fim_middle|> def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
"""Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): <|fim_middle|> def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save()
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): <|fim_middle|> def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number)
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): <|fim_middle|> signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): <|fim_middle|> return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
return False
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): <|fim_middle|> return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS)))
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: <|fim_middle|> elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower()))
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: <|fim_middle|> elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower()))
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: <|fim_middle|> upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
instance.attachment.original_filename = filename
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: <|fim_middle|> if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest())
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: <|fim_middle|> return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
filename += '.upload'
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: <|fim_middle|> filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
return None
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): <|fim_middle|> if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
self.previous_revision = self.attachment.current_revision
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: <|fim_middle|> super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! <|fim_middle|> def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
self.attachment.current_revision = self self.attachment.save()
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: <|fim_middle|> # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) <|fim▁end|>
return