How to separate flask app.route order of events - python

I have a small program that opens up an outlook email when a button is clicked on an html page. The problem is, I don't know the order of my app.route objects and the posted data from my html page.
My html (openemailJS.html):
my flask app:
import win32com.client
from flask import Flask, render_template, jsonify, json, url_for, request, redirect
import pythoncom, time, os, sys
app = Flask(__name__)
#app.route('/',methods = ['POST', 'GET'])
def index():
if request.method == 'POST':
emailid = request.args.get('nm')
time.sleep(1)
pythoncom.CoInitialize()
outlook = win32com.client.dynamic.Dispatch("Outlook.Application").GetNameSpace('MAPI')
inbox = outlook.GetDefaultFolder(6)
sentbox = outlook.GetDefaultFolder(5)
all_sentbox = sentbox.Items
all_inbox = inbox.Items
tryopen = outlook.GetItemFromID(emailid)
tryopen.display()
return render_template('openemailJS.html')
print(emailid)
else:
time.sleep(1)
emailid = request.args.get('nm')
#emailid = request.form.get('nm')
time.sleep(1)
pythoncom.CoInitialize()
outlook = win32com.client.dynamic.Dispatch("Outlook.Application").GetNameSpace('MAPI')
inbox = outlook.GetDefaultFolder(6)
sentbox = outlook.GetDefaultFolder(5)
all_sentbox = sentbox.Items
all_inbox = inbox.Items
tryopen = outlook.GetItemFromID(emailid)
tryopen.display()
print(user)
return render_template('openemailJS.html')
I think I need to separate the ' return render_template('openemailJS.html') 'into its own app.route('/something here/') but I don't know how to do that.
Currently, when I run it how it is, the emailid does not get posted before the def index(): runs, causing a 'parameter not found' where it should be. If I comment out everything but the 'return render_template', run the program, and then uncommment it out and click the button, then it gets posted as it should.

I added an if statement to retrieve the data only if the form is posted. I still think it makes sense to render the template first before doing anything, but I don't know.

Related

Python Code on my XAMPP Website won´t work

from flask import Flask, render_template, request
import random
import datetime
app = Flask(__name__)
# List to store the submitted URLs
urls = []
#app.route('/')
def index():
return render_template('index.html')
#app.route('/submit', methods=['POST'])
def submit():
url = request.form['url']
# Add the URL to the list and return a success message
urls.append(url)
return "URL submitted successfully!"
#app.route('/stream')
def stream():
# Select a random URL from the last 20 days
now = datetime.datetime.now()
twenty_days_ago = now - datetime.timedelta(days=20)
recent_urls = [url for url in urls if url.submission_time > twenty_days_ago]
current_song_url = random.choice(recent_urls)
return render_template('stream.html', url=current_song_url)
if __name__ == '__main__':
app.run(debug=True)
I want to use this Code for my XAMPP Website (Html/php mostly used) but it only shows the code. So I watched some tutorials with config stuff and all that but then there is an internal server error. What should I do?
I tried to config Apache (httpd.conf) and installed everything (Python, Flask etc.)

handling Links and CSS in Flask web proxy

So I tried to develop a web proxy using Flask. in the progress I found out that somehow I need to handle Likns so all redirects take place in the web proxy, this is what I write:
import requests
from flask import Flask , request
from requests import get
import re
app = Flask(__name__)
mainURL = ""
myHost = "http://127.0.0.1:5000/"
#app.route("/", methods =["GET", "POST"])
def Home():
#a small form for users to write thier URL inside it
mainpage = '<!DOCTYPE html><html><body><form action="/" method="post"><label for="url">URL:</label><br><input type="text" id="url" name="url" value="https://www.google.com/"><br><input type="submit" value="Open"></form></body></html>'
#check if submit button trigered
if request.method == "POST":
mainURL = request.form.get("url")
response = requests.get(mainURL)
#this is for handling links and pictures. I know its not optimal, thats why im here!
a = response.text.replace("='/",f"='{mainURL}")
a = a.replace('="/',f'="{mainURL}')
a = a.replace("url(/",f"url({mainURL}")
a = a.replace('href="http',f'href="{myHost}http')
a = a.replace("href='http",f"href='{myHost}http")
a = a.replace(r'href="(?!http)',f'href="{myHost}{mainURL}')
a = a.replace(r"href='(?!http)",f"href='{myHost}{mainURL}")
return a
return mainpage
#decroator for the times when a path opened
#app.route('/<path:path>')
def proxy(path):
#this RegEx find the website FQDN from path
if re.match(r"https?://w{3}\.\w*\.\w*/",path):
temp = re.match(r"https?://w{3}\.\w*\.\w*/",path)
mainURL = temp[0]
response = requests.get(path)
#again links and pictures handler. dont judge me, I wrote a function for it but IDK why it didn't works for pictures!
a = response.text.replace("='/",f"='{mainURL}")
a = a.replace('="/',f'="{mainURL}')
a = a.replace("url(/",f"url({mainURL}")
a = a.replace('href="http',f'href="{myHost}http')
a = a.replace("href='http",f"href='{myHost}http")
a = a.replace(r'href="(?!http)',f'href="{myHost}{mainURL}')
a = a.replace(r"href='(?!http)",f"href='{myHost}{mainURL}")
return a
return "URL is Incorrect!"
if __name__ == "__main__":
app.run(host='127.0.0.1',port='5000',debug=True)
This is Output:
opening Google using proxy
so its open a webpage but its so slow because of all those replace and with all of these its still can't load CSS!
so what I want is a optimized way to redirect all links to proxy and handling CSS!

