def message_compose(): user = utils.get_user_from_cookie(request) page_name = 'messages' if request.method.lower() == "post": message_to = request.form.get("message_to") or "" message_title = request.form.get("message_title") or "" message_contents = request.form.get("message_contents") or "" if not (message_to and message_title and message_contents): message = 'Missing field' page_content = render_template("compose.html", user=user, message=message) return render_page(page_content, page_name, user=user) to_user = utils.check_username(message_to) if not to_user: message = 'Invalid user' page_content = render_template("compose.html", user=user, message=message) return render_page(page_content, page_name, user=user) utils.create_message(to_user["user_id"], user["user_id"], message_title, message_contents) return redirect("/messages/view") page_content = render_template("compose.html", user=user) return render_page(page_content, page_name, user=user)
def message_compose(): user = utils.get_user_from_cookie(request) page_name = "messages" if request.method.lower() == 'post': message_to = request.form.get('message_to') or '' message_title = request.form.get('message_title') or '' message_contents = request.form.get('message_contents') or '' if not (message_to and message_title and message_contents): message = "Missing field" page_content = render_template('compose.html', user=user, message=message) return render_page(page_content, page_name, user=user) to_user = utils.check_username(message_to) if not to_user: message = "Invalid user" page_content = render_template('compose.html', user=user, message=message) return render_page(page_content, page_name, user=user) utils.create_message(to_user['user_id'], user['user_id'], message_title, message_contents) return redirect('/messages/view') page_content = render_template('compose.html', user=user) return render_page(page_content, page_name, user=user)
def test_create_message_single_line(self): code = 200 line = 'Status OK.' expected_result = '200 Status OK.' result = create_message(code, line, as_bytes=False) self.assertEqual(result, expected_result)
def user_session(io_adapter): """ Класс, реализующий логику работы с конкретным подключенным к серверу пользователем. При запуске выводит пользователю приветственное сообщение, затем в распознает команды получаемые от клиента и выполняет их, после выполнения команды exit завершает работу. :type io_adapter: BaseIoAdapter """ # начало сессии, выведем приветстие io_adapter.write(create_message(200, BannerMessage.get())) cmd = None transfer_mode = TransferMode() while cmd != commands_definitions.EXIT: # читаем одну строку из входящих данных: line = yield from io_adapter.read(transfer_mode.mode) """:type: bytes""" # перебираем все зарегистрированные команды: for cmd, callback, in commands.COMMANDS: bin_cmd = cmd.encode() cmd_len = len(bin_cmd) if line[:cmd_len] == bin_cmd: lwc = line[cmd_len + 1:io_adapter.delimiter_slice_start].rstrip(b' ') callback_kwargs = { 'line_without_command': lwc, 'transfer_mode': transfer_mode, } message = callback(**callback_kwargs) io_adapter.write(message, transfer_mode.mode) break else: # это условие выполниться только если цикл завершится нормально, # т.е. без break message = create_message(CODE_BAD_DATA, ERR_COMMAND_NOT_RECOGNIZED) io_adapter.write(message, transfer_mode.mode) io_adapter.close()
def save_message(): # get the message request_data = request.get_json() # insert a record conn = utils.create_connection('/home/pi/projects/ledticker-pi/db/led_messages.db') m_id = utils.create_message(conn, request_data) # return a value return jsonify( message_id=m_id, message="message created" )
def test_create_message_multiple_lines(self): code = 200 text = LINES_DELIMITER.join([ 'line 1', 'line 2', 'line 3' ]) expected_result = LINES_DELIMITER.join([ '200-line 1', 'line 2', '200 line 3' ]) result = create_message(code, text, as_bytes=False) self.assertEqual(expected_result, result)
def transferFile(udp_soc, host, port): global fileList global N global sent_index global ack_index global window_limit window_limit = N - 1 seq_no = -1 length = len(fileList) while 1: #print "Ack Index:"+str(ack_index) if (ack_index == length - 1): break ''' time.sleep(0) if ((window_limit - sent_index) == N): lock.acquire() signal.alarm(0) signal.setitimer(signal.ITIMER_REAL, timeout_timer) lock.release() ''' while ((sent_index < window_limit) and (sent_index < (len(fileList) - 1))): lock.acquire() #print '------------\nlock acquired in transfer file\n--------------' signal.alarm(0) signal.setitimer(signal.ITIMER_REAL, timeout_timer) sent_index += 1 seq_no += 1 msg = fileList[sent_index] pkt = utils.create_message(seq_no, msg) #print 'Sending Msg:'+str(seq_no)+"\n------------------------" udp_soc.sendto(pkt, (host, port)) #print 'Sent_pkts:'+str(sent_index)+' Window Limit:'+str(window_limit)+'\nxxxxxxxxxxxxxxxx' lock.release() #print '------------\nlock released in transfer file\n--------------' time.sleep(0)
def resend_pkts(signum, f): global ack_index global window_limit global fileList global host global port resent_seq_no = ack_index + 1 #print 'reset alarm:Resending_pkts:'+str(resent_seq_no)+'to'+str(window_limit) lock.acquire() #print '------------\nlock acquired in Resend Pkts\n--------------' signal.alarm(0) signal.setitimer(signal.ITIMER_REAL, timeout_timer) while ((resent_seq_no <= window_limit) and (resent_seq_no <= (len(fileList) - 1))): msg = fileList[resent_seq_no] pkt = utils.create_message(resent_seq_no, msg) udp_soc.sendto(pkt, (host, port)) print 'Timeout, sequence number = ' + str(resent_seq_no) #print resent_seq_no resent_seq_no += 1 lock.release()
num_messages = 100 else: num_messages = int(sys.argv[1]) type ="fanOutRead" logger = logging.getLogger("exectime") logger.setLevel(logging.INFO) fh = logging.FileHandler( type + "_" + "insert.log") logger.addHandler(fh) recipient_logger = logging.getLogger("recipients") recipient_logger.setLevel(logging.INFO) fh2 = logging.FileHandler(type+'recipients.log') recipient_logger.addHandler(fh2) connection = MongoClient() db = connection.test messages = db.messages logger.info("FOR save") recipients = [] for i in range(num_messages): msg = utils.create_message() save_message(msg) for recipient in msg.get("to"): if recipient not in recipients: recipients.append(recipient) for r in range(recipients.__len__()): recipient_logger.info(recipients[r])
def report_changes(self, data, data_html, colnames): """ Determine if any jobs have been added or removed since the last check. Report additions or deletions by print report or email as specified. :param data: jobs data returned from self.scrape() :param data_html: jobs HTML data returned from self.scrape() :param colnames: column names of jobs data """ adds, adds_html, deletes = utils.find_adds_deletes( filepath=self.filepath, data=data, data_html=data_html, colnames=colnames) # set these to None in case they don't get defined later adds_table, adds_table_html, deletes_table, deletes_table_html = None, None, None, None # print the added and deleted jobs if print_report == True if adds: adds_table = utils.create_text_table(adds, colnames) adds_table_html = utils.create_html_table(adds_html, colnames) if self.print_report and self.report_adds: utils.print_table(adds_table, company_name=self.company_name, message_start="New jobs posted") if deletes: deletes_table = utils.create_text_table(deletes, colnames) deletes_table_html = utils.create_html_table( deletes, colnames) # don't need links deletes table if self.print_report and self.report_deletes: utils.print_table(deletes_table, company_name=self.company_name, message_start="Jobs removed") # if there were changes that need reporting and email_report == True, send an email needs_report = ((self.report_adds and adds) or (self.report_deletes and deletes)) if self.email_report and needs_report: service = utils.establish_service() # build the message text email_adds = False email_deletes = False if self.report_adds and adds: email_adds = True if self.report_deletes and deletes: email_deletes = True text_msg, html_msg = utils.build_message( adds_table, adds_table_html, deletes_table, deletes_table_html, self.company_name, email_adds, email_deletes) # include link to careers page at bottom of email if available if (self.careers_link is not None) and (self.careers_link != ""): html_msg += '\n<p></p>\n<p>Careers page: <a href="' + self.careers_link + '">' + self.careers_link + \ '</a></p>\n' text_msg += '\n\nCareers page: ' + self.careers_link + '\n' # create and send message using Gmail API msg = utils.create_message(self.sender, self.to, self.subject, text_msg, html_msg) utils.send_message(service, user_id="me", message=msg)
def send_message(self, message, opcode=0x1): self.log_info('send_message({1}): {0}'.format(message, repr(self))) mask = '' if self.mask_outgoing: mask = os.urandom(4) self.push(create_message(message, mask=mask, opcode=opcode))