Catch all path in flask app - javascript

I writing an app in Angular + Flask hosted on heroku. I've been looking to use html5mode to use myapp.co/register for oauth. The problem with html5mode is that server needs to rewrite url if someone refreshes the page or clicks the link that is not root. I tried to use this snippet to catch them all, but it doesn't work.
#app.route("/", defaults={"path": ""})
#app.route("/<path:path>")
def index(path):
print path
return make_response(open(app.static_folder + "index.html").read())
output 404
* Restarting with reloader
127.0.0.1 - - [23/Jan/2014 13:41:48] "GET /ass HTTP/1.1" 404 -
App got root that servers index.html and /api/v1/ that is RESTful api

You need to use something more than you have:
#app.route("/", defaults={"path": ""})
#app.route("/<string:path>") <--- this is missing
#app.route("/<path:path>")
def index(path):
print path
return make_response(open(app.static_folder + "index.html").read())
So:
#app.route("/<string:path>")
is missing. It catches string variables (not path), so in your case just ass from your example, when you try to hit http://localhost:5000/ass.

Your code will catch all urls if you do not have any more routes with more highest priority. But look like it should return 500 error (because I hope you do not have <app_path>/staticindex.html and use unsafe method to send file).
So if you have another rules you must look at rule priority (see https://stackoverflow.com/a/17146563/880326).
If you have error with this route better use:
#app.route("/", defaults={"path": ""})
#app.route("/<path:path>")
def index(path)
return send_from_directory(app.static_folder, "index.html")

Related

Flask change image with JavaScript

I'm working on Flask and I'm stuck in a strange situation.
I'm trying to change an image with javascript but flask gives me these errors:
... 12:05:34] "GET / HTTP/1.1" 200 -
... 12:05:38] "GET /img/immagine.jpg HTTP/1.1" 404 -
JS:
var btnAddImage = document.getElementById("btnAddImage");
btnAddImage.onclick = function() {
var img = document.createElement("img");
img.src = "/static/img/immagine.jpg.jpg";
document.getElementById("asi").appendChild(img);
};
As you can see in the path it's specified as static but it's not read.
I'm using the simply render_template method:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('index.html', nome=nome)
enter code here
The error message clearly states that the image could not be found.
Your code does not match the error message. One time you have .jgp as file ending, one time .jpg.jpg.
Try to compare the image name and path with the one you write in your code.
If you cannot figure out how to fix this, please also give us an overview of your directory structure.

Continuous requests to /socket.io/

I am having trouble pinpointing where my problem is coming from. Currently,
there is a constant request? for /socket.io/ and I am not sure why.
I checked my developer tools in chrome in the network panel and I don't actually see requests being made. However, the console.logs I put in my code are continuously being hit showing that there is a continuous attempt for /socket.io/.
Here is my project:
https://github.com/liondancer/ReviewWeb
I performed a grep on my node_modules and this was the only result:
$grep -rn "socket.io" node_modules/
node_modules//hapi/API.md:324:var SocketIO = require('socket.io');
I am using webpack so grep on the file would give me huge, unreadable results.
In my project's ReviewWeb/server/index.js I put some console.logs
server.ext('onPreResponse', function(request, reply) {
if (typeof request.response.statusCode !== 'undefined') {
console.log('Found server path');
return reply.continue();
}
console.log(request.response.statusCode);
console.log('rendering server side react', request.path)
Router.run(routes, request.path, function(Handler, router) {
var html = React.renderToStaticMarkup(<Handler />);
// http://cheeriojs.github.io/cheerio/
// Server knows HTML with Cheerio
var $ = Cheerio.load(HTMLBASE);
// http://cheeriojs.github.io/cheerio/#manipulation
// prepend inserts content as the first child of each of the selected elements.
$('#app').prepend(html);
// convert to html
var output = $.html();
reply(output);
});
});
This is the result from the console.logs
undefined
rendering server side react /socket.io/
Warning: No route matches path "/socket.io/". Make sure you have <Route path="/socket.io/"> somewhere in your routes
undefined
rendering server side react /socket.io/
Warning: No route matches path "/socket.io/". Make sure you have <Route path="/socket.io/"> somewhere in your routes
...
...
...
continuously...
Not sure how why this is happening and I am having a hard time finding the source of the problem.
* UPDATE *
I was using port 8080 and it was causing a problem. I changed to port 8000 and the problem didn't occur. I have no idea why but perhaps this could be a reason:
http://webpack.github.io/docs/webpack-dev-server.html#hot-mode
But I only have devtools set up to be source-map in my webpack.config.js

Websocket-Rails Channel 'Error during WebSocket Handshake'

