Pass Returned Data From Python to JavaScript? - python

As I'm developing one chat bot for booking bus tickets I get request from user manually and returned response based on user request from API I did almost but I have doubt while passing returned data from Python to JavaScript using my IP address. Please anyone help me.
Here is my py:
import requests,json
import requests, json
from flask import render_template
import os
import time
from flask import render_template, Flask, request
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
# # import win32api
#
# win32api.MessageBox(0, 'hello', 'title')
app = Flask(__name__)
#app.route('/',methods=['GET','POST'])
def map():
return render_template("sara.html")
#app.route('/run',methods=['GET','POST'])
def main():
print("run")
url = 'http://webapi.i2space.co.in/Buses/Sources'
payload = {'some': 'data'}
headers = {'consumerkey': 'D0106432CD19C98E0E8267EDFE9E3DF0', 'consumersecret': '43DEC493EBAE756BF7A2312F55FE5132'}
r = requests.get(url, data=json.dumps(payload), headers=headers)
print(r.text)
# response_data = r.json()
response_data = json.loads(r.text)
# print(type(response_data))
# s=(response_data[0]['Name'])
# print(s)
sorceid=request.args.get('sid')
print(sorceid)
l=''
for a in response_data:
print("hello")
print(a)
print(a['Name'])
if (sorceid==a['Name']):
l=a['Id']
print(l)
break
else:
print("no")
# list={"iden":l}
# print(list)
return render_template("sara.html",l=l)
if __name__ == '__main__':
app.run(host='192.168.1.80')
Here is my JavaScript:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/static/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<h1> HERE COMES!!!</h1>
{{ l }}
<div class="w3-container w3-teal" align="center" style="width: 50%">
<span>Bus-Bot</span>
</div>
<div class="w3-container" align="center" style="width: 50%">
<div id="chatbox">
<p class="botText"> Bus-Bot:<span>Hi! I'm Bus-Bot.</span></p>
</div>
<div id="userInput">
<input id="textInput" type="text" name="msg">
<input id="buttonInput" type="submit" value="submit" >
</div>
<script>
function getBotResponse() {
var rawText = $("#textInput").val();
var userHtml = '<div id="Chatid" class="container">'+
'<p class="userText" >ME:<span>' + rawText + '</span></p>'+'</div>';
$("#chatbox").append(userHtml);
document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});
$.get("run", { msg: rawText }).done(function (data) {
alert(data);
var sou=data.l;
alert(sou);
alert(lol);
var botHtml = '<div id="botcon" class="container darker">'+'<p class="botText">Bus-Bot:<span>' + sou + '</span></p>'+'</div>';
console.log(botHtml);
$("#botcon").append(botHtml);
document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});
});
}
$("#textInput").keypress(function(e) {
if(e.which == 13) {
getBotResponse();
}
});$("#lolInput").keypress(function(e) {
if(e.which == 13) {
alert('weldone');
getBotResponse();
}
});
$("#buttonInput").click(function() {
getBotResponse();
})
</script>
<style>
.container {
border: 2px solid #dedede;
background-color: #f1f1f1;
border-radius: 5px;
padding: 10px;
margin: 10px 0;
}
/* Darker chat container */
.darker {
border-color: #ccc;
background-color: #ddd;
}
/* Clear floats */
.container::after {
content: "";
clear: both;
display: table;
}
/* Style images */
.container img {
float: left;
max-width: 60px;
width: 100%;
margin-right: 20px;
border-radius: 50%;
}
/* Style the right image */
.container img.right {
float: right;
margin-left: 20px;
margin-right:0;
}
/* Style time text */
.time-right {
float: right;
color: #aaa;
}
/* Style time text */
.time-left {
float: left;
color: #999;
}
</style>
</div>
</div>
</body>
</html>
From Python I returned response using variable name "l" but I don't know how to pass this variable to JavaScript I want to get my response below to this line
var botHtml = '<div id="botcon" class="container darker">'+'<p class="botText">Bus-Bot:<span>' + sou + '</span></p>'+'</div>';

The render_template function from Flask doesn't pass any variable from one language to the other. It just replaces strings inside the html-template that it finds with a variable that you handover to it. With
return render_template("sara.html",l=l)
you are telling the program to take the sara.html template and insert your variable l anywhere where it finds {{ l }} in the template. You should see it in the actual HTML that you are sending to the client. because you are inserting it under your heading:
<h1> HERE COMES!!!</h1>
{{ l }}
It is really more helpful if you are using it to render pure HTML and not JavaScript. Of cause you can also replace things inside your JavaScript but that is really not a sensible way to do client-server communication. If you want communication between your client and server you should think about a different architecture.
Doing the get call
url = 'http://webapi.i2space.co.in/Buses/Sources'
payload = {'some': 'data'}
headers = {'consumerkey': 'D0106432CD19C98E0E8267EDFE9E3DF0', 'consumersecret': '43DEC493EBAE756BF7A2312F55FE5132'}
r = requests.get(url, data=json.dumps(payload), headers=headers)
inside your server is probably better kept in your client-side Javascript.

