def test_user_without_userid(self): environ = {'repoze.what.credentials': {}} p = predicates.is_user('gustavo') self.eval_unmet_predicate(p, environ, 'The current user must be "gustavo"')
def test_right_user(self): environ = make_environ('gustavo') p = predicates.is_user('gustavo') self.eval_met_predicate(p, environ)
class RootController(BaseController): """ The root controller for the labyrinth application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() admin = AdminController(model, DBSession, config_type=TGAdminConfig) error = ErrorController() labyrinth = LabyrinthController() def _before(self, *args, **kw): tmpl_context.project_name = "labyrinth" @expose('labyrinth.templates.index') def index(self): """ Este método define el arreglo de celdas a partir de la lectura del archivo de texto. Inicializa la variable global LABYRINTh """ # print("Lab: %s", app_globals.LABYRINTH) if not len(app_globals.LABYRINTH): # Inicializando laberinto create_labyrinth() return dict(page='index') @expose('labyrinth.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('labyrinth.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(page='environ', environment=request.environ) @expose('labyrinth.templates.data') @expose('json') def data(self, **kw): """ This method showcases how you can use the same controller for a data page and a display page. """ return dict(page='data', params=kw) @expose('labyrinth.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('labyrinth.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('labyrinth.templates.login') def login(self, came_from=lurl('/'), failure=None, login=''): """Start the user login.""" if failure is not None: if failure == 'user-not-found': flash(_('User not found'), 'error') elif failure == 'invalid-password': flash(_('Invalid Password'), 'error') login_counter = request.environ.get('repoze.who.logins', 0) if failure is None and login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from, login=login) @expose() def post_login(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) # Do not use tg.redirect with tg.url as it will add the mountpoint # of the application twice. return HTTPFound(location=came_from) @expose() def post_logout(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) return HTTPFound(location=came_from)
def test_user_without_credentials(self): environ = {} p = predicates.is_user('gustavo') self.eval_unmet_predicate(p, environ, 'The current user must be "gustavo"')
Mock TG2 protected controller using the @allow_only decorator, but also using ._failed_authorization() """ @expose() def index(self): return 'Welcome back, foobar!' @classmethod def _failed_authorization(self, reason): # Pay first! abort(402) ControllerWithAllowOnlyDecoratorAndAuthzDenialHandler = allow_only( is_user('foobar'))(ControllerWithAllowOnlyDecoratorAndAuthzDenialHandler) #{ The tests themselves class BaseIntegrationTests(TestCase): """Base test case for the integration tests""" controller = RootController def setUp(self): # Creating the session dir: if not os.path.exists(session_dir): os.makedirs(session_dir) # Setting TG2 up:
class RootController(BaseController): """ The root controller for the Info application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() admin = AdminController(model, DBSession, config_type=TGAdminConfig) error = ErrorController() def _before(self, *args, **kw): tmpl_context.project_name = "info" @expose('info.templates.index') def index(self): """Handle the front-page.""" return dict(page='index') @expose('info.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('info.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(page='environ', environment=request.environ) @expose('info.templates.data') @expose('json') def data(self, **kw): """ This method showcases how you can use the same controller for a data page and a display page. """ return dict(page='data', params=kw) @expose('info.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('info.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('info.templates.login') def login(self, came_from=lurl('/'), failure=None, login=''): """Start the user login.""" if failure is not None: if failure == 'user-not-found': flash(_('User not found'), 'error') elif failure == 'invalid-password': flash(_('Invalid Password'), 'error') login_counter = request.environ.get('repoze.who.logins', 0) if failure is None and login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from, login=login) @expose() def post_login(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) # Do not use tg.redirect with tg.url as it will add the mountpoint # of the application twice. return HTTPFound(location=came_from) @expose() def post_logout(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) return HTTPFound(location=came_from) @expose('info.templates.confe') def confe(self): """Handle the 'confe' page.""" return dict(page='confe') @expose('info.templates.meeting') def meeting(self): """Handle the 'meeting' page.""" return dict(page='meeting') @expose('info.templates.barberino') def barberino(self): """Handle the 'meeting' page.""" return dict(page='barberino') @expose('info.templates.scarperiaesanpiero') def scarperiaesanpiero(self): """Handle the 'meeting' page.""" return dict(page='scarperiaesanpiero') @expose('info.templates.vichio') def vicchio(self): """Handle the 'meeting' page.""" return dict(page='vicchio') @expose('info.templates.marradi') def marradi(self): """Handle the 'meeting' page.""" return dict(page='marradi') @expose('info.templates.dicomano') def dicomano(self): """Handle the 'meeting' page.""" return dict(page='dicomano') @expose('info.templates.firenzuola') def firenzuola(self): """Handle the 'meeting' page.""" return dict(page='firenzuola') @expose('info.templates.palazzuolo') def palazzuolo(self): """Handle the 'meeting' page.""" return dict(page='palazzuolo') @expose('info.templates.include') def include(self): """Handle the 'include' page.""" return dict(page='include') @expose('info.templates.heading') def heading(self): """Handle the 'iheading' page.""" return dict(page='heading') @expose('info.templates.footer') def footer(self): """Handle the 'footer' page.""" return dict(page='footer') @expose('info.templates.MENU') def menu(self): """Handle the 'footer' page.""" return dict(page='MENU') @expose('info.templates.centralino') def centralino(self): """Handle the 'footer' page.""" return dict(page='centralino') @expose('info.templates.slider') def slider(self): """Handle the 'footer' page.""" return dict(page='slider') ### @expose() ### def index(self): ### return 'Hello World' @expose('hello.xhtml') def hello(self, person="Carlo"): return dict(person=person)
class UserController(BaseController): """ The root controller for the addrbook application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() admin = AdminController(model, DBSession, config_type=TGAdminConfig) error = ErrorController() allow_only = not_anonymous() def username(self): try: username = request.identity['repoze.who.userid'] return username except (KeyError, TypeError): raise @expose('addrbook.templates.contacts') def _default(self): """Handle the front-page.""" contacts = self.contactlist() try: username = self.username() except TypeError: username = "" partial, total = self.count_contacts() return dict(page='index', contacts=contacts, user=username, partial=partial) def contactlist(self): try: username = self.username() contacts = DBSession.query(Addressbook).filter( Addressbook.users.any(user_name=username)) return [contact for contact in contacts.order_by(Addressbook.name)] except TypeError: return [] def count_contacts(self): try: username = self.username() partial = DBSession.query(Addressbook).filter( Addressbook.users.any(user_name=username)).count() total = DBSession.query(Addressbook.id).count() return partial, total except TypeError: return 0, 0 @expose('addrbook.templates.add') def add(self): """Handle the 'add' page.""" return dict(page='add', form=AddContactForm) # handles missing fields (failed validation) @expose() def fieldrequired_handler(self, name, number): flash(_('Insert both fields!'), 'error') redirect('/contactlist/add') @expose() @validate(AddContactForm, error_handler=fieldrequired_handler) def addcontact(self, name, number): username = self.username() try: new_contact = Addressbook(name=name, number=number) new_contact.users.append( DBSession.query(User).filter_by(user_name=username).one()) DBSession.add(new_contact) flash(_('New contact added to ' + username)) except TypeError: flash(_('DB query failed'), 'error') redirect('/contactlist') @expose() def deletecontact(self, name, number): username = self.username() toBeDeleted = DBSession.query(Addressbook).filter( Addressbook.users.any(user_name=username)).filter( Addressbook.name == name).filter(Addressbook.number == number) toBeDeleted.delete(synchronize_session='fetch') flash(_('Contact deleted')) redirect('/contactlist') @expose('json') def export(self): username = self.username() contacts = self.contactlist() return dict(username=username, contacts=contacts) @expose('addrbook.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('addrbook.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(page='environ', environment=request.environ) @expose('addrbook.templates.data') @expose('json') def data(self, **kw): """ This method showcases how you can use the same controller for a data page and a display page. """ return dict(page='data', params=kw) @expose('addrbook.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('addrbook.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff')
class RootController(BaseController): """ The root controller for the ucframe application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() admin = AdminController(model, DBSession, config_type=TGAdminConfig) error = ErrorController() RepoLocationList = ['ucframe', 'model', 'TaskCaseRepository'] taskManager = TaskCaseManager(RepoLocationList) def _before(self, *args, **kw): tmpl_context.project_name = "ucframe" @expose('ucframe.templates.index') def index(self): """Handle the front-page.""" self.create_tagtable() return dict(page='index') @expose('ucframe.templates.contribute') def contribute(self, **kw): other_input = {} self_input = {} self_parameters = ["taskName", "Member", "Project"] remove_key = [] for i in kw: if kw[i] == '': remove_key.append(i) elif i in self_parameters: self_input[i] = kw[i] else: other_input[i] = kw[i] return {'parameters': other_input, 'self_input': self_input} @expose('ucframe.templates.contribute_pre') def contribute_pre(self, **kw): other_input = {} self_input = {} self_parameters_name = [ "PreCondition-Status-", "PreCondition-Condition-" ] self_parameters = [] for i in range(1, 10): #[seLain] TOFIX: No better way to do this ? for parameters_name in self_parameters_name: key = parameters_name + str(i) if key not in self_parameters: self_parameters.append(key) remove_key = [] #[seLain] TOFIX: Unknown function code for i in kw: if kw[i] == '': remove_key.append(i) #[seLain] TOFIX: Unknown function code elif i in self_parameters: #[seLain] TOFIX: Unknown function code self_input[i] = kw[i] else: #[seLain] this code seems to be passed other_input[i] = kw[ i] # to the next page, for params accumulation # for embedded view test export_nodes_data, export_edges_data = utils.get_no_redundant_graph() #return {'parameters':other_input, 'self_input': self_input} return { 'parameters': other_input, 'self_input': self_input, 'nodes': export_nodes_data, 'edges': export_edges_data } @expose('ucframe.templates.contribute' ) #[seLain] Does this expose necessary ? def redirect_page(self, **kw): if kw['redirectPage'] == "Pre-Condition-Edit": redirect('/contribute_pre', kw) elif kw['redirectPage'] == "Post-Condition-Edit": redirect('/contribute_post', kw) elif kw['redirectPage'] == "Event-Flow-Edit": redirect('/contribute_event', kw) elif kw['redirectPage'] == "Task-Meta-Edit": redirect('/contribute', kw) elif kw['redirectPage'] == "View-Task-Edit": redirect('/contribute_view', kw) elif kw['redirectPage'] == "Save-Data": redirect('/contribute_save', kw) redirect('/contribute') @expose('ucframe.templates.contribute_event') def contribute_event(self, **kw): other_input = {} self_input = {} self_parameters_name = ["EventFlow-"] self_parameters = [] for i in range(1, 10): for parameters_name in self_parameters_name: key = parameters_name + str(i) if key not in self_parameters: self_parameters.append(key) remove_key = [] for i in kw: if kw[i] == '': remove_key.append(i) elif i in self_parameters: self_input[i] = kw[i] else: other_input[i] = kw[i] return {'parameters': other_input, 'self_input': self_input} @expose('ucframe.templates.contribute_post') def contribute_post(self, **kw): other_input = {} self_input = {} self_parameters_name = [ "PostCondition-Status-", "PostCondition-Condition-" ] self_parameters = [] for i in range(1, 10): for parameters_name in self_parameters_name: key = parameters_name + str(i) if key not in self_parameters: self_parameters.append(key) remove_key = [] for i in kw: if kw[i] == '': remove_key.append(i) elif i in self_parameters: self_input[i] = kw[i] else: other_input[i] = kw[i] return {'parameters': other_input, 'self_input': self_input} @expose('ucframe.templates.contribute_view') def contribute_view(self, **kw): other_input = {} self_input = {} pre_condition_name = [ "PreCondition-Status-", "PreCondition-Condition-" ] pre_condition = [] post_condition_name = [ "PostCondition-Status-", "PostCondition-Condition-" ] post_condition = [] event_flow_name = ["EventFlow-"] event_flow = [] meta_task = ["taskName", "Member", "Project"] for i in range(1, 10): for parameters_name in pre_condition_name: key = parameters_name + str(i) if key not in pre_condition: pre_condition.append(key) for parameters_name in post_condition_name: key = parameters_name + str(i) if key not in post_condition: post_condition.append(key) for parameters_name in event_flow_name: key = parameters_name + str(i) if key not in event_flow: event_flow.append(key) pre_condition_input = {} post_condition_input = {} event_flow_input = {} task_meta_input = {} remove_key = [] for i in kw: if kw[i] == '': remove_key.append(i) elif i in pre_condition: pre_condition_input[i] = kw[i] elif i in post_condition: post_condition_input[i] = kw[i] elif i in event_flow: event_flow_input[i] = kw[i] elif i in event_flow: event_flow_input[i] = kw[i] elif i in meta_task: task_meta_input[i] = kw[i] # get similar CUCs event_list = pre_condition_input.values() + event_flow_input.values( ) + post_condition_input.values() #print 'event_list in contribute_view:', event_list cuc_collecction = self.similar_cucs(event_list)['cucs'] #print 'cuc_collecction:', cuc_collecction return { 'pre_condition': pre_condition_input, 'post_condition': post_condition_input, 'event_flow': event_flow_input, 'task_meta': task_meta_input, 'similar_cucs': cuc_collecction } @expose('ucframe.templates.contribute_save') def contribute_save(self, **kw): self.taskManager.saveTaskCase(kw) #self.taskManager.saveOntologyFromTaskCase(kw) redirect('/index') @expose('json') def taskCase_TypeTag(self, **kw): fileLocation = os.sep.join( ['ucframe', 'model', 'Tag', 'Tag Table.txt']) TagTable = ConfigObj(fileLocation, encoding='UTF8') output = {} output['Actor'] = {} output['Message'] = {} output['System'] = {} for tag in TagTable: if TagTable[tag]['Category'] not in output: continue number = len(output[TagTable[tag]['Category']]) output[TagTable[tag]['Category']][number] = {} name = TagTable[tag]['Name'] tagType = '' if TagTable[tag]['Category'] == 'Actor': tagSig = '@' elif TagTable[tag]['Category'] == 'Message': tagSig = '$' elif TagTable[tag]['Category'] == 'System': tagSig = '*' output[TagTable[tag]['Category']][number]['id'] = "number" output[TagTable[tag]['Category']][number]['name'] = tagSig + name output[TagTable[tag]['Category']][number]['type'] = 'contact' output[TagTable[tag]['Category']][number][ 'img'] = '/img/glyphicons-halflings.png' return output # when this method is called, it will scan the entire repository and # generate a new tag table based on the exisiting content in the repository def create_tagtable(self, ): table_location = os.sep.join( ['ucframe', 'model', 'Tag', 'Tag Table.txt']) TagTable = ConfigObj(table_location, encoding='UTF8') export_nodes_data, export_edges_data = utils.get_no_redundant_graph() for anode in export_nodes_data: TagTable[anode['text']] = { 'Name': anode['text'], 'RealWord': anode['text'], 'Category': anode['type'], 'Type': 'Instance', 'Abstraction': anode['text'] } TagTable.write() @expose('ucframe.templates.view') def view(self): export_nodes_data, export_edges_data = utils.get_no_redundant_graph() # return the json data to the page visualization import json jsonfile = open('graph.json', 'w') jsonfile.write(json.dumps(export_nodes_data)) jsonfile.close() jsonfile = open('edges.json', 'w') jsonfile.write(json.dumps(export_edges_data)) jsonfile.close() return dict(page='view', nodes=export_nodes_data, edges=export_edges_data) @expose('json') def graph(self): import json with open('graph.json') as data_file: data = json.load(data_file) return {'data': data} @expose('json') def edges(self): import json with open('edges.json') as data_file: data = json.load(data_file) return {'data': data} @expose('json') def local_graph(self): import json with open('local_graph.json') as data_file: data = json.load(data_file) return {'data': data} @expose('json') def local_edges(self): import json with open('local_edges.json') as data_file: data = json.load(data_file) return {'data': data} @expose('ucframe.templates.quality') def quality(self): nodes, edges = utils.get_no_redundant_graph() export_data = {'nodes': [], "links": []} type2group = {'Actor': 1, 'Message': 2, 'System': 3} # clustering is needed # prepare the nodes for anode in nodes: export_data['nodes'].append({ 'name': anode['text'], 'group': type2group[anode['type']] }) # prepare the edges for aedge in edges: export_data['links'].append({ 'source': aedge['source-index'], 'target': aedge['target-index'], 'value': aedge['count'] }) # return the json data to the page visualization import json jsonfile = open('ucframe/public/data/ams_matrix.json', 'w') jsonfile.write(json.dumps(export_data)) jsonfile.close() return dict(page='quality') @expose('ucframe.templates.quality_rev') def quality_rev(self): nodes, edges = utils.get_no_redundant_graph() export_data = {'nodes': [], "links": []} type2group = {'Actor': 1, 'Message': 2, 'System': 3} # clustering is needed # prepare the nodes for anode in nodes: export_data['nodes'].append({ 'name': anode['text'], 'group': type2group[anode['type']] }) # prepare the edges # note that the reverse edges are calculated, not natural from the graph # each calculated edge is made by comparing the similarity between two nodes ## prepare the node array ## each node array is made of node[linked_node1, linked_node2...] node_array = {} for anode in nodes: node_array[anode['text']] = {} for aedge in edges: #print '[in comp]', nodes.index(anode), aedge['source-index'] if nodes.index(anode) is aedge['source-index']: node_array[anode['text']][ aedge['target-index']] = aedge['count'] ## compare similarity for key_1 in node_array.keys(): for key_2 in node_array.keys(): node_1 = node_array[key_1] node_2 = node_array[key_2] # print '[in rev]', node_1, node_2 overlaps = [ min(node_1[x], node_2[x]) for x in node_1 if x in node_2 ] # print '[in rev]', key_1, key_2, overlaps ###### worked !!!!!!!! but the correctness is questionable ###### DO THE CODE REVIEW !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! export_data['links'].append({ 'source': node_array.keys().index(key_1), 'target': node_array.keys().index(key_2), 'value': sum(overlaps) }) ''' for aedge in edges: export_data['links'].append({'source':aedge['source-index'], 'target':aedge['target-index'], 'value':aedge['count']}) ''' # return the json data to the page visualization import json jsonfile = open('ucframe/public/data/ams_matrix_rev.json', 'w') jsonfile.write(json.dumps(export_data)) jsonfile.close() return dict(page='quality_rev') @expose('ucframe.templates.quality_indiv') def quality_indiv(self): type_constraint = "Message" nodes, edges = utils.get_no_redundant_graph() export_data = {'nodes': [], "links": []} type2group = {'Actor': 1, 'Message': 2, 'System': 3} # clustering is needed # prepare the nodes. only the actor type is considered this time. for anode in nodes: if anode['type'] is type_constraint: export_data['nodes'].append({ 'name': anode['text'], 'group': type2group[anode['type']] }) # prepare the edges # note that the reverse edges are calculated, not natural from the graph # each calculated edge is made by comparing the similarity between two nodes ## prepare the node array ## each node array is made of node[linked_node1, linked_node2...] node_array = {} for anode in nodes: if anode[ 'type'] is not type_constraint: # only the actor type is considered this time. continue node_array[anode['text']] = {} for aedge in edges: #print '[in comp]', nodes.index(anode), aedge['source-index'] if nodes.index(anode) is aedge['source-index']: node_array[anode['text']][ aedge['target-index']] = aedge['count'] ## compare similarity for key_1 in node_array.keys(): for key_2 in node_array.keys(): node_1 = node_array[key_1] node_2 = node_array[key_2] # print '[in rev]', node_1, node_2 overlaps = [ min(node_1[x], node_2[x]) for x in node_1 if x in node_2 ] # print '[in rev]', key_1, key_2, overlaps ###### worked !!!!!!!! but the correctness is questionable ###### DO THE CODE REVIEW !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! export_data['links'].append({ 'source': node_array.keys().index(key_1), 'target': node_array.keys().index(key_2), 'value': sum(overlaps) }) ''' for aedge in edges: export_data['links'].append({'source':aedge['source-index'], 'target':aedge['target-index'], 'value':aedge['count']}) ''' # return the json data to the page visualization import json jsonfile = open('ucframe/public/data/ams_matrix_indiv.json', 'w') jsonfile.write(json.dumps(export_data)) jsonfile.close() return dict(page='quality_indiv') ''' @expose('json') def ams_matrix(self): import json with open('ams_matrix.json') as data_file: data = json.load(data_file) return {'data': data} ''' def is_ams_term(self, term): if term[0] in ['@', '$', '*']: return True return False # This method receives request for CUC_metrics measurement. # THe CUC metrics measures quality of the specific object term # - kw: the input term # @expose('json') def cuc_metrics(self, **kw): event_list = [] for key in kw.keys(): event_list.append(key.strip()) current_terms = [] for event in event_list: splitted_terms = event.split(' ') for aterm in splitted_terms: if self.is_ams_term(aterm) and aterm not in current_terms: current_terms.append(aterm) print 'current_terms in cuc_metrics', current_terms # metrics evaluation nodes, edges = utils.get_no_redundant_graph() # calculate the number of senders # calculate the numder of receivers ''' NOS = 0 NOR = 0 for aedge in edges: if current_term == nodes[aedge['target-index']]['text']: NOS += 1 if current_term == nodes[aedge['source-index']]['text']: NOR += 1 ''' # CRT computation import metrics CRT_data = {} ## data to be returned ## calculate the CRT CRT_dict = metrics.CRT() CRT_data['terms'] = {} ## get the average CRT CRT_current_terms = [] for aterm in current_terms: if aterm in CRT_dict.keys(): CRT_current_terms.append(CRT_dict[aterm]) CRT_data['terms'][aterm] = CRT_dict[ aterm] ## put ony the context terms CRT_average = round(sum(CRT_current_terms) / len(CRT_current_terms), 2) CRT_data['average'] = CRT_average CRT_data['description'] = 'Contributor Ratio of a Term (CRT)' +'\\n\\n' + \ '在目前輸入頁面中您所使用的 AMS 詞彙(Terms), ' + \ '平均來說也被多少比例的其他使用案例貢獻者所使用.' + \ '\\n\\n' + '舉例來說: PuzzleBreaker(57%) 代表有 57% 的貢獻者' + \ '也使用了 PuzzleBreaker 在他們的使用案例中.' # LLC computation NLLC_data = {} ## calculate the LLC NLLC_result = metrics.NLLC(event_list) NLLC_data['value'] = NLLC_result NLLC_data['description'] = 'Normalized Local Logical Conherence (NLLC)' +'\\n\\n' + \ '在目前輸入頁面中您所有敘述之間的邏輯連貫性高低.' + \ '通常越高的 NLLC 代表所有敘述整體越容易被閱讀及理解.' + \ '\\n\\n' + '我們提供了 Average NLLC 做為參考.' + \ '這是其他已經被貢獻的使用案例之平均 NLLC 值.' ANLLC_result = metrics.ANLLC() NLLC_data['average'] = ANLLC_result return {'CRT': CRT_data, 'NLLC': NLLC_data} @expose('json') def precon_metrics(self, **kw): precon_list = [] for key in kw.keys(): precon_list.append(key.strip()) current_terms = [] for precon in precon_list: splitted_terms = precon.split(' ') for aterm in splitted_terms: if self.is_ams_term(aterm) and aterm not in current_terms: current_terms.append(aterm) print 'current_terms in precon_metrics', current_terms # metrics evaluation nodes, edges = utils.get_no_redundant_graph() # CRT computation import metrics CRT_data = {} ## data to be returned ## calculate the CRT CRT_dict = metrics.CRT() CRT_data['terms'] = {} ## get the average CRT CRT_current_terms = [] for aterm in current_terms: if aterm in CRT_dict.keys(): CRT_current_terms.append(CRT_dict[aterm]) CRT_data['terms'][aterm] = CRT_dict[ aterm] ## put ony the context terms if len(CRT_current_terms) == 0: CRT_average = 0 else: CRT_average = round( sum(CRT_current_terms) / len(CRT_current_terms), 2) CRT_data['average'] = CRT_average CRT_data['description'] = 'Contributor Ratio of a Term (CRT)' +'\\n\\n' + \ '在目前輸入頁面中您所使用的 AMS 詞彙(Terms), ' + \ '平均來說也被多少比例的其他使用案例貢獻者所使用.' + \ '\\n\\n' + '舉例來說: PuzzleBreaker(57%) 代表有 57% 的貢獻者' + \ '也使用了 PuzzleBreaker 在他們的使用案例中.' return {'CRT': CRT_data} @expose('json') def postcon_metrics(self, **kw): postcon_list = [] for key in kw.keys(): postcon_list.append(key.strip()) current_terms = [] for postcon in postcon_list: splitted_terms = postcon.split(' ') for aterm in splitted_terms: if self.is_ams_term(aterm) and aterm not in current_terms: current_terms.append(aterm) print 'current_terms in postcon_metrics', current_terms # metrics evaluation nodes, edges = utils.get_no_redundant_graph() # CRT computation import metrics CRT_data = {} ## data to be returned ## calculate the CRT CRT_dict = metrics.CRT() CRT_data['terms'] = {} ## get the average CRT CRT_current_terms = [] for aterm in current_terms: if aterm in CRT_dict.keys(): CRT_current_terms.append(CRT_dict[aterm]) CRT_data['terms'][aterm] = CRT_dict[ aterm] ## put ony the context terms if len(CRT_current_terms) == 0: CRT_average = 0 else: CRT_average = round( sum(CRT_current_terms) / len(CRT_current_terms), 2) CRT_data['average'] = CRT_average CRT_data['description'] = 'Contributor Ratio of a Term (CRT)' +'\\n\\n' + \ '在目前輸入頁面中您所使用的 AMS 詞彙(Terms), ' + \ '平均來說也被多少比例的其他使用案例貢獻者所使用.' + \ '\\n\\n' + '舉例來說: PuzzleBreaker(57%) 代表有 57% 的貢獻者' + \ '也使用了 PuzzleBreaker 在他們的使用案例中.' return {'CRT': CRT_data} # This method receives request for similar tags. # The similar tags are caculated by their adjencent terms # - kw: the input term # @expose('json') def similar_tags(self, **kw): similar_tags_group = {} tag_defs = {} context_terms = kw.keys()[0].split(' ') for aterm in context_terms: if aterm[0] not in ['@', '$', '*']: continue # skip those not tagged sorted_tags = self.get_similar_tags(aterm, context_terms) if len(sorted_tags) > 6: sorted_tags = sorted_tags[ 1:6] # only get the first five, except the same one similar_tags_group[aterm] = sorted_tags # put the deinition of similar terms for sim_tag in sorted_tags: defition_dict = self.get_term_definition(sim_tag[0]) print 'defition_dict:', defition_dict if defition_dict is None: tag_defs[sim_tag[0]] = None else: tag_defs[sim_tag[0]] = defition_dict['Description'] # also put the deinition of context terms defition_dict = self.get_term_definition(aterm) if defition_dict is None: tag_defs[aterm] = None else: tag_defs[aterm] = defition_dict['Description'] print 'tag_defs:', tag_defs return {'tags': similar_tags_group, 'glossaries': tag_defs} @expose('json') def similar_events(self, **kw): current_event = kw.keys()[0].strip() # determine similar events ## load all cuc from configobj import ConfigObj cuc_repo = os.sep.join(['ucframe', 'model', 'TaskCaseRepository']) all_cuc_content = {} for afile in os.listdir(cuc_repo): cuc_content = open(os.sep.join([cuc_repo, afile]), 'r').read().replace('\n', ' ') all_cuc_content[afile] = cuc_content ## calculate the similarity score import utils all_events = {} # preserves all event content and similarity for afile in all_cuc_content.keys(): ## [TOFIX] This is super handy code due to the bad structure of the CUC task case cuc = ConfigObj(os.sep.join([cuc_repo, afile]))[afile.split('.')[0]] cuc_id = cuc['Task-Meta']['taskId'] events = cuc['Event-Flow'] for event_id in events.keys(): all_events[(cuc_id, event_id)] = { 'content': events[event_id], 'similarity': utils.event_similarity(current_event, events[event_id]) } ## select the top K events similar_events_group = [] sorted_events = sorted(all_events.iteritems(), key=lambda kvt: kvt[1]['similarity'], reverse=True) top_k_events = sorted_events[ 1:6] # assume take the top 5 events, except the original one for an_event in top_k_events: # transfer back to dict format similar_events_group.append(an_event[1]) #similar_events_group[an_event[0][0]+'#'+an_event[0][1]] = an_event[1] return {'events': similar_events_group} @expose('json') def get_cuc(self, **kw): cuc_id = kw.keys()[0].strip() cuc_file = cuc_id + '.txt' cuc_repo = os.sep.join(['ucframe', 'model', 'TaskCaseRepository']) cuc_content = ConfigObj(os.sep.join([cuc_repo, cuc_file]))[cuc_id] return {'cuc': cuc_content} #@expose('json') #def similar_cucs(self, **kw): def similar_cucs(self, event_list): ''' event_list = [] # includes both precon, event, and postcon for key in kw.keys(): event_list.append(key.strip()) ''' # determine similar events ## load all cuc from configobj import ConfigObj cuc_repo = os.sep.join(['ucframe', 'model', 'TaskCaseRepository']) all_cuc_content = {} for afile in os.listdir(cuc_repo): cuc_content = open(os.sep.join([cuc_repo, afile]), 'r').read().replace('\n', ' ') all_cuc_content[afile] = cuc_content ## calculate the similarity score import utils all_cuc_similarity = {} # preserves all event content and similarity for afile in all_cuc_content.keys(): ## [TOFIX] This is super handy code due to the bad structure of the CUC task case cuc = ConfigObj(os.sep.join([cuc_repo, afile]))[afile.split('.')[0]] cuc_id = cuc['Task-Meta']['taskId'] cuc_name = cuc['Task-Meta']['taskName'] precons = cuc['Pre-Condition'] events = cuc['Event-Flow'] postcons = cuc['Post-Condition'] compare_event_list = precons.values() + events.values( ) + postcons.values() all_cuc_similarity[cuc_id] = { 'name': cuc_name, 'id': cuc_id, 'precons': precons, 'events': events, 'postcons': postcons, 'similarity': utils.mass_event_similarity(event_list, compare_event_list) } ## select the top K events similar_cucs_group = [] sorted_cucs = sorted(all_cuc_similarity.iteritems(), key=lambda kvt: kvt[1]['similarity'], reverse=True) top_k_cucs = sorted_cucs[ 1:6] # assume take the top 5 similar cucs, except the original one for a_cuc in top_k_cucs: # transfer back to dict format similar_cucs_group.append(a_cuc[1]) #similar_events_group[an_event[0][0]+'#'+an_event[0][1]] = an_event[1] print 'similar_cucs_group:', similar_cucs_group return {'cucs': similar_cucs_group} # [seLain] the code is basically the same with self.similar_events @expose('json') def similar_postcons(self, **kw): current_event = kw.keys()[0].strip() # determine similar events ## load all cuc from configobj import ConfigObj cuc_repo = os.sep.join(['ucframe', 'model', 'TaskCaseRepository']) all_cuc_content = {} for afile in os.listdir(cuc_repo): cuc_content = open(os.sep.join([cuc_repo, afile]), 'r').read().replace('\n', ' ') all_cuc_content[afile] = cuc_content ## calculate the similarity score import utils all_events = {} # preserves all event content and similarity for afile in all_cuc_content.keys(): ## [TOFIX] This is super handy code due to the bad structure of the CUC task case cuc = ConfigObj(os.sep.join([cuc_repo, afile]))[afile.split('.')[0]] cuc_id = cuc['Task-Meta']['taskId'] events = cuc['Post-Condition'] for event_id in events.keys(): all_events[(cuc_id, event_id)] = { 'content': events[event_id], 'similarity': utils.event_similarity(current_event, events[event_id]) } ## select the top K events similar_events_group = [] sorted_events = sorted(all_events.iteritems(), key=lambda kvt: kvt[1]['similarity'], reverse=True) top_k_events = sorted_events[ 1:6] # assume take the top 5 events, , except the original one for an_event in top_k_events: # transfer back to dict format similar_events_group.append(an_event[1]) #similar_events_group[an_event[0][0]+'#'+an_event[0][1]] = an_event[1] return {'postcons': similar_events_group} # [seLain] the code is basically the same with self.similar_events @expose('json') def similar_precons(self, **kw): current_event = kw.keys()[0].strip() # determine similar events ## load all cuc from configobj import ConfigObj cuc_repo = os.sep.join(['ucframe', 'model', 'TaskCaseRepository']) all_cuc_content = {} for afile in os.listdir(cuc_repo): cuc_content = open(os.sep.join([cuc_repo, afile]), 'r').read().replace('\n', ' ') all_cuc_content[afile] = cuc_content ## calculate the similarity score import utils all_events = {} # preserves all event content and similarity for afile in all_cuc_content.keys(): ## [TOFIX] This is super handy code due to the bad structure of the CUC task case cuc = ConfigObj(os.sep.join([cuc_repo, afile]))[afile.split('.')[0]] cuc_id = cuc['Task-Meta']['taskId'] events = cuc['Pre-Condition'] for event_id in events.keys(): all_events[(cuc_id, event_id)] = { 'content': events[event_id], 'similarity': utils.event_similarity(current_event, events[event_id]) } ## select the top K events similar_events_group = [] sorted_events = sorted(all_events.iteritems(), key=lambda kvt: kvt[1]['similarity'], reverse=True) top_k_events = sorted_events[ 1:6] # assume take the top 5 events, , except the original one for an_event in top_k_events: # transfer back to dict format similar_events_group.append(an_event[1]) #similar_events_group[an_event[0][0]+'#'+an_event[0][1]] = an_event[1] return {'precons': similar_events_group} def type_transform(self, text): if text == 'Actor': return '@' if text == 'Message': return '$' if text == 'System': return '*' if text == '@': return 'Actor' if text == '$': return 'Message' if text == '*': return 'System' def get_similar_tags(self, current_term, context_terms): # analyze the current word current_word = [current_term[1:], None] if current_term[0] == '@': current_word[1] = 'Actor' elif current_term[0] == '$': current_word[1] = 'Message' elif current_term[0] == '*': current_word[1] = 'System' else: # not a tag in AMS, return empty return [] nodes, edges = utils.get_pure_graph() # calc the word similarity from difflib import SequenceMatcher word_similarity = {} for anode in nodes: # if the same type but not the same node if anode[1] == current_word[1] and anode[0] != current_word[0]: key = self.type_transform(anode[1]) + anode[0] word_similarity[key] = SequenceMatcher(None, current_word[0], anode[0]).ratio() # [TODO] calc the context similarity ## get the context of all words context = {} for anode in nodes: ### predecessor -> anode -> successor, usually actor->message->system key = self.type_transform(anode[1]) + anode[0] context[key] = {'predecessors': [], 'successors': []} for aedge in edges: ### if anode is source if aedge[0][0] is anode[0] and aedge[1][0] not in context[key][ 'successors']: context[key]['successors'].append(aedge[1][0]) elif aedge[1][0] is anode[0] and aedge[0][0] not in context[ key]['predecessors']: context[key]['predecessors'].append(aedge[0][0]) ## get the context of current work cotext_current = {'predecessors': [], 'successors': []} current_index = context_terms.index(current_term) for aterm in context_terms: if context_terms.index(aterm) < current_index: cotext_current['predecessors'].append(aterm[1:]) elif context_terms.index(aterm) > current_index: cotext_current['successors'].append(aterm[1:]) ## calculate similarity by matching context context_similarity = {} for key in context.keys(): acontext = context[key] sim_predecessors = 0 sim_successors = 0 if len(acontext['predecessors']) is not 0: sim_predecessors = len([ val for val in cotext_current['predecessors'] if val in acontext['predecessors'] ]) / float(len(acontext['predecessors'])) if len(acontext['successors']) is not 0: sim_successors = len([ val for val in cotext_current['successors'] if val in acontext['successors'] ]) / float(len(acontext['successors'])) context_similarity[ key] = 0.5 * sim_predecessors + 0.5 * sim_successors # [TODO] combine the similarity for key in word_similarity.keys(): word_similarity[key] = round( 0.5 * word_similarity[key] + 0.5 * context_similarity[key], 2) # [TODO] extract the top similarity from operator import itemgetter sorted_tags = sorted(word_similarity.items(), key=itemgetter(1), reverse=True) return sorted_tags def get_term_definition(self, aterm): tags_def_repo = os.sep.join( ['ucframe', 'public', 'data', 'noun_def_repo']) if aterm.startswith('@'): content = aterm[1:] fname = os.sep.join([tags_def_repo, 'Actor_' + content + '.txt']) #print '[fname]', fname if os.path.isfile(fname): return ConfigObj(fname).dict() else: return None elif aterm.startswith('$'): content = aterm[1:] fname = os.sep.join([tags_def_repo, 'Message_' + content + '.txt']) #print '[fname]', fname if os.path.isfile(fname): return ConfigObj(fname).dict() else: return None elif aterm.startswith('*'): content = aterm[1:] fname = os.sep.join([tags_def_repo, 'System_' + content + '.txt']) #print '[fname]', fname if os.path.isfile(fname): return ConfigObj(fname).dict() else: return None else: return None # This method receives request for similar tags. # The similar tags are caculated by their adjencent terms # - kw: the input term # @expose('json') def local_input(self, **kw): print '[in local_input]', kw export_nodes_data = [] export_edges_data = [] # do local analysis local_nodes = [] export_nodes_data_id = 1 for key in kw.keys(): terms = kw[key].split(' ') for aterm in terms: if aterm.startswith('@'): if aterm not in local_nodes: local_nodes.append(aterm) node_text = aterm[1:] export_nodes_data.append({ 'id': export_nodes_data_id, 'reflexive': 'false', 'text': node_text, 'type': 'Actor' }) export_nodes_data_id += 1 elif aterm.startswith('$'): if aterm not in local_nodes: local_nodes.append(aterm) node_text = aterm[1:] export_nodes_data.append({ 'id': export_nodes_data_id, 'reflexive': 'false', 'text': node_text, 'type': 'Message' }) export_nodes_data_id += 1 elif aterm.startswith('*'): if aterm not in local_nodes: local_nodes.append(aterm) node_text = aterm[1:] export_nodes_data.append({ 'id': export_nodes_data_id, 'reflexive': 'false', 'text': node_text, 'type': 'System' }) export_nodes_data_id += 1 # return the json data to the page visualization import json jsonfile = open('local_graph.json', 'w') jsonfile.write(json.dumps(export_nodes_data)) jsonfile.close() jsonfile = open('local_edges.json', 'w') jsonfile.write(json.dumps(export_edges_data)) jsonfile.close() return {'nodes': export_nodes_data, 'edges': export_edges_data} # This method receives request for similar tags. # The similar tags are caculated by their adjencent terms # - kw: the input term # @expose('json') def tags_def(self, **kw): tags_def_repo = os.sep.join( ['ucframe', 'public', 'data', 'noun_def_repo']) matched_tags = [] current_terms = kw.keys()[0].strip().split(' ') # [TOFIX] handy code for aterm in current_terms: if aterm.startswith('@'): content = aterm[1:] fname = os.sep.join( [tags_def_repo, 'Actor_' + content + '.txt']) print '[fname]', fname if os.path.isfile(fname): matched_tags.append(ConfigObj(fname).dict()) elif aterm.startswith('$'): content = aterm[1:] fname = os.sep.join( [tags_def_repo, 'Message_' + content + '.txt']) if os.path.isfile(fname): matched_tags.append(ConfigObj(fname).dict()) elif aterm.startswith('*'): content = aterm[1:] fname = os.sep.join( [tags_def_repo, 'System_' + content + '.txt']) if os.path.isfile(fname): matched_tags.append(ConfigObj(fname).dict()) return {'tags': matched_tags} @expose('ucframe.templates.quality_metrics') def quality_metrics(self): import metrics GLR = metrics.GLR() ACT = metrics.ACT() ACTC = metrics.ACTC() ALLC = metrics.ALLC() AGLC = metrics.AGLC() AAC = metrics.AAC() NCR = metrics.NCR() GCI = metrics.GCI() return { 'metrics': { 'GLR': GLR, 'ACT': ACT, 'ACTC': ACTC, 'ALLC': ALLC, 'AGLC': AGLC, 'AAC': AAC, 'NCR': NCR, 'GCI': GCI } } @expose('ucframe.templates.terms_stat') def terms_stat(self): terms_data = {} fileLocation = os.sep.join( ['ucframe', 'model', 'Tag', 'Tag Table.txt']) TagTable = ConfigObj(fileLocation, encoding='UTF8') for tag_id in TagTable.keys(): tag = TagTable[tag_id] tag_text = tag['Name'] tag_type = tag['Category'] terms_data[tag_id] = { 'type': tag_type, 'text': tag_text, 'count': utils.term_occurence_count(tag_type, tag_text) } return {'terms_data': terms_data} @expose('ucframe.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('ucframe.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(page='environ', environment=request.environ) @expose('ucframe.templates.data') @expose('json') def data(self, **kw): """This method showcases how you can use the same controller for a data page and a display page""" return dict(page='data', params=kw) @expose('ucframe.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('ucframe.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('ucframe.templates.login') def login(self, came_from=lurl('/')): """Start the user login.""" login_counter = request.environ.get('repoze.who.logins', 0) if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from) @expose() def post_login(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) # Do not use tg.redirect with tg.url as it will add the mountpoint # of the application twice. return HTTPFound(location=came_from) @expose() def post_logout(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) return HTTPFound(location=came_from)
class RootController(BaseController): admin = AdminController(model, DBSession, config_type=AdminConfig, translations=config.sa_auth.translations) error = ErrorController() p = UserPortalController() symptom = SymptomController() def _before(self, *args, **kw): tmpl_context.project_name = "BlockMRS" @expose('blockmrs.templates.index') def index(self): """Handle the front-page.""" return dict(page='index') @expose('blockmrs.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('blockmrs.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('blockmrs.templates.login') def login(self, came_from=lurl('/portal'), failure=None, login='', signup=False): """Start the user login.""" if failure is not None: if failure == 'user-not-found': flash(_('User not found'), 'error') elif failure == 'invalid-password': flash(_('Invalid Password'), 'error') login_counter = request.environ.get('repoze.who.logins', 0) if failure is None and login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from, signup=signup, login=login) @expose() def post_login(self, came_from=lurl('/portal')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) # Do not use tg.redirect with tg.url as it will add the mountpoint # of the application twice. return HTTPFound(location=came_from) @expose() def post_logout(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) return HTTPFound(location=came_from) @expose() def portal(self): """Redirect the user to their portal.""" return HTTPFound(location=lurl('/p/'))
class RootController(BaseController): """ The root controller for the animals application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() admin = AdminController(model, DBSession, config_type=TGAdminConfig) error = ErrorController() def _before(self, *args, **kw): tmpl_context.project_name = "animals" @expose('animals.templates.index') def index(self): """Handle the front-page.""" return dict(page='index') @expose('animals.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('animals.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(page='environ', environment=request.environ) @expose('animals.templates.data') @expose('json') def data(self, **kw): """ This method showcases how you can use the same controller for a data page and a display page. """ return dict(page='data', params=kw) @expose('animals.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('animals.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') # @expose('animals.templates.login') # def login(self, came_from=lurl('/'), failure=None, login=''): # """Start the user login.""" # if failure is not None: # if failure == 'user-not-found': # flash(_('User not found'), 'error') # elif failure == 'invalid-password': # flash(_('Invalid Password'), 'error') # login_counter = request.environ.get('repoze.who.logins', 0) # if failure is None and login_counter > 0: # flash(_('Wrong credentials'), 'warning') # return dict(page='login', login_counter=str(login_counter), # came_from=came_from, login=login) # @expose() # def post_login(self, came_from=lurl('/')): # """ # Redirect the user to the initially requested page on successful # authentication or redirect her back to the login page if login failed. # """ # if not request.identity: # login_counter = request.environ.get('repoze.who.logins', 0) + 1 # redirect('/login', # params=dict(came_from=came_from, __logins=login_counter)) # userid = request.identity['repoze.who.userid'] # flash(_('Welcome back, %s!') % userid) # # Do not use tg.redirect with tg.url as it will add the mountpoint # # of the application twice. # return HTTPFound(location=came_from) # @expose() # def post_logout(self, came_from=lurl('/')): # """ # Redirect the user to the initially requested page on logout and say # goodbye as well. # """ # flash(_('We hope to see you soon!')) # return HTTPFound(location=came_from) @expose('json') def registe(self, user_name, password, email_address=''): ''' ''' # import ipdb;ipdb.set_trace() user = model.User() user.user_name = user_name user.password = password user.email_address = email_address # check registed user find_result = DBSession.query( model.User).filter_by(user_name=user_name).first() if find_result: return USER_EXIST try: DBSession.add(user) transaction.commit() return SUCCESS except Exception, e: transaction.abort() print 'error of registe: {}'.format(e) raise UNKNOW_ERROR
class RootController(BaseController): """ The root controller for the python.dispatch.ms application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ #allow_only = predicates.not_anonymous() secc = SecureController() admin = AdminController() log = LogController() notification = NotificationController() error = ErrorController() test = TestController() services = ServicesController() traffic = TrafficController() rabbit = RabbitController() lora = LoraController() pets = PetsController() images = ImagesController() api = ApiController() def _before(self, *args, **kw): tmpl_context.project_name = "pythondispatchms" @expose('pythondispatchms.templates.index') def index(self): """Handle the front-page.""" return dict(page='index') @expose('pythondispatchms.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('pythondispatchms.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose() def check(self): return "UP" @expose() def help(self): app_dir = os.getenv('dispatch_DIR') if app_dir is None: app_dir = os.getcwd() currentDirectory = app_dir #print(currentDirectory) with open(currentDirectory + '/HELP.md', 'r') as markdown_file: content = markdown_file.read() return markdown.markdown(content) @expose('pythondispatchms.templates.main') def main(self): """Handle the front-page.""" return dict(page='index') @expose('json') @expose('jsonp') def uplink(self, **kw): print(response.body) print(response.status) print(request.json_body) print("Entre") print(kw) print(repr(kw)) for k, v in kw.items(): print("{} {} ".format(k, v)) return 'ok' @expose() def join(self, **kw): for k, v in kw.items(): print("{} {} ".format(k, v)) return 'ok' @expose() def status(self, **kw): for k, v in kw.items(): print("{} {} ".format(k, v)) return 'ok' @expose() def location(self, **kw): for k, v in kw.items(): print("{} {} ".format(k, v)) return 'ok' @expose() def ack(self, **kw): for k, v in kw.items(): print("{} {} ".format(k, v)) return 'ok' @expose() def error(self, **kw): for k, v in kw.items(): print("{} {} ".format(k, v)) return 'ok' @expose() def listener(self, listenerID, **kw): currentListener = DBSession.query(Listeners).filter_by( listener_id=listenerID).first() if currentListener is None: newListener = Listeners() newListener.listener_id = listenerID newListener.name = "Not Defined" DBSession.add(newListener) DBSession.flush() if newListener.id is not None: for key, value in kw.items(): newfielditem = ListenerFields() newfielditem.field = key newfielditem.value = value newListener.fields.append(newfielditem) DBSession.add(newfielditem) DBSession.flush() #print("Admin LISTENER") Message.post("adminlistener", 'NEW' + "|") else: if currentListener.state == 1: #print("listern on") if currentListener.logstate == 1: # Enabled Logging currentListenerFields = DBSession.query( ListenerFields).filter_by( listeners_id=currentListener.id).all() mapper = {} for eachListenerField in currentListenerFields: if eachListenerField.assign != 0: mapper[eachListenerField. assign] = eachListenerField.field newListenerLog = ListenerLog() newListenerLog.time_stamp = datetime.utcnow() newListenerLog.listener_id = currentListener.listener_id newListenerLog.mapper_state = 1 if 1 in mapper: newListenerLog.imei = kw[mapper[1]] DBSession.add(newListenerLog) DBSession.flush() currentLog = newListenerLog.id allListenerUsers = DBSession.query(ListenerUsers).filter_by( userlisteners_id=currentListener.id).all() globalExpressionsRequiredbyListener = [] activeListenerUsers = [] for each_user in allListenerUsers: # Getting Users to know which expressions must evaluate #print("Getting users") if each_user.state == 1: #print("USER-->{} userlistener_id{}".format(each_user.user_name,each_user.userlisteners_id)) # If the user is active ---> get all the triggers requested by the user activeListenerUsers.append( dict(id=each_user.id, user_name=each_user.user_name)) currentUseId = each_user.id allUserTriggers = DBSession.query( UserTriggers).filter_by( listener_users_id=currentUseId).all() for eachUserTriger in allUserTriggers: # id=1 / Expression = EVENT_DESC=SOS and CLIENT_ID-510 # id=2 Expression = EVENT_DESC=Paro de Motor and CLIENT_ID=510 currenUserId = eachUserTriger.id allUserGlobalExpressions = DBSession.query( UserGlobalExp).filter_by( usertriggers_id=currenUserId).all() for eachGlobalExpression in allUserGlobalExpressions: found = False for eitem in globalExpressionsRequiredbyListener: if eitem[ 0] == eachGlobalExpression.global_exp_id: found = True if not found: globalExpressionsRequiredbyListener.append( (eachGlobalExpression.global_exp_id, each_user.userlisteners_id)) #print((eachGlobalExpression.global_exp_id,each_user.userlisteners_id)) globalExpState = {} for eachExpression in globalExpressionsRequiredbyListener: # id=1 /Expression EVENT_DESC=SOS /expression_id=3 /expression_op = / expression_value = SOS currentGlobalExpression = DBSession.query( ListenerExpressions).filter_by( id=eachExpression[0]).first() if currentListener.logstate == 1: currentListenerLog = DBSession.query( ListenerLog).filter_by(id=currentLog).first() if currentGlobalExpression is not None: # EVAL EXPRESSIONS currentField = DBSession.query( ListenerFields).filter_by( assign=currentGlobalExpression.expression_id, listeners_id=eachExpression[1]).first() if currentField is not None: currentFieldName = currentField.field operator = "==" if currentGlobalExpression.expression_op == "=" else currentGlobalExpression.expression_op if currentFieldName in kw: utf8 = URLunicode() currentFieldvalue = utf8.decode( kw[currentFieldName]) #evalexpression='kw["'+currentFieldName+'"]'+operator+'"'+currentGlobalExpression.expression_value+'"' evalexpression = '"' + currentFieldvalue + '"' + operator + '"' + currentGlobalExpression.expression_value + '"' isfieldfound = '"' + currentFieldName + '" in kw' else: evalexpression = "" isfieldfound = False # print("EVAL EXPRESSION:{}".format(evalexpression)) # print("Field Exists:{} ---> {}".format(isfieldfound,eval(isfieldfound))) # print("Value:{}".format(currentFieldvalue)) try: booleanEvalState = eval(evalexpression) except Exception as e: #print("ERROR:{}".format(e)) booleanEvalState = False #print("id:{} Exp:{} {} --> {} ".format(eachExpression,currentGlobalExpression.expression,evalexpression,booleanEvalState)) globalExpState[ eachExpression[0]] = booleanEvalState # # Listener Log Fields # if currentListener.logstate == 1: newLogFields = ListenerLogFields() newLogFields.field = currentFieldName newLogFields.assigned_to = currentGlobalExpression.expression_id newLogFields.value = currentGlobalExpression.expression_value newLogFields.isfieldfound = eval(isfieldfound) newLogFields.expression = currentGlobalExpression.expression newLogFields.expression_state = booleanEvalState newLogFields.received = kw[currentFieldName] currentListenerLog.fields.append(newLogFields) DBSession.add(newLogFields) DBSession.flush() if currentListener.logstate == 1: currentListenerLog = DBSession.query( ListenerLog).filter_by(id=currentLog).first() #for k,v in globalExpState.items(): #print("KEY :{} VALUE:{}".format(k,v)) #### ### GET IMEI and pluto once #### currentIMEI = DBSession.query(ListenerFields).filter_by( listeners_id=currentListener.id, assign=1).first() if currentIMEI.field in kw: imei = kw[currentIMEI.field] else: imei = "" #print("IMEI:{}".format(imei)) pluto = Rest() parameters = {} parameters['imei'] = imei venusTicket = "" attended_state = "N" sound = 1 imeiData = pluto.get( app_globals.domainpluto + "/services/imeiInfo", parameters) for eachActiveUser in activeListenerUsers: #print("{} {}".format(eachActiveUser['id'],eachActiveUser['user_name'])) toEvalUserTriggers = DBSession.query( UserTriggers).filter_by( listener_users_id=eachActiveUser['id']).all() for eachEvalTriggers in toEvalUserTriggers: priority = eachEvalTriggers.priority globalExpToEval = DBSession.query( UserGlobalExp).filter_by( usertriggers_id=eachEvalTriggers.id).all() sumOfexpressionsResult = True for eachGlobalExpToEval in globalExpToEval: #print("Expression:{} --> {}".format(eachGlobalExpToEval.global_exp_id,globalExpState[eachGlobalExpToEval.global_exp_id])) k = eachGlobalExpToEval if globalExpState[eachGlobalExpToEval. global_exp_id] == False: sumOfexpressionsResult = False break encoded = eachEvalTriggers.expression.encode('utf8') #print("Global Expression:{} Traffic -->: {}".format(encoded,sumOfexpressionsResult)) currentUserFiltersExpression = '' #################### # # # Checar el valor # # de abajo # #################### userTriggerExpressionState = True currentUserFilters = DBSession.query( UserFilters).filter_by( user_trigger_id=eachEvalTriggers.id).first() if currentUserFilters is not None: eventCounter = currentUserFilters.counter + 1 currentUserFiltersExpression = currentUserFilters.expression senTicketVenusExp = currentUserFilters.reset_expression #### Checar #print("UserFilters ID: {} For this group{} Eval:{} --->{}".format(currentUserFilters.id,eachActiveUser['user_name'],currentUserFiltersExpression,userTriggerExpressionState)) #print("Imei:{}".format(imei)) #print("send to discarded when: {}".format(currentUserFiltersExpression)) #print("Send Ticket to venus when:{}".format(senTicketVenusExp)) else: userTriggerExpressionState = True currentUserFiltersExpression = 'Not Defined' # # Listener Log Users # if currentListener.logstate == 1: newLogUsers = ListenerLogUsers() newLogUsers.user_name = eachActiveUser['user_name'] newLogUsers.trigger_expr = eachEvalTriggers.expression newLogUsers.trigger_expr_state = sumOfexpressionsResult newLogUsers.filter_expr = currentUserFiltersExpression newLogUsers.filter_expr_state = userTriggerExpressionState currentListenerLog.users.append(newLogUsers) DBSession.add(newLogUsers) DBSession.flush() Message.post("logListener", 'NEW' + "|") if sumOfexpressionsResult and userTriggerExpressionState: ################ # CHECK REPEAT only if there are filters to evaluete # ################ if currentUserFilters is not None: venusTicket = '' localtz = 'America/Mexico_City' oper_localtime = datetime.now( pytz.timezone(localtz)) logImeiEvent = DBSession.query( logImei).filter_by( imei=imei, event_desc=eachEvalTriggers. expression[11:], group_name=eachActiveUser['user_name'] ).first() if logImeiEvent is None: newLogImei = logImei() newLogImei.imei = imei newLogImei.event_desc = eachEvalTriggers.expression[ 11:] newLogImei.group_name = eachActiveUser[ 'user_name'] newLogImei.counter = 1 newLogImei.hour = datetime.utcnow().hour newLogImei.hour_counter = 1 newLogImei.weekday = oper_localtime.strftime( "%A") newLogImei.user_filters_id = currentUserFilters.id hour = oper_localtime.strftime("%H:%M") if hour >= "06:00" and hour <= "12:00": newLogImei.morning = 1 else: if hour >= "12:00" and hour <= "18:00": newLogImei.afternoon = 1 else: if hour >= "18:00" and hour <= "23:59": newLogImei.night = 1 else: if hour >= "00:00" and hour <= "06:00": newLogImei.early_morning = 1 DBSession.add(newLogImei) else: time_stamp = logImeiEvent.time_stamp time_diff = datetime.utcnow() - time_stamp days_difference = time_diff.days #print("Time difference since last time stamp in days:{}".format(time_diff.days)) if logImeiEvent.hour == datetime.utcnow( ).hour: logImeiEvent.hour_counter += 1 if logImeiEvent.hour_counter > 15: #send to Venus venus = Rest() venusUrl = "http://venus.gpscontrol.com.mx/dispatch/create_ticket?client_id=" + str( imeiData['client_id'] ) + "&last_report=" + str( imeiData['last_report'] ) + "&folio=0" + "&imei=" + imei + "&comm=" + "Se detecto una inconcistencia en las alertas" res = requests.get(venusUrl) if res is not None: response = res.json() if 'Ticket' in response: venusTicket = response[ 'Ticket'] else: logImeiEvent.hour = datetime.utcnow( ).hour logImeiEvent.hour_counter = 1 if days_difference > 0: logImeiEvent.morning = 0 logImeiEvent.afternoon = 0 logImeiEvent.night = 0 logImeiEvent.early_morning = 0 logImeiEvent.counter = 1 logImeiEvent.weekday = oper_localtime.strftime( "%A") logImeiEvent.time_stamp = datetime.utcnow( ) else: logImeiEvent.counter = logImeiEvent.counter + 1 hour = oper_localtime.strftime("%H:%M") if hour >= "06:00" and hour <= "12:00": logImeiEvent.morning += 1 else: if hour >= "12:00" and hour <= "18:00": logImeiEvent.afternoon += 1 else: if hour >= "18:00" and hour <= "23:59": logImeiEvent.night += 1 else: if hour >= "00:00" and hour <= "06:00": logImeiEvent.early_morning += 1 logImeiEvent.weekday = oper_localtime.strftime( "%A") newLogExpression = "logImeiEvent." + currentUserFiltersExpression evalnewLogExp = eval(newLogExpression) userTriggerExpressionState = True #print("EXPRESSION REJECTED:{} ---> {}".format(newLogExpression,evalnewLogExp)) if evalnewLogExp: attended_state = "R" #if venusTicket=='': #else: # attended_state = "N" DBSession.flush() # resetExpText=currentUserFilters.reset_expression # #print("Reset exp:{}".format(resetExpText)) # resetExpText=resetExpText.replace("=","==") # resetExpression=eval(resetExpText) # if resetExpression: # eventCounter=0 # if sumOfexpressionsResult: # currentUserFilters.counter=eventCounter ################ # END REPEAT # ################ #CREATE TRAFFIC FOR THE USER currentListenerFields = DBSession.query( ListenerFields).filter_by( listeners_id=currentListener.id).all() mapper = {} for eachListenerField in currentListenerFields: if eachListenerField.assign != 0: mapper[eachListenerField. assign] = eachListenerField.field newTraffic = Traffic() sound = eachEvalTriggers.sound #print("SOUND: {}".format(sound)) newTraffic.attended_state = attended_state if imeiData["error"] == "ok": newTraffic.user_name = imeiData['application'] if 1 in mapper: newTraffic.imei = kw[mapper[1]] if 2 in mapper: if kw[mapper[2]] == "": newTraffic.event_id = 0 else: newTraffic.event_id = kw[mapper[2]] if 3 in mapper: newTraffic.event_desc = kw[mapper[3]] else: eventsid = kw[mapper[2]] events = DBSession.query(Events).filter_by( event_id=eventsid).first() if events is not None: newTraffic.event_desc = events.event_desc else: newTraffic.event_desc = "" if 4 in mapper: newTraffic.latitude = kw[mapper[4]] if 5 in mapper: newTraffic.longitude = kw[mapper[5]] if 6 in mapper: if kw[mapper[6]] == "": speed = 0 else: speed = int(float(kw[mapper[6]])) newTraffic.speed = speed if 7 in mapper: newTraffic.azimuth = kw[mapper[7]] if 8 in mapper: newTraffic.valid = kw[mapper[8]] if 9 in mapper: newTraffic.event_time = kw[mapper[9]] if 10 in mapper: newTraffic.client_id = kw[mapper[10]] if 11 in mapper: vehicleData = kw[mapper[11]] vehicleCheck = vehicleData.replace(" ", "") if len(vehicleData) > 0: newTraffic.vehicle = vehicleData else: if imeiData["error"] == "ok": if imeiData[ "brand"] is not None and imeiData[ "model"] is not None: newTraffic.vehicle = imeiData[ "brand"] + ' ' + imeiData[ "model"] + ' ' else: if imeiData["error"] == "ok": if imeiData[ "brand"] is not None and imeiData[ "model"] is not None: newTraffic.vehicle = imeiData[ "brand"] + ' ' + imeiData[ "model"] + ' ' if 12 in mapper: if kw[mapper[12]] == '': kw[mapper[12]] = '0' newTraffic.voltage = kw[mapper[12]] if 13 in mapper: newTraffic.internal_id = kw[mapper[13]] if 14 in mapper: if kw[mapper[14]] == '': newTraffic.mcc = 0 else: newTraffic.mcc = kw[mapper[14]] if 15 in mapper: if kw[mapper[15]] == '': newTraffic.mnc = 0 else: newTraffic.mnc = kw[mapper[15]] if 16 in mapper: if kw[mapper[16]] == '': newTraffic.lac = 0 else: newTraffic.lac = kw[mapper[16]] if 17 in mapper: if kw[mapper[17]] == '': newTraffic.cellid = 0 else: newTraffic.cellid = kw[mapper[17]] newTraffic.user = eachActiveUser['user_name'] newTraffic.priority = priority localtz = 'America/Mexico_City' if 9 in mapper: cuda = kw[mapper[9]] cuda = cuda[:19] dateconversion = datetime.strptime( cuda, '%Y-%m-%dT%H:%M:%S') oper_utc = arrow.get(dateconversion) oper_localtime = oper_utc.to(localtz) else: oper_localtime = datetime.now( pytz.timezone(localtz)) nd = "Evento no definido" if 3 in mapper: nd = kw[mapper[3]] nd = nd.lstrip().rstrip() if len(nd) == 0: nd = "Evento no definido:" + newTraffic.event_desc else: eventsid = kw[mapper[2]] events = DBSession.query(Events).filter_by( event_id=eventsid).first() if events is not None: nd = events.event_desc #print("-------->>> user:{}".format(eachActiveUser['user_name'])) ############################ # logImeiRecord = DBSession.query(logImei).filter_by(imei=parameters['imei'],event_desc=nd,group_name=eachActiveUser['user_name']).first() # if mapper[2] in kw: # if kw[mapper[2]]=="99": # logImeiRecord = None # if logImeiRecord is not None: # #print("FOUND!!!!->{}".format(eachActiveUser['user_name'])) # newTraffic.attended_state = "R" # hour = oper_localtime.strftime("%H:%M") # if hour >= "06:00" and hour <= "12:00": # logImeiRecord.morning += 1 # else: # if hour >= "12:00" and hour <= "18:00": # logImeiRecord.afternoon += 1 # else: # if hour >= "18:00" and hour <= "23:59": # logImeiRecord.night += 1 # else: # if hour >= "00:00" and hour <= "06:00": # logImeiRecord.early_morning += 1 # logImeiRecord.counter=logImeiRecord.counter+1 # if logImeiRecord.counter>100: # logImeiRecord.counter=0 # logImeiRecord.morning = 0 # logImeiRecord.afternoon = 0 # logImeiRecord.night = 0 # logImeiRecord.early_morning = 0 # logImeiRecord.group_name = eachActiveUser['user_name'] # if logImeiRecord.counter==2: # if 'client_id' in imeiData and 'last_report' in imeiData: # venus=Rest() # venusUrl = "http://venus.gpscontrol.com.mx/dispatch/create_ticket?client_id=" + str(imeiData['client_id']) + "&last_report=" + str(imeiData['last_report']) + "&folio=0" + "&imei=" + imei + "&comm=" + "Ignorar Rodo... Cierrala,.. Se detecto una inconcistencia en las alertas" # res = requests.get(venusUrl) # if res is not None: # response=res.json() # if 'Ticket' in response: # venusTicket = response['Ticket'] # # else: # nd = "Evento no definido" # if 3 in mapper: # nd = kw[mapper[3]] # nd = nd.lstrip().rstrip() # if len(nd) == 0: # nd = "Evento no definido:" + newTraffic.event_desc # else: # eventsid = kw[mapper[2]] # events = DBSession.query(Events).filter_by(event_id=eventsid).first() # if events is not None: # nd = events.event_desc # newLogImei=logImei() # newLogImei.imei=parameters['imei'] # newLogImei.event_desc=nd # newLogImei.counter=1 # newLogImei.weekday = oper_localtime.strftime("%A") # newLogImei.group_name = eachActiveUser['user_name'] # DBSession.add(newLogImei) # ############################ DBSession.add(newTraffic) DBSession.flush() #print("Sound: {}".format(sound)) if newTraffic.attended_state == "N": Message.post( "trafficlistener_" + eachActiveUser['user_name'], 'RELOAD' + "|" + str(sound)) elif newTraffic.attended_state == "R": Message.post( "rejectedlistener_" + eachActiveUser['user_name'], 'RELOAD' + "|" + str(sound)) if venusTicket != "": searchticket = DBSession.query( Tickets).filter_by( ticket=venusTicket).first() if searchticket is None: newTickets = Tickets() newTickets.traffic_id = newTraffic.id newTickets.ticket = venusTicket newTickets.comment = "Se detecto una inconcistencia en las alertas" DBSession.add(newTickets) DBSession.flush() return 'ok' # mysql> select event_id,event_desc,user_name,event_time,user,latitude,longitude,imei,speed,azimuth,event_time,time_stamp,priority from traffic where id=42968; # +----------+------------+--------------------------+---------------------+------------+-----------+------------+-----------------+-------+------------+---------------------+---------------------+----------+ # | event_id | event_desc | user_name | event_time | user | latitude | longitude | imei | speed | azimuth | event_time | time_stamp | priority | # +----------+------------+--------------------------+---------------------+------------+-----------+------------+-----------------+-------+------------+---------------------+---------------------+----------+ # | 1 | SOS | 99 NCARGOS S DE RL DE CV | 2018-08-28 16:46:49 | ManagerGPS | 19.366170 | -99.186310 | 864507035846863 | 0.00 | 287.000000 | 2018-08-28 16:46:49 | 2018-08-28 16:46:52 | 1 | # +----------+------------+--------------------------+---------------------+------------+-----------+------------+-----------------+-------+------------+---------------------+---------------------+----------+ # vehicle = 3B6WW Yamaha YBR 125 LBPKE097XF0489255 Roja 3B6WW @expose('json') def addTraffic(self, **kw): fields = 'event_id,event_desc,user_name,user,latitude,longitude,imei,speed,azimuth,priority,vehicle,valid,dedicated_id' error = 'Campos faltantes:' errorName = "" for item in fields.split(","): if not item in kw: errorName = errorName + item + "," if errorName == "": newTraffic = Traffic() for item in fields.split(","): setattr(newTraffic, item, kw[item]) DBSession.add(newTraffic) DBSession.flush() Message.post("trafficlistener_" + kw['user'], 'RELOAD' + "|") return dict(error="ok") return dict(error=error + errorName[:-1]) @expose('json') def storePosition(self, **kw): if 'latitude' in kw and 'longitude' in kw: query = DBSession.query(Position).filter_by(id=1).first() if query is None: new = Position() new.id = 1 new.latitude = kw['latitude'] new.longitude = kw['longitude'] DBSession.add(new) print("added") else: query.latitude = kw['latitude'] query.longitude = kw['longitude'] print("moded") DBSession.flush() return dict(error="ok") else: return dict(error="nok") @expose('json') def getPosition(self, **kw): query = DBSession.query(Position).filter_by(id=1).first() return dict(latitude=query.latitude, longitude=query.longitude) @expose('json') def getBooks(self, **kw): books = [] books.append(dict(title="Sharks", edition="First")) books.append(dict(title="Python Programming", edition="First")) books.append(dict(title="Java Programming", edition="First")) return dict(books=books)
def test_wrong_user(self): environ = make_environ('andreina') p = predicates.is_user('gustavo') self.eval_unmet_predicate(p, environ, 'The current user must be "gustavo"')
class RootController(BaseController): """ The root controller for the wiki20 application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() admin = AdminController(model, DBSession, config_type=TGAdminConfig) error = ErrorController() def _before(self, *args, **kw): tmpl_context.project_name = "wiki20" @expose('wiki20.templates.page') def _default(self, pagename="FrontPage"): from sqlalchemy.exc import InvalidRequestError try: page = DBSession.query(Page).filter_by(pagename=pagename).one() except InvalidRequestError: raise redirect("notfound", params={"pagename": pagename}) content = publish_parts(page.data, writer_name="html")["html_body"] root = url('/') content = wikiwords.sub(r'<a href="%s\1">\1</a>' % root, content) return dict(content=content, wikipage=page) @expose(template="wiki20.templates.edit") def edit(self, pagename): page = DBSession.query(Page).filter_by(pagename=pagename).one() return dict(wikipage=page) @expose("wiki20.templates.edit") def notfound(self, pagename): page = Page(pagename=pagename, data="") DBSession.add(page) return dict(wikipage=page) @expose("wiki20.templates.pagelist") def pagelist(self): pages = [ page.pagename for page in DBSession.query(Page).order_by(Page.pagename) ] return dict(pages=pages) @expose() def save(self, pagename, data, submit): page = DBSession.query(Page).filter_by(pagename=pagename).one() page.data = data redirect("/" + pagename) @expose('wiki20.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('wiki20.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(page='environ', environment=request.environ) @expose('wiki20.templates.data') @expose('json') def data(self, **kw): """ This method showcases how you can use the same controller for a data page and a display page. """ return dict(page='data', params=kw) @expose('wiki20.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('wiki20.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('wiki20.templates.login') def login(self, came_from=lurl('/'), failure=None, login=''): """Start the user login.""" if failure is not None: if failure == 'user-not-found': flash(_('User not found'), 'error') elif failure == 'invalid-password': flash(_('Invalid Password'), 'error') login_counter = request.environ.get('repoze.who.logins', 0) if failure is None and login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from, login=login) @expose() def post_login(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) # Do not use tg.redirect with tg.url as it will add the mountpoint # of the application twice. return HTTPFound(location=came_from) @expose() def post_logout(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) return HTTPFound(location=came_from)
class RootController(BaseController): """ The root controller for the sail application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() admin = AdminController(model, DBSession, config_type=TGAdminConfig) main = MainController() error = ErrorController() def _before(self, *args, **kw): tmpl_context.project_name = "sail" @expose('sail.templates.index') def index(self): """Handle the front-page.""" return dict(page='index') @expose('sail.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('sail.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(page='environ', environment=request.environ) @expose('sail.templates.data') @expose('json') def data(self, **kw): """This method showcases how you can use the same controller for a data page and a display page""" return dict(page='data', params=kw) @expose('sail.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('sail.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('sail.templates.login') def login(self, came_from=lurl('/')): """Start the user login.""" login_counter = request.environ.get('repoze.who.logins', 0) if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from) @expose() def post_login(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) # Do not use tg.redirect with tg.url as it will add the mountpoint # of the application twice. return HTTPFound(location=came_from) @expose() def post_logout(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) return HTTPFound(location=came_from)
class RootController(BaseController): """ The root controller for the fortressd application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ # secc = SecureController() # admin = AdminController(model, DBSession, config_type=FortressAdminConfig) error = ErrorController() profile = ProfileController() authorizations = AuthorizationController() terminal = TerminalController() management = ManagementController() settings = SettingController() def _before(self, *args, **kw): tmpl_context.project_name = _("FORTRESSD") @expose('fortress.templates.index') def index(self): """Handle the front-page.""" # log.debug("Default Root Index .................") return dict(page='index') @expose('fortress.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') # @expose('fortress.templates.management.index') # @require(predicates.has_permission('administration', msg=l_('Only for administrators'))) # def management(self): # """This method showcases TG's access to the wsgi environment.""" # return dict(page='management', environment=request.environ) # # # @expose('fortress.templates.settings.index') # @require(predicates.has_permission('administration', msg=l_('Only for administrators'))) # def settings(self, **kw): # """ # This method showcases how you can use the same controller # for a data page and a display page. # """ # return dict(page='settings', params=kw) @expose('fortress.templates.index') @require( predicates.has_permission('administration', msg=l_('Only for administrators'))) def admin_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='administrator stuff') @expose('fortress.templates.index') @require(predicates.is_user('operate', msg=l_('Only for the operators'))) def operator_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='operator stuff') @expose('fortress.templates.login') def login(self, came_from=lurl('/'), failure=None, login=''): """Start the user login.""" if failure is not None: if failure == 'user-not-found': flash(_('User not found'), 'error') elif failure == 'invalid-password': flash(_('Invalid Password'), 'error') login_counter = request.environ.get('repoze.who.logins', 0) if failure is None and login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from, login=login) @expose() def post_login(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) # userid = request.identity['repoze.who.userid'] user = request.identity['user'] log.debug(">>> request.identity: %s", request.identity.items()) flash(_('Welcome back, %s!') % user.display_name) # Do not use tg.redirect with tg.url as it will add the mountpoint # of the application twice. return HTTPFound(location=came_from) @expose() def post_logout(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) return HTTPFound(location=came_from)
class SmartDenialAllowOnly(TGController): allow_only = require(is_user('developer'), smart_denial=True) @expose('json') def data(self): return {'key': 'value'}
class RootController(BaseController): """ The root controller for the python.dispatch.ms application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ #allow_only = predicates.not_anonymous() secc = SecureController() admin = AdminController() log = LogController() notification = NotificationController() error = ErrorController() services = ServicesController() traffic = TrafficController() rabbit = RabbitController() test = TestController() def _before(self, *args, **kw): tmpl_context.project_name = "pythondispatchms" @expose('pythondispatchms.templates.index') def index(self): """Handle the front-page.""" return dict(page='index') @expose('pythondispatchms.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('pythondispatchms.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose() def check(self): return "UP" @expose() def help(self): app_dir = os.getenv('dispatch_DIR') if app_dir is None: app_dir = os.getcwd() currentDirectory = app_dir #print(currentDirectory) with open(currentDirectory + '/HELP.md', 'r') as markdown_file: content = markdown_file.read() return markdown.markdown(content) @expose('pythondispatchms.templates.main') def main(self): """Handle the front-page.""" return dict(page='index') @expose() def listener(self, listenerID, **kw): currentListener = DBSession.query(Listeners).filter_by( listener_id=listenerID).first() if currentListener is None: newListener = Listeners() newListener.listener_id = listenerID newListener.name = "Not Defined" DBSession.add(newListener) DBSession.flush() if newListener.id is not None: for key, value in kw.items(): newfielditem = ListenerFields() newfielditem.field = key newfielditem.value = value newListener.fields.append(newfielditem) DBSession.add(newfielditem) DBSession.flush() #print("Admin LISTENER") Message.post("adminlistener", 'NEW' + "|") else: if currentListener.state == 0: # The listener is off --> write log and finish listener newListenerLog = ListenerLog() newListenerLog.time_stamp = datetime.utcnow() newListenerLog.listener_id = currentListener.listener_id newListenerLog.mapper_state = 3 DBSession.add(newListenerLog) DBSession.flush() else: # Starting Log newListenerLog = ListenerLog() newListenerLog.time_stamp = datetime.utcnow() newListenerLog.listener_id = currentListener.listener_id newListenerLog.mapper_state = 1 DBSession.add(newListenerLog) DBSession.flush() currentLog = newListenerLog.id allListenerUsers = DBSession.query(ListenerUsers).filter_by( userlisteners_id=currentListener.id).all() globalExpressionsRequiredbyListener = [] activeListenerUsers = [] for each_user in allListenerUsers: # Getting Users to know which expressions must evaluate # jorge # diego if each_user.state == 1: #print("USER-->{} userlistener_id{}".format(each_user.user_name,each_user.userlisteners_id)) # If the user is active ---> get all the triggers requested by the user activeListenerUsers.append( dict(id=each_user.id, user_name=each_user.user_name)) currentUseId = each_user.id allUserTriggers = DBSession.query( UserTriggers).filter_by( listener_users_id=currentUseId).all() for eachUserTriger in allUserTriggers: # id=1 / Expression = EVENT_DESC=SOS and CLIENT_ID-510 # id=2 Expression = EVENT_DESC=Paro de Motor and CLIENT_ID=510 currenUserId = eachUserTriger.id allUserGlobalExpressions = DBSession.query( UserGlobalExp).filter_by( usertriggers_id=currenUserId).all() for eachGlobalExpression in allUserGlobalExpressions: found = False for eitem in globalExpressionsRequiredbyListener: if eitem[ 0] == eachGlobalExpression.global_exp_id: found = True if not found: globalExpressionsRequiredbyListener.append( (eachGlobalExpression.global_exp_id, each_user.userlisteners_id)) #print((eachGlobalExpression.global_exp_id,each_user.userlisteners_id)) globalExpState = {} for eachExpression in globalExpressionsRequiredbyListener: # id=1 /Expression EVENT_DESC=SOS /expression_id=3 /expression_op = / expression_value = SOS currentGlobalExpression = DBSession.query( ListenerExpressions).filter_by( id=eachExpression[0]).first() currentListenerLog = DBSession.query( ListenerLog).filter_by(id=currentLog).first() if currentGlobalExpression is not None: # EVAL EXPRESSIONS currentField = DBSession.query( ListenerFields).filter_by( assign=currentGlobalExpression.expression_id, listeners_id=eachExpression[1]).first() if currentField is not None: currentFieldName = currentField.field operator = "==" if currentGlobalExpression.expression_op == "=" else currentGlobalExpression.expression_op if currentFieldName in kw: utf8 = URLunicode() currentFieldvalue = utf8.decode( kw[currentFieldName]) #evalexpression='kw["'+currentFieldName+'"]'+operator+'"'+currentGlobalExpression.expression_value+'"' evalexpression = '"' + currentFieldvalue + '"' + operator + '"' + currentGlobalExpression.expression_value + '"' isfieldfound = '"' + currentFieldName + '" in kw' else: evalexpression = "" isfieldfound = False #print("EVAL EXPRESSION:{}".format(evalexpression)) #print("Field Exists:{} ---> {}".format(isfieldfound,eval(isfieldfound))) #print("Value:{}".format(currentFieldvalue)) try: booleanEvalState = eval(evalexpression) except Exception as e: #print("ERROR:{}".format(e)) booleanEvalState = False #print("id:{} Exp:{} {} --> {} ".format(eachExpression,currentGlobalExpression.expression,evalexpression,booleanEvalState)) globalExpState[ eachExpression[0]] = booleanEvalState newLogFields = ListenerLogFields() newLogFields.field = currentFieldName newLogFields.assigned_to = currentGlobalExpression.expression_id newLogFields.value = currentGlobalExpression.expression_value newLogFields.isfieldfound = eval(isfieldfound) newLogFields.expression = currentGlobalExpression.expression newLogFields.expression_state = booleanEvalState newLogFields.received = kw[currentFieldName] currentListenerLog.fields.append(newLogFields) DBSession.add(newLogFields) DBSession.flush() currentListenerLog = DBSession.query(ListenerLog).filter_by( id=currentLog).first() #for k,v in globalExpState.items(): #print("KEY :{} VALUE:{}".format(k,v)) #### ### GET IMEI and pluto once #### currentIMEI = DBSession.query(ListenerFields).filter_by( listeners_id=currentListener.id, assign=1).first() if currentIMEI.field in kw: imei = kw[currentIMEI.field] else: imei = "" #print("IMEI:{}".format(imei)) pluto = Rest() parameters = {} parameters['imei'] = imei venusTicket = "" imeiData = pluto.get( app_globals.domainpluto + "/services/imeiInfo", parameters) for eachActiveUser in activeListenerUsers: #print("{} {}".format(eachActiveUser['id'],eachActiveUser['user_name'])) toEvalUserTriggers = DBSession.query( UserTriggers).filter_by( listener_users_id=eachActiveUser['id']).all() for eachEvalTriggers in toEvalUserTriggers: priority = eachEvalTriggers.priority globalExpToEval = DBSession.query( UserGlobalExp).filter_by( usertriggers_id=eachEvalTriggers.id).all() sumOfexpressionsResult = True for eachGlobalExpToEval in globalExpToEval: #print("Expression:{} --> {}".format(eachGlobalExpToEval.global_exp_id,globalExpState[eachGlobalExpToEval.global_exp_id])) k = eachGlobalExpToEval if globalExpState[eachGlobalExpToEval. global_exp_id] == False: sumOfexpressionsResult = False break #print("Global Expression:{} Traffic -->: {}".format(eachEvalTriggers.expression,sumOfexpressionsResult)) currentUserFiltersExpression = '' userTriggerExpressionState = False currentUserFilters = DBSession.query( UserFilters).filter_by( user_trigger_id=eachEvalTriggers.id).first() if currentUserFilters is not None: eventCounter = currentUserFilters.counter + 1 currentUserFiltersExpression = currentUserFilters.expression userTriggerExpressionState = eval( currentUserFiltersExpression) #print("Eval:{} --->{}".format(currentUserFiltersExpression,userTriggerExpressionState)) resetExpText = currentUserFilters.reset_expression #print("Reset exp:{}".format(resetExpText)) resetExpText = resetExpText.replace("=", "==") resetExpression = eval(resetExpText) if resetExpression: eventCounter = 0 if sumOfexpressionsResult: currentUserFilters.counter = eventCounter DBSession.flush() else: userTriggerExpressionState = True currentUserFiltersExpression = 'Not Defined' newLogUsers = ListenerLogUsers() newLogUsers.user_name = eachActiveUser['user_name'] newLogUsers.trigger_expr = eachEvalTriggers.expression newLogUsers.trigger_expr_state = sumOfexpressionsResult newLogUsers.filter_expr = currentUserFiltersExpression newLogUsers.filter_expr_state = userTriggerExpressionState currentListenerLog.users.append(newLogUsers) DBSession.add(newLogUsers) DBSession.flush() Message.post("logListener", 'NEW' + "|") if sumOfexpressionsResult and userTriggerExpressionState: #CREATE TRAFFIC FOR THE USER currentListenerFields = DBSession.query( ListenerFields).filter_by( listeners_id=currentListener.id).all() mapper = {} for eachListenerField in currentListenerFields: if eachListenerField.assign != 0: mapper[eachListenerField. assign] = eachListenerField.field newTraffic = Traffic() if imeiData["error"] == "ok": newTraffic.user_name = imeiData['application'] if 1 in mapper: newTraffic.imei = kw[mapper[1]] if 2 in mapper: if kw[mapper[2]] == "": newTraffic.event_id = 0 else: newTraffic.event_id = kw[mapper[2]] if 3 in mapper: newTraffic.event_desc = kw[mapper[3]] else: eventsid = kw[mapper[2]] events = DBSession.query(Events).filter_by( event_id=eventsid).first() if events is not None: newTraffic.event_desc = events.event_desc else: newTraffic.event_desc = "" if 4 in mapper: newTraffic.latitude = kw[mapper[4]] if 5 in mapper: newTraffic.longitude = kw[mapper[5]] if 6 in mapper: if kw[mapper[6]] == "": speed = 0 else: speed = int(float(kw[mapper[6]])) newTraffic.speed = speed if 7 in mapper: newTraffic.azimuth = kw[mapper[7]] if 8 in mapper: newTraffic.valid = kw[mapper[8]] if 9 in mapper: newTraffic.event_time = kw[mapper[9]] if 10 in mapper: newTraffic.client_id = kw[mapper[10]] if 11 in mapper: vehicleData = kw[mapper[11]] vehicleCheck = vehicleData.replace(" ", "") if len(vehicleData) > 0: newTraffic.vehicle = vehicleData else: if imeiData["error"] == "ok": if imeiData[ "brand"] is not None and imeiData[ "model"] is not None: newTraffic.vehicle = imeiData[ "brand"] + ' ' + imeiData[ "model"] + ' ' else: if imeiData["error"] == "ok": if imeiData[ "brand"] is not None and imeiData[ "model"] is not None: newTraffic.vehicle = imeiData[ "brand"] + ' ' + imeiData[ "model"] + ' ' if 12 in mapper: newTraffic.voltage = kw[mapper[12]] if 13 in mapper: newTraffic.internal_id = kw[mapper[13]] if 14 in mapper: if kw[mapper[14]] == '': newTraffic.mcc = 0 else: newTraffic.mcc = kw[mapper[14]] if 15 in mapper: if kw[mapper[15]] == '': newTraffic.mnc = 0 else: newTraffic.mnc = kw[mapper[15]] if 16 in mapper: if kw[mapper[16]] == '': newTraffic.lac = 0 else: newTraffic.lac = kw[mapper[16]] if 17 in mapper: if kw[mapper[17]] == '': newTraffic.cellid = 0 else: newTraffic.cellid = kw[mapper[17]] newTraffic.user = eachActiveUser['user_name'] newTraffic.priority = priority localtz = 'America/Mexico_City' if 9 in mapper: cuda = kw[mapper[9]] cuda = cuda[:19] dateconversion = datetime.strptime( cuda, '%Y-%m-%dT%H:%M:%S') oper_utc = arrow.get(dateconversion) oper_localtime = oper_utc.to(localtz) else: oper_localtime = datetime.now( pytz.timezone(localtz)) nd = "Evento no definido" if 3 in mapper: nd = kw[mapper[3]] nd = nd.lstrip().rstrip() if len(nd) == 0: nd = "Evento no definido:" + newTraffic.event_desc else: eventsid = kw[mapper[2]] events = DBSession.query(Events).filter_by( event_id=eventsid).first() if events is not None: nd = events.event_desc #print("-------->>> user:{}".format(eachActiveUser['user_name'])) logImeiRecord = DBSession.query(logImei).filter_by( imei=parameters['imei'], event_desc=nd, group_name=eachActiveUser['user_name']).first( ) if mapper[2] in kw: if kw[mapper[2]] == "99": logImeiRecord = None if logImeiRecord is not None: #print("FOUND!!!!->{}".format(eachActiveUser['user_name'])) newTraffic.attended_state = "R" hour = oper_localtime.strftime("%H:%M") if hour >= "06:00" and hour <= "12:00": logImeiRecord.morning += 1 else: if hour >= "12:00" and hour <= "18:00": logImeiRecord.afternoon += 1 else: if hour >= "18:00" and hour <= "23:59": logImeiRecord.night += 1 else: if hour >= "00:00" and hour <= "06:00": logImeiRecord.early_morning += 1 logImeiRecord.counter = logImeiRecord.counter + 1 if logImeiRecord.counter > 100: logImeiRecord.counter = 0 logImeiRecord.morning = 0 logImeiRecord.afternoon = 0 logImeiRecord.night = 0 logImeiRecord.early_morning = 0 logImeiRecord.group_name = eachActiveUser[ 'user_name'] if logImeiRecord.counter == 2: if 'client_id' in imeiData and 'last_report' in imeiData: venus = Rest() venusUrl = "http://venus.gpscontrol.com.mx/dispatch/create_ticket?client_id=" + str( imeiData['client_id'] ) + "&last_report=" + str( imeiData['last_report'] ) + "&folio=0" + "&imei=" + imei + "&comm=" + "Ignorar Rodo... Cierrala,.. Se detecto una inconcistencia en las alertas" res = requests.get(venusUrl) if res is not None: response = res.json() if 'Ticket' in response: venusTicket = response[ 'Ticket'] else: nd = "Evento no definido" if 3 in mapper: nd = kw[mapper[3]] nd = nd.lstrip().rstrip() if len(nd) == 0: nd = "Evento no definido:" + newTraffic.event_desc else: eventsid = kw[mapper[2]] events = DBSession.query(Events).filter_by( event_id=eventsid).first() if events is not None: nd = events.event_desc newLogImei = logImei() newLogImei.imei = parameters['imei'] newLogImei.event_desc = nd newLogImei.counter = 1 newLogImei.weekday = oper_localtime.strftime( "%A") newLogImei.group_name = eachActiveUser[ 'user_name'] DBSession.add(newLogImei) DBSession.add(newTraffic) DBSession.flush() if newTraffic.attended_state == "N": Message.post( "trafficlistener_" + eachActiveUser['user_name'], 'RELOAD' + "|") elif newTraffic.attended_state == "R": Message.post( "rejectedlistener_" + eachActiveUser['user_name'], 'RELOAD' + "|") if venusTicket != "": searchticket = DBSession.query( Tickets).filter_by( ticket=venusTicket).first() if searchticket is None: newTickets = Tickets() newTickets.traffic_id = newTraffic.id newTickets.ticket = venusTicket newTickets.comment = "Se detecto una inconcistencia en las alertas" DBSession.add(newTickets) DBSession.flush() return 'ok'