Using Vue.js and Flask together - python

I had code that worked perfectly fine, then I wanted to use flask, so I copied it into a flask app directory. The html code is below:
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
</head>
<body>
<div id="app" class="container">
<div class="row">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item" v-for="tab in tabs" v-bind:class="tab.active">
{{ tab.name }}
</li>
</ul>
</div>
</nav>
</div>
<div class="row">
<div class="col">
<hr class="navbarDivide">
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="/static/js/challenges.js"></script>
</body>
</html>
When I remove the stuff for Vue, it works perfectly fine (when I remove the v-for, v-bind, and {{ tab.name }}. However, when I add it, it gives me a 500 error. I'm doing all of this using flask. Flask code below:
from flask import Flask, render_template
app = Flask(__name__)
application = app
#app.route('/base')
def index():
return render_template('base.html')
if __name__ == '__main__':
app.run(debug=True)
The javascript code just has the required stuff for Vue.js (the object with the data). The javascript code is below:
var app = new Vue({
el: '#app',
data: {
tabs: [
{ name: "Home", active: "" },
{ name: "Challenges", active: "active" },
{ name: "Scoreboard", active: "" },
{ name: "About", active: "" }
]
}
});
Update:
After a little more debugging, I think I may have figured out the problem. When I comment out all the stuff, and add console.log("it works"); to my javascript code, nothing happens. That probably means the javascript code isn't connecting to the html, but how can I solve that?

I found the solution. I was manually putting the url of the javascript
<script src="/static/js/challenges.js"></script>
What I had to do to fix it was use url_for
<script src="{{ url_for('static', filename='js/challenges.js') }}"></script>
Probably something a lot of people that have used flask before know, but I'm new to this.

Related

Flask python - POST not working 400 bad request

i cannot access the text box data in the back end. i wanna use the textbox value in the backend but it says 400 badrequest. Please help me with this. i cannot see where my code went wrong.i cannot access the text box data in the back end. i wanna use the textbox value in the backend but it says 400 badrequest. Please help me with this. i cannot see where my code went wrong.
python
from flask import Flask, render_template, url_for, request,redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import tweepy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db= SQLAlchemy(app)
#app.route('/')
def index():
return render_template('home.html')
#app.route('/getlivedata', methods=['POST','GET'])
def stream():
if request.method =="POST":
rows = request.form['numtweets']
else:
return render_template('home.html')
if __name__ == "__main__":
app.run(debug=True)
html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - Navigation PageDesign/Lesson</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="sara mazal lessons">
<meta name="keywords" content="HTML, CSS, JavaScript, mazal, icons">
<meta name="author" content="Sara Mazal">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght#200;300;400;500&family=Raleway:wght#100;200;300;400;500&family=Roboto:wght#300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/particlesjs/2.2.3/particles.min.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}">
</head>
<body>
<!-- partial:index.partial.html -->
<section class="nav">
<h1>LIVE TWITTER DATA ANALYSIS</h1>
<h3 class="span loader">
<span class="m">S</spam><span class="m">E</spam><span class="m">N</spam><span class="m">T</spam><span class="m">I</spam><span class="m">M</spam><span class="m">E</spam><span class="m">N</spam><span class="m">T</spam><span class="m">A</spam><span class="m">L</spam><span class="m"> </span><span class="m">A</spam><span class="m">N</spam><span class="m">D</spam><span class="m"> </span><span class="m">C</spam><span class="m">A</spam><span class="m">T</spam><span class="m">E</spam><span class="m">G</spam><span class="m">O</spam><span class="m">R</spam><span class="m">I</spam><span class="m">C</spam><span class="m">A</spam><span class="m">L</spam> </h3>
<div class="nav-container"><a class="nav-tab" href="#tab-pwa">PWA</a><a class="nav-tab" href="#tab-graphql">GraphQL</a><a class="nav-tab" href="#tab-next">NEXT</a><a class="nav-tab" href="#tab-typescript">TYPESCRIPT</a><a class="nav-tab" href="#tab-deno">DENO</a><span class="nav-tab-slider"></span></div>
</section>
<form action="#" method="post">
<main class="main">
<section class="slider" id="tab-pwa">
<h1>PWA</h1>
<input type="text" name="numtweets">
<h3>GetLiveData</h3>
<h2>the best of both worlds...</h2>
</section>
<section class="slider" id="tab-graphql">
<h1>GraphQL</h1>
<h2>a query language for APIs</h2>
</section>
<section class="slider" id="tab-next">
<h1>NEXT</h1>
<h2>framework for Production</h2>
</section>
<section class="slider" id="tab-typescript">
<h1>TYPESCRIPT</h1>
<h2>giving you better tooling at any scale</h2>
</section>
<section class="slider" id="tab-deno">
<h1>DENO</h1>
<h2>a modern runtime</h2>
</section>
</main>
</form>
<canvas class="background"></canvas>
<!-- partial -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script><script src="{{ url_for('static',filename='js/script.js') }}"></script>
</body>
</html>
Change your form action to "/getlivedata" so it would post the data there. Also, it seems that you are using the as the way to go to the url. Use a submitnbutton instead.

data given in the Ajax is not reaching in the views.py file and hence alert function is not working

I tried to reset password using Ajax in Django.For that, firstly I took email id from input box using a function and send it to views.py file using Ajax.In views.py file,there is a code for receiving email-id using GET method and check whether the email-id is available or not in the table.If available send the email-id back to html file using HttpResponse and display it using alert function.But it does not work properly.Can anyone suggest a solution for this.
HTML file :
<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
<meta charset="UTF-8">
<title>Index Page</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link href="{% static 'styles/style.css' %}" rel="stylesheet"/>
<script>
function getpass(){
let username=$("#uname").val()
$.ajax({
url : "{% url 'passwordreset' %}",
type : "GET",
data : {username : username},
success :function(data){
alert(data);
}
})
}
</script>
</head>
<body>
<section class="sflog" id="sflog">
<div class="container-fluid">
<div class="row">
<div class="col-12" id="std">
<form method="GET" action="">
{%csrf_token%}
<center>
<h3>Password <span>Reset</span></h3><br><br>
</center>
<div id="result"></div>
<label style="color:white;padding-left:13%;">Enter Your Username</label>
<center>
<input type="text" id="uname" name="username" placeholder="Username" required><br>
</center>
<button type="submit" style="margin-left:12%;" onclick="getpass()" name="login">Submit</button><br><br><br><br>
</form>
</div>
</div>
</div>
</section>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
urls.py
from django.urls import path
from . import views
urlpatterns=[
path('User/Forgot_Password',views.user_forgot_password,name="ufpassword"),
path('User/Forgot_Password/Reset',views.user_forgot_password_reset,name="passwordreset"),
]
views.py
from django.shortcuts import render,redirect,get_object_or_404
from user.models import clientlogin
from django.http import HttpResponse
def user_forgot_password(request):
return render(request,"forgot_password.html")
def user_forgot_password_reset(request):
if request.method == 'GET':
un = request.GET.get('username')
print(un)
try:
user = get_object_or_404(clientlogin, Username=un)
return HttpResponse(user.Username)
except:
return HttpResponse("No user registered with this Email ID")
else:
return render(request, "forgot_password.html")
First change the order in urls
urlpatterns=[
path('User/Forgot_Password',views.user_forgot_password,name="ufpassword"),
path('User/Forgot_Password/Reset',views.user_forgot_password_reset,name="passwordreset")
]
Because when request arrives, it will match the first always so either edit it to be
re_path('User/Forgot_Password$',views.user_forgot_password,name="ufpassword")
This way your reset URL won't match the forget password.
As some said put JQuery before $ sign.

Error as I'm switching to peewee for flask app. 'peewee.IntegerField object' has no attribute 'flags'

I began switching from using standard basic SQL in my flask app to using peewee and am getting a weird bug I cant seem to find any info about. My endpoints are working fine but when I tried going to the landing page I get "jinja2.exceptions.UndefinedError: 'peewee.IntegerField object' has no attribute 'flags'"
This seems like some weird interaction with wtforms and peewee but I cant seem to find similar issues. Thanks in advance.
Note everything is in one file
My Models:
class pipelineForm(FlaskForm):
pipeline = IntegerField('Pipeline ID')
class Process(Model):
pipeline_id = IntegerField()
process_name= CharField(null = True)
log= CharField(null = True)
exit_code= IntegerField()
started= CharField(null = True)
finsihed= CharField(null = True)
class Meta:
database=db
End Point for Landing Page:
#app.route('/bloodhound', methods=['GET','POST'])
def index():
form =pipelineForm()
print(form.errors)
if form.validate_on_submit():
print(str(form.pipeline.data))
return redirect(url_for('.display', pipelineId=form.pipeline.data))#'<h1>' + str(form.pipeline.data) + '</h1>'
return render_template('index.html',form=form)
Landing Page:
{% extends "bootstrap/base.html" %} {%import "bootstrap/wtf.html" as wtf%} {% block content %}
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Narrow Jumbotron Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="../../dist/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="../../assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="jumbotron-narrow.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="../../assets/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/bloodhound">Bloodhound</a>
</div>
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>Performance</li>
</ul>
</div>
</nav>
<body>
<div class="container">
<div class="jumbotron">
<h1>Welcome to Bloodhound!</h1>
<p class="lead">Enter a pipeline Id to get diagnostic information.</p>
<form class="input" method="POST" action="/bloodhound">
<div class="input-group" style="width: 300px;">
{{form.hidden_tag()}} {{wtf.form_field(form.pipeline)}}
<span class="input-group-btn" style="vertical-align: bottom;">
<button class="btn btn-default" type="submit" >Go!</button>
</span>
</div>
</form>
</div>
<footer class="footer">
<p>© 2017 MITRE.</p>
</footer>
</div>
<!-- /container -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
{% endblock %}
Full Stack Trace
Traceback (most recent call last):
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/patrick/process_tracker/api/tracker_api.py", line 201, in index
    return render_template('index.html',form=form)
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/templating.py", line 134, in render_template
    context, ctx.app)
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/templating.py", line 116, in _render
    rv = template.render(context)
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/jinja2/environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/jinja2/_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
 File "/home/patrick/process_tracker/api/templates/index.html", line 1, in top-level template code
    {% extends "bootstrap/base.html" %} {%import "bootstrap/wtf.html" as wtf%} {% block content %}
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 1, in top-level template
 code
    {% block doc -%}
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 4, in block "doc"
    {%- block html %}
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 20, in block "html"
    {% block body -%}
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 23, in block "body"
    {% block content -%}
  File "/home/patrick/process_tracker/api/templates/index.html", line 58, in block "content"
    <!-- {{form.hidden_tag()}} {{wtf.form_field(form.pipeline)}} -->
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/jinja2/runtime.py", line 553, in _invoke
    rv = self._func(*arguments)
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask_bootstrap/templates/bootstrap/wtf.html", line 36, in template
    {% if field.flags.required and not required in kwargs %}
  File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/jinja2/environment.py", line 430, in getattr
    return getattr(obj, attribute)