Related

Python Flask, redirect after rendering a template

I'm trying to redirect a user after a template has been rendered. Essentially, my code waits till a variable turns to False, and then redirects the user. The code renders a loading animation and tells the user to wait. The code renders the html and css template, but then when the wait is over doesn't redirect the user to a new url. My code:
from flask import Flask, redirect, url_for, request, render_template
import json
import requests
import webbrowser
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
global is_busy
is_busy = False
app = Flask(__name__, template_folder='template')
#app.route('/')
def main_menu():
return redirect(url_for('enteruserid'))
#app.route('/EnterID')
def enteruserid():
global is_busy
return render_template('enterid.html')
def waitUntil(condition, output):
time.sleep(1)
#app.route('/Scrape', methods=['POST', 'GET'])
def login():
global is_busy
if request.method == 'POST':
id = request.form['nm']
try:
int(id)
return render_template('waitingscreen.html')
waitUntil(is_busy, False)
return redirect(url_for('scrapingtheinternet', target_id=id))
except:
return redirect(url_for('notanint'))
else:
id = request.args.get('nm')
if __name__ == '__main__':
app.run(debug=True)
This code doesn't include the function where the "Scraping" occurs.
enterid.html:
<!DOCTYPE html>
<html>
<head>
<title>DCF</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Reverse image search discord user id's">
<meta name="keywords" content="Discord">
<style>
h1 {
font-family: Arial, sans-serif;
color: #2f2d2d;
text-align: Center;
}
p {
font-family: Arial, sans-serif;
font-size: 14px;
text-align: Center;
color: #2f2d2d;
}
</style>
</head>
<body>
<form action = "http://localhost:5000/Scrape" method = "post">
<h1>Reverse Image Search</h1>
<p>Enter User ID: </p>
<p><input type = "text" name = "nm" /></p>
<p><input type = "submit" value = "submit" /></p>
</body>
</html>
waitingscreen.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Loader Bar</title>
<style>
body {
background-color: #262626;
font-family: Lato, sans-serif;
}
.loader {
width: 150px;
margin: 150px auto 70px;
position: relative;
}
.loader .loading_1 {
position: relative;
width: 100%;
height: 10px;
border: 1px solid yellowgreen;
border-radius: 10px;
animation: turn 4s linear 1.75s infinite;
}
.loader .loading_1:before {
content: "";
display: block;
position: absolute;
width: 0;
height: 100%;
background-color: yellowgreen;
box-shadow: 10px 0px 15px 0px yellowgreen;
animation: load 2s linear infinite;
}
.loader .loading_2 {
position: absolute;
width: 100%;
top: 10px;
color: green;
font-size: 22px;
text-align: center;
animation: bounce 2s linear infinite;
}
#keyframes load {
0% {
width: 0%;
}
87.5% {
width: 100%;
}
}
#keyframes turn {
0% {
transform: rotateY(0deg);
}
6.25%,
50% {
transform: rotateY(180deg);
}
56.25%,
100% {
transform: rotateY(360deg);
}
}
#keyframes bounce {
0%,
100% {
top: 10px;
}
12.5% {
top: 30px;
}
}
</style>
</head>
<body>
<div class="loader">
<div class="loading_1"></div>
<div class="loading_2">Please Wait...</div>
</div>
</body>
</html>
I'd appreciate any help. Thanks :)
Basically, the return statement ends the function in almost all languages.
say
def func():
print("hi")
return 0
print("after return")
func()
output:
hi
Whatever after return will not be executed (although see this answer about finally).
In your context, you can try to preview "waitingscreen.html" on the frontend when you click the login button
and avoid rendering it from the backend.
Some simple JS will help.
refer: Display a ‘loading’ message while a time consuming function is executed in Flask
Hope it will clear your query.

trouble retrieving an email from an username from a text document

