Serving HTML+CSS+JS(angular) with flask - angularjs

What i want to do is, just send down the HTML+css+js files as static pages on some routes like:
#app.route('/', methods=[GET])
def index():
return <html+css+js>
Particularly i would like to stay away from templates, and rely on ajax/websocket connecting to other routes of the flask app to get the JSON objects and update the webpage. Also I had a hard time in linking css and js files in html. The url_for method seems to completely rely on template system and doesn't seem to work properly in my case.
eg.
Directory Structure
redirect-server(app home folder)
static
index.html
main.js
venv(python3 virtualenv)
main.py(flask app)
main.py
from flask import Flask, redirect
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return redirect("/abc/xyz")
#app.route('/abc/xyz')
def abc():
return app.send_static_file("index.html")
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>
The error I get is the following
127.0.0.1 - - [28/Oct/2015 14:07:02] "GET /abc/%7B%7B%20url_for('static',%20filename='main.js')%20%7D%7D HTTP/1.1" 404 -
The HTML is returned fine but it cannot find the js file

You send the template as a static file.
app.send_static_file("index.html")
Better render it, as shown in the docs :)

there is no way i could find this to work without relying on templates.
The following worked for me
restructuring my directories as follows
redirect-server
static
main.js
templates
index.html
main.py
main.py
from flask import Flask, redirect
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return redirect("/abc/xyz")
#app.route('/abc/xyz')
def abc():
return render_template("index.html")
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>

Related

flask_babel flash doesn't update in GAE in production

I'm implementing i18n with flask_babel like below and it works in local server.
However it doesn't work in production after deploy.
It can show translated with "_('English')", however it does show {{ _('English')}} as is in HTML.
Is there any way to show an appropriate message in HTML?
[main.py]
from flask_babel import gettext as _
#app.route('/', methods=['GET'])
def root():
flash(_('English'), 'success')
return render_template('index.html')
[index.html]
<!doctype html>
<html>
<head>
</head>
<body>
{{ _('English')}}
</body>
</html>

Integrating SendBird with Reactjs

in the index.html I added the
<div id="sb_widget"></div>
and
<script src="web-widget/SendBird.min.js"></script>
<script src="web-widget/build/widget.SendBird.js"></script>
<script>
sbWidget.start(Appid);
</script>
it works fine but I need to implement it in my react app
my scripts are still in index.html but I put the div(<div id="sb_widget"></div>) in my app.js
but nothing happened it's not working anymore
so how could I implement it in a reactjs app ??

How to conditionally load a different index.html in angularjs

I'm building an angular app, and using a standard index.html file:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.css">
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
What I'd like to do is have a different index.html or a "home.html" file loaded, if a user is not logged into the app. The home.html will be a single static page marketing site with it's own design and css/js. I'd like that page to be served from the '/' route, and other routes to be handled by the angular app.
How would I dynamically load a different starting html file?
The logic to route to another html should be placed in your login module. It could be not related with Angularjs
There are some code to redirect another page from outside or inside of angular app
$location.url('/RouteTo/index');
$location.url('/index');
$window.location.href="http://www.domain.com/home";
window.location = "http://www.domain.com/home";
you can get your host for app $window.location.host

Serving default index.html page when using Angular HTML5mode and Servicestack on the backend

