Python renders wrong page using web.py - python

I am trying to teach myself Python. I have the following code in my controller.py file:
import web
urls = {
'/', 'home',
'/register', 'registerclick'
}
render = web.template.render("views/templates", base="MainLayout")
app = web.application(urls, globals())
# Classes/Routes
class home:
def GET(self):
return render.home()
class registerclick:
def GET(self):
return render.register()
if __name__ == "__main__":
app.run()
And this is the code in my MainLayout.html:
$def with (page)
$var css: static/css/bootstrap.css
$var js1: static/js/jquery-3.1.0.min.js static/js/bootstrap.js static/js/material.min.js static/js/ripple.min.js static/js/scripty.js
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CodeWizard</title>
$if self.css:
$for style in self.css.split():
<link rel="stylesheet" href="$style" />
</head>
<body>
<div id="app">
<div class="navbar navbar-info navbar-fixed-top">
<div class="navbar-header">
<a class="navbar-brand">CodeWizard</a>
</div>
<ul class="nav navbar-nav">
<li>
<a class="waves-effect" href="/">Home Feed<div class="ripple-container"></div></a>
</li>
<li>
Discover<div class="ripple-container"></div>
</li>
<li>
Profile<div class="ripple-container"></div>
</li>
<li>
Settings<div class="ripple-container"></div>
</li>
</ul>
<div class="pull-right">
Register
</div>
</div>
<br /><br />
$:page
</div>
$if self.js1:
$for script in self.js1.split():
<script src="$script"></script>
</body>
</html>
I have 2 additional files (home.html, and register.html) and I have bootstrap available (although that has nothing to do with my issue).
When I start the application and I open a browser and enter localhost:8080 as the url, MainLayout.html is loaded into the browser (which I expect) but the contents of register.html are loaded into $:page and I don't know why.
When I remove the second entry from the urls and remove the regnsterclick class from controller.py, the MainLayout.html page is loaded and nothing appears to be loaded into $:page.
Any ideas why the contents of register.html get presented? Any help is greatly appreciated.
Thanks.

By defining urls with braces, you made it a set, which is unordered. You need to define urls as a tuple which can be done using parentheses.
This answer explains it well: https://stackoverflow.com/a/46633252/2150542

Related

Injecting data into html using Flask

I have a flask app, about saving strings into some db files.
I have a base.html file which is like navbar which i extend to every page. That navbar has a lots of links which require a specific string that the user has to enter, so i wanna know if there's a way to inject strings into that base.html file, cuz i can't make a route for a navbar base file right?
Navbar base file down below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/css/base.css">
<title>
BukkitList - {% block title %}{% endblock %}
</title>
</head>
<body>
<div class="NAV_B Hidden" id="MENU">
<div class="NAV_B_LINKS">
<img src="/static/assets/img/cube.png" alt="">
<a class="SUS" href="/">Home</a>
</div>
<div class="NAV_B_LINKS">
<img src="/static/assets/img/list.png" alt="">
<a class="/List{{UserId}}" href="/List">List</a>
</div>
<div class="NAV_B_LINKS">
<img src="/static/assets/img/add.png" alt="">
<a class="/Task_Add/{{UserId}}">Add Task</a>
</div>
<div class="NAV_B_LINKS">
<img src="/static/assets/img/settings.png" alt="">
<a class="SUS">Settings</a>
</div>
</div>
<div class="NAV_S" id="NAV">
<img src="/static/assets/img/cube.png" alt="">
<h3>{% block navtitle %}
{% endblock %}
</h3>
<img src="/static/assets/img/menu.png" alt="" onclick="Menu()">
</div>
{% block main %}
{% endblock %}
</body>
<script src="/static/js/base.js"></script>
</html>
Yes i need that UserId to be injected.
the question is not very understandable of where the user is inputting the {{UserID}} but from what I understand that there is that userID that you can select from the db in the Python file and you want to pass it into the HTML page or if you have a sign-in in your page, you can grab that ID when they sign in using flask_session either way if you need to pass that userID from the Python file you will need to include it in your return, so in python it will look like that if you are using session:
#app.route("/")
def main():
UserIDpy = Session["YourSessionVar"]
return render_template("YourHTMLpage.html", UserID = UserIDpy)
The UserID is the var name that will be passed into the HTML page and UserIDpy is the var name that what UserID saved at.
So that code will replace all of {{ UserID }} you have at you HTML page
I believe you can do this with Flask's session variable. It allows you to create and update a global variable that can be referenced in templates even when you don't render them directly. This is similar to Lychas' answer, but should be more suited for your purpose.
Create/update a session variable in your login route (or wherever you want to update this value) with this line:
session['UserId'] = your_id_value_here
You can then use this session variable in your jinja templates with something like the following:
<a class="/Task_Add/{{ session['UserId'] }}">Add Task</a>
(Note, if you are not already using session, you will need to import it with from Flask import session.)