Dialogflow response from webhook using flask python integration platform digital human uneeq

I am trying to send a response to Dialogflow Es using webhook written in python-flask.
Integration platform :
digital human --> Uneeq
I tried with the fulfillment library (dialogflow_fulfillment) but it was not working so I tried it without a library like :
if req.get('queryResult').get('action') == 'appointment':
print("ïntent triggered")
return {"fulfillmentText": 'BUDDY!'}
It worked!
Now the issue is before integrating this chatbot to digital human I wrote the whole code using the fulfillment library. Now I need to change the whole code for this purpose.
As I am unable to extract entities using context-based intents (session-vars) like :
case = agent.context.get('session-vars').get('parameters').get('case')
name = agent.context.get('session-vars').get('parameters').get('name')['name']
email = agent.context.get('session-vars').get('parameters').get('email')
phone = agent.context.get('session-vars').get('parameters').get('phone')
So my question is how to accomplish this task successfully?
If I try to use the fulfillment library then how to send a response to Dialogflow so that digital human will understand it since "agent.add" doesn't work.
Or, If I try to do it without a library then how to extract entities(from the session-vars) like (case, name, email, phone).
I need to save all these parameters(entities) in firebase, These output context (only session-vars parameters not other contexts):
This is the response I am getting correctly without library:
Unable to proceed at any cost!
looking forward to your response.
Thanks in advance!
Complete code (with the library):
from dialogflow_fulfillment import WebhookClient
from flask import Flask, request, Response
import json
app = Flask(__name__)
def handler(agent: WebhookClient) :
"""Handle the webhook request.."""
req = request.get_json(force=True)
a= req.get('queryResult').get('action')
if req.get('queryResult').get('action') == 'appointment':
name = agent.context.get('session-vars').get('parameters').get('name')['name']
email = agent.context.get('session-vars').get('parameters').get('email')
phone = agent.context.get('session-vars').get('parameters').get('phone')
print("ïntent triggered")
agent.add('BUDDY!')
#app.route('/webhook', methods=['GET', 'POST'])
def webhook():
req = request.get_json(force=True)
agent = WebhookClient(req)
agent.handle_request(handler)
return agent.response
if __name__ == '__main__':
app.run(debug=True)
Complete code (without library):
import urllib
import json
import os
from flask import Flask
from flask import request
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
#app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
res = makeWebhookResult(req)
res = json.dumps(res, indent=4)
r = make_response(res)
#print(res)
r.headers['Content-Type'] = 'application/json'
return r
def makeWebhookResult(req):
intent_name = req.get('queryResult').get('intent').get('displayName')
print(intent_name)
action_name = req['queryResult']['action']
if req.get('queryResult').get('action') == 'input.welcome':
print("intent trigered")
return {"fulfillmentText": 'Hi there'}
if action_name == 'test':
cont = req.get('queryResult').get('outputContexts')[0]['name']
print(type(cont))
x = cont.split("/")
print(x[6])
if x[6] == 'session-vars' :
para = req['queryResult']['outputContexts']
print(para)
print("test intent trigered")
return {"fulfillmentText": 'Bye there'}
if __name__ == '__main__':
app.run(debug=True)

