Serving static resources with Flask - managing same origin policy

I am having trouble serving static files (images, etc.) for a little game Im running in Phaser . I'm using flask-socketio on the server (and socket.io on the client side) for networking, so I'm trying to get this to work in flask. As far as I can tell, I have to use Flask to serve static resources, because otherwise I am facing the same origin policy issue .

Indeed, I tried using assets with nginx on a different port, but I got this message in my browser console (Safari in this case): SecurityError: DOM Exception 18: An attempt was made to break through the security policy of the user agent.

I looked at Flask's documentation on how to serve static files and said I was using "url_for". However, this only works for HTML template files. I am trying to load static resources inside my javascript code using the Phaser engine like this (for example):

this.load.image('player', 'assets/player.png’);   //this.load.image('player’, url);

      

where I cannot explicitly use 'url_for as it is not a template file but javascript code.

So my question is, how do I serve my static resources so that I don't violate the same origin policy?

  • Is there any other safe way to serve static resources in Flask other than using 'url_for?
  • Or should I use nginx as a reverse proxy? In the flask-socketio documentation I found this nginx config snippet: Flask-SocketIO documentation (scroll down to where it says "Using nginx as WebSocket Reverse Proxy")

As for # 2, I don't quite understand how this is supposed to work. If I do # 2, can someone explain how I can configure nginx if Flask is listening on port 5000? Where in this snippet am I setting up the path to static assets on the file system? And in my javascript code, what url am I using to link to the assets?

+3


source to share


1 answer


Typically, you can configure Nginx (or some other generic web server) to a "primary" port and then configure it to forward specific requests to your application server (in this case Flask) to a secondary port that is invisible / unknown client browser. Flask will provide the result to Nginx, which will then send the result to the user.

This is called a reverse proxy , and Nginx is widely considered a good choice for this setup. This way all files are served by the Nginx client, so the client doesn't notice that some of them actually come from your application server.



This is good from an architectural point of view as it isolates your webapp (somewhat) from the client and allows it to save resources, for example. not serving static files and having an Nginx cache some of the webapp results when it makes sense to do so.

If you are developing this may seem like a lot of overhead; but for production it makes more sense. However, it is a good idea to keep your community environment as close as possible to your prod environment.

+1


source







All Articles