How to print variable present in python with the help of html?

I've written some code for deep learning text summarization, and I'm trying to render the template using the Flask library. I'm unable to see the results. The python code can be found below.
text = ' '.join([summ['summary_text'] for summ in res])
print(text)
return render_template('result.html', prediction=text)
I'm trying to print the prediction variable which is present in the above code. Below is the html code
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/styles.css') }}">
</head>
<body>
<header>
<div class="container">
<div id="brandname">
Deep Learning App
</div>
<h2>Summarized text</h2>
</div>
</header>
<p style="color:blue;font-size:20;text-align: center;"><b>Result for Text</b></p>
<div class="results">
<p><strong>{prediction}</strong></p>
</div>
</body>
</html>
Below is output image
enter image description here
Can anyone help me how to display text present in prediction variable on web page?
You need double curly braces
<p><strong>{{ prediction }}</strong></p>

Unable to use Jinja templating to pass variable from Starlette backend to Javascript frontend

I am using starlette ASGI framework and want to render an HTML response.
Using a dummy route below to test passing a variable to javascript frontend.
#app.route('/error')
async def server_error(request):
template = 'analyze_response.html'
context = {"request": request}
return templates.TemplateResponse(template, context, data=75)
This is my 'analyze_response.html' file:
<html lang='en'>
<head>
<meta charset='utf-8'>
<link rel='stylesheet' href='../static/style.css'>
<script src='../static/client.js'></script>
<link rel="stylesheet" href="../static/cmGauge.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="../static/cmGauge.js"></script>
<script type="text/javascript">
var data = {{ data|tojson }}
</script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div>
<div class='center'>
<div class='title'>Sentiment Analysis of Movie Reviews</div>
<div class='content'>
<form action="/analyze" class="form" method="post">
<div class="form-group">
<textarea rows = "10" cols = "100" name = "review_text"></textarea><br>
</div>
<div class='analyze'>
<input type="submit" class="form-submit-button" value="Analyze">
</div>
</form>
<div id="gaugeDemo" class="gauge gauge-big gauge-green">
<div class="gauge-arrow" data-percentage="40"
style="transform: rotate(0deg);"></div>
</div>
<script type="text/javascript">
$('#gaugeDemo .gauge-arrow').cmGauge();
$('#gaugeDemo .gauge-arrow').trigger('updateGauge', myFunc());
</script>
</div>
</div>
</div>
</body>
As per some of the answers, I tried everything but it's still not working.
Getting below error:
File "app/server.py", line 125, in server_error
return templates.TemplateResponse(template, context, data=data) TypeError: TemplateResponse() got an unexpected keyword argument
'data'
Can you please let me know what the issue is? Thanks.
You need to pass it inside the context variable:
#app.route('/error')
async def server_error(request):
template = 'analyze_response.html'
context = {'request': request, 'data': 75}
return templates.TemplateResponse(template, context)

Text extraction using BeautifulSoup