I'm trying to use websocket-rails to broadcast live routes as they come in to my site. However, I'm unable to get any messages to be published. I've read all of the help I could find, and I can't seem to get a solution.
Here is what the javascript I have in application.html.erb:
var route_name = window.location.pathname + window.location.search;
$.post("/realtimeroutes",
{ data: { route_name: route_name} },
function(response) {
}
);
This data is handed off to a rails controller method realtime_routes which looks like this:
def realtime_routes
puts '*** The Route Data is: ' + params[:data][:route_name]);
new_route = RouteCatcher.new(route_name: params[:data][:route_name]
if new_route.save
route = {route_name: params[:data][:route_name]}
puts '*** Right before the Message is sent ***'
WebsocketRails[:new_route].trigger('new', route)
puts '*** Right After the Message is sent ***'
render nothing: true
else
render nothing: true
end
end
To this point everything is fine. updates are happening in the DB and both the before and after messages are printing to the console, but there is no Websocket Message fired.
Next I have this javascript listening in realtime.html.erb:
var dispatcher = new WebSocketRails(window.location.host + '/websocket');
var channel = dispatcher.subscribe('new_route');
channel.bind('new', function(route) {
console.log('********** Inside Bind Event');
console.log('********** a new route '+ route.route_name +' arrived!');
});
Nothing is ever being received on the bind event and when I look in the Console on Chrome, I get:
'Uncaught ReferenceError: WebSocketRails is not defined'
So I'm absolutely stuck here as I've followed every bit of documentation I can find and really have no idea where to go. Any help with this is greatly appreciated.
UPDATE: That was an initialization error because the WebSocketRails was being rendered before the rest of the application js.
However, now I am getting the error:
WebSocket connection to 'ws://localhost:3000/websocket' failed: Error during WebSocket handshake: Unexpected response code: 301
After reading further about other people with the same error, it seems prudent to mention that I am using Puma on AWS elasticbeanstalk with SSL in production.

Qunit testing an Ember.js app with ember-simple-auth authentication?

So, Am writing a Qunit test (with teaspoon as the test runner), for an Ember application that uses ember-simple-auth gem for login authintication, My test is as follows (coffee script) :
#= require qunit_spec_helper
test "Employee signs in", ->
expect(1)
visit("/login").then(->
fillIn "input.email", "employee1#example.com"
).then(->
fillIn "input.user_password", "password1"
).then(->
click "button.btn-primary"
).andThen ->
equal(find('h2').length,1, "Welcome to the App")
And here is the Test helper:
QUnit.testStart ->
Ember.run ->
App.reset()
Ember.testing = true
App.setupForTesting()
App.injectTestHelpers()
QUnit.testDone ->
Ember.testing = false
QUnit.done ->
Ember.run ->
App.reset()
When I run the test (keeping any eye on the console), I get the following error:
POST http://localhost:3000/teaspoon/qunit/oauth/token 404 (Not Found)
I can't seem to be able to login, No matter what ..
I ran out of ideas, Any help/Advice is highly Appreciated :)
Ember.SimpleAuth makes a request against the server to authenticate the session when the button is clicked - the route isn't handled by your server though (or the server isn't running at all maybe?) I'd stub the token endpoint for testing, find an example e.g. here: https://github.com/digitalplaywright/eak-simple-auth/blob/master/tests/acceptance/login-test.js

websocket-rails, websocket handshake error

I followed the docs on the websocket-rails github wiki page, but couldn't overcome this difficulty, I get this error with chrome:
WebSocket connection to 'ws://0.0.0.0:3000/websocket' failed: Error during WebSocket handshake: Unexpected response code: 301
I installed the websocket-rails gem, generated the install, I set successfully config.middleware.delete Rack::Lock in development.rb; I'm using Rails 4.
I got in the view:
<script type="text/javascript">
var dispatcher = new WebSocketRails('0.0.0.0:3000/websocket');
</script>
I got in my chat_controller.rb:
class ChatController < WebsocketRails::BaseController
def initialize_session
puts "Session Initialized"
end
def user_connected
puts 'user connected'
end
end
in my events.rb:
WebsocketRails::EventMap.describe do
subscribe :client_connected, :to => ChatController, :with_method => :user_connected
end
As you can see, my goal is to display "Session Initialized", and "user connected", in my thin server console each time that someone goes on a page. Between, I run the server with bundle exec thin start, but I got a javascript error instead (websocket connection failed error 301).
Thanks to the members of the Websocket Rails IRC, I found out that in my route, I was appending the locale before every path, so it coudln't find it.
Check your routes.rb if someone hit that issue too !

Categories

Resources