prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>cecog.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Methods for working with cecog Copyright 2010 University of Dundee, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt """ import os import re import sys from omero.cli import BaseControl, CLI import omero import omero.constants from omero.rtypes import rstring class CecogControl(BaseControl): """CeCog integration plugin. Provides actions for prepairing data and otherwise integrating with Cecog. See the Run_Cecog_4.1.py script. """ # [MetaMorph_PlateScanPackage] # regex_subdirectories = re.compile('(?=[^_]).*?(?P<D>\d+).*?') # regex_position = re.compile('P(?P<P>.+?)_') # continuous_frames = 1 regex_token = re.compile(r'(?P<Token>.+)\.') regex_time = re.compile(r'T(?P<T>\d+)') regex_channel = re.compile(r'_C(?P<C>.+?)(_|$)') regex_zslice = re.compile(r'_Z(?P<Z>\d+)') def _configure(self, parser): sub = parser.sub() merge = parser.add(sub, self.merge, self.merge.__doc__) merge.add_argument("path", help="Path to image files") rois = parser.add(sub, self.rois, self.rois.__doc__) rois.add_argument( "-f", "--file", required=True, help="Details file to be parsed") rois.add_argument( "-i", "--image", required=True, help="Image id which should have ids attached") for x in (merge, rois): x.add_login_arguments() # # Public methods # def <|fim_middle|>(self, args): """Uses PIL to read multiple planes from a local folder. Planes are combined and uploaded to OMERO as new images with additional T, C, Z dimensions. It should be run as a local script (not via scripting service) in order that it has access to the local users file system. Therefore need EMAN2 or PIL installed locally. Example usage: $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/0037/ Since this dir does not contain folders, this will upload images in '0037' into a Dataset called Demo_data in a Project called 'Data'. $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/ Since this dir does contain folders, this will look for images in all subdirectories of 'Demo_data' and upload images into a Dataset called Demo_data in a Project called 'Data'. Images will be combined in Z, C and T according to the \ MetaMorph_PlateScanPackage naming convention. E.g. tubulin_P0037_T00005_Cgfp_Z1_S1.tiff is Point 37, Timepoint 5, Channel \ gfp, Z 1. S? see \ /Applications/CecogPackage/CecogAnalyzer.app/Contents/Resources/resources/\ naming_schemes.conf """ """ Processes the command args, makes project and dataset then calls uploadDirAsImages() to process and upload the images to OMERO. """ from omero.rtypes import unwrap from omero.util.script_utils import uploadDirAsImages path = args.path client = self.ctx.conn(args) queryService = client.sf.getQueryService() updateService = client.sf.getUpdateService() pixelsService = client.sf.getPixelsService() # if we don't have any folders in the 'dir' E.g. # CecogPackage/Data/Demo_data/0037/ # then 'Demo_data' becomes a dataset subDirs = [] for f in os.listdir(path): fullpath = path + f # process folders in root dir: if os.path.isdir(fullpath): subDirs.append(fullpath) # get the dataset name and project name from path if len(subDirs) == 0: p = path[:-1] # will remove the last folder p = os.path.dirname(p) else: if os.path.basename(path) == "": p = path[:-1] # remove slash datasetName = os.path.basename(p) # e.g. Demo_data p = p[:-1] p = os.path.dirname(p) projectName = os.path.basename(p) # e.g. Data self.ctx.err("Putting images in Project: %s Dataset: %s" % (projectName, datasetName)) # create dataset dataset = omero.model.DatasetI() dataset.name = rstring(datasetName) dataset = updateService.saveAndReturnObject(dataset) # create project project = omero.model.ProjectI() project.name = rstring(projectName) project = updateService.saveAndReturnObject(project) # put dataset in project link = omero.model.ProjectDatasetLinkI() link.parent = omero.model.ProjectI(project.id.val, False) link.child = omero.model.DatasetI(dataset.id.val, False) updateService.saveAndReturnObject(link) if len(subDirs) > 0: for subDir in subDirs: self.ctx.err("Processing images in %s" % subDir) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, subDir, dataset) self.ctx.out("%s" % unwrap(rv)) # if there are no sub-directories, just put all the images in the dir else: self.ctx.err("Processing images in %s" % path) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, path, dataset) self.ctx.out("%s" % unwrap(rv)) def rois(self, args): """Parses an object_details text file, as generated by CeCog Analyzer and saves the data as ROIs on an Image in OMERO. Text file is of the form: frame objID classLabel className centerX centerY mean sd 1 10 6 lateana 1119 41 76.8253796095 \ 54.9305640673 Example usage: bin/omero cecog rois -f \ Data/Demo_output/analyzed/0037/statistics/P0037__object_details.txt -i 502 """ """ Processes the command args, parses the object_details.txt file and creates ROIs on the image specified in OMERO """ from omero.util.script_utils import uploadCecogObjectDetails filePath = args.file imageId = args.image if not os.path.exists(filePath): self.ctx.die(654, "Could find the object_details file at %s" % filePath) client = self.ctx.conn(args) updateService = client.sf.getUpdateService() ids = uploadCecogObjectDetails(updateService, imageId, filePath) self.ctx.out("Rois created: %s" % len(ids)) try: register("cecog", CecogControl, CecogControl.__doc__) except NameError: if __name__ == "__main__": cli = CLI() cli.register("cecog", CecogControl, CecogControl.__doc__) cli.invoke(sys.argv[1:]) <|fim▁end|>
merge
<|file_name|>cecog.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Methods for working with cecog Copyright 2010 University of Dundee, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt """ import os import re import sys from omero.cli import BaseControl, CLI import omero import omero.constants from omero.rtypes import rstring class CecogControl(BaseControl): """CeCog integration plugin. Provides actions for prepairing data and otherwise integrating with Cecog. See the Run_Cecog_4.1.py script. """ # [MetaMorph_PlateScanPackage] # regex_subdirectories = re.compile('(?=[^_]).*?(?P<D>\d+).*?') # regex_position = re.compile('P(?P<P>.+?)_') # continuous_frames = 1 regex_token = re.compile(r'(?P<Token>.+)\.') regex_time = re.compile(r'T(?P<T>\d+)') regex_channel = re.compile(r'_C(?P<C>.+?)(_|$)') regex_zslice = re.compile(r'_Z(?P<Z>\d+)') def _configure(self, parser): sub = parser.sub() merge = parser.add(sub, self.merge, self.merge.__doc__) merge.add_argument("path", help="Path to image files") rois = parser.add(sub, self.rois, self.rois.__doc__) rois.add_argument( "-f", "--file", required=True, help="Details file to be parsed") rois.add_argument( "-i", "--image", required=True, help="Image id which should have ids attached") for x in (merge, rois): x.add_login_arguments() # # Public methods # def merge(self, args): """Uses PIL to read multiple planes from a local folder. Planes are combined and uploaded to OMERO as new images with additional T, C, Z dimensions. It should be run as a local script (not via scripting service) in order that it has access to the local users file system. Therefore need EMAN2 or PIL installed locally. Example usage: $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/0037/ Since this dir does not contain folders, this will upload images in '0037' into a Dataset called Demo_data in a Project called 'Data'. $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/ Since this dir does contain folders, this will look for images in all subdirectories of 'Demo_data' and upload images into a Dataset called Demo_data in a Project called 'Data'. Images will be combined in Z, C and T according to the \ MetaMorph_PlateScanPackage naming convention. E.g. tubulin_P0037_T00005_Cgfp_Z1_S1.tiff is Point 37, Timepoint 5, Channel \ gfp, Z 1. S? see \ /Applications/CecogPackage/CecogAnalyzer.app/Contents/Resources/resources/\ naming_schemes.conf """ """ Processes the command args, makes project and dataset then calls uploadDirAsImages() to process and upload the images to OMERO. """ from omero.rtypes import unwrap from omero.util.script_utils import uploadDirAsImages path = args.path client = self.ctx.conn(args) queryService = client.sf.getQueryService() updateService = client.sf.getUpdateService() pixelsService = client.sf.getPixelsService() # if we don't have any folders in the 'dir' E.g. # CecogPackage/Data/Demo_data/0037/ # then 'Demo_data' becomes a dataset subDirs = [] for f in os.listdir(path): fullpath = path + f # process folders in root dir: if os.path.isdir(fullpath): subDirs.append(fullpath) # get the dataset name and project name from path if len(subDirs) == 0: p = path[:-1] # will remove the last folder p = os.path.dirname(p) else: if os.path.basename(path) == "": p = path[:-1] # remove slash datasetName = os.path.basename(p) # e.g. Demo_data p = p[:-1] p = os.path.dirname(p) projectName = os.path.basename(p) # e.g. Data self.ctx.err("Putting images in Project: %s Dataset: %s" % (projectName, datasetName)) # create dataset dataset = omero.model.DatasetI() dataset.name = rstring(datasetName) dataset = updateService.saveAndReturnObject(dataset) # create project project = omero.model.ProjectI() project.name = rstring(projectName) project = updateService.saveAndReturnObject(project) # put dataset in project link = omero.model.ProjectDatasetLinkI() link.parent = omero.model.ProjectI(project.id.val, False) link.child = omero.model.DatasetI(dataset.id.val, False) updateService.saveAndReturnObject(link) if len(subDirs) > 0: for subDir in subDirs: self.ctx.err("Processing images in %s" % subDir) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, subDir, dataset) self.ctx.out("%s" % unwrap(rv)) # if there are no sub-directories, just put all the images in the dir else: self.ctx.err("Processing images in %s" % path) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, path, dataset) self.ctx.out("%s" % unwrap(rv)) def <|fim_middle|>(self, args): """Parses an object_details text file, as generated by CeCog Analyzer and saves the data as ROIs on an Image in OMERO. Text file is of the form: frame objID classLabel className centerX centerY mean sd 1 10 6 lateana 1119 41 76.8253796095 \ 54.9305640673 Example usage: bin/omero cecog rois -f \ Data/Demo_output/analyzed/0037/statistics/P0037__object_details.txt -i 502 """ """ Processes the command args, parses the object_details.txt file and creates ROIs on the image specified in OMERO """ from omero.util.script_utils import uploadCecogObjectDetails filePath = args.file imageId = args.image if not os.path.exists(filePath): self.ctx.die(654, "Could find the object_details file at %s" % filePath) client = self.ctx.conn(args) updateService = client.sf.getUpdateService() ids = uploadCecogObjectDetails(updateService, imageId, filePath) self.ctx.out("Rois created: %s" % len(ids)) try: register("cecog", CecogControl, CecogControl.__doc__) except NameError: if __name__ == "__main__": cli = CLI() cli.register("cecog", CecogControl, CecogControl.__doc__) cli.invoke(sys.argv[1:]) <|fim▁end|>
rois
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object):<|fim▁hole|> return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin)<|fim▁end|>
def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): <|fim_middle|> class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self)
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): <|fim_middle|> def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
self.append({'cbs': [], 'dirty': False})
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): <|fim_middle|> def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs)
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): <|fim_middle|> def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
self.pop()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): <|fim_middle|> def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
self[-1]['cbs'].append(item)
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): <|fim_middle|> def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
self[-1]['dirty'] = True
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): <|fim_middle|> class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
return any(context['dirty'] for context in self)
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): <|fim_middle|> transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs)
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): <|fim_middle|> def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState)
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): <|fim_middle|> def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
return self._states[key or DEFAULT_DB_ALIAS]
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): <|fim_middle|> transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
return any(self[db].is_dirty() for db in dbs)
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): <|fim_middle|> class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): <|fim_middle|> class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): <|fim_middle|> def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using)
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): <|fim_middle|> class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): <|fim_middle|> CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): <|fim_middle|> def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): <|fim_middle|> def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): <|fim_middle|> CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway <|fim_middle|> @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): <|fim_middle|> <|fim▁end|>
monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin)
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint <|fim_middle|> else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty']
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction <|fim_middle|> def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
for func, args, kwargs in context['cbs']: func(*args, **kwargs)
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: <|fim_middle|> else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
transaction_states[call.using].push((call, (), {}))
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: <|fim_middle|> class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
return call()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: <|fim_middle|> def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
on_commit(transaction_states[self.using].commit, self.using)
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: <|fim_middle|> class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: <|fim_middle|> else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
if transaction_states[self.using]: transaction_states[self.using].commit()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: <|fim_middle|> else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
transaction_states[self.using].commit()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: <|fim_middle|> class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
transaction_states[self.using].rollback()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: <|fim_middle|> return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
transaction_states[self.db.alias].mark_dirty()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): <|fim_middle|> return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
transaction_states[self.db.alias].mark_dirty()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): <|fim_middle|> return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
transaction_states[self.db.alias].mark_dirty()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): <|fim_middle|> # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
sql = sql.decode()
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: <|fim_middle|> start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
continue
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): <|fim_middle|> else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
return True
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: <|fim_middle|> @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
return False
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def <|fim_middle|>(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
begin
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def <|fim_middle|>(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
commit
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def <|fim_middle|>(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
rollback
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def <|fim_middle|>(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
push
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def <|fim_middle|>(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
mark_dirty
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def <|fim_middle|>(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
is_dirty
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def <|fim_middle|>(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
__init__
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def <|fim_middle|>(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
__getitem__
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def <|fim_middle|>(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
is_dirty
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def <|fim_middle|>(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
queue_when_in_transaction
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def <|fim_middle|>(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
__enter__
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def <|fim_middle|>(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
__exit__
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def <|fim_middle|>(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
callproc
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def <|fim_middle|>(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
execute
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def <|fim_middle|>(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
executemany
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def <|fim_middle|>(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
is_sql_dirty
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>import threading from collections import defaultdict from funcy import once, decorator from django.db import DEFAULT_DB_ALIAS, DatabaseError from django.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def <|fim_middle|>(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) <|fim▁end|>
install_cacheops_transaction_support
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self):<|fim▁hole|> the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
""" Questions with a pub_date in the future should not be displayed on
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): <|fim_middle|> def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True)
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): <|fim_middle|> def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
""" was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False)
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): <|fim_middle|> def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
""" was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False)
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): <|fim_middle|> def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
""" was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True)
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): <|fim_middle|> class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
""" Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time)
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): <|fim_middle|> class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] )
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): <|fim_middle|> def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
""" If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], [])
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): <|fim_middle|> def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
""" Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] )
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): <|fim_middle|> def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
""" Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], [])
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): <|fim_middle|> def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
""" Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] )
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): <|fim_middle|> class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
""" The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] )
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): <|fim_middle|> <|fim▁end|>
def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): <|fim_middle|> def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
""" The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404)
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): <|fim_middle|> <|fim▁end|>
""" The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def <|fim_middle|>(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
test_was_published_recently_with_future_question
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def <|fim_middle|>(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
test_was_published_recently_with_old_question
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def <|fim_middle|>(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
test_was_published_recently_with_recent_question
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def <|fim_middle|>(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
create_question
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def <|fim_middle|>(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
test_index_view_with_no_questions
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def <|fim_middle|>(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
test_index_view_with_a_past_question
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def <|fim_middle|>(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
test_index_view_with_a_future_question
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def <|fim_middle|>(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
test_index_view_with_future_question_and_past_question
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def <|fim_middle|>(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
test_index_view_with_two_past_questions
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def <|fim_middle|>(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
test_detail_view_with_a_future_question
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def <|fim_middle|>(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)<|fim▁end|>
test_detail_view_with_a_past_question
<|file_name|>stateful.py<|end_file_name|><|fim▁begin|>""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be valid Python 2.7 modules - Have #!/sevabot magic string at the head of the file - Exports Python attribute *sevabot_handler* which is an instance of the class as described below Please note that in the future we might have different chat backends (GTalk) and thus have a same-same-but-different stateful handlers. """ class StatefulSkypeHandler: """ Base class for stateful handlers. All exceptions slip through are caught and logged. """ def init(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def handle_message(self, msg, status): """Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """ def shutdown(): """ Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may terminate with SIGKILL. <|fim▁hole|> def register_callback(self, skype, event, callback): """ Register any callable as a callback for a skype event. Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as RegisterEventHandler """ return skype.RegisterEventHandler(event, callback) def unregister_callback(self, skype, event, callback): """ Unregister a callback previously registered with register_callback. Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as UnregisterEventHandler """ return skype.UnregisterEventHandler(event, callback)<|fim▁end|>
"""
<|file_name|>stateful.py<|end_file_name|><|fim▁begin|>""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be valid Python 2.7 modules - Have #!/sevabot magic string at the head of the file - Exports Python attribute *sevabot_handler* which is an instance of the class as described below Please note that in the future we might have different chat backends (GTalk) and thus have a same-same-but-different stateful handlers. """ class StatefulSkypeHandler: <|fim_middle|> <|fim▁end|>
""" Base class for stateful handlers. All exceptions slip through are caught and logged. """ def init(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def handle_message(self, msg, status): """Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """ def shutdown(): """ Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may terminate with SIGKILL. """ def register_callback(self, skype, event, callback): """ Register any callable as a callback for a skype event. Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as RegisterEventHandler """ return skype.RegisterEventHandler(event, callback) def unregister_callback(self, skype, event, callback): """ Unregister a callback previously registered with register_callback. Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as UnregisterEventHandler """ return skype.UnregisterEventHandler(event, callback)
<|file_name|>stateful.py<|end_file_name|><|fim▁begin|>""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be valid Python 2.7 modules - Have #!/sevabot magic string at the head of the file - Exports Python attribute *sevabot_handler* which is an instance of the class as described below Please note that in the future we might have different chat backends (GTalk) and thus have a same-same-but-different stateful handlers. """ class StatefulSkypeHandler: """ Base class for stateful handlers. All exceptions slip through are caught and logged. """ def init(self, sevabot): <|fim_middle|> def handle_message(self, msg, status): """Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """ def shutdown(): """ Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may terminate with SIGKILL. """ def register_callback(self, skype, event, callback): """ Register any callable as a callback for a skype event. Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as RegisterEventHandler """ return skype.RegisterEventHandler(event, callback) def unregister_callback(self, skype, event, callback): """ Unregister a callback previously registered with register_callback. Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as UnregisterEventHandler """ return skype.UnregisterEventHandler(event, callback) <|fim▁end|>
""" Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """
<|file_name|>stateful.py<|end_file_name|><|fim▁begin|>""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be valid Python 2.7 modules - Have #!/sevabot magic string at the head of the file - Exports Python attribute *sevabot_handler* which is an instance of the class as described below Please note that in the future we might have different chat backends (GTalk) and thus have a same-same-but-different stateful handlers. """ class StatefulSkypeHandler: """ Base class for stateful handlers. All exceptions slip through are caught and logged. """ def init(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def handle_message(self, msg, status): <|fim_middle|> def shutdown(): """ Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may terminate with SIGKILL. """ def register_callback(self, skype, event, callback): """ Register any callable as a callback for a skype event. Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as RegisterEventHandler """ return skype.RegisterEventHandler(event, callback) def unregister_callback(self, skype, event, callback): """ Unregister a callback previously registered with register_callback. Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as UnregisterEventHandler """ return skype.UnregisterEventHandler(event, callback) <|fim▁end|>
"""Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """
<|file_name|>stateful.py<|end_file_name|><|fim▁begin|>""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be valid Python 2.7 modules - Have #!/sevabot magic string at the head of the file - Exports Python attribute *sevabot_handler* which is an instance of the class as described below Please note that in the future we might have different chat backends (GTalk) and thus have a same-same-but-different stateful handlers. """ class StatefulSkypeHandler: """ Base class for stateful handlers. All exceptions slip through are caught and logged. """ def init(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def handle_message(self, msg, status): """Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """ def shutdown(): <|fim_middle|> def register_callback(self, skype, event, callback): """ Register any callable as a callback for a skype event. Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as RegisterEventHandler """ return skype.RegisterEventHandler(event, callback) def unregister_callback(self, skype, event, callback): """ Unregister a callback previously registered with register_callback. Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as UnregisterEventHandler """ return skype.UnregisterEventHandler(event, callback) <|fim▁end|>
""" Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may terminate with SIGKILL. """
<|file_name|>stateful.py<|end_file_name|><|fim▁begin|>""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be valid Python 2.7 modules - Have #!/sevabot magic string at the head of the file - Exports Python attribute *sevabot_handler* which is an instance of the class as described below Please note that in the future we might have different chat backends (GTalk) and thus have a same-same-but-different stateful handlers. """ class StatefulSkypeHandler: """ Base class for stateful handlers. All exceptions slip through are caught and logged. """ def init(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def handle_message(self, msg, status): """Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """ def shutdown(): """ Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may terminate with SIGKILL. """ def register_callback(self, skype, event, callback): <|fim_middle|> def unregister_callback(self, skype, event, callback): """ Unregister a callback previously registered with register_callback. Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as UnregisterEventHandler """ return skype.UnregisterEventHandler(event, callback) <|fim▁end|>
""" Register any callable as a callback for a skype event. Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as RegisterEventHandler """ return skype.RegisterEventHandler(event, callback)
<|file_name|>stateful.py<|end_file_name|><|fim▁begin|>""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be valid Python 2.7 modules - Have #!/sevabot magic string at the head of the file - Exports Python attribute *sevabot_handler* which is an instance of the class as described below Please note that in the future we might have different chat backends (GTalk) and thus have a same-same-but-different stateful handlers. """ class StatefulSkypeHandler: """ Base class for stateful handlers. All exceptions slip through are caught and logged. """ def init(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def handle_message(self, msg, status): """Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """ def shutdown(): """ Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may terminate with SIGKILL. """ def register_callback(self, skype, event, callback): """ Register any callable as a callback for a skype event. Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as RegisterEventHandler """ return skype.RegisterEventHandler(event, callback) def unregister_callback(self, skype, event, callback): <|fim_middle|> <|fim▁end|>
""" Unregister a callback previously registered with register_callback. Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as UnregisterEventHandler """ return skype.UnregisterEventHandler(event, callback)
<|file_name|>stateful.py<|end_file_name|><|fim▁begin|>""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be valid Python 2.7 modules - Have #!/sevabot magic string at the head of the file - Exports Python attribute *sevabot_handler* which is an instance of the class as described below Please note that in the future we might have different chat backends (GTalk) and thus have a same-same-but-different stateful handlers. """ class StatefulSkypeHandler: """ Base class for stateful handlers. All exceptions slip through are caught and logged. """ def <|fim_middle|>(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def handle_message(self, msg, status): """Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """ def shutdown(): """ Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may terminate with SIGKILL. """ def register_callback(self, skype, event, callback): """ Register any callable as a callback for a skype event. Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as RegisterEventHandler """ return skype.RegisterEventHandler(event, callback) def unregister_callback(self, skype, event, callback): """ Unregister a callback previously registered with register_callback. Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as UnregisterEventHandler """ return skype.UnregisterEventHandler(event, callback) <|fim▁end|>
init
<|file_name|>stateful.py<|end_file_name|><|fim▁begin|>""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be valid Python 2.7 modules - Have #!/sevabot magic string at the head of the file - Exports Python attribute *sevabot_handler* which is an instance of the class as described below Please note that in the future we might have different chat backends (GTalk) and thus have a same-same-but-different stateful handlers. """ class StatefulSkypeHandler: """ Base class for stateful handlers. All exceptions slip through are caught and logged. """ def init(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def <|fim_middle|>(self, msg, status): """Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """ def shutdown(): """ Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may terminate with SIGKILL. """ def register_callback(self, skype, event, callback): """ Register any callable as a callback for a skype event. Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as RegisterEventHandler """ return skype.RegisterEventHandler(event, callback) def unregister_callback(self, skype, event, callback): """ Unregister a callback previously registered with register_callback. Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as UnregisterEventHandler """ return skype.UnregisterEventHandler(event, callback) <|fim▁end|>
handle_message
<|file_name|>stateful.py<|end_file_name|><|fim▁begin|>""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be valid Python 2.7 modules - Have #!/sevabot magic string at the head of the file - Exports Python attribute *sevabot_handler* which is an instance of the class as described below Please note that in the future we might have different chat backends (GTalk) and thus have a same-same-but-different stateful handlers. """ class StatefulSkypeHandler: """ Base class for stateful handlers. All exceptions slip through are caught and logged. """ def init(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def handle_message(self, msg, status): """Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """ def <|fim_middle|>(): """ Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may terminate with SIGKILL. """ def register_callback(self, skype, event, callback): """ Register any callable as a callback for a skype event. Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as RegisterEventHandler """ return skype.RegisterEventHandler(event, callback) def unregister_callback(self, skype, event, callback): """ Unregister a callback previously registered with register_callback. Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as UnregisterEventHandler """ return skype.UnregisterEventHandler(event, callback) <|fim▁end|>
shutdown
<|file_name|>stateful.py<|end_file_name|><|fim▁begin|>""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be valid Python 2.7 modules - Have #!/sevabot magic string at the head of the file - Exports Python attribute *sevabot_handler* which is an instance of the class as described below Please note that in the future we might have different chat backends (GTalk) and thus have a same-same-but-different stateful handlers. """ class StatefulSkypeHandler: """ Base class for stateful handlers. All exceptions slip through are caught and logged. """ def init(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def handle_message(self, msg, status): """Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """ def shutdown(): """ Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may terminate with SIGKILL. """ def <|fim_middle|>(self, skype, event, callback): """ Register any callable as a callback for a skype event. Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as RegisterEventHandler """ return skype.RegisterEventHandler(event, callback) def unregister_callback(self, skype, event, callback): """ Unregister a callback previously registered with register_callback. Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as UnregisterEventHandler """ return skype.UnregisterEventHandler(event, callback) <|fim▁end|>
register_callback
<|file_name|>stateful.py<|end_file_name|><|fim▁begin|>""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be valid Python 2.7 modules - Have #!/sevabot magic string at the head of the file - Exports Python attribute *sevabot_handler* which is an instance of the class as described below Please note that in the future we might have different chat backends (GTalk) and thus have a same-same-but-different stateful handlers. """ class StatefulSkypeHandler: """ Base class for stateful handlers. All exceptions slip through are caught and logged. """ def init(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def handle_message(self, msg, status): """Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """ def shutdown(): """ Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may terminate with SIGKILL. """ def register_callback(self, skype, event, callback): """ Register any callable as a callback for a skype event. Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as RegisterEventHandler """ return skype.RegisterEventHandler(event, callback) def <|fim_middle|>(self, skype, event, callback): """ Unregister a callback previously registered with register_callback. Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py :param skype: Skype4Py instance :param event: Same as Event :param callback: Same as Target :return: Same as UnregisterEventHandler """ return skype.UnregisterEventHandler(event, callback) <|fim▁end|>
unregister_callback
<|file_name|>regex_matcherator_naturectr.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- patterns = [r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$']*10 strings = ["/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470409.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470408_1.jpg", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470407_alt01.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470406_1.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/346880405.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470404_1.jpg", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470403.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/336470402.jpg"]*10 <|fim▁hole|> for pattern in patterns: if pattern.match(str): return pattern.match(str), pattern return False def regex_matcherator(strings,patterns): import re compiled_patterns = list(map(re.compile, patterns)) for s in strings: if matches_pattern(s, compiled_patterns): print matches_pattern(s, compiled_patterns)[1].pattern print '--'.join(s.split('/')[-2:]) print matches_pattern(s, compiled_patterns)[0].groups() print '\n' r = regex_matcherator(strings,patterns) #print r.next()<|fim▁end|>
def matches_pattern(str, patterns):
<|file_name|>regex_matcherator_naturectr.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- patterns = [r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$']*10 strings = ["/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470409.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470408_1.jpg", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470407_alt01.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470406_1.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/346880405.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470404_1.jpg", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470403.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/336470402.jpg"]*10 def matches_pattern(str, patterns): <|fim_middle|> def regex_matcherator(strings,patterns): import re compiled_patterns = list(map(re.compile, patterns)) for s in strings: if matches_pattern(s, compiled_patterns): print matches_pattern(s, compiled_patterns)[1].pattern print '--'.join(s.split('/')[-2:]) print matches_pattern(s, compiled_patterns)[0].groups() print '\n' r = regex_matcherator(strings,patterns) #print r.next()<|fim▁end|>
for pattern in patterns: if pattern.match(str): return pattern.match(str), pattern return False
<|file_name|>regex_matcherator_naturectr.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- patterns = [r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$']*10 strings = ["/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470409.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470408_1.jpg", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470407_alt01.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470406_1.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/346880405.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470404_1.jpg", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470403.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/336470402.jpg"]*10 def matches_pattern(str, patterns): for pattern in patterns: if pattern.match(str): return pattern.match(str), pattern return False def regex_matcherator(strings,patterns): <|fim_middle|> r = regex_matcherator(strings,patterns) #print r.next()<|fim▁end|>
import re compiled_patterns = list(map(re.compile, patterns)) for s in strings: if matches_pattern(s, compiled_patterns): print matches_pattern(s, compiled_patterns)[1].pattern print '--'.join(s.split('/')[-2:]) print matches_pattern(s, compiled_patterns)[0].groups() print '\n'
<|file_name|>regex_matcherator_naturectr.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- patterns = [r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$']*10 strings = ["/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470409.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470408_1.jpg", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470407_alt01.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470406_1.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/346880405.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470404_1.jpg", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470403.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/336470402.jpg"]*10 def matches_pattern(str, patterns): for pattern in patterns: if pattern.match(str): <|fim_middle|> return False def regex_matcherator(strings,patterns): import re compiled_patterns = list(map(re.compile, patterns)) for s in strings: if matches_pattern(s, compiled_patterns): print matches_pattern(s, compiled_patterns)[1].pattern print '--'.join(s.split('/')[-2:]) print matches_pattern(s, compiled_patterns)[0].groups() print '\n' r = regex_matcherator(strings,patterns) #print r.next()<|fim▁end|>
return pattern.match(str), pattern
<|file_name|>regex_matcherator_naturectr.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- patterns = [r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$']*10 strings = ["/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470409.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470408_1.jpg", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470407_alt01.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470406_1.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/346880405.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470404_1.jpg", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470403.png", "/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/336470402.jpg"]*10 def matches_pattern(str, patterns): for pattern in patterns: if pattern.match(str): return pattern.match(str), pattern return False def regex_matcherator(strings,patterns): import re compiled_patterns = list(map(re.compile, patterns)) for s in strings: if matches_pattern(s, compiled_patterns): <|fim_middle|> r = regex_matcherator(strings,patterns) #print r.next()<|fim▁end|>
print matches_pattern(s, compiled_patterns)[1].pattern print '--'.join(s.split('/')[-2:]) print matches_pattern(s, compiled_patterns)[0].groups() print '\n'