I'm building a webchat application in python. Basically I have all the messages stored in a MySQL DB and I need to have them populate in the chat one by one.
Here is the DB:
Here I generate HTML Template:
class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
# Sending an '200 OK' response
self.send_response(200)
self.send_header("Content-type", "text/html")
# Whenever using 'send_header', you also have to call 'end_headers'
self.end_headers()
query_components = parse_qs(urlparse(self.path).query)
if 'mymessage' in query_components:
MyMessage = query_components["mymessage"][0]
send_message = f'INSERT INTO lora_messages (mymessages, yourmessages) VALUES ("{MyMessage}", "")'
insertmsg.execute(send_message)
# Some custom HTML code, possibly generated by another function
styler = """
body {
font-family: helvetica;
display: flex ;
flex-direction: column;
align-items: center;
}
input[type=text] {
width: auto;
}
.chat {
-ms-transform: scale(1);
-webkit-transform: scale(1);
-moz-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
.messages {
margin-top: 30px;
display: flex;
flex-direction: column;
}
.message {
border-radius: 20px;
padding: 8px 15px;
margin-top: 5px;
margin-bottom: 5px;
display: inline-block;
}
.yours {
align-items: flex-start;
}
.yours .message {
margin-right: 25%;
background-color: #eee;
position: relative;
}
.mine {
align-items: flex-end;
}
.mine .message {
color: white;
margin-left: 25%;
background: linear-gradient(to bottom, #00D0EA 0%, #0085D1 100%);
background-attachment: fixed;
position: relative;
} """
html = f"""
<html>
<head>
<style>{styler}</style>
</head>
<h1>LoRa Chat</h1>
{mymessagetemplate}
{yourmessagetemplate}
<form action="" Method="GET">
<input type="text" id="body" name="mymessage">
<input type="submit" value="Submit">
</form>"""
# Writing the HTML contents with UTF-8
self.wfile.write(bytes(html, "utf8"))
return
# Create an object of the above class
handler_object = MyHttpRequestHandler
PORT = 8035
my_server = socketserver.TCPServer(("", PORT), handler_object)
my_server.allow_reuse_address = True
# Start the server
my_server.serve_forever()
Here I'm writing the while loop and assigning it to the variable that I added to the HTML template {yourmessagetemplate} and {mymessagetemplate}.
import http.server
import socketserver
import mysql.connector
from urllib.parse import urlparse
from urllib.parse import parse_qs
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="pass",
database="allmessages",
autocommit=True
)
yourmess = mydb.cursor()
mymess = mydb.cursor()
insertmsg = mydb.cursor()
yourmess.execute("SELECT yourmessages FROM lora_messages WHERE yourmessages != ''")
yourmsg = yourmess.fetchone()
while yourmsg is not None:
yourmsg = yourmess.fetchone()
yourmessagetemplate = f"<div class='chat'><div class='yours messages'><div class='message'>{yourmsg}</div></div>"
mymess.execute("SELECT mymessages FROM lora_messages WHERE mymessages != ''")
mymsg = mymess.fetchone()
while mymsg is not None:
mymsg = mymess.fetchone()
mymessagetemplate = f"<div class='chat'><div class='mine messages'><div class='message'>{mymsg}</div></div>"
How can I get this program to write each line one by one? The result I get is that {yourmessagetemplate} only shows the last message in the DB which is "None" for both sides of the conversation and omits the rest of the messages.
The code is overwriting the message templates in each iteration of the while loops. You probably want to collect each template in a list, and then join them together once they have all been collected.
# Create a list to hold templates
yourmessagetemplates = []
yourmess.execute("SELECT yourmessages FROM lora_messages WHERE yourmessages != ''")
yourmsg = yourmess.fetchone()
while yourmsg is not None:
yourmsg = yourmess.fetchone()
yourmessagetemplates.append(f"<div class='chat'><div class='yours messages'><div class='message'>{yourmsg}</div></div>")
# Join the individual templates into a single piece of html.
yourmessagetemplate = '<br>'.join(yourmessagetemplates)
# Create a list to hold templates
mymessagetemplates = []
mymess.execute("SELECT mymessages FROM lora_messages WHERE mymessages != ''")
mymsg = mymess.fetchone()
while mymsg is not None:
mymsg = mymess.fetchone()
mymessagetemplates.append(f"<div class='chat'><div class='mine messages'><div class='message'>{mymsg}</div></div>")
# Join the individual templates into a single piece of html.
mymessagetemplate = '<br>'.join(mymessagetemplates)
Related
I am using wtf forms with flask to create a form.
I have a file input, which is styled so the default button is not shown.
How can I dynamically change the style after a file is loaded?
Here is my code:
html:
<div class="file-upload my-form">
<img src="https://i.stack.imgur.com/dy62M.png" />
{{ wtf.form_field(form.file)}}
</div>
css:
.my-form input {
margin: 0;
padding: 0;
height: 100%;
opacity: 0;
}
.file-upload {
margin: 40px auto;
border: 1px solid #149174;
border-radius: 100px;
overflow: hidden;
position: relative;
}
.file-upload input {
position: absolute;
width: 300px;
height: 600px;
left: 10px;
top: 20px;
}
.file-upload img {
height: 170px;
width: 170px;
margin: 60px;
}
how can I change the style on input? or show a label with the file name in the worst case...
In the end I dealt with it like this:
function fileCheck() {
var checked = document.getElementById('file')
if (checked.value.length > 0) {
var file_name = checked.value.split(/(\\|\/)/g).pop();
var re = /(?:\.([^.]+))?$/;
var ext = re.exec(file_name)[1];
if (ext != 'pdf') {
document.getElementById('file-container').style.backgroundColor = '#ca2c2c';
document.getElementById("file-desc").innerHTML = "File Loaded with illegal extension: " + ext + " !!";
document.getElementById("final-submit").disabled = true;
}
else {
document.getElementById('file-container').style.backgroundColor = '#149174';
document.getElementById("file-desc").innerHTML = "File Loaded: " + checked.value.split(/(\\|\/)/g).pop();
document.getElementById("final-submit").disabled = false;
}
}
else {
document.getElementById("final-submit").disabled = true;
}
}
And my html looks like this:
<div class="file-upload my-form" id="file-container">
<img src="static/images/upload_icon.png" />
{{ form.file(oninput="fileCheck()") }}
</div>
I have a python script that will be triggered to read an inbox and send email to an gmail account when some condition is meet. In order to send , the script will filter through subject or text of the incoming email. Currently the script is just hard-coded format and I prefer the condition is dynamically set by the user. I created a django website and let user to input their condition, but I do not know how can I pass the parameter from the web to my python script. I already do my researched on the internet but couldn't found any useful source, does anyone can help me or send my any related article for me to read ? Thanks
My py script
import datetime
import email
import imaplib
import mailbox
import smtplib
EMAIL_ACCOUNT = "xxx#gmail.com"
PASSWORD = "xxx"
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(EMAIL_ACCOUNT, PASSWORD)
mail.list()
mail.select('inbox')
result, data = mail.uid('search', None, "UNSEEN") # (ALL/UNSEEN)
i = len(data[0].split())
for x in range(i):
latest_email_uid = data[0].split()[x]
result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
# result, email_data = conn.store(num,'-FLAGS','\\Seen')
# this might work to set flag to seen, if it doesn't already
raw_email = email_data[0][1]
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
# Header Details
date_tuple = email.utils.parsedate_tz(email_message['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
local_message_date = "%s" %(str(local_date.strftime("%a, %d %b %Y %H:%M:%S")))
email_from = str(email.header.make_header(email.header.decode_header(email_message['From'])))
email_to = str(email.header.make_header(email.header.decode_header(email_message['To'])))
subject = str(email.header.make_header(email.header.decode_header(email_message['Subject'])))
# Body details
for part in email_message.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True)
print("From:", email_from)
print("Email To:", email_to)
print("date:", local_message_date)
print("Subject:", subject)
print("body:", body.decode('utf-8'))
'''If subject have test it will send specific email to recipient'''
if "Consent" in subject:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(EMAIL_ACCOUNT, PASSWORD)
msg = "ALERT NOTICE!"
server.sendmail(EMAIL_ACCOUNT, "xxx#gmail.com", msg)
server.quit()
else:
print( "no email");
else:
continue
My django web currently is just html form
My django web interface
Html
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Quicksand:300,500" rel="stylesheet">
<style>
body {font-family: 'Quicksand', sans-serif;}
.button {
border-radius: 50px;
background-color: #ff9633;
border: none;
color: #FFFFFF;
text-align: center;
font-size: 15px;
padding: 10px;
width: 80px;
transition: all 0.5s;
cursor: pointer;
margin: 5px;
margin-left:500px;
}
.button span {
cursor: pointer;
display: inline-block;
position: relative;
transition: 0.5s;
}
.button span:after {
content: '\00bb';
position: absolute;
opacity: 0;
top: 0;
right: -20px;
transition: 0.5s;
}
.button:hover span {
padding-right: 25px;
}
.button:hover span:after {
opacity: 1;
right: 0;
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 45%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}
/* Add Animation */
#-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
#keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
/* The Close Button */
.close {
color: white;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.modal-header {
padding: 2px 16px;
background-color: #ff9633;
color: white;
}
.modal-body {padding: 2px 16px;}
.modal-footer {
padding: 2px 16px;
background-color: #ff9633;
color: white;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #ff9633;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover {
background-color:
#fa7d34;
}
</style>
</head>
<body>
<ul>
<li><div id="myBtn1">Alert Policies</div></li>
<li>Test3</li>
<li>Test4</li>
</ul>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Alert Policies</h2>
</div>
<div class="modal-body">
<p style="font-size:14px">Please select an event parameter as well as the condition type and value that apply.</p>
<!-- parameter drop down -->
<form action="/action_page.php">
<label for="Parameter"> <b style="font-size:13px" > Event parameter to evaluate </b></label>
<select name="Parameter" id="Parameter" style="width:340px; font-family: 'Quicksand', sans-serif;">
<option disabled selected value>select a parameter</option>
<option value="Subject">Subject</option>
<option value="Text">Text</option>
</select>
<br><br>
<label for="Condition"> <b style="font-size:13px" > Type of condition </b></label>
<select name="Condition" id="Condition" style="width:340px; margin-left:69px; font-family: 'Quicksand', sans-serif;">
<option disabled selected value>select a condition</option>
<option value="Equals">Equals</option>
<option value="Contain">Contain</option>
<option value="NotContain">Does not contain</option>
</select>
<br><br>
<label for="valuetomatch"> <b style="font-size:13px" > Value to match</b></label>
<input type="text" id="valuetomatch" name="valuetomatch" style="width:333px; margin-left:80px; font-family: 'Quicksand', sans-serif;">
<br>
<br>
<button class="button"><span>OK</span></button>
</form>
</div>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn1");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
If your condition data is serializable, then you can use Celery to run python script. It'll be as simple as:
# in your Django code that run on user submitting data
...
send_email.delay()
...
# Celery task
#shared_task(bind=True)
def send_email(list_of_your_condition_parameters):
# do job
Currently I had developed a script that will read incoming/latest email and filter the email based on certain criteria such as email subject and text. When user select subject or text, they are able to choose which condition they want to filter the email (Equals, Does not contain etc).
My Problem
I have a demo website that will let user to add different conditions to filter the email. But now my script can only handle one condition and execute at one time . How can I make my script to detect there are multiple condition and filter the email based on the multiple rules ? Im using Django to do my website
My previous script:
After user click on OK, the script in view.py will directly be executed and it will parse the email based on the current condition only
What I trying to achieve:
I had modify my html template and it will continuously letting user to add few conditions rather than just execute one condition only. Example: When user choose the parameter etc and click OK and new row will be store and the script will parse the email based on how many rules that user want to be parse. (After clicking submit the script will only be triggered when all the rules are met)
Expected output (based on the above picture)
The system able to parse incoming email with these two rules which are Email subject must equal to test and the text must contain text contain
Possible solution
Is it able to dynamically add the If Else statement when there are new rules coming in? and count until the last row of the rules then just execute.
My py script (This code is previous version, it only able to execute one time when user click on OK)
from django.http import HttpResponse
import datetime
import email
import imaplib
import mailbox
import smtplib
def index(request):
return render(request,'DemoApp/hi.html')
def send(request):
EMAIL_ACCOUNT = "xxx#gmail.com"
PASSWORD = "xxx"
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(EMAIL_ACCOUNT, PASSWORD)
mail.list()
mail.select('inbox')
result, data = mail.uid('search', None, "UNSEEN") # (ALL/UNSEEN)
i = len(data[0].split())
for x in range(i):
latest_email_uid = data[0].split()[x]
result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
# result, email_data = conn.store(num,'-FLAGS','\\Seen')
# this might work to set flag to seen, if it doesn't already
raw_email = email_data[0][1]
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
# Header Details
date_tuple = email.utils.parsedate_tz(email_message['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
local_message_date = "%s" % (str(local_date.strftime("%a, %d %b %Y %H:%M:%S")))
email_from = str(email.header.make_header(email.header.decode_header(email_message['From'])))
email_to = str(email.header.make_header(email.header.decode_header(email_message['To'])))
subject = str(email.header.make_header(email.header.decode_header(email_message['Subject'])))
# Body details
for part in email_message.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True)
#Get all value from
ParameterGet = str(request.POST.get('Parameter', None))
ConditionGet = str(request.POST.get('Condition', None))
valuetomatch = str(request.POST["valuetomatch"])
def emailSendDetails():
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(EMAIL_ACCOUNT, PASSWORD)
msg = "ALERT NOTICE!"
server.sendmail(EMAIL_ACCOUNT, "xxx#gmail.com", msg)
server.quit()
#<----------------Parameter---------------->
#Subject
if ParameterGet == "Subject":
# <----------------Condition---------------->
#Equals
if ConditionGet == "Equals":
if valuetomatch == subject:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(EMAIL_ACCOUNT, PASSWORD)
msg = "subject equals!"
server.sendmail(EMAIL_ACCOUNT, "xxx#gmail.com", msg)
server.quit()
else:
print("no email");
# Contain
if ConditionGet == "Contain":
if valuetomatch in subject:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(EMAIL_ACCOUNT, PASSWORD)
msg = "subject contain!"
server.sendmail(EMAIL_ACCOUNT, "xxx#gmail.com", msg)
server.quit()
else:
print("no email");
# Does not contain
if ConditionGet == "NotContain":
if valuetomatch not in subject:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(EMAIL_ACCOUNT, PASSWORD)
msg = "subject not contain!"
server.sendmail(EMAIL_ACCOUNT, "xxx#gmail.com", msg)
server.quit()
else:
print("no email");
# <----------------Parameter---------------->
#Text
if ParameterGet == "Text":
# <----------------Condition---------------->
# Equals
if ConditionGet == "Equals":
if valuetomatch == body.decode('utf-8').rstrip():
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(EMAIL_ACCOUNT, PASSWORD)
msg = "text equals!"
server.sendmail(EMAIL_ACCOUNT, "xxx#gmail.com", msg)
server.quit()
else:
print("no email");
# Contain
if ConditionGet == "Contain":
if valuetomatch in body.decode('utf-8'):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(EMAIL_ACCOUNT, PASSWORD)
msg = "text contain!"
server.sendmail(EMAIL_ACCOUNT, "xxx#gmail.com", msg)
server.quit()
else:
print("no email");
# Does not contain
if ConditionGet == "NotContain":
if valuetomatch not in body.decode('utf-8'):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(EMAIL_ACCOUNT, PASSWORD)
msg = "text notcontain!"
server.sendmail(EMAIL_ACCOUNT, "xxx#gmail.com", msg)
server.quit()
else:
print("no email");
else:
continue
return render(request, 'DemoApp/hi.html', {'key': "Send successfully"})
The same script but it doesn't link to the Html or django template, its all hard coded parameter But it help for debugging
import datetime
import email
import imaplib
import mailbox
import smtplib
while True:
EMAIL_ACCOUNT = "xxx#gmail.com"
PASSWORD = "xxx"
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(EMAIL_ACCOUNT, PASSWORD)
mail.list()
mail.select('inbox')
result, data = mail.uid('search', None, "UNSEEN") # (ALL/UNSEEN)
i = len(data[0].split())
for x in range(i):
latest_email_uid = data[0].split()[x]
result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
# result, email_data = conn.store(num,'-FLAGS','\\Seen')
# this might work to set flag to seen, if it doesn't already
raw_email = email_data[0][1]
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
# Header Details
date_tuple = email.utils.parsedate_tz(email_message['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
local_message_date = "%s" % (str(local_date.strftime("%a, %d %b %Y %H:%M:%S")))
email_from = str(email.header.make_header(email.header.decode_header(email_message['From'])))
email_to = str(email.header.make_header(email.header.decode_header(email_message['To'])))
subject = str(email.header.make_header(email.header.decode_header(email_message['Subject'])))
# Body details
for part in email_message.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True)
print("From:", email_from)
print("Email To:", email_to)
print("date:", local_message_date)
print("Subject:", subject)
print("body:", body.decode('utf-8'))
'''If subject have "Consent" it will send specific email to recipient'''
if "Consent" in subject:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(EMAIL_ACCOUNT, PASSWORD)
msg = "ALERT NOTICE!"
server.sendmail(EMAIL_ACCOUNT, "xxx#gmail.com", msg)
server.quit()
else:
print("no email");
else:
continue
My Current Html template
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Quicksand:300,500" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.buttonSubmit{
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
body {font-family: 'Quicksand', sans-serif;}
.button {
border-radius: 50px;
background-color: #ff9633;
border: none;
color: #FFFFFF;
text-align: center;
font-size: 15px;
padding: 10px;
width: 80px;
transition: all 0.5s;
cursor: pointer;
margin: 5px;
margin-left:500px;
}
.button span {
cursor: pointer;
display: inline-block;
position: relative;
transition: 0.5s;
}
.button span:after {
content: '\00bb';
position: absolute;
opacity: 0;
top: 0;
right: -20px;
transition: 0.5s;
}
.button:hover span {
padding-right: 25px;
}
.button:hover span:after {
opacity: 1;
right: 0;
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 45%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}
/* Add Animation */
#-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
#keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
/* The Close Button */
.close {
color: white;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.modal-header {
padding: 2px 16px;
background-color: #ff9633;
color: white;
}
.modal-body {padding: 2px 16px;}
.modal-footer {
padding: 2px 16px;
background-color: #ff9633;
color: white;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #ff9633;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover {
background-color:
#fa7d34;
}
</style>
</head>
<body>
<ul>
<li>
<div id="myBtn1">Alert Policies</div>
</li>
<li>Test3</li>
<li>Test4</li>
</ul>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Alert Policies</h2>
</div>
<div class="modal-body">
<p style="font-size:14px">Please select an event parameter as well as the condition type and value that
apply.</p>
<!-- parameter drop down -->
<form method="post">
<label for="Parameter"> <b style="font-size:13px"> Event parameter to evaluate </b></label>
<select name="Parameter" id="Parameter" style="width:340px; font-family: 'Quicksand', sans-serif;">
<option disabled selected value>select a parameter</option>
<option value="Subject">Subject</option>
<option value="Text">Text</option>
</select>
<br><br>
<label for="Condition"> <b style="font-size:13px"> Type of condition </b></label>
<select name="Condition" id="Condition"
style="width:340px; margin-left:69px; font-family: 'Quicksand', sans-serif;">
<option disabled selected value>select a condition</option>
<option value="Equals">Equals</option>
<option value="Contain">Contain</option>
<option value="NotContain">Does not contain</option>
</select>
<br><br>
<label for="valuetomatch"> <b style="font-size:13px"> Value to match</b></label>
<input type="text" id="valuetomatch" name="valuetomatch"
style="width:333px; margin-left:80px; font-family: 'Quicksand', sans-serif;">
<br>
<br>
</form>
<button class="button"><span>OK</span></button>
</div>
</div>
</div>
<table id="myTable">
<tr>
<th>Event Parameter</th>
<th>Condition</th>
<th>Value to match</th>
<th>Action</th>
</tr>
</table>
<br>
Submit
<script>
//add tablebox
$(document).ready(function(){
$(".button").on('click', function () {
para = document.getElementById("Parameter").value;
condi = document.getElementById("Condition").value;
value2match = document.getElementById("valuetomatch").value;
if (para && condi && value2match !== null) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = document.getElementById("Parameter").value;
cell2.innerHTML = document.getElementById("Condition").value;
cell3.innerHTML = document.getElementById("valuetomatch").value;
cell4.innerHTML = '<button class = "del_img "onClick="delSpec(this)">Delete</button> </div>';
//close the modal
modal.style.display = "none";
}else
{
alert("All the input box cannot be empty!");
}
});
});
function delSpec(node)
{
r=node.parentNode.parentNode;
r.parentNode.removeChild(r);
}
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn1");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
This problem looks interesting. Let me give my try,
I can see there are only three conditions that need to be performed. So let make a dictionary out of it:
con = {
"Equals": "==",
"Contain": "in",
"NotContain": "not in"
}
I can see you have the required values ready in hand here:
#Get all value from
ParameterGet = str(request.POST.get('Parameter', None))
ConditionGet = str(request.POST.get('Condition', None))
valuetomatch = str(request.POST["valuetomatch"])
Let's take the for loop to iterate the table alert policies rows for iteration,
con = {
"Equals": "==",
"Contain": "in",
"NotContain": "not in"
}
for each_row in rows:
***your other logic goes here***
ParameterGet = str(request.POST.get('Parameter', None))
ConditionGet = str(request.POST.get('Condition', None))
valuetomatch = str(request.POST["valuetomatch"])
text = "body.decode('utf-8').rstrip()"
current_condition = "(valuetomatch "+ con[ConditionGet] + " " + ParameterGet.lower() + ")"
if eval(current_condition):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(EMAIL_ACCOUNT, PASSWORD)
msg = "subject not contain!"
server.sendmail(EMAIL_ACCOUNT, "xxx#gmail.com", msg)
server.quit()
else:
print("no email");
OUTPUT:
>>> con = {
"Equals": "==",
"Contain": "in",
"NotContain": "not in"
}
>>> valuetomatch = "hi"
>>> ConditionGet = "Contain"
>>> ParameterGet = "Subject"
>>> subject = "hi"
>>> current_condition = "(valuetomatch "+ con[ConditionGet] + " " + ParameterGet.lower() + ")"
>>> current_condition
'(valuetomatch in subject)'
>>> eval(current_condition)
True
Check eval for reference.
You could try something like this in server side:
# What you get from frontend
arr=[["Subject","Equals","test"],["Text","Contain","Testing 1 2 3"],["Text","Contain","rhrhj"]]
email_message = email.message_from_string(raw_email_string)
subject = str(email.header.make_header(email.header.decode_header(email_message['Subject'])))
# Dict with mapping between patterns and objects
to_compare = {
'Subject': subject,
'Text': email_message,
}
# Returns right object between email_message or subject
def get_compare(target, to_compare):
try:
return to_compare[target]
except:
raise Exception(f"{target} not found in comparable elements.")
# Loop over arr, perform checks and do actions
for alert in arr:
if arr[1] == 'Equals':
if get_compare(arr[0]) == arr[3]:
# Do something
elif arr[1] == 'Contain':
if arr[3] in get_compare(arr[0]):
# Do something
elif arr[1] == 'NotContain':
if arr[3] not in get_compare(arr[0]):
# Do something
else:
raise Exception(f"{arr[1]} does not belong to recognize operators.")
I have implement simple app in flask. I can get data and process it also but how can I get random created folder. In this app, I tried to input some data to text area. When export deck button clicked then the data post to flask. I can get data and generate deck also but unable send generated deck file or redirect to the random folder.
I get the following error.
raise TypeError(
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.)
So, How can I implement this? Redirect to new random generated folder or send the generated file as download link.
Thanks
app.py
from flask import Flask, render_template, request, redirect, url_for, flash, send_file, send_from_directory
import image_occ_deck_export
import random, os
app = Flask(__name__)
app.config["CACHE_TYPE"] = "null"
#app.route("/", methods=["GET","POST"])
def home():
if request.method == "POST":
print(request.form['notes'])
notes = request.form['notes']
# random folder
data = request.form['notes']
print(data)
random_f = random.randrange(1 << 30, 1 << 31)
create_random_folder(random_f, data)
else:
return render_template("index.html")
def create_random_folder(random_f, data):
directory = str(random_f)
parent_dir = "static/uploads/"
path = os.path.join(parent_dir, directory)
if not os.path.exists(path):
os.mkdir(path)
random_file = directory + ".txt"
random_deck_name = directory + ".apkg"
file_loc = path + "/" + random_file
deck_loc = path + "/" + random_deck_name
with open(file_loc, 'w') as f:
f.write(str(data))
image_occ_deck_export.exportDeck(file_loc, deck_loc)
return redirect(url_for('uploaded', path=path))
#app.route('/uploaded/<path>', methods=['GET'])
def uploaded():
return render_template("upload.html")
if __name__ == "__main__":
app.run(debug=False)
index.js
function export() {
var textToExport = document.getElementById("noteData").value;
var formData = new FormData();
formData.append("notes", textToExport);
var request = new XMLHttpRequest();
request.open("POST", "/");
request.send(formData);
}
index.html
<html>
<textarea id="noteData"></textarea>
<button onclick="export()">Export Deck</button>
</html>
sample input
cordova-img-occ-note-1602529000819 <img src='art-1851483_640.jpg'></img> <img src='cordova-img-occ-ques-1602529000819.svg'></img> <img src='cordova-img-occ-ans-1602529000819.svg'></img> <img src='cordova-img-occ-orig-1602529000819.svg'></img>
cordova-img-occ-note-1602529001248 <img src='art-1851483_640.jpg'></img> <img src='cordova-img-occ-ques-1602529001248.svg'></img> <img src='cordova-img-occ-ans-1602529001248.svg'></img> <img src='cordova-img-occ-orig-1602529000819.svg'></img>
cordova-img-occ-note-1602529001673 <img src='art-1851483_640.jpg'></img> <img src='cordova-img-occ-ques-1602529001673.svg'></img> <img src='cordova-img-occ-ans-1602529001673.svg'></img> <img src='cordova-img-occ-orig-1602529000819.svg'></img>
image_occ_deck_export.py
The file use to generate anki deck from txt
import random
import genanki
import csv
import traceback
anki_deck_title = "learn"
anki_model_name = "image occ"
model_id = random.randrange(1 << 30, 1 << 31)
def exportDeck(data_filename, deck_filename):
try:
# front side
front = """
{{#Image}}
<div id="io-header">{{Header}}</div>
<div id="io-wrapper">
<div id="io-overlay">{{Question Mask}}</div>
<div id="io-original">{{Image}}</div>
</div>
<div id="io-footer">{{Footer}}</div>
<script>
// Prevent original image from loading before mask
aFade = 50, qFade = 0;
var mask = document.querySelector('#io-overlay>img');
function loaded() {
var original = document.querySelector('#io-original');
original.style.visibility = "visible";
}
if (mask === null || mask.complete) {
loaded();
} else {
mask.addEventListener('load', loaded);
}
</script>
{{/Image}}
"""
style = """
/* GENERAL CARD STYLE */
.card {
font-family: "Helvetica LT Std", Helvetica, Arial, Sans;
font-size: 150%;
text-align: center;
color: black;
background-color: white;
}
/* OCCLUSION CSS START - don't edit this */
#io-overlay {
position:absolute;
top:0;
width:100%;
z-index:3
}
#io-original {
position:relative;
top:0;
width:100%;
z-index:2;
visibility: hidden;
}
#io-wrapper {
position:relative;
width: 100%;
}
/* OCCLUSION CSS END */
/* OTHER STYLES */
#io-header{
font-size: 1.1em;
margin-bottom: 0.2em;
}
#io-footer{
max-width: 80%;
margin-left: auto;
margin-right: auto;
margin-top: 0.8em;
font-style: italic;
}
#io-extra-wrapper{
/* the wrapper is needed to center the
left-aligned blocks below it */
width: 80%;
margin-left: auto;
margin-right: auto;
margin-top: 0.5em;
}
#io-extra{
text-align:center;
display: inline-block;
}
.io-extra-entry{
margin-top: 0.8em;
font-size: 0.9em;
text-align:left;
}
.io-field-descr{
margin-bottom: 0.2em;
font-weight: bold;
font-size: 1em;
}
#io-revl-btn {
font-size: 0.5em;
}
/* ADJUSTMENTS FOR MOBILE DEVICES */
.mobile .card, .mobile #content {
font-size: 120%;
margin: 0;
}
.mobile #io-extra-wrapper {
width: 95%;
}
.mobile #io-revl-btn {
font-size: 0.8em;
}
"""
# back side
back = """
{{#Image}}
<div id="io-header">{{Header}}</div>
<div id="io-wrapper">
<div id="io-overlay">{{Answer Mask}}</div>
<div id="io-original">{{Image}}</div>
</div>
{{#Footer}}<div id="io-footer">{{Footer}}</div>{{/Footer}}
<button id="io-revl-btn" onclick="toggle();">Toggle Masks</button>
<div id="io-extra-wrapper">
<div id="io-extra">
{{#Remarks}}
<div class="io-extra-entry">
<div class="io-field-descr">Remarks</div>{{Remarks}}
</div>
{{/Remarks}}
{{#Sources}}
<div class="io-extra-entry">
<div class="io-field-descr">Sources</div>{{Sources}}
</div>
{{/Sources}}
{{#Extra 1}}
<div class="io-extra-entry">
<div class="io-field-descr">Extra 1</div>{{Extra 1}}
</div>
{{/Extra 1}}
{{#Extra 2}}
<div class="io-extra-entry">
<div class="io-field-descr">Extra 2</div>{{Extra 2}}
</div>
{{/Extra 2}}
</div>
</div>
<script>
// Toggle answer mask on clicking the image
var toggle = function() {
var amask = document.getElementById('io-overlay');
if (amask.style.display === 'block' || amask.style.display === '')
amask.style.display = 'none';
else
amask.style.display = 'block'
}
// Prevent original image from loading before mask
aFade = 50, qFade = 0;
var mask = document.querySelector('#io-overlay>img');
function loaded() {
var original = document.querySelector('#io-original');
original.style.visibility = "visible";
}
if (mask === null || mask.complete) {
loaded();
} else {
mask.addEventListener('load', loaded);
}
</script>
{{/Image}}
"""
# print(self.fields)
anki_model = genanki.Model(
model_id,
anki_model_name,
fields=[{"name": "id"},{"name": "Header"}, {"name": "Image"}, {"name": "Question Mask"}, {"name": "Footer"}, {"name": "Remarks"}, {"name": "Sources"}, {"name": "Extra 1"}, {"name": "Extra 2"}, {"name": "Answer Mask"}, {"name": "Original"}],
templates=[
{
"name": "Card 1",
"qfmt": front,
"afmt": back,
},
],
css=style,
)
anki_notes = []
with open(data_filename, "r", encoding="utf-8") as csv_file:
csv_reader = csv.reader(csv_file, delimiter="\t")
for row in csv_reader:
flds = []
for i in range(len(row)):
flds.append(row[i])
anki_note = genanki.Note(
model=anki_model,
fields=flds,
)
anki_notes.append(anki_note)
random.shuffle(anki_notes)
anki_deck = genanki.Deck(model_id, anki_deck_title)
anki_package = genanki.Package(anki_deck)
for anki_note in anki_notes:
anki_deck.add_note(anki_note)
anki_package.write_to_file(deck_filename)
print("Deck generated with {} flashcards".format(
len(anki_deck.notes)))
except Exception:
traceback.print_exc()
create_random_folder() returns a redirect, but when you call it from your home() request handler, you don’t do anything with the returned value and you don’t return a response in that code branch of your home() handler. It seems you intend to return that redirect from your home() handler like so:
return create_random_folder(random_f, data)
Remember, when you return a value from a function, you’re returning the value to the calling code, not to the browser. If you call a function from a request handler and receive a return value, that doesn’t automatically get sent back to the browser; you need to return it from the request handler.
I don't have any idea about html. Some how i got code to convert csv to html.
Below is code:
import sys
import csv
# Open the CSV file for reading
def populate_table(csv_fl):
reader = csv.reader(open(csv_fl))
# Create the HTML file for output
html_table = ''
# initialize rownum variable
rownum = 0
# write <table> tag
html_table= '<table>\n'
# generate table contents
for row in reader: # Read a single row from the CSV file
# write header row. assumes first row in csv contains header
if rownum == 0:
html_table += '<tr>\n' # write <tr> tag
for column in row:
html_table += '<th>' + column + '</th>\n'
html_table += '</tr>\n'
#write all other rows
else:
html_table += '<tr>\n'
for column in row:
if 'fail' in column or 'Fail' in column:
html_table += "<td style='color:red'>" + column + '</td>\n'
continue
html_table += '<td>' + column + '</td>\n'
html_table += '</tr>\n'
#increment row count
rownum += 1
# write </table> tag
html_table += '</table>\n'
return html_table
Above code if string contains Fail or fail it will make red color cell.
I need help here to make full line in red color (Not single cell).
Below is code to fill html (Indent is wrong. If need correct indent code i will share in link ).
I will excute below code like below:
python2.7 fil.py test.csv test.html
import csv2html
import sys
class Sketch:
def __init__(self):
"""
Returns html sketch for a defined scenario
Scenarios asccessible as functions.
supported ones are:
-fail
-pass
-status_update
-final
"""
def _style (self):
body = """
<style>
p {
font-family : Calibri;
font-size: 14px;
font-weight: bolder;
text-align : left;
}
p.fade {
color : #CCCCCC;
font-size: 14px;
}
em {
font-style : italic ;
font-size : 16px;
font-weight: lighter ;
}
em.pass {
font-style : italic ;
font-size : 16px;
color: green ;
}
em.fail {
font-style : italic ;
font-size : 16px;
color: red ;
}
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
hr {
align: left ;
margin-left: 0px ;
width: 500px;
height:1px;
}
table {
border-collapse: collapse;
}
tr {
padding: 4px;
text-align: center;
border-right:2px solid #FFFFFF;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #cceeff;
color: black;
padding: 4px;
border-right:2px solid #FFFFFF;
}
</style>
"""
return body
def _start(self):
return """
<!DOCTYPE html>
<html>
"""
def _end(self):
body ="""
<hr/>
<p class="fade">Note: Link might be disabled,
please put me in safe sender list, by right
click on message.
This is a system generated mail, please don't
respond to it.</p>
</html>
"""
return body
def _fail (self):
body = """
<p>STATUS :
<em class="fail">failed</em>
</p>
"""
return body
def _critical_fail(self):
str_ = 'Failure is critical, terminating the run.'
body = """
<p>
<em class="fail">%s</em>
</p>
"""%str_
return body
def _pass (self):
body = """
<p>STATUS :
<em class="pass">passed</em>
</p>
"""
return body
def _type (self, title, val):
body = """
<p>%s :
<em>%s</em>
</p>
"""%(title.upper(), val)
return body
def _loglink(self, logs):
body = """ <p> LOGS :</p>
<a href=%s>%s</a>
"""%(logs,logs)
return body
def render (self, test_id, descr, platform=None, pass_=True, \
logs=None, critical=False):
body = self._start() +\
self._style() + \
self._type("test id", test_id) + \
self._type("description", descr) +\
self._type("platform", platform)
if pass_==True:
body += self._pass ()
else:
body += self._fail ()
if critical:
body += self._critical_fail()
body += self._loglink(logs)
body += self._end()
return body
def status_update (self, ):
pass
def final (self, logs):
body += self._end()
return body
def add_html_header (csv_fl, fname):
""" html data returned by sqlite needs to be enclosed in
some of the mandatory tags for the web to parse it
properly. ! """
sketch =Sketch()
content ="""
%s %s
<body>
%s
</body>
</html>
"""%(sketch._start(), sketch._style(), csv2html.populate_table(csv_fl))
open (fname, 'w').write (content)
if len(sys.argv) < 3:
print "Usage: csvToTable.py csv_file html_file"
exit(1)
csv_fl = sys.argv[1]
html_fl = sys.argv[2]
add_html_header(csv_fl, html_fl)
To color the whole row in red, simply
<tr style="color:red"> where <tr> is the row you want to color.
p {
font-family: Calibri;
font-size: 14px;
font-weight: bolder;
text-align: left;
}
p.fade {
color: #CCCCCC;
font-size: 14px;
}
em {
font-style: italic;
font-size: 16px;
font-weight: lighter;
}
em.pass {
font-style: italic;
font-size: 16px;
color: green;
}
em.fail {
font-style: italic;
font-size: 16px;
color: red;
}
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
hr {
align: left;
margin-left: 0px;
width: 500px;
height: 1px;
}
table {
border-collapse: collapse;
}
tr {
padding: 4px;
text-align: center;
border-right: 2px solid #FFFFFF;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
th {
background-color: #cceeff;
color: black;
padding: 4px;
border-right: 2px solid #FFFFFF;
}
<table>
<tr>
<th>AAA</th>
<th>BBB</th>
</tr>
<tr>
<td>CCC</td>
<td>DDD</td>
</tr>
<tr style="color:red"> <!-- Here -->
<td>EEE</td>
<td>FFF</td>
</tr>
<tr>
<td>GGG</td>
<td>HHH</td>
</tr>
</table>