Cannot add file as inline attachment python flask using CID

I have spent hours searching for a solution to no avail. I am trying to include some images in automatically generated emails, and have come up against some problems. I Cannot include the actual url as gmail blocks the images totally, so I am trying to send as attachments and then use Cids to reference the attachments. The issue is I haven't found a way to do this. Any help would be ace.
I am running python 3.6 on with Apache2 on an Ubuntu server. I have tried encoding images in base64 but that didnt work at all. the images in the email simply didnt show up.
def createVoucher(email, expiry):
voucherId = str(uuid.uuid4())
email = email
value = 1
expiryDate = expiry
redeemed = 1
connection = mysql.get_db()
cursor = connection.cursor()
cursor.execute("INSERT INTO vouchers (VoucherID, Value, ExpiryDate, Redeemed, Email) VALUES (%s,%s,%s,%s,%s)", (voucherId, value, expiryDate, redeemed, email))
msgBody = render_template('admin/eVoucherEmail.html', voucherId=voucherId, expiry=expiry)
msg = Message('New Sunday Funday eVoucher Received', sender = MAIL_USERNAME, recipients = [email])
msg.html = msgBody
with app.open_resource("static/img/Facebook.jpg") as fp:
msg.attach("Facebook.jpg", "image/jpg", fp.read())
mail.send(msg)
connection.commit()
So the code posted works fine attaching the file, it's just assigning a content id that I can use where I am struggling.
Here's how I insert an inline jpg using flask_mail.
versions: python=3.7.6, flask=1.1.2, and flask-mail=0.9.1
The "disposition" in message.attach needs to be "inline", and the html for the img should contain "cid:my_cid" as the src.
import uuid
from flask import Flask
from flask_mail import Mail, Message
from pathlib import Path
app = Flask(__name__)
app.config.update(
MAIL_SERVER='smtp.gmail.com', MAIL_PORT=465, MAIL_USE_SSL=True,
MAIL_USERNAME="myfakeemail54858939#gmail.com", MAIL_PASSWORD="myfakepw54858939")
flask_mail = Mail(app)
def test_send_voucher():
to_addr = "myfakeemail54858939#gmail.com"
expiry = "29 February"
voucher_png_path = Path(__file__).parent / "static/Facebook.jpg"
sendVoucherEmail(app, to_addr, expiry, voucher_png_path)
def sendVoucherEmail(app: Flask, to_addr: str, expiry: str, voucher_png_path: Path):
voucher_id = str(uuid.uuid4())
html = f"""<html><head></head><body>
<p>Congratulations on your voucher!<br>Your voucher code is {voucher_id}.
The offer expires on {expiry}.<br>
<img src="cid:voucher_png" width=200>
</p></body></html>"""
with app.app_context():
mail = Mail(app)
message: Message = Message(subject="my subject", sender="myfakeemail54858939#gmail.com",
recipients=[to_addr], html=html)
with app.open_resource(voucher_png_path) as fp:
message.attach(filename="myfilename.png", content_type="image/png", data=fp.read(),
disposition="inline", headers=[['Content-ID', '<voucher_png>']])
mail.send(message)
This example successfully sent an email via gmail, with an inline image "Facebook.jpg," as in the original question.
screenshot of received email

Flashing message using Flask up task completion

I'm still new to Flask and I am trying to build a flask app that flashes status as and when tasks are complete
`
app.route("/", methods=['GET', 'POST'])
def root():
form = ReusableForm(request.form)
if request.method == 'POST':
name = request.form['name']
if form.validate():
Reports1 = RunReport1()
flash('Report 1 run successfully')
Report2 = RunReport2()
flash('Report 2 run successfully')
return render_template('run.html', form=form)'
However, there doesn't seem to be a way to flash messages without rendering the html page each time. Any assistance would be greatly appreciated. Thanks.
You can do it with Flask without roundtrip to the system. You have to use content streaming. For this you have to use stream_with_context for the response.
#app.route("/")
def root():
reports = ["Reports1", "Reports2"]
def generate_output():
for i in range(0, len(reports)):
report = reports[i]
template = '<p>{{ report }}.</p>'
context = {'report': report}
yield render_template_string(template, **context)
time.sleep(5)
return Response(stream_with_context(generate_output()))
So this will update the response till server side complete its tasks. Normally this is used for long running processes. Refer the documentation.
Hope this helps!

Categories

Resources