According to your error message this field
class pipelineForm(FlaskForm):
pipeline = IntegerField('Pipeline ID')
is of type pewee.IntegerField and you wan it to be the IntegerField type of WTForms. If you have both classes in the same file you need to:
import pewee
import wtforms.fields
class pipelineForm(FlaskForm):
pipeline = fields.IntegerField('Pipeline ID')
class Process(Model):
pipeline_id = pewee.IntegerField() # and so on

Get <span> value from web page and authentication without asking user and password

I have this video surveillance software on Windows that has it's brower remote access with user/password authentication, on PC's IP. (I can also view from remote since I have a public IP).
I check the code in the browser UI and want to take these span values (liveCameraCount and totalCameraCount):
I use the lime code, that is work but reply with:
None
None
ON
While it should be
2
2
ON
(I've also try with a time.sleep() to let the page load but without success)
from bs4 import BeautifulSoup
import urllib
import urllib2
import base64
url = "http://my.pc.ip.address:port"
username = "myuser"
password = "mypass"
handle = urllib2.Request(url)
authheader = "Basic %s" % base64.encodestring('%s:%s' % (username,password))
data = urllib.urlopen(url)
soup = BeautifulSoup(data, "html.parser")
cameras = soup.findAll('span')
for span in cameras:
print span.string
I'm also trying to login automatically without that it ask every time:
Enter username [for my.pc.ip.address:port]:------
Enter password for username at [for my.pc.ip.address:port]:-----
EDIT 1:
OK. that's strange.
If I press F12 I can see the value inside as the image posted, but if I press CRTL + U i see this code (without value). I don't understand:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
var isMobile = navigator.userAgent.match(/(iPhone|iPod|Android|BlackBerry)/);
if(isMobile){
window.location = '/mobile/';
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Sighthound</title>
<link rel="stylesheet" href="/css/sighthound-desktop.css" />
<style type="text/css">
#liveTime{
margin-left: 6px;
}
.views {
margin-right: 6px;
}
</style>
<!-- Favicons and touch icons -->
<!-- For retina-display iPads -->
<link href="/img/apple-touch-icon-xlarge.png" rel="apple-touch-icon- precomposed" sizes="144x144" type="image/png"/>
<!-- For retina-display iPhones -->
<link href="/img/apple-touch-icon-large.png" rel="apple-touch-icon-precomposed" sizes="114x114" type="image/png"/>
<!-- For iPad 1 -->
<link href="/img/apple-touch-icon-medium.png" rel="apple-touch-icon-precomposed" sizes="72x72" type="image/png"/>
<!-- For iPhone 3G, iPod Touch and Android -->
<link href="/img/apple-touch-icon-small.png" rel="apple-touch-icon-precomposed" type="image/png"/>
<!-- For Nokia -->
<link href="/img/apple-touch-icon-small.png" rel="shortcut icon"/>
<!-- For everything else -->
<link href="/img/favicon.png" rel="shortcut icon" type="image/png"/>
<link href="/img/favicon.ico" rel="shortcut icon" type="image/x-icon"/>
</head>
<body>
<script type="text/javascript"> if (!window.console) console = {log: function() {}}; </script>
<script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/handlebars.js"></script>
<script src="/js/underscore-min.js"></script>
<script src="/js/handlebars-extras.js"></script>
<script src="/js/xmlrpc.js"></script>
<script src="/js/sighthoundxmlrpc.js"></script>
<script src="/js/sighthound.js"></script>
<script src="/js/purl.js"></script>
<script src="/js/moment.min.js"></script>
<script src="/js/camera_display.js"></script>
<script src="/js/all_cameras_control.js"></script>
<script src="/js/common.js"></script>
<div class="container">
<div class="header">
<div class="logo"><img src="img/logo.png" height="80" /></div><!-- End of Logo -->
<div class="pageNav buttonBar">
Cameras
Clips
</div><!-- End of Page Nav -->
<div class="on-off buttonBar">
<a id="allOffButton" href="#" class="button">Off</a>
<a id="allOnButton" href="#" class="button">On</a>
</div><!-- End of Buttons -->
<div class="cameras">
Cameras<br />
<strong> <span id="liveCameraCount"></span> / <span id="totalCameraCount"></span> <span class="expressive">ON</span></strong>
</div><!-- Camera -->
</div><!-- End of Header -->
<div class="content">
<div class="contextMenu">
<div id="liveTime" class="date"></div><!-- End of Date -->
<!--<div class="fullscreen buttonBar">
<img src="img/iconFullscreen.png" width="18" />
</div>--><!-- End of Context Fullscreen -->
<div class="views buttonBar">
<!--<a id="view1up" href="#" class="button viewButton"<img src="img/icon1upBlue.png" /></a>-->
<a id="view2up" href="#" class="button viewButton"><img src="img/icon2upBlue.png" /></a>
<a id="view3up" href="#" class="button viewButton"><img src="img/icon3upBlue.png" /></a>
<a id="view4up" href="#" class="button active viewButton"><img src="img/icon4upWhite.png" /></a>
</div><!-- End of Context Views -->
</div><!-- End of Context -->
<div id="cameraGrid"></div>
<script id="cameraGridTemplate" type="text/x-handlebars-template">
{{#everyNth cameras {(columns)}}}
{{#if isModZeroNotFirst}}
</div>
{{/if}}
{{#if isModZero}}
<div class="videos">
{{/if}}
<div class="video-{(columns)}up cameraVideo">
<a href="live.html?camera={{name}}&live={{live}}&cameraindex={{index}}">
<div class="videoImgContainer"
data-camera_index="{{index}}">
<!-- Image stream content is built by camera_display.js -->
</div>
<div class="cameraTitle">
<span>{{name}}<span>
</div>
</a>
</div>
{{#if isLast}}
</div>
{{/if}}
{{/everyNth}}
</script>
</div><!-- End of Content -->
</div><!-- End of Container -->
<script src="/js/index.js" type="text/javascript"></script>
</body>
</html>
You could try swapping string for text as follows:
data = """<strong>
<span id="liveCameraCount">2</span>
" / "
<span id="totalCameraCount">2</span>
<span class="expressive">ON</span>
</strong>
</div>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, "html.parser")
for span in soup.findAll('span'):
print span.text
This would display the following for your small example:
2
2
ON
For your full HTML, the first two <span>s are empty, so empty strings will be printed.

Post JSON data using Angular.js

This is my first crack at Angular. I'm posting JSON data to an html page using Angular.js. I know I'm missing something but can't seem to get it working. Below is the html. I have a python script posting to the same URL below.
<!doctype html>
<html lang="en" ng-app id="ng-app">
<head>
<title>File Analysis</title>
<script src="js/angular.js"></script>
<script>
var myApp = angular.module('fileAnalysis', []);
myapp.controller('PostsCtrlAjax', function($scope, $http)
{
$http({method: 'POST', url: 'http://test.com'}).success(function(data)
{$scope.posts = data;}) // response data
});
</script>
</head>
<body>
<h1>You should begin to see new files being analyzed!</h1>
<div id="ng-app" ng-app ng-controller="PostsCtrlAjax">
<div ng-repeat="post in posts" >
<h2>
<a href='{{post.url}}'>{{post.title}}</a>
</h2>
<td>
{{post.filename}}
</td>
</div>
</body>
</html>

Categories