I have html data like:
<!DOCTYPE html>
<html>
<head>
<script type="text/blzscript">
</script>
<title></title>
</head>
<body>
<p class="status-box">In some countries, this medicine may only be approved for veterinary use.</p>
<h3>Scheme</h3>
<p>Rec.INN</p>
<h3>CAS registry number (Chemical Abstracts Service)</h3>
<p>0000850-52-2</p>
<h3>Chemical Formula</h3>
<p>C21-H26-O2</p>
<h3>Molecular Weight</h3>
<p>310</p>
<h3>Therapeutic Category</h3>
<p>Progestin</p>
<h3>Chemical Names</h3>
<p>17α-Allyl-17-hydroxyesta-4,9,11-trien-3-one (WHO)</p>
<p>Estra-4,9,11-trien-3-one, 17β-hydroxy-17-(2-propenyl)- (USAN)</p>
<h3>Foreign Names</h3>
<ul>
<li>Altrenogestum (Latin)</li>
<li>Altrenogest (German)</li>
<li>
Altrénogest (French)
</li>
<li>Altrenogest (Spanish)</li>
</ul>
<h3>Generic Names</h3>
<ul>
<li>Altrenogest (OS: BAN, USAN)</li>
<li>
Altrénogest (OS: DCF)
</li>
<li>A 35957 (IS)</li>
<li>A 41300 (IS)</li>
<li>RH 2267 (IS)</li>
<li>RU 2267 (IS: RousselUclaf)</li>
</ul>
<h3>Brand Names</h3>
<div class='contentAdRight' id='third_ad_unit'>
<div class='adsense-ad adsense-ad-text-image-flash-html adsense-ad-300 adsense-ad-300x600 adsense-ad-international'>
<script type="text/blzscript">
google_ad_client="pub-3964816748264478";google_ad_channel="";google_ad_format="300x600_pas_abgc";google_ad_width="300";google_ad_height="600";google_ad_type="text,image,flash,html";google_color_border="FFFFFF";google_color_bg="FFFFFF";google_color_link="0000FF";google_color_text="000000";google_color_url="008000";google_analytics_domain_name="drugs.com";
</script>
<h1></h1>
</div>
</div>
</body>
</html>
and i want to extract :
Foreign names , generic names and brand names:
I tried
test = soup.select('h1')[0].text.strip()
print(test)
But it is not giving what i want i also tried to extract for script but none of them are giving result as i required

Why does twilios call forwarding not work when I am calling through browser, but work fine when calling a twilio number with exact same request url

I have one phone number with a request url which works (speaks the text and then forwards the call) but then I have an app (a browser outbound call) going to the same request url and only the text to speech works, and the forwarding of the call gives an error and hangs up. Why doesn't it forward like the number's request url? I checked and the capability token renders fine...
views.py
def once_connected_view(request):
response = twiml.Response()
response.say("Please wait while we connect your call.", voice='alice')
response.dial("xxx-xx-xxx-xxxx")
return HttpResponse(str(response))
def home_view(request):
capability = TwilioCapability(account_sid, auth_token)
capability.allow_client_outgoing(application_sid)
token = capability.generate()
query_set = Model.objects.all()
return render(request, "base.html", {"query_set":query_set, "token":token})
urls.py
urlpatterns = [
url(r'^$', views.home_view, name="home"),
url(r'^once_connected/', views.once_connected_view, name="once_connected"),
]
number request url
http://xx.xx.com/once_connected/ http GET
app request url
http://xx.xx.com/once_connected/ http GET
main site url
https://xx.xx.com/
base.html
<!doctype html>
<head>
<script type="text/javascript" src="https://static.twilio.com/libs/twiliojs/1.2/twilio.min.js"></script>
<script type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=320, height=device-height, target-densitydpi=medium-dpi" />
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'cars/responsive.css' %}">
</head>
<body>
<div class="container" id="wrapper">
<div class="video-background-container">
<video preload="auto" autoplay="" loop="" muted="" class="video-background hidden-xs hidden-sm">
<source type="video/mp4" src="omitted">
</video>
</div>
<div class="grid-overlay text-center">
<nav class="navbar navbar-default navbar-fixed-top" style="background:none;">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" id="logo" href="#">Brand Name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="replace-call">Contact Us</li>
</ul>
</div>
</div>
</nav>
...
<script src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script type="text/javascript">
/* Create the Client with a Capability Token */
Twilio.Device.setup("{{ token }}");
/* Let us know when the client is ready. */
Twilio.Device.ready(function (device) {
$(".replace-call").html("<a href='#' onclick='call()'>Call From Browser</a>");
});
/* Report any errors on the screen */
Twilio.Device.error(function (error) {
$(".replace-call").html('Contact Us');
});
Twilio.Device.connect(function (conn) {
$(".replace-call").html("<a href='#' onclick='hangup()'>End Call</a>");
});
/* Connect to Twilio when we call this function. */
function call() {
Twilio.Device.connect();
}
function hangup() {
Twilio.Device.disconnectAll();
$(".replace-call").html('Contact Us');
}
</script>
</body>
</html>
I am hosted on pythonanywhere.
After only minimal hair loss, I have made it work by adding a callerID attribute to the dial verb.
def once_connected_view(request):
response = twiml.Response()
response.say("Please wait while we connect your call.", voice='alice')
response.dial("xxx-xx-xxx-xxxx", callerId="+xxxxxxxxxx") # here
return HttpResponse(str(response))

Categories

Resources