prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>problem404.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # ProjectEuler/src/python/problem404.py # # Crisscross Ellipses # =================== # Published on Sunday, 2nd December 2012, 01:00 am # # Ea is an ellipse with an equation of the form x2 + 4y2 = 4a2. Ea' is the # rotated image of Ea by θ degrees counterclockwise around the origin O(0, 0) # for 0° θ 90°. b is the distance to the origin of the two intersection # points closest to the origin and c is the distance of the two other # intersection points. We call an ordered triplet (a, b, c) a canonical # ellipsoidal triplet if a, b and c are positive integers. For example, (209, # 247, 286) is a canonical ellipsoidal triplet. Let C(N) be the number of # distinct canonical ellipsoidal triplets (a, b, c) for a N. It can be # verified that C(103) = 7, C(104) = 106 and C(106) = 11845. Find C(1017). import projecteuler as pe def main(): pass if __name__ == "__main__": main() <|fim_middle|> <|fim▁end|>
<|file_name|>problem404.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # ProjectEuler/src/python/problem404.py # # Crisscross Ellipses # =================== # Published on Sunday, 2nd December 2012, 01:00 am # # Ea is an ellipse with an equation of the form x2 + 4y2 = 4a2. Ea' is the # rotated image of Ea by θ degrees counterclockwise around the origin O(0, 0) # for 0° θ 90°. b is the distance to the origin of the two intersection # points closest to the origin and c is the distance of the two other # intersection points. We call an ordered triplet (a, b, c) a canonical # ellipsoidal triplet if a, b and c are positive integers. For example, (209, # 247, 286) is a canonical ellipsoidal triplet. Let C(N) be the number of # distinct canonical ellipsoidal triplets (a, b, c) for a N. It can be # verified that C(103) = 7, C(104) = 106 and C(106) = 11845. Find C(1017). import projecteuler as pe def main()<|fim_middle|> pass if __name__ == "__main__": main() <|fim▁end|>
:
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue()<|fim▁hole|> self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END<|fim▁end|>
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): <|fim_middle|> # END <|fim▁end|>
def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set()
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so <|fim_middle|> def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): <|fim_middle|> def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
"""Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): <|fim_middle|> def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
"""General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): <|fim_middle|> def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
"""General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait()
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): <|fim_middle|> def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
self.gui_queue.put(future) return future
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): <|fim_middle|> def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task)
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): <|fim_middle|> def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task)
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): <|fim_middle|> def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task)
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): <|fim_middle|> def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e)
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): <|fim_middle|> def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id))
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): <|fim_middle|> def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id))
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id <|fim_middle|> def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout)
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): <|fim_middle|> # END <|fim▁end|>
"Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set()
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: <|fim_middle|> self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
queue = que.Queue()
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: <|fim_middle|> self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
logger = logging.getLogger('GtkHelper')
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: <|fim_middle|> self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
ev_quit = threading.Event()
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: <|fim_middle|> def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
return future
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: <|fim_middle|> else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
return method(*args, **kwdargs)
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: <|fim_middle|> def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
future = self.gui_do(method, *args, **kwdargs) return future.wait()
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def <|fim_middle|>(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
__init__
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def <|fim_middle|>(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
update_pending
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def <|fim_middle|>(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
gui_do
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def <|fim_middle|>(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
gui_call
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def <|fim_middle|>(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
gui_do_future
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def <|fim_middle|>(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
nongui_do
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def <|fim_middle|>(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
nongui_do_cb
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def <|fim_middle|>(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
nongui_do_future
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def <|fim_middle|>(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
nongui_do_task
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def <|fim_middle|>(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
assert_gui_thread
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def <|fim_middle|>(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
assert_nongui_thread
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def <|fim_middle|>(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def gui_quit(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
mainloop
<|file_name|>GtkMain.py<|end_file_name|><|fim▁begin|># # GtkMain.py -- pygtk threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ GUI threading help routines. Usage: import GtkMain # See constructor for GtkMain for options self.mygtk = GtkMain.GtkMain() # NOT THIS #gtk.main() # INSTEAD, main thread calls this: self.mygtk.mainloop() # (asynchronous call) self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # OR # (synchronous call) res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN) # To cause the GUI thread to terminate the mainloop self.mygtk.qui_quit() """ import sys, traceback import thread, threading import logging import Queue as que import gtk from ginga.misc import Task, Future class GtkMain(object): def __init__(self, queue=None, logger=None, ev_quit=None): # You can pass in a queue if you prefer to do so if not queue: queue = que.Queue() self.gui_queue = queue # You can pass in a logger if you prefer to do so if logger == None: logger = logging.getLogger('GtkHelper') self.logger = logger if not ev_quit: ev_quit = threading.Event() self.ev_quit = ev_quit self.gui_thread_id = None def update_pending(self, timeout=0.0): """Process all pending GTK events and return. _timeout_ is a tuning parameter for performance. """ # Process "out-of-band" GTK events try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass done = False while not done: # Process "in-band" GTK events try: future = self.gui_queue.get(block=True, timeout=timeout) # Execute the GUI method try: try: res = future.thaw(suppress_exception=False) except Exception, e: future.resolve(e) self.logger.error("gui error: %s" % str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception, e: self.logger.error("Traceback information unavailable.") finally: pass except que.Empty: done = True except Exception, e: self.logger.error("Main GUI loop error: %s" % str(e)) # Process "out-of-band" GTK events again try: while gtk.events_pending(): #gtk.main_iteration(False) gtk.main_iteration() finally: pass def gui_do(self, method, *args, **kwdargs): """General method for asynchronously calling into the GUI. It makes a future to call the given (method) with the given (args) and (kwdargs) inside the gui thread. If the calling thread is a non-gui thread the future is returned. """ future = Future.Future() future.freeze(method, *args, **kwdargs) self.gui_queue.put(future) my_id = thread.get_ident() if my_id != self.gui_thread_id: return future def gui_call(self, method, *args, **kwdargs): """General method for synchronously calling into the GUI. This waits until the method has completed before returning. """ my_id = thread.get_ident() if my_id == self.gui_thread_id: return method(*args, **kwdargs) else: future = self.gui_do(method, *args, **kwdargs) return future.wait() def gui_do_future(self, future): self.gui_queue.put(future) return future def nongui_do(self, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) return self.nongui_do_task(task) def nongui_do_cb(self, tup, method, *args, **kwdargs): task = Task.FuncTask(method, args, kwdargs, logger=self.logger) task.register_callback(tup[0], args=tup[1:]) return self.nongui_do_task(task) def nongui_do_future(self, future): task = Task.FuncTask(future.thaw, (), {}, logger=self.logger) return self.nongui_do_task(task) def nongui_do_task(self, task): try: task.init_and_start(self) return task except Exception, e: self.logger.error("Error starting task: %s" % (str(e))) raise(e) def assert_gui_thread(self): my_id = thread.get_ident() assert my_id == self.gui_thread_id, \ Exception("Non-GUI thread (%d) is executing GUI code!" % ( my_id)) def assert_nongui_thread(self): my_id = thread.get_ident() assert my_id != self.gui_thread_id, \ Exception("GUI thread (%d) is executing non-GUI code!" % ( my_id)) def mainloop(self, timeout=0.001): # Mark our thread id self.gui_thread_id = thread.get_ident() while not self.ev_quit.isSet(): self.update_pending(timeout=timeout) def <|fim_middle|>(self): "Call this to cause the GUI thread to quit the mainloop.""" self.ev_quit.set() # END <|fim▁end|>
gui_quit
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body)<|fim▁hole|> request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None<|fim▁end|>
def List(self, **kwargs): """Make a request to the issue tracker to list bugs."""
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): <|fim_middle|> <|fim▁end|>
"""Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): <|fim_middle|> def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
"""Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http)
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): <|fim_middle|> def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
"""Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body)
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): <|fim_middle|> def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
"""Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request)
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): <|fim_middle|> def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
"""Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): <|fim_middle|> def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
"""Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body)
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): <|fim_middle|> def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
"""Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): <|fim_middle|> def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
"""Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): <|fim_middle|> def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
"""Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request)
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): <|fim_middle|> <|fim▁end|>
"""Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: <|fim_middle|> self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
additional_credentials.authorize(self._http)
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: <|fim_middle|> body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
return False
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: <|fim_middle|> if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue)
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: <|fim_middle|> if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
updates['status'] = status
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: <|fim_middle|> if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
updates['cc'] = cc_list
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: <|fim_middle|> if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
updates['labels'] = labels
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: <|fim_middle|> body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
updates['owner'] = owner
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: <|fim_middle|> return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
logging.error('Error updating bug %s with body %s', bug_id, body) return False
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: <|fim_middle|> return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
body['owner'] = {'name': owner}
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: <|fim_middle|> return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
return response['id']
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: <|fim_middle|> response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
return None
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): <|fim_middle|> return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') }
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): <|fim_middle|> return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') }
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def <|fim_middle|>(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
__init__
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def <|fim_middle|>(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
AddBugComment
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def <|fim_middle|>(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
List
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def <|fim_middle|>(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
_MakeCommentRequest
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def <|fim_middle|>(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
NewBug
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def <|fim_middle|>(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
_MakeCreateRequest
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def <|fim_middle|>(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
GetLastBugCommentsAndTimestamp
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def <|fim_middle|>(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
_MakeGetCommentsRequest
<|file_name|>issue_tracker_service.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a layer of abstraction for the issue tracker API.""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """Class for updating bug issues.""" def __init__(self, http=None, additional_credentials=None): """Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """ self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be "Duplicate". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """ if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """Make a request to the issue tracker to list bugs.""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """Make a request to the issue tracker to update a bug.""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """ body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """ request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """ if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """Make a request to the issue tracker to get comments in the bug.""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def <|fim_middle|>(self, request): """Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """ try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None <|fim▁end|>
_ExecuteRequest
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod<|fim▁hole|> if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage'))<|fim▁end|>
def _is_new(item): days = news_settings.get('new_days')
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): <|fim_middle|> class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
@staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): <|fim_middle|> def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date()
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): <|fim_middle|> class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): <|fim_middle|> class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): <|fim_middle|> def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
self.item = NewsItem.get_or_404(request.view_args['news_id'])
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): <|fim_middle|> class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
return WPNews.render_template('news_item.html', item=self.item)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): <|fim_middle|> class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
pass
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): <|fim_middle|> class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): <|fim_middle|> class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): <|fim_middle|> class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): <|fim_middle|> class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): <|fim_middle|> class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): <|fim_middle|> class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): <|fim_middle|> class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id'])
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): <|fim_middle|> class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id'])
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): <|fim_middle|> class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): <|fim_middle|> class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): <|fim_middle|> <|fim▁end|>
def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage'))
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): <|fim_middle|> <|fim▁end|>
db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage'))
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: <|fim_middle|> return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
return False
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): <|fim_middle|> return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data()
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): <|fim_middle|> return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): <|fim_middle|> return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False)
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def <|fim_middle|>(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
_is_new
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def <|fim_middle|>(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
_process
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def <|fim_middle|>(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
_process_args
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def <|fim_middle|>(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
_process
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def <|fim_middle|>(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
_process
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def <|fim_middle|>(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
_process
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def <|fim_middle|>(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) <|fim▁end|>
_process