No Secret Key... I imagine it was something else - javascript

I am making a chat app using Flask/ Socketio/ Javascript, and when I am designing the "create channel" function and when the app is run it said RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret..
I've seen other "secret key" related topics but first: I did not place the secret_key declaration somewhere strange, and second: I remembered to add the app.config['SESSION_TYPE'], since this is where I tripped last time.
I figured the problem was related to the flash function since when I removed it, everything works. Is there some way that I can flash a message but not getting an error?
My code:
application.py
import os
import requests
from flask import Flask, jsonify, render_template, request, redirect, url_for, flash
from flask_socketio import SocketIO, emit, join_room, leave_room
app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_PERMANENT']= False
socketio = SocketIO(app)
channels = {"1":0,"2":0,"3":0}
#app.route("/")
def home():
return render_template('home.html', channels = channels)
#app.route("/chat")
def chat():
username = request.args.get('username')
channel_id = request.args.get("channel_id")
if username and channel_id:
channels[channel_id] +=1
return render_template("index.html", username=username, channel_id=channel_id)
print("Wait")
return redirect(url_for('home'))
#app.route("/create")
def make_channel():
channel_name = request.args.get("channel_name")
if channel_name and not str.isspace(channel_name):
channels[channel_name] = 0
flash("Channel created!")
return redirect(url_for('home'))
flash('You have not filled in the channel name!')
return render_template('home.html', channels=channels)
#socketio.on('join_room')
def join_room_event(data):
app.logger.info("{} has joined channel {}. ".format(data['username'], data['channel']))
join_room(data['channel'])
socketio.emit('joined_room', data)
#socketio.on('leave_room')
def leave_room_event(data):
app.logger.info("{} has left channel {}.".format(data['username'], data['channel']))
leave_room(data['channel'])
socketio.emit('left_room', data)
channel_id = data['channel']
channels[channel_id] -= 1
#socketio.on("send")
def vote(data):
emit("announce message", data, broadcast=True)
if __name__ == '__main__':
app.run(debug=True)
home.html
<!DOCTYPE HTML>
<html>
<head>
<title>Hello, world!</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
{% if message != () %}
<h4 class="text-danger">{{ message }}</h4>
{% endif %}
<form action="{{ url_for('chat') }}">
<div>
<label>Enter your name:</label>
<label>
<input type="text" name="username">
</label>
</div>
<div>
<label>Enter Channel ID:</label>
<select name="channel_id">
{% for channel in channels %}
<option value="{{ channel }}">{{ channel }} --- {{ channels[channel] }} users online</option>
{% endfor %}
</select>
</div>
<button type="submit">Enter Room</button>
</form>
<form action="{{ url_for('make_channel') }}">
<label>Enter Channel Name:</label>
<label>
<input type="text" name="channel_name">
</label>
<button type="submit">Create Channel</button>
</form>
<script>
document.addEventListener('DOMContentLoaded')
</script>
</body>
</html>
index.html
Note: I know I shouldn't place javascript and HTML in the same file, so don't talk about that.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdn.jsdelivr.net/npm/handlebars#latest/dist/handlebars.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
// Connect to websocket
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
socket.on('connect', () => {
socket.emit('join_room', {
'username': "{{ username }}",
'channel': '{{ channel_id }}'
})
});
// The button should emit the value of the textbox
document.getElementById('send').onclick = e => {
e.preventDefault();
let message_input = document.getElementById('textbox');
const message = message_input.value.trim();
if(message.length){
socket.emit('send', {
'message': message,
'username': "{{ username }}",
'channel': "{{ channel_id }}"
});
}
message_input.value = '';
message_input.focus();
};
document.getElementById('leave').onclick = () =>{
const data = {
'username': '{{ username }}',
'channel': '{{ channel_id }}'
};
socket.emit('leave_room', data);
window.location.href = "{{ url_for('home') }}";
};
socket.on('left_room', data =>{
if (data.channel === "{{ channel_id }}"){
const inner = document.createElement('div');
inner.innerHTML = `<b>${data.username}</b> has left the room.`;
inner.style.backgroundColor = "#e1f3fb";
inner.style.fontFamily = "sans-serif";
inner.style.fontSize = "12px";
inner.style.borderColor = "#d5cec7";
inner.className = "rounded";
inner.style.display= "inline-block";
inner.style.border= '2px solid #d5cec7';
const div = document.createElement('div');
div.appendChild(inner);
div.style.width = "100%";
document.getElementById('message').appendChild(div);
}
});
socket.on('joined_room', data => {
if (data.channel === "{{ channel_id }}"){
const inner = document.createElement('div');
if (data.username !== "{{ username }}"){
console.log('not me.');
inner.innerHTML = `<b>${data.username}</b> has joined the channel!`;
} else {
console.log('me.');
inner.innerHTML = `<b>You</b> joined the channel.`;
}
inner.style.backgroundColor = "#e1f3fb";
inner.style.fontFamily = "sans-serif";
inner.style.fontSize = "12px";
inner.style.borderColor = "#d5cec7";
inner.className = "rounded";
inner.style.display= "inline-block";
inner.style.border= '2px solid #d5cec7';
const div = document.createElement('div');
div.appendChild(inner);
div.style.width = "100%";
document.getElementById('message').appendChild(div);
}
});
socket.on('announce message', data => {
console.log(data.channel);
console.log("{{ channel_id }}");
if (data.channel === "{{ channel_id }}") {
const inner = document.createElement('div');
const div = document.createElement('div');
inner.innerHTML = `${data.username}: ${data.message}`;
inner.style.fontFamily = "sans-serif";
inner.style.fontSize = "12px";
inner.style.borderColor = "#d5cec7";
inner.className = "rounded";
inner.style.display = "inline-block";
inner.style.border = '2px solid #d5cec7';
if (data.username === "{{username}}") {
inner.style.backgroundColor = "#dcf8c7";
div.style.textAlign = "right";
} else {
inner.style.backgroundColor = "#ffffff";
div.style.textAlign = "left";
}
div.appendChild(inner);
div.style.width = "100%";
document.getElementById('message').appendChild(div);
}
});
});
</script>
<style>
body{
font-family: Arial, sans-serif;
}
div{
padding: 2px 12px;
text-align: center;
}
</style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css">
<title>Messages on Channel {{ channel_id }}</title>
</head>
<body>
<h1>Welcome to Channel {{ channel_id }}</h1>
<button id="leave">Leave Channel</button>
<label for="textbox"></label><input id="textbox" placeholder="Message..." type="text">
<button id="send">Send</button>
<hr>
<div id="message">
</div>
</body>
</html>
can anyone help?
Error Message:
127.0.0.1 - - [11/Jul/2020 14:22:35] "GET /create?channel_name=Hi HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask_socketio/__init__.py", line 46, in __call__
start_response)
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/engineio/middleware.py", line 74, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/scythia/Desktop/Project2/application.py", line 33, in make_channel
flash("Channel created!")
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask/helpers.py", line 423, in flash
session["_flashes"] = flashes
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/werkzeug/local.py", line 350, in __setitem__
self._get_current_object()[key] = value
File "/Users/scythia/Desktop/Project2/venv/lib/python3.7/site-packages/flask/sessions.py", line 103, in _fail
"The session is unavailable because no secret "
RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.