so I have this website that allows me to get the email from a user that has signed up to the website, so when you sign up it adds your discord username and your email after it in a text file like this
Discorduser#0182 Test#example.com
Discordusernumber_one#0182 Testboi#example.co.uk
However, it retrieves the email from the first line when i put in the first option, but if i do the 2nd user, it cant seem to find it, here is the code to the website... the code is part of a bottle.py script but here is the main parts of this page
#get('/get_confirm')
def confirm():
return CONFIRM_PAGE
#post('/get_confirm')
def confirm():
name = request.forms.get('name')
for line in open('Confirmations.txt', 'r').readlines():
login_info = line.replace('\n', '').split()
if name == login_info[0]:
return CONFIRM_PAGE.replace('''<h1 id='emailbox'></h1>''', '<h1>' + login_info[1] + '</h1>')
else:
return CONFIRM_PAGE.replace('''<h1 id='emailbox'></h1>''', '<h1>' + 'That user is not valid' + '</h1>')
CONFIRM_PAGE = '''
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="/static/icon.ico">
<title>TylerR - get_confirms</title>
<style>
.content {
background: white;
padding: 15px;
border-radius: 3px;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a, .dropbtn {
display: inline-block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover, .dropdown:hover .dropbtn {
background-color: red;
}
li.dropdown {
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown:hover .dropdown-content {
display: block;
}
</style>
</head>
<body style='background-size: cover; background-image: url(\"/static/WebisteBackground.png\"); background-attachment: fixed;'>
<ul>
<li><a href='/'>Home</a></li>
<li><a href='/commands'>Commands</a></li>
<li><a href='/youtube'>Youtube</a></li>
<li><a href='/downloads'>Downloads</a></li>
<a href='https://www.youtube.com/channel/UCTHnGh3DpDXMyuL03ove1tQ'>
<img align='right' src='/static/youtubelogo.png' style="width:40px;height:40px;">
</a>
<a href='https://www.instagram.com/drumsnaps/'>
<img align='right' src='/static/Insta.png' style="width:40px;height:40px;">
</a>
</ul>
</div>
<center>
<h1 style="font-family:Cooper Black; font-size: 7em;"><b>Confirmations<b></h1>
<br>
<h1>Please enter an username to retrieve email</h1>
<h3>When entering name, replace any spaces with _</h3>
<form method='POST' action='/get_confirm'>
<h2>Discord Username:</h2>
<input name='name' type='text' placeholder='User#0000'>
<br>
<input type='submit'>
</form>
<div class='content'>
<h1 id='emailbox'></h1>
</div>
</center>
</body>
</html>
'''
I am using bottle.py
so if anyone could let me know why this is happening that would be great
In your check it returns immediately - with success (if user is on the first line) or no success (if user is not on first line). You want to return no success, only after you checked all lines.
#post('/get_confirm')
def confirm():
name = request.forms.get('name')
with open('Confirmations.txt', 'r') as f:
for line in f:
user, email = line.strip().split()
if name == user:
return CONFIRM_PAGE.replace('''<h1 id='emailbox'></h1>''', '<h1>' + email + '</h1>')
return CONFIRM_PAGE.replace('''<h1 id='emailbox'></h1>''', '<h1>' + 'That user is not valid' + '</h1>')
Also, better use template engine like jinja2 to construct the HTML page.

Django filter local folders