I am new to ServiceStack and Angular. Apologies if this is verbose.
with reference to Html5 pushstate Urls on ServiceStack
I would like to be able to have my api service served up from the root. ie http://mydomain.com/
If a user browses the route, I would like to serve up a default html page that bootstraps my angular app.
In the the app itself if angular calls mydomain.com/customer/{id} json should be served but if this is browsed directly it should serve the default html page and keep the url but the route in the service method does not need to be called. as this will be resolved by angular which will call the customer service itself for a json result.
There are probably a few different ways to make this work, as long as you don't need to support html5mode urls. I have hope that I'll be able to leverage this code to eventually support html5mode, but at the moment, I've resigned myself to hash based URLs.
Given urls like: http://example.com/ or http://example.com/#/customer/{id}, here's how to bootstap an angularjs single page app on a self-hosted servicestack project from the root of the domain.
To enable the markdown razor engine, add this to your AppHost config (not absolutely necessary, but my preference over the default razor engine):
Plugins.Add(new RazorFormat());
Place a file, default.md, in the root of your project, and ensure it's properties are "content/copy when newer". Put whatever content you want in there. The important thing is to assign the template file. (If you're using the default razor engine, an equivalent default.cshtml file should also work, but I've never tried it. ) The template file is what will bootstrap your angularjs app. This is what I have in my default.md:
#template "Views\Shared\_Layout.shtml"
# This file only exists in order to trigger the load of the template file,
# which bootstraps the angular.js app
# The content of this file is not rendered by the template.
My _Layout.shtml file looks like this (omitting irrelevant details). Note ng-app in the html tag, and the ng-view div in the body. Also note that I don't include <!--#Body--> in the file. I'm not using server side templates for this project.
<!DOCTYPE html>
<html lang="en" ng-app="MyApp">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="Content/css/app-specific.css"/>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<!-- Navbar goes here -->
<div class="container">
<header id="header">
<!-- Header goes here -->
</header>
<div ng-view></div>
<hr>
<footer id="footer">
<!-- Footer goes here -->
</footer>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="/Scripts/app-specific/app.js?3ba152" type="text/javascript"></script>
<script src="/Scripts/app-specific/app-services.js?3ba152" type="text/javascript"></script>
<script src="/Scripts/app-specific/app-controllers.js?3ba152" type="text/javascript"></script>
</body>
</html>

Including javascript files with templates

I am using AppEngine with the webapp framework (python). In my script I am generating javascript code dynamically with Django, for example:
python controller file
template_values = {
'page': '1',
}
path = os.path.join(os.path.dirname(__file__), "../views/index.html")
self.response.out.write(template.render(path, template_values))
index.html file
<html>
<head>
...
<script>
{% if page %}
alert("test");
{% endif %}
</script>
</head>
<body>
...
</body>
</html>
Now, instead of using inline <script> tags I would like to use the <link> tags with a reference to a JS file containing the script. However, I can't quite understand I can do that using the templates engine. If I include a JS file (dynamically) it would somehow have to know the value of "page", but "page" is known in the scope of index.html only.
Any ideas?
Thanks,
Joel
If you want dynamically generate your javascript code in your html,
you can write the code inside python code
page = 0
template_values = {
'js_code': 'alert("test:'+str(page)+'")',
}
path = os.path.join(os.path.dirname(__file__), "../views/index.html")
self.response.out.write(template.render(path, template_values))
in index.html
<script>
{{js_code}}
</script>
If you want to generate a js file dynamically, you can try to pretend there is a js file,
and generate its content.
class JSHandler(BaseHandler):
def get(self):
page= str(self.request.get("page"))
js_code ='alert("page:'+page+'");'
self.response.out.write(js_code)
def main():
application = webapp.WSGIApplication([
('/code.js', JSHandler),
], debug=True)
wsgiref.handlers.CGIHandler().run(application)
Then you can write this code in your html
<script type="text/javascript" src="/code.js?page={{page}}">></script>
You are either over-complicating a simple situation, or you haven't explained your problem clearly.
If you want to include an externally-located JavaScript file, you would use a <script> tag, not <link>.
If you have template code like this:
<html>
<head>
{% if page %}
<script type="text/javascript" src="/js/foo.js"></script>
{% endif %}
</head>
...
</html>
and page is not None, the template will render the following HTML to the browser:
<html>
<head>
<script type="text/javascript" src="/js/foo.js"></script>
</head>
...
</html>
and the browser will try to load the resource pointed to by the <script> tag. The browser has no knowledge of how that tag got into the HTML that it loaded.

Resources