No need to change your code.In your command prompt, after setting up the environment(if u r using) and other things, just write this;
set SECRET_KEY=your secret key
Where in place of "your secret key" set some string as your secret key.

Edit
Did you try to change app.run(debug=True) to socketio.run(app, debug=True) as instructed in Flask-SocketIO docs?
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
if __name__ == '__main__':
socketio.run(app)
Not tested.
Original answer
Here's a snippet from Flask docs:
from flask import Flask, session, redirect, url_for, request
from markupsafe import escape
app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
So you should change app.config["SECRET_KEY"] = os.getenv("SECRET_KEY") to app.secret_key = os.getenv("SECRET_KEY").
https://flask-socketio.readthedocs.io/en/latest/#initialization

Check if you've installed python-dotenv, you will never get the env var with os.getenv() function if your .env file is not loaded automatically (with python-dotenv)
Before this, you can manually set app.secret_key = 'xxx' to see if it's the issue I mentioned above.

Related

zukf8.png:1 Failed to load resource: the server responded with a status of 404 (NOT FOUND)

I have two files, one is a Python file
import random
import imageio as iio
from flask import Flask, render_template
from captcha.image import ImageCaptcha
app = Flask(__name__)
result_str = ''.join(
(random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') for i in range(5)))
#app.route('/')
def generateCaptcha():
# Create an image instance of the given size
image = ImageCaptcha(width=280, height=90)
# Image captcha text will equal random result
captcha_text = result_str
# generate the image of the given text
data = image.generate(captcha_text)
# write the image on the given file and save it
image.write(captcha_text, result_str + '.png')
newData = {'CaptchaValue': result_str}
return render_template('main.html', newData=newData)
if __name__ == "__main__":
app.run(debug=True)
The other is an HTML
<!DOCTYPE HTML>
<html>
<head>
<title> Example </title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<link rel="shortcut icon" href="#">
</head>
<body onload="example()">
<h1> Captcha Example </h1>
<label> Enter the text from Captcha above </label>
<input type="text" id="CaptchaInput">
<br> <br>
<input type="button" value="Enter" id="Button">
<script>
var Captcha ='{{ newData.CaptchaValue }}';
Button.addEventListener("click", function() {
if(Input === Captcha) {
console.log("Match");
} else {
console.log("Incorrect");
}
})
function example () {
$.ajax({
url: "/",
context: document.body
})
var img1 = new Image();
img1.src = ".//zukf8.png"
}
</script>
</body>
</html>
However, I always get the error Failed to load resource: the server responded with a status of 404 (NOT FOUND) zukf8.png.
If you need to know the file directories.
Python File: "C:\Users\Abdulahad\PycharmProjects\Captcha\main.py"
HTML File: "C:\Users\Abdulahad\PycharmProjects\Captcha\templates\main.html"
PNG File: "C:\Users\Abdulahad\PycharmProjects\Captcha\zukf8.png"
I feel like maybe it's a directory issue, maybe because it's using
Request URL: http://127.0.0.1:5000//zukf8.png
I have tried many different ways of linking the png including an absolute file path, but that's blocked

URL Redirection while on video streaming using Javascript and Flask

I have created an object recognition file that is successfully recognizing the objects like Apple and Mango. I have implemented the real time video streaming on Flask by following the tutorial from,
Video Streaming Blog
Here is my Flask File.
from flask import Flask, render_template, Response, redirect, url_for
from camera import VideoCamera
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
def gen(camera1):
while True:
label, frame = camera1.get_frame()
yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n'
yield frame
yield b'\r\n\r\n'
def genlabel(camera1):
while True:
label, frame = camera1.get_frame()
return label
#app.route('/form')
def form():
return Response(genlabel(VideoCamera()),
mimetype='text')
#app.route('/video_feed')
def video_feed():
label = gen(VideoCamera())
return Response((label),
mimetype='multipar/x-mixed-replace; boundary=frame')
#app.route('/apple')
def add():
return render_template('apple.html')
And Here is my rendered index.html file.
<html>
<head>
<title>Video Streaming Demonstration</title>
</head>
<body>
<p id="label">Here will be date|time</p>
<script>
var label = document.getElementById("label");
if (label == "apple"){
label.addEventListener('change', doThing);
}
setInterval(() => {
fetch("{{ url_for('form') }}")
.then(response => {
response.text().then(t => {label.innerHTML = t})
});
}, 100);
/* function */
function doThing(){
location.href = "{{ url_for('apple') }}";
}
</script>
</body>
</html>
It's not redirecting even when apple detected in video stream. Why ?

GET and POST methods and how they should be used

I am building a locally hosted website via flask that I will use to scrape sites like craigslist. I have run into some problems getting the main index page to update correctly. I am a novice when it comes to this sort of fullstack level development.
Why is the front page of my website not updating when I change the variable being passed into the javascript? Whenever I POST(i.e. make a submission via a search box, the Entries variable doesn't appear to update. I am very new to javascript so please be gentle. ;)
below is the code:
<head>
<title>Flask app</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="topnav">
<a class="active" href="#home">Home</a>
About
Contact
<form class = "form" action="/index" method="POST">
<input id ="textbox" name="textbox" type="text" placeholder="Search..">
<button type="submit">submit</button>
</form>
</div>
<p id="search-query"> you searched: </p>
<div id="div1">
<p id="p1"></p>
<p id="p2"></p>
</div>
<script>
var value = $('.textbox').val();
//alert(value);
$("button").click(function (e) {
e.preventDefault();
var value = $("#textbox").val();
//alert(value);
$.ajax({
type: 'POST',
url: "index",
data: JSON.stringify({"text" : value}),
contentType: 'application/json; charset=utf-8',
success: function(data){
$("#search-query").text("you search: " + data["text"]);
//alert(JSON.stringify(data));
}
});
});
var jsonz = {{ entries|tojson }};
var s = JSON.parse(jsonz);
var i;
for (i = 0; i < s.length; i++) {
var para = document.createElement("p");
var node = document.createTextNode(s[i].product_name + "\n" + s[i].product_link);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
}
</script>
</body>
</html>
and here is app.py
from scraper import scrape
from flask import Flask, render_template, jsonify, make_response, request
import json
app = Flask(__name__)
#app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
search = request.get_json()
search = json.dumps(search)
search = json.loads(search)
search = search['text']
print search
#search = json.loads(search)
entries = json.dumps(scrape(search))
return render_template('index.html', entries = entries)
elif request.method == "GET":
entries = json.dumps(scrape("cars"))
return render_template('index.html', entries= entries)
else:
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5000)
you can make a check below these steps
1、check your ajax url is define in your flask app, your flask app do not define '/index', so please check your api is work correctly, like this
#app.route("/index", methods=['GET', 'POST'])
2、ajax receive data but not html page, so your flask should return data(i.e,{text:"xxxx"}),then you can use $("#search-query").text("you search: " + data["text"]); to update, like this
#app.route("/index", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
search = request.get_json()
search = json.dumps(search)
search = json.loads(search)
search = search['text']
print search
#search = json.loads(search)
entries = json.dumps(scrape(search))
return entries
hope it can help you!

How do I update the javascript in my index.html file?

I am currently making a flask app. I cant get the javascript to update whenever I do a post request. It just stays the same. Here is the code I am focused on that is supposed to update whenever I do a post request:
var jsonz = {{ entries|tojson }};
var s = JSON.parse(jsonz);
var i;
for (i = 0; i < s.length; i++) {
var para = document.createElement("p");
var node = document.createTextNode(s[i].product_name + "\n" + s[i].product_link);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
I am very new to javascript. I want to pass in "entries" from the back end and then have that json be displayed in the index.html.
Someone please help.
Here is the full code for index.html
<!DOCTYPE html>
<html>
<head>
<title>Flask app</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="topnav">
<a class="active" href="#home">Home</a>
About
Contact
<form class = "form" action="/index" method="POST">
<input id ="textbox" name="textbox" type="text" placeholder="Search..">
<button type="submit">submit</button>
</form>
</div>
<p id="search-query"> you searched: </p>
<div id="div1">
<p id="p1"></p>
<p id="p2"></p>
</div>
<script>
var value = $('.textbox').val();
//alert(value);
$("button").click(function (e) {
e.preventDefault();
var value = $("#textbox").val();
//alert(value);
$.ajax({
type: 'POST',
url: "index",
data: JSON.stringify({"text" : value}),
contentType: 'application/json; charset=utf-8',
success: function(data){
$("#search-query").text("you search: " + data["text"]);
//alert(JSON.stringify(data));
}
});
});
var jsonz = {{ entries|tojson }};
var s = JSON.parse(jsonz);
var i;
for (i = 0; i < s.length; i++) {
var para = document.createElement("p");
var node = document.createTextNode(s[i].product_name + "\n" + s[i].product_link);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
}
</script>
</body>
</html>
and here is app.py
from scraper import scrape
from flask import Flask, render_template, jsonify, make_response, request
import json
app = Flask(__name__)
#app.route("/", methods=['GET', 'POST'])
#app.route("/index", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
search = request.get_json()
search = json.dumps(search)
search = json.loads(search)
search = search['text']
print search
#search = json.loads(search)
entries = json.dumps(scrape(search))
return entries
elif request.method == "GET":
entries = json.dumps(scrape("cars"))
return render_template('index.html', entries= entries)
else:
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5000)
Again, I want the scraped data in the form of "entries" to be passed to the front end and displayed in the html.
Thanks for any help!
HERES WHAT I DID TO FINALLY GET IT WORKING
<!DOCTYPE html>
<html>
<head>
<title>Flask app</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="topnav">
<a class="active" href="#home">Home</a>
About
Contact
<form class = "form" action="/index" method="POST">
<input id ="textbox" name="textbox" type="text" placeholder="Search..">
<button type="submit">submit</button>
</form>
</div>
<p id="search-query"> search results: </p>
<div id="div1">
<p id="p1"></p>
<p id="p2"></p>
</div>
<script>
var value = $('.textbox').val();
//alert(value);
$("button").click(function (e) {
e.preventDefault();
var value = $("#textbox").val();
alert(value);
$.ajax({
type: 'POST',
url: "parse_data",
data: JSON.stringify({"text" : value}),
contentType: 'application/json; charset=utf-8',
success: function(data){
$("p#search-query").append(data.data);
alert(JSON.parse(data));
}
});
});
</script>
</body>
</html>
and app.py
from scraper import scrape
from flask import Flask, render_template, jsonify, make_response, request
import json
app = Flask(__name__)
#app.route("/")
def index():
return render_template('index.html')
#app.route("/parse_data", methods=['POST'])
def parse_data():
search = request.get_json()
search = json.dumps(search)
search = json.loads(search)
search = search['text']
print search
#search = json.loads(search)
entries = json.dumps(scrape(search))
#entries = jsonify({'name' : entries})
return jsonify({'data' : render_template('response.html', entries= entries)})
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5000)

Flask, REST, JQuery, JSONP trying to get data from one end to the other

What I've done so far.
Created a Flask app
from flask import Flask
import json
from os import path
app = Flask(__name__)
from functools import wraps
from flask import redirect, request, current_app
def jsonp(func):
"""Wraps JSONified output for JSONP requests."""
#wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callback:
data = str(func(*args, **kwargs).data)
content = str(callback) + '(' + data + ')'
mimetype = 'application/javascript'
return current_app.response_class(content, mimetype=mimetype)
else:
return func(*args, **kwargs)
return decorated_function
def getdatafromfile():
my_dir = path.dirname(__file__)
json_file_path = path.join(my_dir, 'items.json')
with open(json_file_path, 'r') as f:
thedata = json.load(f)
return str(thedata)
#app.route('/test', methods=['GET'])
#jsonp
def test():
thedata = getdatafromfile()
return thedata
if __name__ == '__main__':
app.run(debug=True)
The jsonp stuff I added after finding people facing issues similar to mine on here. If I run this directly in the browser
http://127.0.0.1:5000/test
I get the output I'm looking for
[{'country': ['United Kingdom', 'Italy', 'United Kingdom',
etc. same with curl -i
Then I created a simple HTML page with jquery and bootstrap
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tour De France - Winners</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="#">Tour De France Winners</a>
</div>
</div>
<div id="main" class="container">
<button id="button">ajax call</button>
<div id="stuff"></div>
</div>
<script>
$(document).ready(function() {
function onDataReceived (data){
alert('test');
};
$("button").click(function(){
$.ajax({
url: "http://127.0.0.1:5000/test",
type: "GET",
dataType: "jsonp",
success: onDataReceived
});
});
});
</script>
</body>
</html>
When I click the button I get the following URL generated in the console
http://127.0.0.1:5000/test?callback=jQuery19008545286196749657_1455885069986&_=1455885069987
and a 500 error (in the console, silently).
If I paste that URL into my browser I get
builtins.AttributeError
AttributeError: 'str' object has no attribute 'data'
with the traceback looking like this
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/antlockyer/PycharmProjects/tdfvis/tdfvis.py", line 15, in decorated_function
data = str(func(*args, **kwargs).data)
AttributeError: 'str' object has no attribute 'data'
I'm very new to all this and would appreciate any help.
Thank you

Categories