I have a templatetag function that returns a Collapse menu with all folders, subfolders and images in a root directory but now I want to be able to filter which folders I get, the templatetag function recives one parameter, the root directory, and I know it should recibe a second parameter with the folder I want to get but I'm confused in this part.
in my settings.py I have this:
STATICFILES_DIRS = [
BASE_DIR / 'static',
'D:/Users/my_user/Documents/Luis/results',
]
in my templatetag.py I have this:
from django import template
from django.utils.safestring import mark_safe
import os
register = template.Library()
#register.simple_tag
def my_tag(path):
html=''
for file in os.listdir(path):
rel = os.path.join(path, file)
if os.path.isdir(rel):
html += f"""<button type="button" class="collapsible">{file}</button>"""
html +='<div class="content"><div class="row mt-2">'
html += my_tag(rel)
html += '</div></div>'
else:
html +=f'<div class="col-md-6 d-flex align-items-stretch"><picture>'
x=str(rel)[43:]
print(x)
html += """<img src="/static"""+"""/%s" """%(x)
html += """ class="lazy card-img-top" width="500" height="400" """
html += """alt="/static"""+"""/%s" """%(x)
html +='></picture></div>'
return mark_safe(html)
and in my template.html I have this:
{% load static files %}
<style>
.collapsible {
background-color: #F8F8F8;
color: #858E9B;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
/* .active, .collapsible:hover {
background-color: #555;
}*/
.content {
padding: 0 18px;
display: none;
overflow: hidden;
background-color: #F8F8F8;
}.card-img-top {
height: 90vh !important;
object-fit: contain;
}
</style>
{% my_tag 'D:/Users/my_user/Documents/Luis/results' %}
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
</script>
This is an example of the final result:
So the idea is to get a specific day, can anyone give me an idea?

How to remove margins from PDF? (Generated using WeasyPrint)

I am trying to render a PDF document within my Flask application. For this, I am using the following HTML template:
<!DOCTYPE html>
<html>
<head>
<style>
#page {
margin:0
}
h1 {
color:white;
}
.header{
background: #0a0045;
height: 250px;
}
.center {
position: relative;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
text-align:center;
}
</style>
</head>
<body>
<div class="header">
<div class="center">
<h1>Name</h1>
</div>
</div>
</body>
</html>
I keep getting white margins at the top and right/left of my header section:
Is there a way to remove them?
Edit:
Below is the code used to generate the PDF file using WeasyPrint in my Flask app:
def generate_pdf(id):
element = Element.query.filter_by(id=id).first()
attri_dict = get_element_attri_dict_for_tpl(element)
html = render_template('element.html', attri_dict=attri_dict)
pdf = HTML(string=html).write_pdf()
destin_loc = app.config['ELEMENTS_FOLDER']
timestamp = dt.datetime.now().strftime('%Y%m%d%H%M%S')
file_name = '_'.join(['new_element', timestamp])
path_to_new_file = destin_loc + '/%s.pdf' % file_name
f = open(path_to_new_file, 'wb')
f.write(pdf)
filename = return_latest_element_path()
return send_from_directory(directory=app.config['ELEMENTS_FOLDER'],
filename=filename,
as_attachment=True)
Maybe you forgot " ; " or/and " mm ",
it works:
#page {
size: A4; /* Change from the default size of A4 */
margin: 0mm; /* Set margin on each page */
}
The weasyprint uses 3 sources of css, one of them is default user agent stylesheet
(https://doc.courtbouillon.org/weasyprint/stable/api_reference.html#supported-features)
That defines:
body {
display: block;
margin: 8px;
}
make sure to override that margin on tag and you will loose the margin.

use textarea for python input() to Skulpt

i want to use a textarea whenever the Python input() function is run in Skulpt. The default is to use an alert box - i want to use a textarea instead.
i've tried to get this working, but nothing happens when i try this example:
https://github.com/skulpt/skulpt/issues/685
everything else works fine as i want it. please help! :D
<!DOCTYPE html>
<html lang="en">
<head>
<script src="js/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="js/debugger.js" type="text/javascript"></script>
<script src="js/skulpt.min.js" type="text/javascript"></script>
<script src="js/skulpt-stdlib.js" type="text/javascript"></script>
<title>i dont like the alert boxes</title>
<style type="text/css" media="screen">
#source{
position: relative;
width: 500px;
height: 300px;
}
#console{
position: relative;
width: 500px;
height: 100px;
overflow: scroll;
}
body{
background-color: whitesmoke;
}
#turtleCanvas{
position: relative;
border: 1px;
border-color: firebrick;
border-collapse: collapse;
border-style: solid;
width: 500px;
}
</style>
<script src="js/brython/brython.js" type="text/javascript"></script>
</head>
<body onload="brython()">
<script type="text/javascript">
function outf(text) {
var mypre = document.getElementById("console");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
}
function runit() {
var editor = ace.edit("source");
var code = editor.getValue();
document.getElementById("hiddenCode").innerHTML = code;
var prog = document.getElementById("hiddenCode").value;
var mypre = document.getElementById("console");
mypre.innerHTML = '';
Sk.pre = "console";
Sk.configure({output:outf, read:builtinRead});
(Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'turtleCanvas';
var myPromise = Sk.misceval.asyncToPromise(function() {
return Sk.importMainWithBody("<stdin>", false, prog, true);
});
myPromise.then(function(mod) {
console.log('success');
},
function(err) {
console.log(err.toString());
});
}
</script>
<textarea id="hiddenCode" style="display:none;"></textarea><br />
<div id="source">import turtle
myName = input("who r u?")
print(myName)
t = turtle.Turtle()
t.forward(100)</div>
<button type="button" onclick="runit()">Run</button>
<textarea id="programInputField">some input lines</textarea>
<pre id="console">output</pre>
<div id="turtleCanvas"></div>
<script src="js/ace/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
var window1 = ace.edit("source");
var window2 = ace.edit("console");
window1.setTheme("ace/theme/textmate");
window2.setTheme("ace/theme/twilight");
window1.getSession().setMode("ace/mode/python");
</script>
</body>
Never mind!!!! This worked perfectly, just had to change the id of my text area, otherwise i just copied and pasted it and commented out my own sk.configure line..... brilliant, thankyou whoever you are!!!!!!! :D :D :D :D
Wait for an event to occur within a function in Javascript for Skulpt

Categories

Resources